_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | 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'... | 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', filename)
doecode_json = json.load(open(filename))
for record in doecode_json['records']:
yield... | 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!')
re... | 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 server
"""
if filena... | 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 Fac... | 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:
out... | python | {
"resource": ""
} |
q272607 | connect | test | def connect(url, username, password):
"""
Return a connected Bitbucket session
"""
bb_session = stashy.connect(url, username, password)
logger.info('Connected to: %s as %s', url, username)
return bb_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:
gl_session.versi... | 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)
if not repos:
for project in gl_session.projects.list(as_list=False):
... | 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":... | 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/scenario... | 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]
if isinstance(value, dict):
dictionary[key] = _prune... | 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.
... | 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 conta... | 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'
... | 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.
"""
resetTim... | 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'
... | 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... | 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. D... | 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 = BasicAuthentication('', token)
tfs_connection = VssConnection(base_url=url, creds=tfs_credentials)
return tfs_connectio... | 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 attem... | 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_... | 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.GitC... | 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_clien... | 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 = create_tfs_git_client('{url}/{collection_name}'.format(url=url, collection_name=collection.name), token)
logger.debug('Retrieving Git Repos... | 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)
logge... | 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(dateti... | 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 fr... | 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,... | 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 eith... | 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 back... | 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 ... | 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
... | 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... | 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 ... | python | {
"resource": ""
} |
q272636 | LoggingMetrics.timing | test | def timing(self, stat, value, tags=None):
"""Report a timing."""
self._log('timing', stat, value, tags) | python | {
"resource": ""
} |
q272637 | LoggingMetrics.histogram | test | def histogram(self, stat, value, tags=None):
"""Report a histogram."""
self._log('histogram', stat, value, tags) | 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:... | 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... | 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
"""
if value is None:
return value
return self.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
if isinstance(value, self.enum):
return value
return self.enum[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):
return value.name
raise ValueError("Unknown value {value:r} of type {cls}".format(
... | 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):
... | 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 i... | python | {
"resource": ""
} |
q272645 | Histogram.mean | test | def mean(self):
"""Returns the mean value."""
if self.counter.value > 0:
return self.sum.value / self.counter.value
return 0.0 | 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 of event to record
"""
self.counter += value
self.m1_rate.update(value)
self.m5_rate.update(value)
self.m15_rate.update(value) | 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
else:
elapsed = time() - self.start_time
return self.counter.value / elapsed | python | {
"resource": ""
} |
q272648 | Derive.mark | test | def mark(self, value=1):
"""Record an event with the derive.
:param value: counter value to record
"""
last = self.last.get_and_set(value)
if last <= value:
value = value - last
super(Derive, self).mark(value) | 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'],
... | 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 [
self.format_metric_string(m_name, getattr(metric, key), m_type)
for key in keys
] | 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.
template = '{name}:{value}|{m_type}\n'
if self.prefix:... | 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
# has reached the threshold for sending.
if self.bat... | 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:
raise ValueError(
'Expected valid UTF8 for JSON data, got %r' % (data,))
... | 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:
ret = self.get(section, option)
except MissingSetting:
self.set(section, option, value)
ret = v... | 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>',
... | 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(curr... | 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 t... | 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... | python | {
"resource": ""
} |
q272660 | view | test | def view(injector):
"""Create Django class-based view from injector class."""
handler = create_handler(View, injector)
apply_http_methods(handler, injector)
return injector.let(as_view=handler.as_view) | 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)
apply_form_methods(handler, injector)
return injector.let(as_view=handler.as_view) | python | {
"resource": ""
} |
q272662 | method_view | test | def method_view(injector):
"""Create Flask method based dispatching view from injector class."""
handler = create_handler(MethodView)
apply_http_methods(handler, injector)
return injector.let(as_view=handler.as_view) | 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)
apply_api_view_methods(handler, injector)
return injector.let(as_view=handler.as_view) | 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)
apply_api_view_methods(handler, injector)
apply_generic_api_view_methods(handler, injector)
return 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)
apply_generic_api_view_methods(handler, injector)
apply_model_view_set_methods(handler, injector)
return injector.let(as_... | 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)
transport = UnixFileDescriptorTransport(
loop=loop,
file... | 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, cras... | python | {
"resource": ""
} |
q272668 | UnixFileDescriptorTransport._close | test | def _close(self, error=None):
"""Actual closing code, both from manual close and errors."""
self._closing = True
self.pause_reading()
self._loop.call_soon(self._call_connection_lost, error) | python | {
"resource": ""
} |
q272669 | UnixFileDescriptorTransport._call_connection_lost | test | def _call_connection_lost(self, error):
"""Finalize closing."""
try:
self._protocol.connection_lost(error)
finally:
os.close(self._fileno)
self._fileno = None
self._protocol = None
self._loop = None | 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:
raise ValueError("A watch request is already scheduled for alias %s" % alias)
self.requests[alias] = (path, flags)
if self... | 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)
... | 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, path, flags)
if wd < 0:
raise IOError("Error setting up watch on %s with flags %s: wd=%s" % (... | 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) in self.requests.items():
self._setup_watch(alias, path, flags)
# We pass ownership of the fd to the transport; ... | 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
... | python | {
"resource": ""
} |
q272675 | Message.touch | test | def touch(self):
"""
Respond to ``nsqd`` that you need more time to process the message.
"""
assert not self._has_responded
self.trigger(event.TOUCH, message=self) | 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
self.short_interval = max(self.short_interval, Decimal(0))
self.long_interval = ... | 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
self.short_interval = min(self.short_interval, self.max_short_timer)
self.long_interval = min(self.long_interval, self.max_long_timer)
... | python | {
"resource": ""
} |
q272678 | Reader.close | test | def close(self):
"""
Closes all connections stops all periodic callbacks
"""
for conn in self.conns.values():
conn.close()
self.redist_periodic.stop()
if self.query_periodic is not None:
self.query_periodic.stop() | 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 configure... | 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 = As... | 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() i... | 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
... | 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
"""
logger.warning('[... | 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
"""
assert calla... | 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
"""
if callback not in... | 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.
All extra arguments are passed through to each callback.
:param name: the name of the event
:type name: string
"""
f... | 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: function which takes (conn, data) (data may be nsq.Error)
"""
self._pub('pub', topic, msg, callback=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.fe... | 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 p... | python | {
"resource": ""
} |
q272690 | LogisticRegression.theta | test | def theta(self, s):
'''
Theta sigmoid function
'''
s = np.where(s < -709, -709, s)
return 1 / (1 + np.exp((-1) * s)) | 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.... | 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:
o... | 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)]
filepat... | 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.
... | 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 ... | 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_dic... | 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
... | 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... | 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 t... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.