seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _optimize_ir(ctx, src):
"""Optimizes an IR file.
The macro creates an action in the context that optimizes an IR file.
Args:
ctx: The current rule's context object.
src: The source file.
Returns:
A File referencing the optimized IR file.
"""
entry = ctx.attr.entry
ar... | bigcode/self-oss-instruct-sc2-concepts |
def AUlight(exclude=()):
"""Return AU standard colors (light).
Available colors: 'blue', 'purple', 'cyan', 'turquoise', 'green', 'yellow', 'orange', 'red', 'magenta', and 'gray'.
Keyword arguments:
exclude -- tuple of strings (default empty)
"""
AU_colors = {'blue' :( 0, 61,115),
... | bigcode/self-oss-instruct-sc2-concepts |
def closest_power_2(x):
""" Returns the closest power of 2 that is less than x
>>> closest_power_2(6)
4
>>> closest_power_2(32)
16
>>> closest_power_2(87)
64
>>> closest_power_2(4095)
2048
>>> closest_power_2(524290)
524288
"""
n=1
while 2**n <x:
n = n+1
... | bigcode/self-oss-instruct-sc2-concepts |
def stateful_flags(rep_restart_wait=None, quorum_loss_wait=None,
standby_replica_keep=None):
"""Calculate an integer representation of flag arguments for stateful
services"""
flag_sum = 0
if rep_restart_wait is not None:
flag_sum += 1
if quorum_loss_wait is not None:
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_bool(probability=0.5):
"""Returns True with given probability
Args:
probability: probability to return True
"""
assert (0 <= probability <= 1), "probability needs to be >= 0 and <= 1"
return random.random() < probability | bigcode/self-oss-instruct-sc2-concepts |
def seperate_messsage_person(message_with_person):
"""
Seperates the person from the message and returns both
"""
# Split by the first colon
split_colon = message_with_person.split(":")
# Get the person out of it and avoid the first whitespace
person = split_colon.pop(0)[1:]
# Stitch the... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
from dateutil import tz
def _epoch_to_datetime(epoch_seconds):
"""
Converts a UTC UNIX epoch timestamp to a Python DateTime object
Args:
epoch_seconds: A UNIX epoch value
Returns:
DateTime: A Python DateTime representation of the epoch value
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def list_arg(raw_value):
"""argparse type for a list of strings"""
return str(raw_value).split(",") | bigcode/self-oss-instruct-sc2-concepts |
def _get_nodes_without_in_edges(graph):
"""Get all nodes in directed graph *graph* that don't have incoming edges.
The graph is represented by a dict mapping nodes to incoming edges.
Example:
>>> graph = {'a': [], 'b': ['a'], 'c': ['a'], 'd': ['b']}
>>> _get_nodes_without_in_edges(graph)
({'a... | bigcode/self-oss-instruct-sc2-concepts |
import re
def sentences(s):
"""Convert a string of text to a list of cleaned sentences."""
result = []
for sentence in s.split('.'):
sentence = re.sub(r"[^A-Za-z0-9 ']", " ", sentence)
sentence = re.sub(r"[ ]+", " ", sentence).strip()
result.append(sentence)
return result | bigcode/self-oss-instruct-sc2-concepts |
def generate_pents(limit):
"""Generates pentagonal numbers up to limit"""
n = 1
pents = []
while n*(3*n - 1)/2 < limit:
pents.append((n*(3*n - 1)//2))
n += 1
return pents | bigcode/self-oss-instruct-sc2-concepts |
def _is_plain_value(dict_):
"""Return True if dict is plain JSON-LD value, False otherwise."""
return len(dict_) == 1 and '@value' in dict_ | bigcode/self-oss-instruct-sc2-concepts |
def normalize_boolean(value):
""" Normalize a boolean value to a bool(). """
if isinstance(value, bool):
return value
if isinstance(value, str):
if value.lower().strip() == "true":
return True
if value.lower().strip() == "false":
return False
raise ValueEr... | bigcode/self-oss-instruct-sc2-concepts |
def full_rgiid(rgiid, region_id):
"""
return the full rgiid from region and rgi_id
"""
full_id = f"RGI60-{region_id}.{rgiid}"
return full_id | bigcode/self-oss-instruct-sc2-concepts |
def get_snx_host_ioc_context(indicator, ioc_type, threat_data):
"""
Make the dictionary for SlashNext IoC contexts for hosts
:param indicator: IoC value
:param ioc_type: IoC type
:param threat_data: Threat data by SlashNext OTI cloud
:return: SlashNext IoC context dictionary
"""
snx_ioc_... | bigcode/self-oss-instruct-sc2-concepts |
def navigate_diagnosis(driver):
""" Searches for submit button """
return driver.find_element_by_css_selector("input[type='submit']") | bigcode/self-oss-instruct-sc2-concepts |
def get_vehicle_attrs_url(props):
""" Returns vehicle properties from dict as URL params for Routino """
param = '{key}={val};'
return ''.join([param.format(key=k, val=v) for k, v in props.items()]) | bigcode/self-oss-instruct-sc2-concepts |
def S_IFMT(mode):
"""Return the portion of the file's mode that describes the
file type.
"""
return mode & 0o170000 | bigcode/self-oss-instruct-sc2-concepts |
def get_cls_import_path(cls):
"""Return the import path of a given class"""
module = cls.__module__
if module is None or module == str.__module__:
return cls.__name__
return module + '.' + cls.__name__ | bigcode/self-oss-instruct-sc2-concepts |
def notas(*n, situacao=False):
"""
==> função para analisar a nota e situação de vários alunos.
:param n: valores para analisar a situação (aceita vários números)
:param situacao: analisa a situação como ruim, razoável ou boa,
:return: retorna um dicionário com as informações.
"""
dic = dict... | bigcode/self-oss-instruct-sc2-concepts |
import bisect
def clip_around_detections_instant(detections, time):
"""Return the narrowest sublist of detections (a list of Detections)
containing time. If there is a detection at exactly time, try to
expand in either direction.
"""
times = [d.timestamp for d in detections]
lo = max(bisect.... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_interval(timeout_int):
"""Calculates interval based on timeout.
Some customers require long timeouts and polling every 0.1s results
very longs logs. Poll less often if timeout is large.
"""
if timeout_int > 60:
interval = 3
elif timeout_int > 10:
interval = 1
e... | bigcode/self-oss-instruct-sc2-concepts |
def get_attribute(s, ob):
"""
Break apart a string `s` and recursively fetch attributes from object `ob`.
"""
spart = s.partition('.')
f = ob
for part in spart:
if part == '.':
continue
f = f.__getattribute__(part)
return f | bigcode/self-oss-instruct-sc2-concepts |
def desi_proc_command(prow, queue=None):
"""
Wrapper script that takes a processing table row (or dictionary with NIGHT, EXPID, OBSTYPE, JOBDESC, PROCCAMWORD defined)
and determines the proper command line call to process the data defined by the input row/dict.
Args:
prow, Table.Row or dict. Mu... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_string(strlen):
"""Our little helper function for creating a random string
"""
return ''.join([
random.choice('ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789') #Note no O (letter 'OH')
for _ in range(strlen)
]) | bigcode/self-oss-instruct-sc2-concepts |
def get_gdeploy_cmd(gdeploy_file):
"""
Return process args list for gdeploy run.
"""
gdeploy_command = [
'gdeploy',
'-c',
gdeploy_file
]
return gdeploy_command | bigcode/self-oss-instruct-sc2-concepts |
def get_review_status(context):
"""Gets the review status of an award"""
FSJ_user = context['FSJ_user']
award = context['award']
return award.get_review_status(FSJ_user) | bigcode/self-oss-instruct-sc2-concepts |
def sign (x):
"""Returns the sign of `x` as `-1`, `0`, or `+1`."""
return 0 if x == 0 else +1 if x > 0 else -1 | bigcode/self-oss-instruct-sc2-concepts |
def number_of_lines(filename=""):
"""Returns the number of lines of a text file.
Keyword Arguments:
filename {str} -- file name (default: {""})
Returns:
Int -- number of lines of a text file.
"""
with open(filename, mode="r", encoding="utf-8") as file:
return len(file.readl... | bigcode/self-oss-instruct-sc2-concepts |
def build_data(_data, kwds):
"""
Returns property data dict, regardless of how it was entered.
:param _data: Optional property data dict.
:type _data: dict
:param kwds: Optional property data keyword pairs.
:type kwds: dict
:rtype: dict
"""
# Doing this rather than defaulting th... | bigcode/self-oss-instruct-sc2-concepts |
def GetXMLTreeRoot(tree):
"""Get the root node of an xml tree."""
root = tree.getroot()
return root | bigcode/self-oss-instruct-sc2-concepts |
def all_files_fixture(
bad_link, link_dir, link_txt_file, tmp_path, txt_file, jpeg_file, zip_file
):
"""Return a dict of different fixture file cases."""
return {
"bad_link": bad_link,
"link_dir": link_dir,
"link_txt_file": link_txt_file,
"tmp_path": tmp_path,
"txt_fi... | bigcode/self-oss-instruct-sc2-concepts |
def append_unless(unless, base, appendable):
"""
Conditionally append one object to another. Currently the intended usage is for strings.
:param unless: a value of base for which should not append (and return as is)
:param base: the base value to which append
:param appendable: the value to append t... | bigcode/self-oss-instruct-sc2-concepts |
import typing
def override_parameter_in_conf(configuration: typing.Dict, override_parameter: typing.Optional[typing.Dict]):
"""
Given a configuration dict (mapping from hyperparameter name to value), it will override the values using an
override dict (mapping from hyperparameter name to new value)
"""... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
import logging
def get_module_logger(sublogger:str=""):
""" Return a logger class for the calling module.
Add a 'sublogger' string to differentiate multiple loggers in a module.
"""
caller = inspect.getmodulename(inspect.stack()[2][1])
if caller is None:
caller = __name__
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def dict_partition(d, keyfunc, dict=OrderedDict):
"""
Partition a dictionary.
Args:
d (dict): the dictionary to operate on.
keyfunc (function): the function to partition with. It must accept the
dictionary key and value as arguments, and should r... | bigcode/self-oss-instruct-sc2-concepts |
def prompt_propositions(proposals, message_add="", integer=False):
""" Asks the user to choose from among the proposals.
The propositions must be in the form of a dictionary keys, options.
The user is asked to enter the key of the desired proposal.
If the answer is not in the dictionary keys of proposa... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def label_correcting(graph, start, target, Queue=None):
"""
Find the shortest path in graph from start to target.
Parameters
----------
graph : object
start : object
Node in the graph.
target : object
Node in the graph.
Queue : class
Datastructur... | bigcode/self-oss-instruct-sc2-concepts |
def parse_counts_line(line):
"""
Parses the counts line of a molecule and returns it asd a dictionary
aaabbblllfffcccsssxxxrrrpppiiimmmvvvvvv
aaa = number of atoms (current max 255)*
bbb = number of bonds (current max 255)*
lll = number of atom lists (max 30)*
fff = (obsolete)
ccc = ... | bigcode/self-oss-instruct-sc2-concepts |
def trans_matrix(M):
"""Take the transpose of a matrix."""
n = len(M)
return [[ M[i][j] for i in range(n)] for j in range(n)] | bigcode/self-oss-instruct-sc2-concepts |
import re
def decontract(phrase):
"""
Substitutes occurrences in the text like
n't to not
're to are
'll to will
eg.
haven't -> have not
must've -> must have
:type phrase : string
:returns phrase : decontracted phrase
"""
phrase = re.sub(r"won't", "wil... | bigcode/self-oss-instruct-sc2-concepts |
def typename(type):
"""
Get the name of `type`.
Parameters
----------
type : Union[Type, Tuple[Type]]
Returns
-------
str
The name of `type` or a tuple of the names of the types in `type`.
Examples
--------
>>> typename(int)
'int'
>>> typename((int, float))... | bigcode/self-oss-instruct-sc2-concepts |
def atom_count(data, **params):
"""
Calculate number of occurrencies of a given atomic element in the data.
Args:
data (list): values.
params (kwargs):
atom: element for which occurencies are counted.
Returns the number of occurencies of the atom in the data.
"""
ato... | bigcode/self-oss-instruct-sc2-concepts |
def _rindex(seq, element):
"""Like list.index, but gives the index of the *last* occurrence."""
seq = list(reversed(seq))
reversed_index = seq.index(element)
return len(seq) - 1 - reversed_index | bigcode/self-oss-instruct-sc2-concepts |
import re
import keyword
def _make_valid_attribute_name(s):
"""Return a string that is a valid Python attribute name.
Leading digits are prefixed with underscores, non-alpha numeric characters
are replaced with underscores, and keywords are appended with an underscore.
This function ensures the strin... | bigcode/self-oss-instruct-sc2-concepts |
def parse_resolution(resolution_string):
"""
Parse and raise ValueError in case of wrong format
@param resolution_string string representing a resolution, like "128x128"
@return resolution as a tuple of integers
"""
tokens = resolution_string.split('x')
if len(tokens) != 2:
raise Val... | bigcode/self-oss-instruct-sc2-concepts |
def get_previous_season(season):
"""
Convert string e.g. '1819' into one for previous season, i.e. '1718'
"""
start_year = int(season[:2])
end_year = int(season[2:])
prev_start_year = start_year - 1
prev_end_year = end_year - 1
prev_season = "{}{}".format(prev_start_year, prev_end_year)
... | bigcode/self-oss-instruct-sc2-concepts |
def test_equalto(value, other):
"""Test to see if two values are the same."""
return value == other | bigcode/self-oss-instruct-sc2-concepts |
import bisect
def _find_closest(sorted_values,
value,
before=False):
"""
Convenience function for finding the list index of the first (leftmost) value greater than x in list sorted_values.
:param sorted_values:
:param value:
:param before: if True then re... | bigcode/self-oss-instruct-sc2-concepts |
def get_indentation(line):
"""Returns the indentation (number of spaces and tabs at the begining) of a given line"""
i = 0
while (i < len(line) and (line[i] == ' ' or line[i] == '\t')):
i += 1
return i | bigcode/self-oss-instruct-sc2-concepts |
def merge_diffs(d1, d2):
"""
Merge diffs `d1` and `d2`, returning a new diff which is
equivalent to applying both diffs in sequence. Do not modify `d1`
or `d2`.
"""
if not isinstance(d1, dict) or not isinstance(d2, dict):
return d2
diff = d1.copy()
for key, val in d2.items():
... | bigcode/self-oss-instruct-sc2-concepts |
def subsample_image(input_image, zoom_box_coords):
"""
Crops the input image to the coordinates described in the
'zoom_box_coords' argument.
Args:
input_image (numpy.array): The input image.
zoom_box_coords (tuple, list): Coordinates corresponding to the first
(low-resolution)... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_auth(url: str, login: str, password: str) -> tuple:
"""
Function get authentication token and user ID from Rocket.Chat.
:param url: Rocket.Chat API login URL
:type: str
:param login: Rocket.Chat user login
:type: str
:param password: Rocket.Chat user password
:... | bigcode/self-oss-instruct-sc2-concepts |
def split(list_to_split, amount_of_parts):
"""Split a list into equal parts
Args:
list_to_split: Any list
amount_of_parts: Number of equally sized parts
Returns:
splitted list as list of lists
"""
k, m = divmod(len(list_to_split), amount_of_parts)
return (list_to_split... | bigcode/self-oss-instruct-sc2-concepts |
def input_profile(t, x0):
"""
calculate the user input x as a function of time
x0 is the initial value
ramp down from 100% to 50% load at 5%/min rate
hold for half an hour
ramp up from 50% to 100% load at 5%/min rate
hold for 20 minutes
"""
if t < 60:
x = x0
elif t < 660:... | bigcode/self-oss-instruct-sc2-concepts |
def corr_shift(x, y, x_shift=0, y_shift=0):
"""compute the correlation with shift
Args:
x (series): first series
y (series): second series
x_shift (int, optional): shift of first series. Defaults to 0.
y_shift (int, optional): shift of second series. Defaults to 0.
Returns:... | bigcode/self-oss-instruct-sc2-concepts |
def GetOperationError(error):
"""Returns a human readable string representation from the operation.
Args:
error: A string representing the raw json of the operation error.
Returns:
A human readable string representation of the error.
"""
return 'OperationError: code={0}, message={1}'.format(
e... | bigcode/self-oss-instruct-sc2-concepts |
def map_age(age):
"""Map ages to standard buckets."""
try:
age = int(age)
if age >= 90:
return '90+'
lower = (age // 10) * 10
upper = age+9 if age % 10 == 0 else ((age + 9) // 10) * 10 - 1
return f'{lower}-{upper}'
except:
if 'month' in age.lower... | bigcode/self-oss-instruct-sc2-concepts |
def remove_url_trailing_slash(url):
"""
Returns the input url without any trailing / if it had a trailing slash. This is useful for repository url
where https://github.com/lwhjon/repo-labels-cli/ and https://github.com/lwhjon/repo-labels-cli both are equivalent
hence for consistency we remove the traili... | bigcode/self-oss-instruct-sc2-concepts |
def set_intersection(*sets):
"""Return the intersection of all the given sets.
As of Python 2.6 you can write ``set.intersection(*sets)``.
Examples
========
>>> from sympy.core.compatibility import set_intersection
>>> set_intersection(set([1, 2]), set([2, 3]))
set([2])
>>> set_inters... | bigcode/self-oss-instruct-sc2-concepts |
def get_mf6_blockdata(f, blockstr):
"""Return list with all non comments between start and end of block
specified by blockstr.
Parameters
----------
f : file object
open file object
blockstr : str
name of block to search
Returns
-------
data : list
list of d... | bigcode/self-oss-instruct-sc2-concepts |
def filter_genre(genre):
"""
Create filter function for row of pandas df
:param genre: string genre to filter out
:return: Function that returns True if genre is in the row genre string
"""
def wrap(row):
genres = row['genre']
if isinstance(genres, str):
return genre... | bigcode/self-oss-instruct-sc2-concepts |
def GenerateContext(kind, project_id, location, cluster_id):
"""Generates a kubeconfig context for an Anthos Multi-Cloud cluster.
Args:
kind: str, kind of the cluster e.g. aws, azure.
project_id: str, project ID accociated with the cluster.
location: str, Google location of the cluster.
cluster_id:... | bigcode/self-oss-instruct-sc2-concepts |
def fix_ncesid(ncesid, mode):
"""
Applies standard formatting (zero padding and typecasting) to
both schools' and districts' NCES IDs.
Args:
ncesid (int): Target NCES ID to fix (e.g. 100005).
mode (str): Should be either "school" or "district".
Returns:
str: Standardi... | bigcode/self-oss-instruct-sc2-concepts |
def predict(clf, test_data, probabilities=True):
"""
Returns an array of predictions for the given *test_data* using the classifier *clf*.
If *probabilities* is True and the classifier supports it, the predictions will be Preictal probabilites.
Otherwise, the class labels are used.
:param clf: The ... | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def _generate_postcode() -> str:
"""
Generates a postcode string. This is not guaranteed to be valid currently, but will
have the properties of
- One letter
- 1 or 2 numbers
- A space
- A number and 2 letters.
:returns: Postcode string
"""
firs... | bigcode/self-oss-instruct-sc2-concepts |
import json
def _response(**resp):
"""
Return an API Gateway compatible response.
"""
return {'body': json.dumps(resp)} | bigcode/self-oss-instruct-sc2-concepts |
def build_independent_priors(priors):
""" Build priors for Bayesian fitting. Priors should has a (scipy-like) ppf class method."""
def prior_transform(u):
v = u.copy()
for i in range(len(u)):
v[i] = priors[i].ppf(u[i])
return v
return prior_transform | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_valid_recurrence(text):
"""Check that text is a valid recurrence string.
A valid recurrence string is 'DAILY', 'ONCE', 'WEEKDAYS', 'WEEKENDS' or
of the form 'ON_DDDDDD' where D is a number from 0-7 representing a day
of the week (Sunday is 0), e.g. 'ON_034' meaning Sunday, Wednesday... | bigcode/self-oss-instruct-sc2-concepts |
import re
def split_into_attributes(s):
"""Split each purchase into a list of its attributes"""
return re.split(r"\t",s) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
import re
def parse_func_path(path: str) -> Tuple[str, str]:
"""
Parses a function path 'file_or_module::func'.
Parameters
----------
path : str
path should have the format: 'file_or_module::func', where `file_or_module`
is a filename or python module and ... | bigcode/self-oss-instruct-sc2-concepts |
def make_patterns(dirs):
"""Returns a list of git match patterns for the given directories."""
return ['%s/**' % d for d in dirs] | bigcode/self-oss-instruct-sc2-concepts |
def normalize_basename(s, force_lowercase=True, maxlen=255):
"""Replaces some characters from s with a translation table:
trans_table = {" ": "_",
"/": "_slash_",
"\\": "_backslash_",
"?": "_question_",
"%": "_percent_",
... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def opt_int64(buf, byte_order):
"""
Convert to a signed 64-bit integer.
"""
opt_val, = struct.unpack(byte_order+"q", buf)
return opt_val | bigcode/self-oss-instruct-sc2-concepts |
def get_line_offsets(block):
""" Compute the list of offsets in DataBlock 'block' which correspond to
the beginnings of new lines.
Returns: (offset list, count of lines in "current block")
"""
# Note: this implementation based on string.find() benchmarks about twice as
# fast as a list comprehe... | bigcode/self-oss-instruct-sc2-concepts |
def numbertoampm(hour: int, minute: int) -> tuple:
"""
Convert time in hh:mm format to AM/PM.
"""
if hour < 12 or hour == 24:
period = 'AM'
else:
period = 'PM'
hour = hour % 12
if hour == 0:
hour = 12
return (hour, minute, period) | bigcode/self-oss-instruct-sc2-concepts |
def reported_news(file_paths):
"""Check if Misc/NEWS has been changed."""
return True if 'Misc/NEWS' in file_paths else False | bigcode/self-oss-instruct-sc2-concepts |
def heuristic_distances(judgments, repeats):
"""
Returns a numeric value for each distance (i, j) in judgments: d = (a + 1)/ (a + b + 2)
a is number of times a distance is greater than another
:param repeats: number of times each pairwise comparison is repeated
:param judgments: (dict) key: pairs of... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def set_int(bytearray_: bytearray, byte_index: int, _int: int):
"""Set value in bytearray to int
Notes:
An datatype `int` in the PLC consists of two `bytes`.
Args:
bytearray_: buffer to write on.
byte_index: byte index to start writing from.
_int: int value ... | bigcode/self-oss-instruct-sc2-concepts |
def title(s: str) -> str:
"""Capitalize sentence.
``"foo bar" -> "Foo Bar"``
``"foo-bar" -> "Foo Bar"``
"""
return ' '.join(
p.capitalize()
for p in s.replace('-', ' ')
.replace('_', ' ').split()) | bigcode/self-oss-instruct-sc2-concepts |
def train_calc_split(pd_shots, match_id, features, label='is_goal'):
"""
INPUT
pd_shots: (pandas) shots data (all type / on Target)
match_id: statsbomb match_id
features: list of features (column names)
label: label column name
OUTPUT
train_x: shots data
calc_... | bigcode/self-oss-instruct-sc2-concepts |
def get_max_split(splits, keyfunc):
""" Returns the split in a transaction with the largest absolute value
Args:
splits (List[dict]): return value of group_transactions()
keyfunc (func): key function
Returns:
(Tuple[str]): splits collapsed content
Examples:
>>> from op... | bigcode/self-oss-instruct-sc2-concepts |
def breadcrumbs_li(links):
"""Returns HTML: an unordered list of URLs (no surrounding <ul> tags).
``links`` should be a iterable of tuples (URL, text).
"""
crumbs = ""
li_str = '<li><a href="{}">{}</a></li>'
li_str_last = '<li class="active"><span>{}</span></li>'
# Iterate over the list, exc... | bigcode/self-oss-instruct-sc2-concepts |
def heuristicPortMatch(p1, p2):
"""takes two ports and returns 1 if exact match,
0 if partial match, -1 if no match
"""
if p1.db_moduleId == p2.db_moduleId:
return 1
elif p1.db_type == p2.db_type and \
p1.db_moduleName == p2.db_moduleName and \
p1.sig == p2.sig:
... | bigcode/self-oss-instruct-sc2-concepts |
def make_dict(list1, list2):
"""
Makes a dictionary using the provided lists.
Input:
list1 (list): List to be used for keys.
list2 (list): list to be used for values.
Output:
out_dict (dict): Dictionary using the input lists
"""
out_dict = {}
i = 0
for item in list1:
... | bigcode/self-oss-instruct-sc2-concepts |
def partition_fxn(output_string):
""" Reads the parition function from the MESSPF output
:param str output_string: string of lines for MESSPF output file
:return temps: List of temperatures
:rtype: list: float
:return logq: loq(Q) where Q is partition function
:rtype: list: ... | bigcode/self-oss-instruct-sc2-concepts |
def mixin_enabled(plugin, key, *args, **kwargs):
""" Return if the mixin is existant and configured in the plugin """
return plugin.mixin_enabled(key) | bigcode/self-oss-instruct-sc2-concepts |
def check_lammps_sim(out_file, verbose=True):
"""
Check if LAMMPS simulation is finished.
"""
FINISHED = False
try:
with open(out_file, 'r') as f:
lines = f.readlines()
if 'Total wall time' in lines[-1]:
FINISHED = True
except Exception as e:
if ve... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _date_tuple(strdate):
"""_date_tuple(strdate)
Converts a date string of the format "[YY]YY/[M]M/[D]D" into a 3-tuple
of month, day, and year integers.
Positional arguments:
strdate (str) - date string of the format "[YY]YY/[M]M/[D]D"
Returns:
tuple ((int, int, int)... | bigcode/self-oss-instruct-sc2-concepts |
def find_motif_positions(sequence: str, motif: str):
"""
Returns the start and end position(s) of a core motif in a sequence
Args:
sequence: string of nucleotides
motif: string of nucleotides representing a motif
Returns:
startpositions: list of start position(s) of core motif ... | bigcode/self-oss-instruct-sc2-concepts |
def zeta_a(eN,cL,w):
"""
EnKF-N inflation estimation via w.
Returns zeta_a = (N-1)/pre-inflation^2.
Using this inside an iterative minimization as in the iEnKS
effectively blends the distinction between the primal and dual EnKF-N.
"""
N = len(w)
N1 = N-1
za = N1*cL/(eN + w@w)
return za | bigcode/self-oss-instruct-sc2-concepts |
def get_ptf_server_intf_index(tor, tbinfo, iface):
"""Get the index of ptf ToR-facing interface on ptf."""
mg_facts = tor.get_extended_minigraph_facts(tbinfo)
return mg_facts["minigraph_ptf_indices"][iface] | bigcode/self-oss-instruct-sc2-concepts |
def get_unique_locations(db):
"""
Gets an iterator to the unique locations (lat, lon)
:param db: Source database (VedDb)
:return: Iterator to the unique locations
"""
sql = "select distinct latitude, longitude from signal"
locations = db.query_iterator(sql)
return locations | bigcode/self-oss-instruct-sc2-concepts |
def preplace(schema, reverse_lookup, t):
"""
Replaces basic types and enums with default values.
:param schema:
the output of a simplified schema
:param reverse_lookup:
a support hash that goes from typename to graphql type, useful to navigate the schema in O(1)
:param t:
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def snap(x, y, url, resource='/grid/snap'):
"""Determine the chip and tile coordinates for a point.
Args:
x (int): projection coordinate x
y (int): projection coordinate y
url (str): protocol://host:port/path
resource (str): /grid/snap/resource (default: /gri... | bigcode/self-oss-instruct-sc2-concepts |
import ast
def str_rep_to_list(s):
"""
convert a string representation of list to a python list object.
:param s:
:return:
"""
return ast.literal_eval(s) | bigcode/self-oss-instruct-sc2-concepts |
def _split_list_by_function(l, func):
"""For each item in l, if func(l) is truthy, func(l) will be added to l1.
Otherwise, l will be added to l2.
"""
l1 = []
l2 = []
for item in l:
res = func(item)
if res:
l1.append(res)
else:
l2.append(item)
r... | bigcode/self-oss-instruct-sc2-concepts |
def print_time(time):
"""Format a datetime object to be human-readable"""
return time.astimezone(tz=None).strftime('%m/%d') | bigcode/self-oss-instruct-sc2-concepts |
def compute_eer(target_scores, nontarget_scores):
"""Calculate EER following the same way as in Kaldi.
Args:
target_scores (array-like): sequence of scores where the
label is the target class
nontarget_scores (array-like): sequence of scores where the
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def get_module_and_func_names(command: str) -> Tuple[str, str]:
"""
Given a string of module.function, this functions returns the module name and func names.
It also checks to make sure that the string is of expected 'module.func' format
Args:
command (str): String o... | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.