_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q272600
GitHub_Traffic.write_referrers_to_file
test
def write_referrers_to_file(self, file_path='', date=str(datetime.date.today()), organization='llnl'): """ Writes the referrers data to file. """ self.remove_date(file_path=file_path, date=date) referrers_exists = os.path.isfile(file_path) with open(file_path, 'a') as out: if not referrers_exists: out.write('date,organization,referrer,count,count_log,uniques,' + 'uniques_logged\n') sorted_referrers = sorted(self.referrers_lower)#sort based on lowercase
python
{ "resource": "" }
q272601
process_json
test
def process_json(filename): """ Converts a DOE CODE .json file into DOE CODE projects Yields DOE CODE records from a DOE CODE .json file """ logger.debug('Processing DOE CODE json: %s',
python
{ "resource": "" }
q272602
process_url
test
def process_url(url, key): """ Yields DOE CODE records from a DOE CODE .json URL response Converts a DOE CODE API .json URL response into DOE CODE projects """ logger.debug('Fetching DOE CODE JSON: %s', url) if key is None: raise ValueError('DOE CODE API Key value is missing!') response
python
{ "resource": "" }
q272603
process
test
def process(filename=None, url=None, key=None): """ Yeilds DOE CODE records based on provided input sources param: filename (str): Path to a DOE CODE .json file url (str): URL for a DOE CODE server json file key (str): API Key for connecting to DOE CODE
python
{ "resource": "" }
q272604
GitHub_Users_Emails.login
test
def login(self, username='', password=''): """ Performs a login and sets the Github object via given credentials. If credentials are empty or incorrect then prompts user for credentials. Stores the authentication token in a CREDENTIALS_FILE used for future logins. Handles Two Factor Authentication. """ try: token = '' id = '' if not os.path.isfile('CREDENTIALS_FILE'): if(username == '' or password == ''): username = raw_input('Username: ') password = getpass.getpass('Password: ') note = 'GitHub Organization Stats App' note_url = 'http://software.llnl.gov/' scopes = ['user', 'repo'] auth = github3.authorize(username, password, scopes, note, note_url, two_factor_callback=self.prompt_2fa) token = auth.token id = auth.id with open('CREDENTIALS_FILE', 'w+') as fd:
python
{ "resource": "" }
q272605
GitHub_Users_Emails.get_mems_of_org
test
def get_mems_of_org(self): """ Retrieves the emails of the members of the organization. Note this Only gets public emails. Private emails would need authentication for each user. """ print 'Getting members\' emails.' for member in self.org_retrieved.iter_members():
python
{ "resource": "" }
q272606
GitHub_Users_Emails.write_to_file
test
def write_to_file(self, file_path=''): """ Writes the user emails to file. """ with open(file_path, 'w+') as out: out.write('user, email\n') sorted_names = sorted(self.logins_lower)#sort based on lowercase for login in sorted_names:
python
{ "resource": "" }
q272607
connect
test
def connect(url, username, password): """ Return a connected Bitbucket session """
python
{ "resource": "" }
q272608
connect
test
def connect(url='https://gitlab.com', token=None): """ Return a connected GitLab session ``token`` should be a ``private_token`` from Gitlab """ if token is None: token = os.environ.get('GITLAB_API_TOKEN', None) gl_session = gitlab.Gitlab(url, token) try:
python
{ "resource": "" }
q272609
query_repos
test
def query_repos(gl_session, repos=None): """ Yields Gitlab project objects for all projects in Bitbucket """ if repos is None: repos = [] for repo in repos: yield gl_session.projects.get(repo)
python
{ "resource": "" }
q272610
git_repo_to_sloc
test
def git_repo_to_sloc(url): """ Given a Git repository URL, returns number of lines of code based on cloc Reference: - cloc: https://github.com/AlDanial/cloc - https://www.omg.org/spec/AFP/ - Another potential way to calculation effort Sample cloc output: { "header": { "cloc_url": "github.com/AlDanial/cloc", "cloc_version": "1.74", "elapsed_seconds": 0.195950984954834, "n_files": 27, "n_lines": 2435, "files_per_second": 137.78956000769, "lines_per_second": 12426.5769858787 }, "C++": { "nFiles": 7, "blank": 121, "comment": 314, "code": 371 }, "C/C++ Header": { "nFiles": 8, "blank": 107, "comment": 604, "code": 191 }, "CMake": { "nFiles": 11, "blank": 49, "comment": 465, "code": 165 }, "Markdown": { "nFiles": 1, "blank": 18, "comment": 0, "code": 30 }, "SUM": { "blank": 295,
python
{ "resource": "" }
q272611
compute_labor_hours
test
def compute_labor_hours(sloc, month_hours='cocomo_book'): """ Compute the labor hours, given a count of source lines of code The intention is to use the COCOMO II model to compute this value. References: - http://csse.usc.edu/tools/cocomoii.php - http://docs.python-guide.org/en/latest/scenarios/scrape/ """ # Calculation of hours in a month if month_hours == 'hours_per_year': # Use number of working hours in a year: # (40 Hours / week) * (52 weeks / year) / (12 months / year) ~= 173.33 HOURS_PER_PERSON_MONTH = 40.0 * 52 / 12 else: # Use value from COCOMO II Book (month_hours=='cocomo_book'): # Reference: https://dl.acm.org/citation.cfm?id=557000 # This is the value used by the Code.gov team: # https://github.com/GSA/code-gov/blob/master/LABOR_HOUR_CALC.md
python
{ "resource": "" }
q272612
_prune_dict_null_str
test
def _prune_dict_null_str(dictionary): """ Prune the "None" or emptry string values from dictionary items """ for key, value in list(dictionary.items()): if value is None or str(value) == '': del dictionary[key]
python
{ "resource": "" }
q272613
GitHubQueryManager._readGQL
test
def _readGQL(self, filePath, verbose=False): """Read a 'pretty' formatted GraphQL query file into a one-line string. Removes line breaks and comments. Condenses white space. Args: filePath (str): A relative or absolute path to a file containing a GraphQL query. File may use comments and multi-line formatting. .. _GitHub GraphQL Explorer: https://developer.github.com/v4/explorer/ verbose (Optional[bool]): If False, prints will be suppressed. Defaults to False. Returns: str: A single line GraphQL query. """ if not os.path.isfile(filePath):
python
{ "resource": "" }
q272614
GitHubQueryManager.queryGitHubFromFile
test
def queryGitHubFromFile(self, filePath, gitvars={}, verbosity=0, **kwargs): """Submit a GitHub GraphQL query from a file. Can only be used with GraphQL queries. For REST queries, see the 'queryGitHub' method. Args: filePath (str): A relative or absolute path to a file containing a GraphQL query. File may use comments and multi-line formatting. .. _GitHub GraphQL Explorer: https://developer.github.com/v4/explorer/
python
{ "resource": "" }
q272615
GitHubQueryManager._submitQuery
test
def _submitQuery(self, gitquery, gitvars={}, verbose=False, rest=False): """Send a curl request to GitHub. Args: gitquery (str): The query or endpoint itself. Examples: query: 'query { viewer { login } }' endpoint: '/user' gitvars (Optional[Dict]): All query variables. Defaults to empty. verbose (Optional[bool]): If False, stderr prints will be suppressed. Defaults to False. rest (Optional[bool]): If True, uses the REST API instead of GraphQL. Defaults to False. Returns: { 'statusNum' (int): The HTTP status code. 'headDict' (Dict[str]): The response headers. 'linkDict' (Dict[int]): Link based pagination data. 'result' (str): The body of the response. } """ errOut = DEVNULL if not verbose else None authhead = 'Authorization: bearer ' + self.__githubApiToken bashcurl = 'curl -iH TMPauthhead -X POST -d TMPgitquery https://api.github.com/graphql' if not rest \ else 'curl -iH TMPauthhead https://api.github.com' + gitquery bashcurl_list = bashcurl.split() bashcurl_list[2] = authhead if not rest: gitqueryJSON = json.dumps({'query': gitquery, 'variables': json.dumps(gitvars)}) bashcurl_list[6] = gitqueryJSON fullResponse = check_output(bashcurl_list, stderr=errOut).decode() _vPrint(verbose, "\n" + fullResponse) fullResponse =
python
{ "resource": "" }
q272616
GitHubQueryManager._awaitReset
test
def _awaitReset(self, utcTimeStamp, verbose=True): """Wait until the given UTC timestamp. Args: utcTimeStamp (int): A UTC format timestamp. verbose (Optional[bool]): If False, all extra printouts will be suppressed. Defaults to True. """ resetTime = pytz.utc.localize(datetime.utcfromtimestamp(utcTimeStamp)) _vPrint(verbose, "--- Current Timestamp") _vPrint(verbose, " %s" % (time.strftime('%c'))) now = pytz.utc.localize(datetime.utcnow()) waitTime = round((resetTime - now).total_seconds()) + 1 _vPrint(verbose, "--- Current UTC Timestamp") _vPrint(verbose, "
python
{ "resource": "" }
q272617
GitHubQueryManager._countdown
test
def _countdown(self, waitTime=0, printString="Waiting %*d seconds...", verbose=True): """Makes a pretty countdown. Args: gitquery (str): The query or endpoint itself. Examples: query: 'query { viewer { login } }' endpoint: '/user' printString (Optional[str]): A counter message to display. Defaults to 'Waiting %*d seconds...' verbose (Optional[bool]): If False, all extra printouts will be suppressed. Defaults to True.
python
{ "resource": "" }
q272618
DataManager.fileLoad
test
def fileLoad(self, filePath=None, updatePath=True): """Load a JSON data file into the internal JSON data dictionary. Current internal data will be overwritten. If no file path is provided, the stored data file path will be used. Args: filePath (Optional[str]): A relative or absolute path to a '.json' file. Defaults to None. updatePath (Optional[bool]): Specifies whether or not to update the stored data file path. Defaults to True. """ if not filePath: filePath = self.filePath
python
{ "resource": "" }
q272619
DataManager.fileSave
test
def fileSave(self, filePath=None, updatePath=False): """Write the internal JSON data dictionary to a JSON data file. If no file path is provided, the stored data file path will be used. Args: filePath (Optional[str]): A relative or absolute path to a '.json' file. Defaults to None. updatePath (Optional[bool]): Specifies whether or not to update the stored data file path. Defaults to False. """ if not filePath: filePath = self.filePath if not os.path.isfile(filePath): print("Data file '%s' does not exist, will create new file."
python
{ "resource": "" }
q272620
create_tfs_connection
test
def create_tfs_connection(url, token): """ Creates the TFS Connection Context """ if token is None: token = os.environ.get('TFS_API_TOKEN', None) tfs_credentials
python
{ "resource": "" }
q272621
create_tfs_project_analysis_client
test
def create_tfs_project_analysis_client(url, token=None): """ Create a project_analysis_client.py client for a Team Foundation Server Enterprise connection instance. This is helpful for understanding project languages, but currently blank for all our test conditions. If token is not provided, will attempt to use the TFS_API_TOKEN environment variable if present. """ if token is None: token = os.environ.get('TFS_API_TOKEN', None)
python
{ "resource": "" }
q272622
create_tfs_core_client
test
def create_tfs_core_client(url, token=None): """ Create a core_client.py client for a Team Foundation Server Enterprise connection instance If token is not provided, will attempt to use the TFS_API_TOKEN environment variable if present. """ if token is None: token = os.environ.get('TFS_API_TOKEN', None) tfs_connection = create_tfs_connection(url, token) tfs_client =
python
{ "resource": "" }
q272623
create_tfs_git_client
test
def create_tfs_git_client(url, token=None): """ Creates a TFS Git Client to pull Git repo info """ if token is None: token = os.environ.get('TFS_API_TOKEN', None) tfs_connection = create_tfs_connection(url, token) tfs_git_client = tfs_connection.get_client('vsts.git.v4_1.git_client.GitClient') if tfs_git_client is None:
python
{ "resource": "" }
q272624
create_tfs_tfvc_client
test
def create_tfs_tfvc_client(url, token=None): """ Creates a TFS TFVC Client to pull TFVC repo info """ if token is None: token = os.environ.get('TFS_API_TOKEN', None) tfs_connection = create_tfs_connection(url, token) tfs_tfvc_client = tfs_connection.get_client('vsts.tfvc.v4_1.tfvc_client.TfvcClient') if tfs_tfvc_client is None:
python
{ "resource": "" }
q272625
get_git_repos
test
def get_git_repos(url, token, collection, project): """ Returns a list of all git repos for the supplied project within the supplied collection """ git_client
python
{ "resource": "" }
q272626
get_tfvc_repos
test
def get_tfvc_repos(url, token, collection, project): """ Returns a list of all tfvc branches for the supplied project within the supplied collection """ branch_list = [] tfvc_client = create_tfs_tfvc_client('{url}/{collection_name}'.format(url=url, collection_name=collection.name), token) logger.debug('Retrieving Tfvc Branches for Project: {project_name}'.format(project_name=project.name)) branches =
python
{ "resource": "" }
q272627
GitHub_LLNL_Year_Commits.get_year_commits
test
def get_year_commits(self, username='', password='', organization='llnl', force=True): """ Does setup such as login, printing API info, and waiting for GitHub to build the commit statistics. Then gets the last year of commits and prints them to file. """ date = str(datetime.date.today()) file_path = ('year_commits.csv') if force or not os.path.isfile(file_path): my_github.login(username, password) calls_beginning = self.logged_in_gh.ratelimit_remaining + 1 print 'Rate Limit: ' + str(calls_beginning) my_github.get_org(organization) my_github.repos(building_stats=True) print "Letting GitHub build statistics."
python
{ "resource": "" }
q272628
GitHub_LLNL_Year_Commits.calc_total_commits
test
def calc_total_commits(self, starting_commits=0): """ Uses the weekly commits and traverses back through the last year, each week subtracting the weekly commits and storing them. It needs an initial starting commits number, which should be taken from the most up to date number from github_stats.py output. """ for week_of_commits in self.commits_dict_list: try: self.commits[week_of_commits['week']] -= week_of_commits['total'] except KeyError: total = self.commits[week_of_commits['week']] \
python
{ "resource": "" }
q272629
GitHub_LLNL_Year_Commits.write_to_file
test
def write_to_file(self): """ Writes the weeks with associated commits to file. """ with open('../github_stats_output/last_year_commits.csv', 'w+') as output: output.write('date,organization,repos,members,teams,' + 'unique_contributors,total_contributors,forks,' + 'stargazers,pull_requests,open_issues,has_readme,' + 'has_license,pull_requests_open,pull_requests_closed,' + 'commits\n') #no reverse this time to print oldest first previous_commits = 0 for week in self.sorted_weeks:
python
{ "resource": "" }
q272630
configure
test
def configure(backends, raise_errors=False): """Instantiate and configures backends. :arg list-of-dicts backends: the backend configuration as a list of dicts where each dict specifies a separate backend. Each backend dict consists of two things: 1. ``class`` with a value that is either a Python class or a dotted Python path to one 2. ``options`` dict with options for the backend in question to configure it See the documentation for the backends you're using to know what is configurable in the options dict. :arg raise_errors bool: whether or not to raise an exception if something happens in configuration; if it doesn't raise an exception, it'll log the exception For example, this sets up a :py:class:`markus.backends.logging.LoggingMetrics` backend:: markus.configure([ { 'class': 'markus.backends.logging.LoggingMetrics', 'options': { 'logger_name': 'metrics' } } ]) You can set up as many backends as you like. .. Note:: During application startup, Markus should get configured before the app starts generating metrics. Any metrics generated before Markus is configured will get dropped. However, anything can call
python
{ "resource": "" }
q272631
get_metrics
test
def get_metrics(thing, extra=''): """Return MetricsInterface instance with specified name. The name is used as the prefix for all keys generated with this :py:class:`markus.main.MetricsInterface`. The :py:class:`markus.main.MetricsInterface` is not tied to metrics backends. The list of active backends are globally configured. This allows us to create :py:class:`markus.main.MetricsInterface` classes without having to worry about bootstrapping order of the app. :arg class/instance/str thing: The name to use as a key prefix. If this is a class, it uses the dotted Python path. If this is an instance, it uses the dotted Python path plus ``str(instance)``. :arg str extra: Any extra bits to add to the end of the name. :returns: a ``MetricsInterface`` instance Examples: >>> from markus import get_metrics Create a MetricsInterface with the name "myapp" and generate a count with stat "myapp.thing1" and value 1: >>> metrics = get_metrics('myapp') >>> metrics.incr('thing1', value=1) Create a MetricsInterface with the prefix of the Python module it's being called in: >>> metrics = get_metrics(__name__) Create a MetricsInterface with the prefix as the qualname of the class: >>> class Foo: ... def __init__(self): ... self.metrics = get_metrics(self) Create a prefix of the class path plus some identifying information: >>> class Foo:
python
{ "resource": "" }
q272632
MetricsInterface.timing
test
def timing(self, stat, value, tags=None): """Record a timing value. Record the length of time of something to be added to a set of values from which a statistical distribution is derived. Depending on the backend, you might end up with count, average, median, 95% and max for a set of timing values. This is useful for analyzing how long things take to occur. For example, how long it takes for a function to run, to upload files, or for a database query to execute. :arg string stat: A period delimited alphanumeric key. :arg int value: A timing in milliseconds. :arg list-of-strings tags: Each string in the tag consists of a key and a value separated by a colon. Tags can make it easier to break down metrics for analysis. For example ``['env:stage', 'compressed:yes']``. For example: >>> import time >>> import markus >>> metrics = markus.get_metrics('foo') >>> def upload_file(payload): ... start_time = time.perf_counter() # this is in seconds
python
{ "resource": "" }
q272633
MetricsInterface.timer
test
def timer(self, stat, tags=None): """Contextmanager for easily computing timings. :arg string stat: A period delimited alphanumeric key. :arg list-of-strings tags: Each string in the tag consists of a key and a value separated by a colon. Tags can make it easier to break down metrics for analysis. For example ``['env:stage', 'compressed:yes']``. For example: >>> mymetrics = get_metrics(__name__)
python
{ "resource": "" }
q272634
MetricsInterface.timer_decorator
test
def timer_decorator(self, stat, tags=None): """Timer decorator for easily computing timings. :arg string stat: A period delimited alphanumeric key. :arg list-of-strings tags: Each string in the tag consists of a key and a value separated by a colon. Tags can make it easier to break down metrics for analysis. For example ``['env:stage', 'compressed:yes']``. For example: >>> mymetrics = get_metrics(__name__) >>> @mymetrics.timer_decorator('long_function') ... def long_function(): ... # perform some thing we want to keep metrics on
python
{ "resource": "" }
q272635
generate_tag
test
def generate_tag(key, value=None): """Generate a tag for use with the tag backends. The key and value (if there is one) are sanitized according to the following rules: 1. after the first character, all characters must be alphanumeric, underscore, minus, period, or slash--invalid characters are converted to "_" 2. lowercase If a value is provided, the final tag is `key:value`. The final tag must start with a letter. If it doesn't, an "a" is prepended. The final tag is truncated to 200 characters. If the final tag is "device", "host", or "source", then a "_" will be appended the end. :arg str key: the key to use :arg str value: the value (if any) :returns: the final tag Examples: >>> generate_tag('yellow')
python
{ "resource": "" }
q272636
LoggingMetrics.timing
test
def timing(self, stat, value, tags=None): """Report a timing."""
python
{ "resource": "" }
q272637
LoggingMetrics.histogram
test
def histogram(self, stat, value, tags=None): """Report a histogram."""
python
{ "resource": "" }
q272638
LoggingRollupMetrics.rollup
test
def rollup(self): """Roll up stats and log them.""" now = time.time() if now < self.next_rollup: return self.next_rollup = now + self.flush_interval for key, values in sorted(self.incr_stats.items()): self.logger.info( '%s INCR %s: count:%d|rate:%d/%d', self.leader, key, len(values), sum(values), self.flush_interval ) self.incr_stats[key] = [] for key, values in sorted(self.gauge_stats.items()): if values: self.logger.info( '%s GAUGE %s: count:%d|current:%s|min:%s|max:%s', self.leader, key, len(values), values[-1], min(values), max(values), ) else: self.logger.info('%s (gauge) %s: no data', self.leader, key) self.gauge_stats[key] = [] for key, values in sorted(self.histogram_stats.items()): if values: self.logger.info( ( '%s HISTOGRAM %s: '
python
{ "resource": "" }
q272639
order_enum
test
def order_enum(field, members): """ Make an annotation value that can be used to sort by an enum field. ``field`` The name of an EnumChoiceField. ``members`` An iterable of Enum members in the order to sort by. Use like: .. code-block:: python desired_order = [MyEnum.bar, MyEnum.baz, MyEnum.foo] ChoiceModel.objects\\ .annotate(my_order=order_enum('choice', desired_order))\\ .order_by('my_order') As Enums are iterable, ``members`` can be the Enum itself if the default ordering is desired: .. code-block:: python ChoiceModel.objects\\ .annotate(my_order=order_enum('choice', MyEnum))\\ .order_by('my_order') .. warning:: On Python 2, Enums may not
python
{ "resource": "" }
q272640
EnumChoiceField.from_db_value
test
def from_db_value(self, value, expression, connection, context): """ Convert a string from the database into an Enum value """
python
{ "resource": "" }
q272641
EnumChoiceField.to_python
test
def to_python(self, value): """ Convert a string from a form into an Enum value. """ if value is None: return value
python
{ "resource": "" }
q272642
EnumChoiceField.get_prep_value
test
def get_prep_value(self, value): """ Convert an Enum value into a string for the database """ if value is None: return None if isinstance(value, self.enum):
python
{ "resource": "" }
q272643
_resolve_path
test
def _resolve_path(obj, path): """path is a mul of coord or a coord""" if obj.__class__ not in path.context.accept: result = set() for ctx in path.context.accept: result |= {e for u in obj[ctx] for e in _resolve_path(u, path)} return result if isinstance(obj, Text): if path.index is not None:
python
{ "resource": "" }
q272644
project_usls_on_dictionary
test
def project_usls_on_dictionary(usls, allowed_terms=None): """`usls` is an iterable of usl. return a mapping term -> usl list """ cells_to_usls = defaultdict(set) tables = set() for u in usls: for t in u.objects(Term): for c in t.singular_sequences: # This is the first time we meet the cell c if not cells_to_usls[c]: tables.update(c.relations.contained) cells_to_usls[c].add(u) if allowed_terms: allowed_terms = set(allowed_terms)
python
{ "resource": "" }
q272645
Histogram.mean
test
def mean(self): """Returns the mean value.""" if self.counter.value
python
{ "resource": "" }
q272646
Meter.mark
test
def mark(self, value=1): """Record an event with the meter. By default it will record one event. :param value: number
python
{ "resource": "" }
q272647
Meter.mean_rate
test
def mean_rate(self): """ Returns the mean rate of the events since the start of the process. """ if self.counter.value == 0: return 0.0
python
{ "resource": "" }
q272648
Derive.mark
test
def mark(self, value=1): """Record an event with the derive. :param value: counter value to record
python
{ "resource": "" }
q272649
StatsDReporter.send_metric
test
def send_metric(self, name, metric): """Send metric and its snapshot.""" config = SERIALIZER_CONFIG[class_name(metric)] mmap( self._buffered_send_metric, self.serialize_metric( metric, name, config['keys'], config['serialized_type'] ) ) if hasattr(metric, 'snapshot') and config.get('snapshot_keys'): mmap(
python
{ "resource": "" }
q272650
StatsDReporter.serialize_metric
test
def serialize_metric(self, metric, m_name, keys, m_type): """Serialize and send available measures of a metric.""" return [
python
{ "resource": "" }
q272651
StatsDReporter.format_metric_string
test
def format_metric_string(self, name, value, m_type): """Compose a statsd compatible string for a metric's measurement.""" # NOTE(romcheg): This serialized metric template is based on # statsd's documentation.
python
{ "resource": "" }
q272652
StatsDReporter._buffered_send_metric
test
def _buffered_send_metric(self, metric_str): """Add a metric to the buffer.""" self.batch_count += 1 self.batch_buffer += metric_str # NOTE(romcheg): Send metrics if the number of metrics in the buffer #
python
{ "resource": "" }
q272653
IniStorage.get
test
def get(self, section, option, **kwargs): """ Get method that raises MissingSetting if the value was unset. This differs from the SafeConfigParser which may raise either a NoOptionError or a NoSectionError. We take extra **kwargs because the Python 3.5 configparser extends the
python
{ "resource": "" }
q272654
_json_safe
test
def _json_safe(data): """ json.loads wants an unistr in Python3. Convert it. """ if not hasattr(data, 'encode'): try: data = data.decode('utf-8') except UnicodeDecodeError:
python
{ "resource": "" }
q272655
ExactOnlineConfig.get_or_set_default
test
def get_or_set_default(self, section, option, value): """ Base method to fetch values and to set defaults in case they don't exist. """ try:
python
{ "resource": "" }
q272656
ExactInvoice.get_ledger_code_to_guid_map
test
def get_ledger_code_to_guid_map(self, codes): """ Convert set of human codes and to a dict of code to exactonline guid mappings. Example:: ret = inv.get_ledger_code_to_guid_map(['1234', '5555']) ret == {'1234': '<guid1_from_exactonline_ledgeraccounts>', '5555': '<guid2_from_exactonline_ledgeraccounts>'} """ if codes: codes = set(str(i) for i in codes) ledger_ids = self._api.ledgeraccounts.filter(code__in=codes)
python
{ "resource": "" }
q272657
V1Division.get_divisions
test
def get_divisions(self): """ Get the "current" division and return a dictionary of divisions so the user can select the right one. """ ret = self.rest(GET('v1/current/Me?$select=CurrentDivision')) current_division = ret[0]['CurrentDivision'] assert isinstance(current_division, int) urlbase = 'v1/%d/' % (current_division,) resource
python
{ "resource": "" }
q272658
Invoices.map_exact2foreign_invoice_numbers
test
def map_exact2foreign_invoice_numbers(self, exact_invoice_numbers=None): """ Optionally supply a list of ExactOnline invoice numbers. Returns a dictionary of ExactOnline invoice numbers to foreign (YourRef) invoice numbers. """ # Quick, select all. Not the most nice to the server though. if exact_invoice_numbers is None: ret = self.filter(select='InvoiceNumber,YourRef') return dict((i['InvoiceNumber'], i['YourRef']) for i in ret) # Slower, select what we want to know. More work for us. exact_to_foreign_map = {} # Do it in batches. If we append 300 InvoiceNumbers at once, we
python
{ "resource": "" }
q272659
solve
test
def solve(grid): """ solve a Sudoku grid inplace """ clauses = sudoku_clauses() for i in range(1, 10): for j in range(1, 10): d = grid[i - 1][j - 1] # For each digit already known, a clause (with one literal). # Note: # We could also remove all variables for the known cells # altogether (which would be more efficient). However, for # the sake of simplicity, we decided not to do that. if d: clauses.append([v(i, j, d)])
python
{ "resource": "" }
q272660
view
test
def view(injector): """Create Django class-based view from injector class.""" handler
python
{ "resource": "" }
q272661
form_view
test
def form_view(injector): """Create Django form processing class-based view from injector class.""" handler = create_handler(FormView, injector)
python
{ "resource": "" }
q272662
method_view
test
def method_view(injector): """Create Flask method based dispatching view from injector class.""" handler = create_handler(MethodView)
python
{ "resource": "" }
q272663
api_view
test
def api_view(injector): """Create DRF class-based API view from injector class.""" handler = create_handler(APIView, injector) apply_http_methods(handler, injector)
python
{ "resource": "" }
q272664
generic_api_view
test
def generic_api_view(injector): """Create DRF generic class-based API view from injector class.""" handler = create_handler(GenericAPIView, injector) apply_http_methods(handler, injector)
python
{ "resource": "" }
q272665
model_view_set
test
def model_view_set(injector): """Create DRF model view set from injector class.""" handler = create_handler(ModelViewSet, injector) apply_api_view_methods(handler, injector)
python
{ "resource": "" }
q272666
stream_from_fd
test
def stream_from_fd(fd, loop): """Recieve a streamer for a given file descriptor.""" reader = asyncio.StreamReader(loop=loop) protocol = asyncio.StreamReaderProtocol(reader, loop=loop) waiter = asyncio.futures.Future(loop=loop)
python
{ "resource": "" }
q272667
UnixFileDescriptorTransport._read_ready
test
def _read_ready(self): """Called by the event loop whenever the fd is ready for reading.""" try: data = os.read(self._fileno, self.max_size) except InterruptedError: # No worries ;) pass except OSError as exc: # Some OS-level problem, crash. self._fatal_error(exc, "Fatal read error on file descriptor read") else: if data: self._protocol.data_received(data) else:
python
{ "resource": "" }
q272668
UnixFileDescriptorTransport._close
test
def _close(self, error=None): """Actual closing code, both from manual close and errors.""" self._closing = True
python
{ "resource": "" }
q272669
UnixFileDescriptorTransport._call_connection_lost
test
def _call_connection_lost(self, error): """Finalize closing.""" try: self._protocol.connection_lost(error)
python
{ "resource": "" }
q272670
Watcher.watch
test
def watch(self, path, flags, *, alias=None): """Add a new watching rule.""" if alias is None: alias = path if alias in self.requests:
python
{ "resource": "" }
q272671
Watcher.unwatch
test
def unwatch(self, alias): """Stop watching a given rule.""" if alias not in self.descriptors: raise ValueError("Unknown watch alias %s; current set is %r" % (alias, list(self.descriptors.keys()))) wd = self.descriptors[alias] errno = LibC.inotify_rm_watch(self._fd, wd) if errno != 0:
python
{ "resource": "" }
q272672
Watcher._setup_watch
test
def _setup_watch(self, alias, path, flags): """Actual rule setup.""" assert alias not in self.descriptors, "Registering alias %s twice!" % alias wd = LibC.inotify_add_watch(self._fd,
python
{ "resource": "" }
q272673
Watcher.setup
test
def setup(self, loop): """Start the watcher, registering new watches if any.""" self._loop = loop self._fd = LibC.inotify_init() for alias, (path, flags)
python
{ "resource": "" }
q272674
Watcher.get_event
test
def get_event(self): """Fetch an event. This coroutine will swallow events for removed watches. """ while True: prefix = yield from self._stream.readexactly(PREFIX.size) if prefix == b'': # We got closed, return None. return wd, flags, cookie, length = PREFIX.unpack(prefix) path = yield from self._stream.readexactly(length) # All async performed, time to look at the event's content. if wd not in self.aliases:
python
{ "resource": "" }
q272675
Message.touch
test
def touch(self): """ Respond to ``nsqd`` that you need more time to process the message. """
python
{ "resource": "" }
q272676
BackoffTimer.success
test
def success(self): """Update the timer to reflect a successfull call""" if self.interval == 0.0: return self.short_interval -= self.short_unit self.long_interval -= self.long_unit
python
{ "resource": "" }
q272677
BackoffTimer.failure
test
def failure(self): """Update the timer to reflect a failed call""" self.short_interval += self.short_unit self.long_interval += self.long_unit
python
{ "resource": "" }
q272678
Reader.close
test
def close(self): """ Closes all connections stops all periodic callbacks """ for conn in self.conns.values(): conn.close()
python
{ "resource": "" }
q272679
Reader.is_starved
test
def is_starved(self): """ Used to identify when buffered messages should be processed and responded to. When max_in_flight > 1 and you're batching messages together to perform work is isn't possible to just compare the len of your list of buffered messages against your configured max_in_flight (because max_in_flight may not be evenly divisible by the number of producers you're connected to, ie. you might never get that many messages... it's a *max*). Example:: def message_handler(self, nsq_msg, reader): # buffer messages
python
{ "resource": "" }
q272680
Reader.connect_to_nsqd
test
def connect_to_nsqd(self, host, port): """ Adds a connection to ``nsqd`` at the specified address. :param host: the address to connect to :param port: the port to connect to """ assert isinstance(host, string_types) assert isinstance(port, int) conn = AsyncConn(host, port, **self.conn_kwargs) conn.on('identify', self._on_connection_identify) conn.on('identify_response', self._on_connection_identify_response) conn.on('auth', self._on_connection_auth) conn.on('auth_response', self._on_connection_auth_response) conn.on('error', self._on_connection_error) conn.on('close', self._on_connection_close) conn.on('ready', self._on_connection_ready) conn.on('message', self._on_message) conn.on('heartbeat', self._on_heartbeat) conn.on('backoff', functools.partial(self._on_backoff_resume, success=False)) conn.on('resume', functools.partial(self._on_backoff_resume, success=True)) conn.on('continue', functools.partial(self._on_backoff_resume, success=None))
python
{ "resource": "" }
q272681
Reader.query_lookupd
test
def query_lookupd(self): """ Trigger a query of the configured ``nsq_lookupd_http_addresses``. """ endpoint = self.lookupd_http_addresses[self.lookupd_query_index] self.lookupd_query_index = (self.lookupd_query_index + 1) % len(self.lookupd_http_addresses) # urlsplit() is faulty if scheme not present if '://' not in endpoint: endpoint = 'http://' + endpoint scheme, netloc, path, query, fragment = urlparse.urlsplit(endpoint) if not path or path == "/": path = "/lookup" params = parse_qs(query) params['topic'] = self.topic query = urlencode(_utf8_params(params), doseq=1)
python
{ "resource": "" }
q272682
Reader.set_max_in_flight
test
def set_max_in_flight(self, max_in_flight): """Dynamically adjust the reader max_in_flight. Set to 0 to immediately disable a Reader""" assert isinstance(max_in_flight, int) self.max_in_flight = max_in_flight if max_in_flight == 0: # set RDY 0 to all connections for conn in itervalues(self.conns): if conn.rdy > 0:
python
{ "resource": "" }
q272683
Reader.giving_up
test
def giving_up(self, message): """ Called when a message has been received where ``msg.attempts > max_tries`` This is useful to subclass and override to perform a task (such as writing to disk, etc.) :param message: the :class:`nsq.Message` received """
python
{ "resource": "" }
q272684
EventedMixin.on
test
def on(self, name, callback): """ Listen for the named event with the specified callback. :param name: the name of the event :type name: string :param callback: the callback to execute when the event is triggered :type callback: callable """
python
{ "resource": "" }
q272685
EventedMixin.off
test
def off(self, name, callback): """ Stop listening for the named event via the specified callback. :param name: the name of the event :type name: string :param callback: the callback that was originally used :type callback: callable
python
{ "resource": "" }
q272686
EventedMixin.trigger
test
def trigger(self, name, *args, **kwargs): """ Execute the callbacks for the listeners on the specified event with the supplied arguments.
python
{ "resource": "" }
q272687
Writer.pub
test
def pub(self, topic, msg, callback=None): """ publish a message to nsq :param topic: nsq topic :param msg: message body (bytes) :param callback:
python
{ "resource": "" }
q272688
Learner.set_feature_transform
test
def set_feature_transform(self, mode='polynomial', degree=1): ''' Transform data feature to high level ''' if self.status != 'load_train_data': print("Please load train data first.") return self.train_X self.feature_transform_mode = mode self.feature_transform_degree = degree self.train_X = self.train_X[:,
python
{ "resource": "" }
q272689
Learner.prediction
test
def prediction(self, input_data='', mode='test_data'): ''' Make prediction input test data output the prediction ''' prediction = {} if (self.status != 'train'): print("Please load train data and init W then train the W first.") return prediction if (input_data == ''): print("Please input test data for prediction.") return prediction if mode == 'future_data': data = input_data.split() input_data_x = [float(v) for v in data] input_data_x = utility.DatasetLoader.feature_transform( np.array(input_data_x).reshape(1, -1), self.feature_transform_mode, self.feature_transform_degree ) input_data_x = np.ravel(input_data_x) prediction = self.score_function(input_data_x, self.W) return {"input_data_x": input_data_x, "input_data_y": None, "prediction": prediction} else: data = input_data.split()
python
{ "resource": "" }
q272690
LogisticRegression.theta
test
def theta(self, s): ''' Theta sigmoid function '''
python
{ "resource": "" }
q272691
parse_log
test
def parse_log(log_file): """Retrieves some statistics from a single Trimmomatic log file. This function parses Trimmomatic's log file and stores some trimming statistics in an :py:class:`OrderedDict` object. This object contains the following keys: - ``clean_len``: Total length after trimming. - ``total_trim``: Total trimmed base pairs. - ``total_trim_perc``: Total trimmed base pairs in percentage. - ``5trim``: Total base pairs trimmed at 5' end. - ``3trim``: Total base pairs trimmed at 3' end. Parameters ---------- log_file : str Path to trimmomatic log file. Returns ------- x : :py:class:`OrderedDict` Object storing the trimming statistics. """ template = OrderedDict([ # Total length after trimming ("clean_len", 0), # Total trimmed base pairs ("total_trim", 0), # Total trimmed base pairs in percentage ("total_trim_perc", 0), # Total trimmed at 5' end ("5trim", 0), # Total trimmed at 3' end ("3trim", 0), # Bad reads (completely trimmed) ("bad_reads", 0) ]) with open(log_file) as fh:
python
{ "resource": "" }
q272692
clean_up
test
def clean_up(fastq_pairs, clear): """Cleans the working directory of unwanted temporary files""" # Find unpaired fastq files unpaired_fastq = [f for f in os.listdir(".") if f.endswith("_U.fastq.gz")] # Remove unpaired fastq files, if any for fpath in unpaired_fastq: os.remove(fpath)
python
{ "resource": "" }
q272693
merge_default_adapters
test
def merge_default_adapters(): """Merges the default adapters file in the trimmomatic adapters directory Returns ------- str Path with the merged adapters file. """ default_adapters = [os.path.join(ADAPTERS_PATH, x) for x in os.listdir(ADAPTERS_PATH)] filepath = os.path.join(os.getcwd(),
python
{ "resource": "" }
q272694
main
test
def main(sample_id, fastq_pair, trim_range, trim_opts, phred, adapters_file, clear): """ Main executor of the trimmomatic template. Parameters ---------- sample_id : str Sample Identification string. fastq_pair : list Two element list containing the paired FastQ files. trim_range : list Two element list containing the trimming range. trim_opts : list Four element list containing several trimmomatic options: [*SLIDINGWINDOW*; *LEADING*; *TRAILING*; *MINLEN*] phred : int Guessed phred score for the sample. The phred score is a generated output from :py:class:`templates.integrity_coverage`. adapters_file : str Path to adapters file. If not provided, or the path is not available, it will use the default adapters from Trimmomatic will be used clear : str Can be either 'true' or 'false'. If 'true', the input fastq files will be removed at the end of the run, IF they are in the working directory """ logger.info("Starting trimmomatic") # Create base CLI cli = [ "java", "-Xmx{}".format("$task.memory"[:-1].lower().replace(" ", "")), "-jar", TRIM_PATH.strip(), "PE", "-threads", "$task.cpus" ] # If the phred encoding was detected, provide it try: # Check if the provided PHRED can be converted to int phred = int(phred) phred_flag = "-phred{}".format(str(phred)) cli += [phred_flag] # Could not detect phred encoding. Do not add explicit encoding to # trimmomatic and let it guess except ValueError: pass # Add input samples to CLI cli += fastq_pair # Add output file names output_names = [] for i in range(len(fastq_pair)): output_names.append("{}_{}_trim.fastq.gz".format( SAMPLE_ID, str(i + 1))) output_names.append("{}_{}_U.fastq.gz".format( SAMPLE_ID, str(i + 1))) cli += output_names if trim_range != ["None"]: cli += [ "CROP:{}".format(trim_range[1]), "HEADCROP:{}".format(trim_range[0]), ] if os.path.exists(adapters_file): logger.debug("Using the provided adapters file '{}'".format( adapters_file)) else: logger.debug("Adapters file '{}' not provided or does not exist. Using" " default adapters".format(adapters_file)) adapters_file = merge_default_adapters() cli += [ "ILLUMINACLIP:{}:3:30:10:6:true".format(adapters_file) ] #create log file im temporary dir to avoid issues when running on a docker container in macOS logfile = os.path.join(tempfile.mkdtemp(prefix='tmp'), "{}_trimlog.txt".format(sample_id)) # Add trimmomatic options
python
{ "resource": "" }
q272695
depth_file_reader
test
def depth_file_reader(depth_file): """ Function that parse samtools depth file and creates 3 dictionaries that will be useful to make the outputs of this script, both the tabular file and the json file that may be imported by pATLAS Parameters ---------- depth_file: textIO the path to depth file for each sample Returns ------- depth_dic_coverage: dict dictionary with the coverage per position for each plasmid """ # dict to store the mean coverage for each reference depth_dic_coverage = {} for line in depth_file: tab_split = line.split() # split by any white space reference = "_".join(tab_split[0].strip().split("_")[0:3]) # store # only the gi for the reference
python
{ "resource": "" }
q272696
main
test
def main(depth_file, json_dict, cutoff, sample_id): """ Function that handles the inputs required to parse depth files from bowtie and dumps a dict to a json file that can be imported into pATLAS. Parameters ---------- depth_file: str the path to depth file for each sample json_dict: str the file that contains the dictionary with keys and values for accessions and their respective lengths cutoff: str the cutoff used to trim the unwanted matches for the minimum coverage results from mapping. This value may range between 0 and 1. sample_id: str the id of the sample being parsed """ # check for the appropriate value for the cutoff value for coverage results logger.debug("Cutoff value: {}. Type: {}".format(cutoff, type(cutoff))) try: cutoff_val = float(cutoff) if cutoff_val < 0.4: logger.warning("This cutoff value will generate a high volume of " "plot data. Therefore '.report.json' can be too big") except ValueError: logger.error("Cutoff value should be a string such as: '0.6'. " "The outputted value: {}. Make sure to provide an " "appropriate value for --cov_cutoff".format(cutoff)) sys.exit(1) # loads dict from file, this file is provided in docker image plasmid_length = json.load(open(json_dict)) if plasmid_length: logger.info("Loaded dictionary of plasmid lengths") else: logger.error("Something went wrong and plasmid lengths dictionary" "could not be loaded. Check if process received this" "param successfully.") sys.exit(1) # read depth file depth_file_in = open(depth_file) # first reads the depth file and generates dictionaries to handle the input # to a simpler format logger.info("Reading depth file and creating dictionary to dump.") depth_dic_coverage = depth_file_reader(depth_file_in) percentage_bases_covered, dict_cov = generate_jsons(depth_dic_coverage, plasmid_length, cutoff_val) if percentage_bases_covered and dict_cov:
python
{ "resource": "" }
q272697
Process._set_template
test
def _set_template(self, template): """Sets the path to the appropriate jinja template file When a Process instance is initialized, this method will fetch the location of the appropriate template file, based on the ``template`` argument. It will raise an exception is the template file is not found. Otherwise, it will set the :py:attr:`Process.template_path` attribute. """ # Set template directory tpl_dir = join(dirname(abspath(__file__)), "templates") # Set template file path
python
{ "resource": "" }
q272698
Process.set_main_channel_names
test
def set_main_channel_names(self, input_suffix, output_suffix, lane): """Sets the main channel names based on the provide input and output channel suffixes. This is performed when connecting processes. Parameters ---------- input_suffix : str Suffix added to the input channel. Should be based on the lane and an arbitrary unique id output_suffix : str Suffix added to the output channel. Should be based on the lane and an
python
{ "resource": "" }
q272699
Process.get_user_channel
test
def get_user_channel(self, input_channel, input_type=None): """Returns the main raw channel for the process Provided with at least a channel name, this method returns the raw channel name and specification (the nextflow string definition) for the process. By default, it will fork from the raw input of the process' :attr:`~Process.input_type` attribute. However, this behaviour can be overridden by providing the ``input_type`` argument. If the specified or inferred input type exists in the :attr:`~Process.RAW_MAPPING` dictionary, the channel info dictionary will be retrieved along with the specified input channel. Otherwise, it will return None. An example of the returned dictionary is:: {"input_channel": "myChannel",
python
{ "resource": "" }