seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _get_raw(platform: str, command: str) -> str:
"""Get raw cli output."""
command = str(command.replace(" ", "_"))
with open(
"tests/" + platform + "_" + command + "/" + platform + "_" + command + ".txt",
"r",
) as structured:
raw = structured.read()
return raw | bigcode/self-oss-instruct-sc2-concepts |
import torch
def angle_axis_to_quaternion(angle_axis: torch.Tensor) -> torch.Tensor:
"""Convert an angle axis to a quaternion.
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
Args:
angle_axis (torch.Tensor): tensor with angle axis.
Return:
torch.Tensor: tensor ... | bigcode/self-oss-instruct-sc2-concepts |
def t_evap(r, phi):
"""Return estimated evaporation time at T=293 K.
- r: radius (m)
- phi: relative humidity
"""
return 3.6e9 * r**2 / (1 - phi) | bigcode/self-oss-instruct-sc2-concepts |
def is_kanji(character):
""" Return if the character is a kanji character """
return 0x4E00 <= ord(character) <= 0x9FBF or character == '々' | bigcode/self-oss-instruct-sc2-concepts |
def get_verbose_name(model, field):
"""
Get Django instance's field's verbose_name.
"""
return model._meta.get_field(field).verbose_name.title() | bigcode/self-oss-instruct-sc2-concepts |
def _has_method(obj, name):
"""
Check if the object has a method with that name
Args:
obj: the object
name: the name of the method
Returns:
True if the object has a callable method with that name, otherwise False
"""
mth = getattr(obj, name, None)
if mth is None:
... | bigcode/self-oss-instruct-sc2-concepts |
def replace(template, pattern, subst) :
"""If pattern in the template replaces it with subst.
Returns str object template with replaced patterns.
"""
fields = template.split(pattern, 1)
if len(fields) > 1 :
return '%s%s%s' % (fields[0], subst, fields[1])
else :
return templa... | bigcode/self-oss-instruct-sc2-concepts |
def _edge_mapping(G):
"""Assigns a variable for each edge in G.
(u, v) and (v, u) map to the same variable.
"""
edge_mapping = {edge: idx for idx, edge in enumerate(G.edges)}
edge_mapping.update({(e1, e0): idx for (e0, e1), idx in edge_mapping.items()})
return edge_mapping | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_format(text: str) -> str:
"""Simple utility to parse json text and format it for printing.
"""
obj = json.loads(text)
return json.dumps(obj, indent=4, sort_keys=True) | bigcode/self-oss-instruct-sc2-concepts |
def get_all_followings(igapi, target_userid):
"""
Returns a list of {"username": "", "userid": 0, "is_private": false, "full_name": ""}
"""
following_list = []
current_followings_list = igapi.getTotalFollowings(target_userid)
for following in current_followings_list:
user = {
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def flag(argument: Any) -> bool:
"""
Check for a valid flag option (no argument) and return :py:obj:`True`.
Used in the ``option_spec`` of directives.
.. seealso::
:class:`docutils.parsers.rst.directives.flag`, which returns :py:obj:`None` instead of :py:obj:`True`.
:raises: :exc:`Va... | bigcode/self-oss-instruct-sc2-concepts |
import math
def _calculate_label_rotation(startx, starty, endx, endy):
"""
Calculates the appropriate rotation angle for a label on an arrow (matches line, is between -90 and 90 degrees)
:param startx: start of arrow (x)
:param starty: start of arrow (y)
:param endx: end of arrow (x)
:param e... | bigcode/self-oss-instruct-sc2-concepts |
def object_info_as_dict(object_info):
"""Convert a KBase object_info list into a dictionary."""
[
_id,
_name,
_type,
_save,
_version,
_owner,
_ws,
_ws_name,
_md5,
_size,
_meta,
] = object_info
return dict(
ob... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_promotion(data_objects, distance_function):
"""
Randomly chooses two objects to be promoted.
"""
data_objects = list(data_objects)
return random.sample(data_objects, 2) | bigcode/self-oss-instruct-sc2-concepts |
def css_rgb(color, a=False):
"""Get a CSS `rgb` or `rgba` string from a `QtGui.QColor`."""
return ("rgba({}, {}, {}, {})" if a else "rgb({}, {}, {})").format(*color.getRgb()) | bigcode/self-oss-instruct-sc2-concepts |
def _calc_basic_subreddit_stats(sr_about):
"""
:param dict sr_about: An unmarshalled sub-Reddit about.json 'data' dict.
:rtype: tuple
:returns: Tuple in the form of: sub_count, accounts_active
"""
sub_count = int(sr_about['subscribers'])
accounts_active = int(sr_about['accounts_active'])
... | bigcode/self-oss-instruct-sc2-concepts |
def read_database(db, query, params):
"""
Execute query with params against the database.
:param db: database connection
:param query: str: query to execute
:param params: [object]: list of parameters to use with query
:return [object] rows returned from query
"""
rows = []
cur = db.... | bigcode/self-oss-instruct-sc2-concepts |
def match_shared(self, shared_length: int, shared_features: int) -> int: # pylint: disable=unused-argument
"""Calculate the size of the task variable to match the shared variable."""
return shared_length * shared_features | bigcode/self-oss-instruct-sc2-concepts |
def length(value):
"""
Find the length of a value
:type value: variable
:param value: The value to find the length of
"""
# Try to return the length
return len(value) | bigcode/self-oss-instruct-sc2-concepts |
def read_template(template_path):
"""Read template file.
Args:
template_path: template file path
Returns:
template file data
"""
with open(template_path, "r") as f:
template_data = f.read()
return template_data | bigcode/self-oss-instruct-sc2-concepts |
import math
def binomial(n, k):
"""Computes the binomial coefficient "n over k".
"""
if k == n:
return 1
if k == 1:
return n
if k > n:
return 0
return math.factorial(n) // (
math.factorial(k) * math.factorial(n - k)
) | bigcode/self-oss-instruct-sc2-concepts |
def export_to_pascal(ibs, *args, **kwargs):
"""Alias for export_to_xml"""
return ibs.export_to_xml(*args, **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
def daily_visit_count(user, count):
"""Returns True if the number of the user daily visit equals to count."""
return user.get_profile().daily_visit_count >= count | bigcode/self-oss-instruct-sc2-concepts |
def _remove_whitespaces_beginning_end_text(text: str) -> str:
"""
Removes whitespace from the beginning and end of the given text.
"""
return text.strip() | bigcode/self-oss-instruct-sc2-concepts |
import math
def is_relative_prime(num, larger_num):
"""Determine if num is a relative prime to larger_num."""
return math.gcd(num, larger_num) == 1 | bigcode/self-oss-instruct-sc2-concepts |
def _user_profile(user_profile):
"""
Returns the user profile object. For now, this just comprises the
profile_image details.
"""
return {
'profile': {
'image': user_profile['profile_image']
}
} | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def FindLatestTime(time_list):
"""Find latest time from |time_list|.
The current status is compared to the status of the latest file in
|RESULT_DIR|.
Args:
time_list: a list of time string in the form of 'Year-Month-Day-Hour'
(e.g., 2011-10-23-23). Strings not in th... | bigcode/self-oss-instruct-sc2-concepts |
def is_proper_component_name(component):
"""Check if the component name is properly formatted."""
return "@" not in component and "/" not in component | bigcode/self-oss-instruct-sc2-concepts |
def is_ssh_for_nimbus(env_config):
"""Check if we need to use SSH access to Nimbus or not."""
return env_config.get("use_ssh_for_nimbus", True) | bigcode/self-oss-instruct-sc2-concepts |
import string
def has_string_formatters(s):
"""
Determine if a string has ``{}`` operators.
Parameters
----------
s : str
The string to analyze.
Returns
-------
bool
``True`` if yes, ``False`` if no.
"""
assert isinstance(s, str), f'`s` of wrong type: {type(s)... | bigcode/self-oss-instruct-sc2-concepts |
def run_model(*params, return_preds=False, integrate=False):
"""
Given a model, loss function and daily death data, along with the parameters, run the model on these parameters.
Arguments
--------------
params : A list of parameters. The last three must be the model function, loss function a... | bigcode/self-oss-instruct-sc2-concepts |
import re
def replace_spaces(some_string):
""" Substitute spaces with underscores"""
return re.sub(" ", "_", some_string) | bigcode/self-oss-instruct-sc2-concepts |
def get_all_constraints(max_domain_val):
"""
Purpose: get all binary constraints of the form xi,xj and put them in
a list. To save space, we just put the row and column indices in the
list.
@param max_domain_val int, The dimensions of each side of the square board
@return constraints list of t... | bigcode/self-oss-instruct-sc2-concepts |
def tier_count(count):
"""
If a tier quota is 9999, treat it as unlimited.
"""
if count == 9999:
return "Unlimited"
else:
return count | bigcode/self-oss-instruct-sc2-concepts |
def get_card_split(df, cols, n=11):
"""
Splits categorical columns into 2 lists based on cardinality (i.e # of unique values)
Parameters
----------
df : Pandas DataFrame
DataFrame from which the cardinality of the columns is calculated.
cols : list-like
Categorical columns to lis... | bigcode/self-oss-instruct-sc2-concepts |
def degrees_to_cardinal(degrees):
"""Convert degrees >= 0 to one of 16 cardinal directions."""
CARDINALS = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
if degrees < 0: return None
i = (degrees + 11.25)/22.5
return CARDINALS[int(i % 16)] | bigcode/self-oss-instruct-sc2-concepts |
def get_401_error_hint(ctx, opts, exc):
"""Get the hint for a 401/Unauthorised error."""
# pylint: disable=unused-argument
if opts.api_key:
return (
'Since you have an API key set, this probably means '
'you don\'t have the permision to perform this action.')
if ctx.info... | bigcode/self-oss-instruct-sc2-concepts |
def model_summary(model):
"""Return a summary of Keras model intance.
Args:
model (Keras model instance): A Keras model instance.
Returns:
str: A summary for the model.
"""
summary = model.summary()
return summary | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sha(data):
"""hashes data
Args:
data (bytes): the data to hash
"""
sha2 = hashlib.sha256()
sha2.update(data)
return sha2.digest() | bigcode/self-oss-instruct-sc2-concepts |
def build_tree(elems, root, currentkey, parentkey):
""" Constructs a hierarchic tree from a flat dictionary.
https://stackoverflow.com/questions/35452512/construct-hierarchy-tree-from-python-flat-parent-children-dict-list
:param elems: flat dictionary
:param root: root node of current recursion
:p... | bigcode/self-oss-instruct-sc2-concepts |
def match_strings(str_in, match_list):
""" Check if any of a list of strings is found in another string.
str_in input string.
match_list list of strings to find in str_in.
returns True if a match is found and False if no match is found.
"""
for match in match_list:
if match i... | bigcode/self-oss-instruct-sc2-concepts |
def parse_destination(phone_number, destinations):
"""Find the matching destination for a phone number.
Args:
phone_number: a string number with no leading '+'
destinations: a list of Destination instances
Returns:
a Destination instance or None if the prefix wasn't found.
"""
# ... | bigcode/self-oss-instruct-sc2-concepts |
def bedl_matches_vcf(variant, line_split: list) -> bool:
""" Consecutive checks of whether the chromosome, start position and repeat unit
in the supplied variant and (split + stripped) bedl line match. If all matches, return True,
otherwise return False
"""
if not line_split[0] == variant.CHROM:
... | bigcode/self-oss-instruct-sc2-concepts |
def add_try_clause(code, excpt):
"""Add a try/except clause, excepting 'excpt' around code."""
code = code.replace('\t', ' ')
return ("try:\n" + '\n'.join([" " + line for line in code.split('\n')])
+ "\nexcept " + excpt.__name__ + ":\n pass") | bigcode/self-oss-instruct-sc2-concepts |
def recursive_binomial_coefficient(n, k):
"""Calculates the binomial coefficient, C(n,k), with n>=k using recursion
Time complexity is O(k), so can calculate fairly quickly for large values of k.
>>> recursive_binomial_coefficient(5,0)
1
>>> recursive_binomial_coefficient(8,2)
28
>>> recu... | bigcode/self-oss-instruct-sc2-concepts |
def check_file(df):
"""Check a file format for correct column names and structure"""
if not all(x in df.columns
for x in ["image_path", "xmin", "xmax", "ymin", "ymax", "label"]):
raise IOError(
"Input file has incorrect column names, the following columns must exist 'image_pa... | bigcode/self-oss-instruct-sc2-concepts |
def sort_by_numnodes(node):
"""
Sort by number of nodes.
"""
return len(node.nodes) | bigcode/self-oss-instruct-sc2-concepts |
def MostSimilar(caseAttrib, queryValue, weight):
"""
Most similar matches using ES default (works for all attribute types). Default similarity for strings and exact match for other types.
"""
# build query string
query = {
"match": {
caseAttrib: {
"query": queryValue,
"boost": weight,
"_name": "... | bigcode/self-oss-instruct-sc2-concepts |
def split_data(dataframe):
""" Split the dataset into features and labels
Parameters
----------
dataframe : the full dataset
Returns
-------
features : the features of the dataset
labels : the attack flag label of the dataset
"""
label = ... | bigcode/self-oss-instruct-sc2-concepts |
def is_instance_or_subclass(val, class_):
"""Return True if ``val`` is either a subclass or instance of ``class_``."""
try:
return issubclass(val, class_)
except TypeError:
return isinstance(val, class_) | bigcode/self-oss-instruct-sc2-concepts |
def require_atlas(f):
"""Decorator that ensures a subject (the first argument) is from the ATLAS
survey.
"""
def g(subject, *args, **kwargs):
if subject['metadata']['survey'] != 'atlas':
raise ValueError('Subject not from ATLAS survey.')
return f(subject, *args, **kwargs)
... | bigcode/self-oss-instruct-sc2-concepts |
def add2(a, b):
"""
Test coverage with docstring
>>> add2(1, 2)
3
"""
return a + b | bigcode/self-oss-instruct-sc2-concepts |
def rl_decode(buf):
"""
Uncompresses the buffer by adding the correct number of 1s identified by the digit after 0
(since 0 indicates a repeated character when the original compression is performed).
"""
decoding = []
for index, char in enumerate(buf):
if char == 0:
for repeats in range(buf[index+1]):... | bigcode/self-oss-instruct-sc2-concepts |
def _make_choices_from_int_list(source_list):
"""
Converts a given list of Integers to tuple choices.
Returns a dictionary containing two keys:
- max_length: the maximum char length for this source list,
- choices: the list of (value, value) tuple choices.
"""
_choices = []
for value in... | bigcode/self-oss-instruct-sc2-concepts |
def readlines_without_newlines(path):
"""
Read file into a list of lines, this exists because open(path).readlines() will preserve trailing newlines
"""
with open(path) as file:
return [line.strip() for line in file] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import json
def _parse_str_list(string: str) -> List[str]:
"""
Parse a list of string from string like "['a', 'b', 'c']" or those separated by \n
:param string: string like "['a', 'b', 'c']" or those separated by \n
:return: a list of string
"""
try:
res = json.... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
import uuid
def get_cache_key_for_site(site_uuid: Union[str, uuid.UUID]):
"""
Get the cache key for a site.
"""
return 'site_config_client.backend.{site_uuid}'.format(
site_uuid=site_uuid,
) | bigcode/self-oss-instruct-sc2-concepts |
def add_node_ids(node):
"""
Adds node IDs to the tree (the recursive Python dict)
in a breadth-first fasion.
Arguments:
node -- the root node for the tree
Returns:
the same tree (Python dict), but with a new key for
each node (the ID)
"""
nodes_to_explore = [node]
counter ... | bigcode/self-oss-instruct-sc2-concepts |
def contains_whitespace(text):
"""
Returns True if there are any whitespace characters in the string
"""
return any(x.isspace() for x in text) | bigcode/self-oss-instruct-sc2-concepts |
def guess_content_type(name):
"""Return the content type by the extension of the filename."""
if name.endswith(".jpg"):
return "image/jpg"
elif name.endswith(".jpeg"):
return "image/jpeg"
elif name.endswith(".png"):
return "image/png"
elif name.endswith(".gif"):
retur... | bigcode/self-oss-instruct-sc2-concepts |
def h1(text):
"""h1 tag
>>> h1('my heading')
'<h1>my heading</h1>'
"""
return '<h1>{}</h1>'.format(text) | bigcode/self-oss-instruct-sc2-concepts |
def find_verb(sent):
"""Pick a candidate verb for the sentence."""
verb = None
for word, part_of_speech in sent.pos_tags:
if part_of_speech.startswith('VB'): # This is a verb
verb = word
break
return verb | bigcode/self-oss-instruct-sc2-concepts |
def deal_with_out_boundary(img):
"""
Deal with the outlier.
:param img: input image.
:return: image without outlier.
"""
img[img > 255.] = 255.
img[img < 0.] = 0.
return img | bigcode/self-oss-instruct-sc2-concepts |
def is_this_list(lst: list, count: int) -> bool:
"""
Returns true iff the list is not empty and the last item of the list equals the 'count'
:param lst:
:param count:
:return:
"""
return len(lst) > 0 and lst[-1] == count | bigcode/self-oss-instruct-sc2-concepts |
def open_no_nl(filepath, mode="r"):
"""Open a file for reading without translating newlines."""
return open(filepath, mode, newline="") | bigcode/self-oss-instruct-sc2-concepts |
def apply_polynomial(coeff, x):
"""Given coefficients [a0, a1, ..., an] and x, compute f(x) = a0 + a1*x + ... + ai*x**i +
... + an*x**n.
Args:
coeff (list(int)): Coefficients [a0, a1, ..., an].
x (int): Point x to on which to evaluate the polynomial.
Returns:
int: f(x) = a0 + a... | bigcode/self-oss-instruct-sc2-concepts |
def limit_speed(speed):
"""Limit speed in range [-900,900]."""
if speed > 900:
speed = 900
elif speed < -900:
speed = -900
return speed | bigcode/self-oss-instruct-sc2-concepts |
def decomposition(x):
"""
Return the decomposition of ``x``.
EXAMPLES::
sage: M = matrix([[2, 3], [3, 4]])
sage: M.decomposition()
[
(Ambient free module of rank 2 over the principal ideal domain Integer Ring, True)
]
sage: G.<a,b> = DirichletGroup(20)
... | bigcode/self-oss-instruct-sc2-concepts |
def _sum_ft(tensor):
"""sum over the first and last dimention"""
return tensor.sum(dim=0).sum(dim=-1) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _get_anchor_negative_triplet_mask(labels):
"""Return a 2D mask where mask[a, n] is True iff a and n have distinct labels.
Args:
labels: torch.Tensor with shape [batch_size]
Returns:
mask: Variable with torch.ByteTensor with shape [batch_size, batch_size]
"""
# Chec... | bigcode/self-oss-instruct-sc2-concepts |
def bool_as_int(val: object) -> str:
"""Convert a True/False value into '1' or '0'.
Valve uses these strings for True/False in editoritems and other
config files.
"""
if val:
return '1'
else:
return '0' | bigcode/self-oss-instruct-sc2-concepts |
import re
def pack_article(article_raw):
"""
article preprocessing, splitting paragraphs
:param article_raw: article as string
:return: list of paragraphs
"""
article = list()
article_split = re.split(r'(?<=>)(.+?)(?=<)', article_raw)
## parse articles (no tags)
for p in range(1,... | bigcode/self-oss-instruct-sc2-concepts |
def read_file(fname):
"""Read file and return the its content."""
with open(fname, "r") as f:
return f.read() | bigcode/self-oss-instruct-sc2-concepts |
def get_config_file_needed(args):
"""
Determines whether or not we need to fetch additional config variables from a file.
"""
return not (args.project_name and args.source_dir and args.data_dir and args.volumes_dir) | bigcode/self-oss-instruct-sc2-concepts |
def mastinMER(H, DRE = 2500):
"""Calculates Mass Eruption Rate (MER) using Mastin et al. 2009 equation.
Input is height (km), dense rock equivalent (DRE) (kg/m^3).
dV = volumetric flow rate (m^3/s)
Output is MER (kg/s). Optional input is DRE"""
p=1/0.241
dV=(H/2.00)**p
MER=dV*DRE
return... | bigcode/self-oss-instruct-sc2-concepts |
def _set_vmin_vmax(d, cbrange):
"""Set minimum and maximum values of the color map."""
if 'vmin' not in d.keys():
d['vmin'] = cbrange[0]
if 'vmax' not in d.keys():
d['vmax'] = cbrange[1]
return d | bigcode/self-oss-instruct-sc2-concepts |
def save_userLUT(voidef, out_lut_file):
"""
Save look-up table for user-defined VOI.
Format for outputted table:
|user VOI No.|user VOI name|
"""
df = voidef[["user VOI No.", "user VOI name"]]
df2 = df.drop_duplicates(["user VOI name"])
df2.to_csv(out_lut_file, index=False, sep=" ... | bigcode/self-oss-instruct-sc2-concepts |
import six
import re
def _replace_series_name(seriesname, replacements):
"""Performs replacement of series name.
Allow specified replacements of series names in cases where default
filenames match the wrong series, e.g. missing year gives wrong answer,
or vice versa. This helps the TVDB query get the... | bigcode/self-oss-instruct-sc2-concepts |
def is_experimental_class(klass):
"""
Test CIM compoments of the klass parameter and if any have the experimental
qualifier and its value is True return True. Otherwise return False
Parameters:
klass :class:`~pywbem.CIMClass`:
The CIMClass to test for the experimental qualifier
Retur... | bigcode/self-oss-instruct-sc2-concepts |
def long2base(n, q):
""" Maps n to a list of digits corresponding to the base q representation of n in reverse order
:param int n: a positive integer
:param int q: base to represent n
:return: list of q-ary 'digits', that is, elements of {0,1,..,q-1}
:rtype: list"""
lt = []
while n > 0:
... | bigcode/self-oss-instruct-sc2-concepts |
def not_found(request):
"""
This is the view that handles 404 (not found) http responses
"""
request.response.status_int = 404
return {
'url': request.resource_url(request.root)
} | bigcode/self-oss-instruct-sc2-concepts |
def assign_assumed_width_to_province_roads_from_file(asset_width, width_range_list):
"""Assign widths to Province roads assets in Vietnam
The widths are assigned based on our understanding of:
1. The reported width in the data which is not reliable
2. A design specification based understanding of the ... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_mturk_cost(payment_opt):
"""MTurk Pricing: https://requester.mturk.com/pricing
20% fee on the reward and bonus amount (if any) you pay Workers.
HITs with 10 or more assignments will be charged an additional
20% fee on the reward you pay Workers.
Example payment_opt format for paying r... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def dict_union(*args: Dict) -> Dict:
"""
Unite two or more dicts into one.
Results in a new dict.
>>> dict_union({'a': 1}, {'b': 2})
{'a': 1, 'b': 2}
"""
new_dict = {}
for dict_ in args:
new_dict.update(dict_)
return new_dict | bigcode/self-oss-instruct-sc2-concepts |
def assign_linux_server_policy(api, configuration, api_version, api_exception, computer_id):
""" Assigns a Linux server policy to a computer.
:param api: The Deep Security API modules.
:param configuration: Configuration object to pass to the api client.
:param api_version: The version of the API to us... | bigcode/self-oss-instruct-sc2-concepts |
def _df_elements(df):
"""Yields all the values in the data frame serially."""
return (x for row in df.itertuples() for x in row) | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def filter_graph(dictionary, include_keys):
"""
Create new list that contains only values
specified in the ``include_keys`` attribute.
Parameters
----------
dictionary : dict
Original dictionary
include_keys : list or tuple
Keys that will co... | bigcode/self-oss-instruct-sc2-concepts |
def _get_collapsed_course_and_dist_req_sets(req):
"""
Returns the sets of all courses and all distribution requirements
in req's subtree as a tuple:
(course_set, dist_req_set)
Note: Sets may contain duplicate courses if a course is listed in multiple
different ways
"""
if "course_list" i... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_required_cols(geom_type: str, columns: List[str]) -> List[str]:
"""Get the required columns for a given geometry type."""
req_cols = ["id", geom_type, "dates", "region"]
for var in ["time_scale", "pet", "alpha"]:
if var in columns:
req_cols.append(var)
... | bigcode/self-oss-instruct-sc2-concepts |
def parse_spinsolve_par_line(line):
"""
Parse lines in acqu.par and return a tuple (paramter name, parameter value)
"""
line = line.strip() # Drop newline
name, value = line.split("=", maxsplit=1) # Split at equal sign (and ignore further equals in attribute values)
# remove spaces
name =... | bigcode/self-oss-instruct-sc2-concepts |
def create_sloping_step_function(start_x, start_y, end_x, end_y):
"""
create sloping step function, returning start y-value for input values below starting x-value, ending y-value
for input values above ending x-value and connecting slope through the middle
:param start_x: float
starting x-... | bigcode/self-oss-instruct-sc2-concepts |
def is_crud(sql):
"""Check that given sql is insert , update, delete or select
:param sql: Sql string to check for is_crud
:return: Boolean result
"""
crud = ['insert', 'update', 'delete', 'select']
if not isinstance(sql, str):
raise TypeError('`sql` argument is not valid. `sql` must... | bigcode/self-oss-instruct-sc2-concepts |
def is_table(cur, table_name):
"""
Simple check to see if table exists or not
:param cur: cursor
:param table_name: str - name of table
:return: True/False
"""
sql_command = f"SELECT EXISTS ( SELECT FROM information_schema.tables WHERE table_name = '{table_name}' );"
cur.execute(sql_comm... | bigcode/self-oss-instruct-sc2-concepts |
def generic_mon_cb(source, signal):
"""
Create a generic callback for sending a signal from source value.
:param source: Object representing the EPICS PV data source. This object
needs to be properly initialized and monitored.
:type source: Pv
:param signal: Signal to send the v... | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def _make_job_id(job_id, prefix=None):
"""Construct an ID for a new job.
:type job_id: str or ``NoneType``
:param job_id: the user-provided job ID
:type prefix: str or ``NoneType``
:param prefix: (Optional) the user-provided prefix for a job ID
:rtype: str
:returns: A job ID... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def all_transceivers_detected(dut, asic_index, interfaces, xcvr_skip_list):
"""
Check if transceiver information of all the specified interfaces have been detected.
"""
cmd = "redis-cli --raw -n 6 keys TRANSCEIVER_INFO\*"
asichost = dut.asic_instance(asic_index)
docker_cmd = asi... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def get_version(rel_path):
"""Get the version of the library
Args:
rel_path (str): Relative path to __init__.py with version.
Returns:
str: Version of library
"""
for line in pathlib.Path(rel_path).open('r').read().splitlines():
if line.startswith('__version_... | bigcode/self-oss-instruct-sc2-concepts |
def should_be_deactivated(message):
"""
Determines whether a message stands for an option to be turned off.
Args:
message(str): A message to test
Returns:
bool: True if the message is negative, False otherwise
"""
NEGATIVE_TERMS = ["deactivated", "disabled", "false", "no", "none"... | bigcode/self-oss-instruct-sc2-concepts |
import hmac
import hashlib
import time
def verify_access_token(token, key):
"""Verify that the given access token is still valid. Returns true if it is,
false if it either failed to validate or has expired.
A token is a combination of a unix timestamp and a signature"""
t = token[:15]
signature =... | bigcode/self-oss-instruct-sc2-concepts |
def get_fake_context(**config):
"""Generates a fake context description for testing."""
fake_credential = {
"user": "fake_user",
"host": "fake_host",
"port": -1,
"key": "fake_key",
"password": "fake_password",
}
return {
"task": {
"uuid": "fa... | 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.