seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import torch
def get_box_attribute(probability):
"""
Return the argmax on `probability` tensor.
"""
return torch.argmax(probability, dim=-1) | bigcode/self-oss-instruct-sc2-concepts |
def parse_arg_array(arguments):
"""
Parses array of arguments in key=value format into array
where keys and values are values of the resulting array
:param arguments: Arguments in key=value format
:type arguments: list(str)
:returns Arguments exploded by =
:rtype list(str)
"""
results = []
for arg in arguments:
if len(arg) == 0:
continue
results.extend(arg.split("=", 1))
return results | bigcode/self-oss-instruct-sc2-concepts |
def get_json_data(json_dict):
"""
Parameters
----------
json_dict : :obj:`dict`
QCJSON dictionary.
Returns
-------
:obj:`list` [:obj:`int`]
Atomic numbers of all atoms
:obj:`list` [:obj:`float`]
Cartesian coordinates.
:obj:`float`
Total energy of the structure
:obj:`list` [:obj:`float`]
Gradients of the structure.
"""
atom_nums = json_dict['atomic_numbers']
coords = json_dict['molecule']['geometry']
energy = json_dict['properties']['return_energy']
gradient = json_dict['return_result']
return atom_nums, coords, energy, gradient | bigcode/self-oss-instruct-sc2-concepts |
def get_total(shopping_list, prices):
"""
Getting shopping list and prices for goods in it,
returns total cost of available products.
>>> goods = {'Apple': 2.5, 'Pear': 1, 'Pumpkin': 1.5}
>>> prices = {'Apple': 9.50, 'Pear': 23.80, 'Pumpkin': 4.50}
>>> get_total(goods, prices)
54.3
If there's no price available for product, don't include it in total
>>> goods = {'Apple': 2.5, 'Pear': 1, 'Pumpkin': 1.5}
>>> prices = {'Apple': 9.50, 'Coconut': 20}
>>> get_total(goods, prices)
23.75
>>> get_total(goods, {})
0
You may assume that units and names in shopping list and price list are
unified. I.e. if you have kg in shopping list, price will be per kg
Args:
shopping_list: dict with {product_name : amount} pairs as key-value
product_name is string
amount is numeric
prices: dictionary with {product_name : price} pairs as key-value
product_name is string
price is numeric
Returns:
Total cost as single number
"""
goods = shopping_list
prices = prices
result = []
goods = list(goods.items())
for i in goods:
if i[0] in prices:
k = i[-1] * prices[i[0]]
result.append((i[0], k))
d = dict(result)
return sum(d.values()) | bigcode/self-oss-instruct-sc2-concepts |
def create_index_query(node_type, indexed_property):
""" Create the query for the index statement. See:
https://neo4j.com/docs/cypher-manual/current/indexes-for-search-performance/
"""
print(f'CREATE INDEX ON :{node_type}({indexed_property});')
return f'CREATE INDEX ON :{node_type}({indexed_property});' | bigcode/self-oss-instruct-sc2-concepts |
def get_indexes(dfobj, value):
"""Get a list with location index of a value or string in the
DataFrame requested.
Parameters
----------
dfobj : pandas.DataFrame
Data frame where the value will be searched.
value : str, int, float
String, integer or float to be searched.
Returns
-------
listofpos : list
List which contains the location of the value in the Data
frame. The first elements will correspond to the index and
the second element to the columns
"""
# Empty list
listofpos = []
# isin() method will return a dataframe with boolean values,
# True at the positions where element exists
result = dfobj.isin([value])
# any() method will return a boolean series
seriesobj = result.any()
# Get list of column names where element exists
columnnames = list(seriesobj[seriesobj].index)
# Iterate over the list of columns and extract the row index
# where element exists
for col in columnnames:
rows = list(result[col][result[col]].index)
for row in rows:
listofpos.append((row, col))
return listofpos | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def unwrap_fullargspec(func):
"""recursively searches through wrapped function to get the args"""
func_dict = func.__dict__
if "__wrapped__" in func_dict:
return unwrap_fullargspec(func_dict["__wrapped__"])
else:
return inspect.getfullargspec(func) | bigcode/self-oss-instruct-sc2-concepts |
def squared_error(prediction, observation):
"""
Calculates the squared error.
Args:
prediction - the prediction from our linear regression model
observation - the observed data point
Returns:
The squared error
"""
return (observation - prediction) ** 2 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def recover_message(messages, least_frequent=False):
"""For each position in the recovered message,
find the most- (least-) frequently-occurring
character in the same position in the set of
raw messages.
"""
i = len(messages) if least_frequent else 1
return ''.join([Counter(seq).most_common(i)[-1][0]
for seq in zip(*messages)]) | bigcode/self-oss-instruct-sc2-concepts |
def strip_leading_zeros(version: str) -> str:
"""
Strips leading zeros from version number.
This converts 1974.04.03 to 1974.4.3 as the format with leading month and day zeros is not accepted
by PIP versioning.
:param version: version number in CALVER format (potentially with leading 0s in date and month)
:return: string with leading 0s after dot replaced.
"""
return ".".join(str(int(i)) for i in version.split(".")) | bigcode/self-oss-instruct-sc2-concepts |
def tie_account_to_order(AccountKey, order):
"""tie_account_to_order - inject the AccountKey in the orderbody.
An order specification is 'anonymous'. To apply it to an account it needs
the AccountKey of the account.
Parameters
----------
AccountKey: string (required)
the accountkey
order: dict representing an orderbody or <...>Order instance
the details of the order.
"""
_r = order.copy() if isinstance(order, dict) else order.data.copy()
# add the key to the orderbody, but ONLY if this is not a positionclose
# body
if "PositionId" not in _r:
_r.update({'AccountKey': AccountKey})
# and add it to related orders in Orders (if any)
if 'Orders' in _r:
for o in _r['Orders']:
o.update({'AccountKey': AccountKey})
return _r | bigcode/self-oss-instruct-sc2-concepts |
def renamefromto(row, renaming):
"""Rename keys in a dictionary.
For each (oldname, newname) in renaming.items(): rename row[oldname] to
row[newname].
"""
if not renaming:
return row
for old, new in renaming.items():
row[new] = row[old]
del row[old] | bigcode/self-oss-instruct-sc2-concepts |
import json
def is_bootstrap(event):
"""
Determines if the message sent in was for an bootstrap action -
Bootstrap (success) events are always just strings so loading it as json should
raise a ValueError
"""
try:
message = json.loads(event['Records'][0]['Sns']['Message'])
if isinstance(message, dict):
if message.get('Error'):
return True
return False
except ValueError:
return True | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import yaml
def to_yaml_str(val: Any) -> str:
"""
:param val: value to get yaml str value of
:return: direct str cast of val if it is an int, float, or bool, otherwise
the stripped output of yaml.dump
"""
if isinstance(val, (str, int, float, bool)):
return str(val)
else:
return yaml.dump(val).strip() | bigcode/self-oss-instruct-sc2-concepts |
def remove_comments(line):
"""
Remove all comments from the line
:param line: assembly source line
:return: line without comments (; ....)
"""
comment = line.find(';')
if comment >= 0:
line = line[0:comment]
return line | bigcode/self-oss-instruct-sc2-concepts |
import re
def like(matchlist: list, array: list, andop=False):
"""Returns a list of matches in the given array by doing a comparison of each object with the values given to the matchlist parameter.
Examples:
>>> subdir_list = ['get_random.py',
... 'day6_15_payload-by-port.py',
... 'worksheet_get_exif.py',
... 'worksheet_get_random.py',
... 'day6_19_browser-snob.py',
... 'day6_12_letterpassword.py',
... 'day6_21_exif-tag.py',
... 'day6_17_subprocess_ssh.py',
... 'day6_16._just_use_split.py']
>>> like('day', subdir_list)\n
['day6_15_payload-by-port.py', 'day6_19_browser-snob.py', 'day6_12_letterpassword.py', 'day6_21_exif-tag.py', 'day6_17_subprocess_ssh.py', 'day6_16._just_use_split.py']
>>> like(['get','exif'], subdir_list)\n
['get_random.py', 'worksheet_get_exif.py', 'worksheet_get_random.py', 'day6_21_exif-tag.py']
>>> like(['get','exif'], subdir_list, andop=True)\n
['worksheet_get_exif.py']
Args:
matchlist (list): Submit one or many substrings to match against
array (list): This is the list that we want to filter
andop (bool, optional): This will determine if the matchlist criteria is an "And Operation" or an "Or Operation. Defaults to False (which is the "Or Operation"). Only applies when multiple arguments are used for the "matchlist" parameter
Returns:
list: Returns a list of matches
References:
https://stackoverflow.com/questions/469913/regular-expressions-is-there-an-and-operator
https://stackoverflow.com/questions/3041320/regex-and-operator
https://stackoverflow.com/questions/717644/regular-expression-that-doesnt-contain-certain-string
"""
if isinstance(matchlist, str):
# matchlist is a single string object
thecompile = re.compile(rf"^(?=.*{matchlist}).*$")
result_list = [x for x in array if re.findall(thecompile, x)]
return result_list
else:
if andop:
# We will be doing an "AND" match or an "And" "Operation"
match_string = r"(?=.*?" + r".*?)(?=.*?".join(matchlist) + r".*?)"
# e.g. for the above... ['6_19','6_21','6_24'] turns to: '(?=.*?6_19.*?)(?=.*?6_21.*?)(?=.*?6_24.*?)'
thecompile = re.compile(rf"^{match_string}.*$")
# equivalent to: '^(?=.*?6_19.*?)(?=.*?6_21.*?)(?=.*?6_24.*?).*$'
result_list = [x for x in array if re.findall(thecompile, x)]
return result_list
else:
# We will be doing an "OR" match
match_string = r"(?=.*" + r"|.*".join(matchlist) + ")"
# e.g. for the above... ['6_19','6_21','6_24'] turns to: '(?=.*6_19|.*6_21|.*6_24)'
thecompile = re.compile(rf"^{match_string}.*$")
# equivalent to: '^(?=.*6_19|.*6_21|.*6_24).*$'
result_list = [x for x in array if re.findall(thecompile, x)]
return result_list | bigcode/self-oss-instruct-sc2-concepts |
def colvec(vec):
""" Convert to column vector """
return vec.reshape(-1, 1) | bigcode/self-oss-instruct-sc2-concepts |
def parse_genes(gene_file):
"""Select gene to exclude: where sgt column is not 'yes'
input: csv file with genes
return: set of genes which should be exluded"""
to_exlude = set()
with open(gene_file) as lines:
next(lines)
for line in lines:
gene, _, _, sgt = line.split('\t')
if sgt.strip().lower() != 'yes':
to_exlude.add(gene)
return to_exlude | bigcode/self-oss-instruct-sc2-concepts |
def intervals_to_list(data):
"""Transform list of pybedtools.Intervals to list of lists."""
return [interval.fields for interval in data] | bigcode/self-oss-instruct-sc2-concepts |
def consume(queue_name):
"""
Decorate a function to signal it is a WCraaS consumer and provide its queue name.
>>> @consume("awesome_queue")
... def func(): pass
...
>>> func.is_consume
True
>>> func.consume_queue
'awesome_queue'
"""
def decorator(fn):
fn.is_consume = True
fn.consume_queue = queue_name
return fn
return decorator | bigcode/self-oss-instruct-sc2-concepts |
def presale_investor_4(accounts) -> str:
"""Test account planted in fake_seed_investor_data.csv"""
return accounts[9] | bigcode/self-oss-instruct-sc2-concepts |
import numbers
def is_numeric(value):
"""Return True if value is really numeric (int, float, whatever).
>>> is_numeric(+53.4)
True
>>> is_numeric('53.4')
False
"""
return isinstance(value, numbers.Number) | bigcode/self-oss-instruct-sc2-concepts |
def RIGHT(string, num_chars=1):
"""
Returns a substring of length num_chars from the end of a specified string. If num_chars is
omitted, it is assumed to be 1. Same as `string[-num_chars:]`.
>>> RIGHT("Sale Price", 5)
'Price'
>>> RIGHT('Stock Number')
'r'
>>> RIGHT('Text', 100)
'Text'
>>> RIGHT('Text', -1)
Traceback (most recent call last):
...
ValueError: num_chars invalid
"""
if num_chars < 0:
raise ValueError("num_chars invalid")
return string[-num_chars:] | bigcode/self-oss-instruct-sc2-concepts |
import math
def degrees(d):
"""Convert degrees to radians.
Arguments:
d -- Angle in degrees.
"""
return d / 180 * math.pi | bigcode/self-oss-instruct-sc2-concepts |
def gasoline_cost_sek(dist, sekpl=20.0, kmpl=9.4):
"""Gets cost of commute via car in Swedish Krona.
Input
dist: distance in kilometers (numeric)
sekpl: Swedish Krona (SEK) per liter (L). Obtained from gasoline_price() function.
kmpl: Kilometers (km) per liter (L). (Fuel efficiency)
kmpl estimation from:
https://www.bts.gov/content/average-fuel-efficiency-us-passenger-cars-and-light-trucks
"""
return sekpl * dist / kmpl | bigcode/self-oss-instruct-sc2-concepts |
def reverse_array_2(arr, start, end):
"""
A method to reverse an array within the given start and end ranges
Space complexity = O(1)
Time complexity = O(n)/2
:param arr: The array to reverse
:param start: The start index within array to reverse
:param end: The end index within array to reverse
:return: reversed array
"""
while start < end:
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start += 1
end -= 1
return arr | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
def pad_list(l: List[Any], length: int, item: Any) -> List[Any]: # noqa: E741
"""Pads a list to the specified length.
Note that if the input list is longer than the specified length it is not
truncated.
Args:
l: The input list.
length: The desired length of the list.
item: The item to use to pad the list.
Returns:
The padded list.
"""
return l + [item] * (length - len(l)) | bigcode/self-oss-instruct-sc2-concepts |
def get_user_id(flickr, user):
"""Get the user_id from the username."""
user_data = flickr.people.findByUsername(username=user)
return user_data['user']['id'] | bigcode/self-oss-instruct-sc2-concepts |
import math
def angle_to_pixel(angle, fov, num_pixels):
"""
angle: object angle
fov: field of view of the camera
num_pixels: number of pixels along the dimension that fov was measured
"""
if angle > 90.0 or angle < -90.0:
raise ValueError
x = math.tan(math.radians(angle))
limit = math.tan(math.radians(fov / 2))
return int(x / limit * num_pixels / 2 + num_pixels / 2) | bigcode/self-oss-instruct-sc2-concepts |
def create_data_dict(data):
"""
Function to convert data to dictionary format
Args:
-----------
data: train/dev data as a list
Returns:
--------
a dictionary containing dev/train data
"""
train = {}
train['para'] = []
train['answer'] = []
train['question'] = []
train['question_len'] = []
train['para_len'] = []
train['para_mask'] = []
train['question_mask'] = []
for (para_idx, question_idx, para_len, question_len, answer, para_mask, ques_mask) in data:
train['para'].append(para_idx)
train['question'].append(question_idx)
train['para_len'].append(para_len)
train['question_len'].append(question_len)
train['answer'].append(answer)
train['para_mask'].append(para_mask)
train['question_mask'].append(ques_mask)
return train | bigcode/self-oss-instruct-sc2-concepts |
import re
def replace_halogen(smiles):
"""
Replace halogens with single letters (Cl -> L and Br -> R), following
Olivecrona et al. (J Cheminf 2018).
"""
br = re.compile('Br')
cl = re.compile('Cl')
smiles = br.sub('R', smiles)
smiles = cl.sub('L', smiles)
return smiles | bigcode/self-oss-instruct-sc2-concepts |
def form_dataframe_to_arrays(df):
"""
Convert dataframes into arrays in both variables and target
"""
feature_order = list(df.filter(regex="[^M_t+\d]").columns)
X = df.filter(regex="[^M_t+\d]").values
Y = df.filter(regex="[\+]").values.flatten()
return X,Y,feature_order | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import re
def _read_url_slug(file_contents: str) -> Optional[str]:
"""Returns slug parsed from file contents, None if not found."""
regex = r"""url=[^"]+\.[^"]+\/(?P<slug>[-\w]+)(\/|[\w.]+)?\""""
match = re.search(regex, file_contents, re.VERBOSE)
if match:
return match["slug"]
return None | bigcode/self-oss-instruct-sc2-concepts |
def permute_dimensions(x, pattern):
"""Transpose dimensions.
pattern should be a tuple or list of
dimension indices, e.g. [0, 2, 1].
"""
pattern = tuple(pattern)
return x.transpose(pattern) | bigcode/self-oss-instruct-sc2-concepts |
import base64
def _make_user_code(code: str) -> str:
"""Compose the user code into an actual base64-encoded string variable."""
code = base64.b64encode(code.encode("utf8")).decode("utf8")
return f'USER_CODE = b"{code}"' | bigcode/self-oss-instruct-sc2-concepts |
def find_missing_items(intList):
"""
Returns missing integers numbers from a list of integers
:param intList: list(int), list of integers
:return: list(int), sorted list of missing integers numbers of the original list
"""
original_set = set(intList)
smallest_item = min(original_set)
largest_item = max(original_set)
full_set = set(range(smallest_item, largest_item + 1))
return sorted(list(full_set - original_set)) | bigcode/self-oss-instruct-sc2-concepts |
def AsList(arg):
"""return the given argument unchanged if already a list or tuple, otherwise return a single
element list"""
return arg if isinstance(arg, (tuple, list)) else [arg] | bigcode/self-oss-instruct-sc2-concepts |
import io
def has_fileno(stream):
"""
Cleanly determine whether ``stream`` has a useful ``.fileno()``.
.. note::
This function helps determine if a given file-like object can be used
with various terminal-oriented modules and functions such as `select`,
`termios`, and `tty`. For most of those, a fileno is all that is
required; they'll function even if ``stream.isatty()`` is ``False``.
:param stream: A file-like object.
:returns:
``True`` if ``stream.fileno()`` returns an integer, ``False`` otherwise
(this includes when ``stream`` lacks a ``fileno`` method).
"""
try:
return isinstance(stream.fileno(), int)
except (AttributeError, io.UnsupportedOperation):
return False | bigcode/self-oss-instruct-sc2-concepts |
def select_dropdown(options, id=None):
"""Generate a new select dropdown form
Parameters
----------
options: List[str]
list of options the user can select
id: str
DOM id used to refer to this input form
"""
html_options = ''.join(f'<option>{opt}</option>' for opt in options)
return f"""
<select class="form-control form-control-sm" id="{id}">
{html_options}
</select>
""" | bigcode/self-oss-instruct-sc2-concepts |
def read(path):
"""
Read a file
"""
with open(path) as file_:
return file_.read() | bigcode/self-oss-instruct-sc2-concepts |
def createDict(data, index):
"""
Create a new dictionnay from dictionnary key=>values:
just keep value number 'index' from all values.
>>> data={10: ("dix", 100, "a"), 20: ("vingt", 200, "b")}
>>> createDict(data, 0)
{10: 'dix', 20: 'vingt'}
>>> createDict(data, 2)
{10: 'a', 20: 'b'}
"""
return dict( (key,values[index]) for key, values in data.iteritems() ) | bigcode/self-oss-instruct-sc2-concepts |
def is_port_vlan_member(config_db, port, vlan):
"""Check if port is a member of vlan"""
vlan_ports_data = config_db.get_table('VLAN_MEMBER')
for key in vlan_ports_data:
if key[0] == vlan and key[1] == port:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import random
def uniformly_split_num(
sum: int,
n: int,
) -> List[int]:
"""Generate `n` non-negative numbers that sum up to `sum`"""
assert n > 0, 'n should be > 0'
assert sum >= 0, 'sum should be >= 0'
random_numbers = [random.randint(0, sum) for _ in range(n - 1)]
values = [0] + sorted(random_numbers) + [sum]
values.sort()
intervals = [values[i + 1] - values[i] for i in range(len(values) - 1)]
return intervals | bigcode/self-oss-instruct-sc2-concepts |
def _update_count_down(previous_count_down_minutes, check_mail_interval, current_time, start_time, main_window) -> int:
"""
Utility method, update status message text ("count down") until next mail check begins
:param previous_count_down_minutes: current state of counter
:param check_mail_interval: given mail check interval from config
:param current_time: current timestamp ("now")
:param start_time: timestamp starting point of the current interval
:param main_window: the main window (PySimpleGUI element)
:return: current countdown counter in minutes (int)
"""
# count down minutes until analysis is launched
count_down_minutes = check_mail_interval - int((current_time - start_time) / 60)
if previous_count_down_minutes >= (count_down_minutes + 1):
main_window['-STATUS_MSG-'].update('AKTIV - nächste Analyse in ' + str(count_down_minutes) + ' Minuten',
text_color='red')
return count_down_minutes | bigcode/self-oss-instruct-sc2-concepts |
async def get_int_list(redis, key):
"""Get a list of integers on redis."""
str_list = await redis.lrange(key, 0, -1)
int_list = [int(i) for i in str_list]
return int_list | bigcode/self-oss-instruct-sc2-concepts |
def swap_list_order(alist):
"""
Args:
alist: shape=(B, num_level, ....)
Returns:
alist: shape=(num_level, B, ...)
"""
new_order0 = len(alist[0])
return [[alist[i][j] for i in range(len(alist))] for j in range(new_order0)] | bigcode/self-oss-instruct-sc2-concepts |
def PWM_scorer(seq, pwm, pwm_dict, pwm_type):
"""
Generate score for current seq given a pwm.
"""
seq_score = 0.0
for i in range(0, len(seq)):
seq_score += pwm[pwm_dict[seq[i:i+1]]][i]
return seq_score | bigcode/self-oss-instruct-sc2-concepts |
def _collect_facts(operators):
"""
Collect all facts from grounded operators (precondition, add
effects and delete effects).
"""
facts = set()
for op in operators:
facts |= op.preconditions | op.add_effects | op.del_effects
return facts | bigcode/self-oss-instruct-sc2-concepts |
import math
def _brevity_penalty(candidate, references):
"""Calculate brevity penalty.
As the modified n-gram precision still has the problem from the short
length sentence, brevity penalty is used to modify the overall BLEU
score according to length.
An example from the paper. There are three references with length 12, 15
and 17. And a terse candidate of the length 12. The brevity penalty is 1.
>>> references = [['a'] * 12, ['a'] * 15, ['a'] * 17]
>>> candidate = ['a'] * 12
>>> _brevity_penalty(candidate, references)
1.0
In case a candidate translation is shorter than the references, penalty is
applied.
>>> references = [['a'] * 28, ['a'] * 28]
>>> candidate = ['a'] * 12
>>> _brevity_penalty(candidate, references)
0.2635...
The length of the closest reference is used to compute the penalty. If the
length of a candidate is 12, and the reference lengths are 13 and 2, the
penalty is applied because the candidate length (12) is less then the
closest reference length (13).
>>> references = [['a'] * 13, ['a'] * 2]
>>> candidate = ['a'] * 12
>>> _brevity_penalty(candidate, references)
0.92...
The brevity penalty doesn't depend on reference order. More importantly,
when two reference sentences are at the same distance, the shortest
reference sentence length is used.
>>> references = [['a'] * 13, ['a'] * 11]
>>> candidate = ['a'] * 12
>>> _brevity_penalty(candidate, references) == _brevity_penalty(candidate, reversed(references)) == 1
True
A test example from mteval-v13a.pl (starting from the line 705):
>>> references = [['a'] * 11, ['a'] * 8]
>>> candidate = ['a'] * 7
>>> _brevity_penalty(candidate, references)
0.86...
>>> references = [['a'] * 11, ['a'] * 8, ['a'] * 6, ['a'] * 7]
>>> candidate = ['a'] * 7
>>> _brevity_penalty(candidate, references)
1.0
"""
c = len(candidate)
ref_lens = (len(reference) for reference in references)
r = min(ref_lens, key=lambda ref_len: (abs(ref_len - c), ref_len))
if c > r:
return 1
else:
return math.exp(1 - r / c) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
import json
def hash_dump(data):
"""Hash an arbitrary JSON dictionary by dumping it in sorted order, encoding it in UTF-8, then hashing the bytes.
:param data: An arbitrary JSON-serializable object
:type data: dict or list or tuple
:rtype: str
"""
return hashlib.sha512(json.dumps(data, sort_keys=True).encode('utf-8')).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def clean_dict(dictionary):
""" Remove items with None value in the dictionary and recursively in other nested dictionaries. """
if not isinstance(dictionary, dict):
return dictionary
return {k: clean_dict(v) for k, v in dictionary.items() if v is not None} | bigcode/self-oss-instruct-sc2-concepts |
def get_padding_prp(hparams):
"""Get padding for pad_rotate_project measurements"""
if hparams.dataset == 'mnist':
paddings = [[0, 0], [6, 6], [6, 6], [0, 0]]
elif hparams.dataset == 'celebA':
paddings = [[0, 0], [14, 14], [14, 14], [0, 0]]
else:
raise NotImplementedError
return paddings | bigcode/self-oss-instruct-sc2-concepts |
def get_post_data(request):
"""
Attempt to coerce POST json data from the request, falling
back to the raw data if json could not be coerced.
:type request: flask.request
"""
try:
return request.get_json(force=True)
except:
return request.values | bigcode/self-oss-instruct-sc2-concepts |
def sort_by_hw_count(user):
"""Sort students by the number of completed homeworks"""
return sum([1 if hw['status'] == 'success' else 0 for hw in user['homeworks']]) | bigcode/self-oss-instruct-sc2-concepts |
def getOrientation( geom , camera=True):
"""
build and return a dictionary storing the orientation for geom
orientDict <- getOrientation( geom )
"""
orientMem = {}
orientMem['rotation'] = geom.rotation[:]
orientMem['translation'] = geom.translation.copy()
orientMem['scale'] = geom.scale[:]
orientMem['pivot'] = geom.pivot[:]
if camera:
cam = geom.viewer.currentCamera
orientMem['fieldOfView'] = cam.fovy
orientMem['lookFrom'] = cam.lookFrom.copy()
return orientMem | bigcode/self-oss-instruct-sc2-concepts |
def patch_from_tupled_dict(tupled_dict):
""" Creates a nested dictionary that f90nml can interpret as a patch."""
patch = {}
for replace_this, replace_val in tupled_dict.items():
group, field = replace_this
group, field = group.lower(), field.lower()
gdict = patch.get(group, {})
gdict.update({field: replace_val})
patch[group] = gdict
return patch | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def yaml_to_base_type(node, loader):
"""
Converts a PyYAML node type to a basic Python data type.
Parameters
----------
node : yaml.Node
The node is converted to a basic Python type using the following:
- MappingNode -> dict
- SequenceNode -> list
- ScalarNode -> str, int, float etc.
loader : yaml.Loader
Returns
-------
basic : object
Basic Python data type.
"""
if isinstance(node, yaml.MappingNode):
return loader.construct_mapping(node, deep=True)
elif isinstance(node, yaml.SequenceNode):
return loader.construct_sequence(node, deep=True)
elif isinstance(node, yaml.ScalarNode):
return loader.construct_scalar(node)
else:
raise TypeError("Don't know how to implicitly construct '{0}'".format(
type(node))) | bigcode/self-oss-instruct-sc2-concepts |
import re
def find_note_contents_start(md_text_lines):
"""
Some notes in Bear contain #tags near the title. This returns the index in the list that\
isn't the title or contains tags. If no index found, return len(md_text_lines)
"""
# Start at 1 to skip the title
# Look for regex matches of tags and if lines from the top contain tags, then skip
for i in range(1, len(md_text_lines)):
if re.search(r'((?<=^)|(?<=\n|\r| ))(#[^#\r\n]+#|#[^#\r\n ]+)', md_text_lines[i]) is None:
return i
return len(md_text_lines) | bigcode/self-oss-instruct-sc2-concepts |
def resize_fn(attributions, inputs, mode):
"""Mocked resize function for test."""
del inputs, mode
return attributions | bigcode/self-oss-instruct-sc2-concepts |
def print_module(module, print_flag=None):
"""Returns module in XML format. Accepts only {dict}.\n
- Only works with one module at a time: otherwise iteration is needed.
- Module "value" field accepts str type or [list] for datalists.
- Use print_flag to show modules' XML in STDOUT.
"""
data = dict(module)
module_xml = ("<module>\n"
"\t<name><![CDATA[" + str(data["name"]) + "]]></name>\n"
"\t<type>" + str(data["type"]) + "</type>\n"
)
if type(data["type"]) is not str and "string" not in data["type"]: #### Strip spaces if module not generic_data_string
data["value"] = data["value"].strip()
if isinstance(data["value"], list): # Checks if value is a list
module_xml += "\t<datalist>\n"
for value in data["value"]:
if type(value) is dict and "value" in value:
module_xml += "\t<data>\n"
module_xml += "\t\t<value><![CDATA[" + str(value["value"]) + "]]></value>\n"
if "timestamp" in value:
module_xml += "\t\t<timestamp><![CDATA[" + str(value["timestamp"]) + "]]></timestamp>\n"
module_xml += "\t</data>\n"
module_xml += "\t</datalist>\n"
else:
module_xml += "\t<data><![CDATA[" + str(data["value"]) + "]]></data>\n"
if "desc" in data:
module_xml += "\t<description><![CDATA[" + str(data["desc"]) + "]]></description>\n"
if "unit" in data:
module_xml += "\t<unit><![CDATA[" + str(data["unit"]) + "]]></unit>\n"
if "interval" in data:
module_xml += "\t<module_interval><![CDATA[" + str(data["interval"]) + "]]></module_interval>\n"
if "tags" in data:
module_xml += "\t<tags>" + str(data["tags"]) + "</tags>\n"
if "module_group" in data:
module_xml += "\t<module_group>" + str(data["module_group"]) + "</module_group>\n"
if "module_parent" in data:
module_xml += "\t<module_parent>" + str(data["module_parent"]) + "</module_parent>\n"
if "min_warning" in data:
module_xml += "\t<min_warning><![CDATA[" + str(data["min_warning"]) + "]]></min_warning>\n"
if "min_warning_forced" in data:
module_xml += "\t<min_warning_forced><![CDATA[" + str(data["min_warning_forced"]) + "]]></min_warning_forced>\n"
if "max_warning" in data:
module_xml += "\t<max_warning><![CDATA[" + str(data["max_warning"]) + "]]></max_warning>\n"
if "max_warning_forced" in data:
module_xml += "\t<max_warning_forced><![CDATA[" + str(data["max_warning_forced"]) + "]]></max_warning_forced>\n"
if "min_critical" in data:
module_xml += "\t<min_critical><![CDATA[" + str(data["min_critical"]) + "]]></min_critical>\n"
if "min_critical_forced" in data:
module_xml += "\t<min_critical_forced><![CDATA[" + str(data["min_critical_forced"]) + "]]></min_critical_forced>\n"
if "max_critical" in data:
module_xml += "\t<max_critical><![CDATA[" + str(data["max_critical"]) + "]]></max_critical>\n"
if "max_critical_forced" in data:
module_xml += "\t<max_critical_forced><![CDATA[" + str(data["max_critical_forced"]) + "]]></max_critical_forced>\n"
if "str_warning" in data:
module_xml += "\t<str_warning><![CDATA[" + str(data["str_warning"]) + "]]></str_warning>\n"
if "str_warning_forced" in data:
module_xml += "\t<str_warning_forced><![CDATA[" + str(data["str_warning_forced"]) + "]]></str_warning_forced>\n"
if "str_critical" in data:
module_xml += "\t<str_critical><![CDATA[" + str(data["str_critical"]) + "]]></str_critical>\n"
if "str_critical_forced" in data:
module_xml += "\t<str_critical_forced><![CDATA[" + str(data["str_critical_forced"]) + "]]></str_critical_forced>\n"
if "critical_inverse" in data:
module_xml += "\t<critical_inverse><![CDATA[" + str(data["critical_inverse"]) + "]]></critical_inverse>\n"
if "warning_inverse" in data:
module_xml += "\t<warning_inverse><![CDATA[" + str(data["warning_inverse"]) + "]]></warning_inverse>\n"
if "max" in data:
module_xml += "\t<max><![CDATA[" + str(data["max"]) + "]]></max>\n"
if "min" in data:
module_xml += "\t<min><![CDATA[" + str(data["min"]) + "]]></min>\n"
if "post_process" in data:
module_xml += "\t<post_process><![CDATA[" + str(data["post_process"]) + "]]></post_process>\n"
if "disabled" in data:
module_xml += "\t<disabled><![CDATA[" + str(data["disabled"]) + "]]></disabled>\n"
if "min_ff_event" in data:
module_xml += "\t<min_ff_event><![CDATA[" + str(data["min_ff_event"]) + "]]></min_ff_event>\n"
if "status" in data:
module_xml += "\t<status><![CDATA[" + str(data["status"]) + "]]></status>\n"
if "timestamp" in data:
module_xml += "\t<timestamp><![CDATA[" + str(data["timestamp"]) + "]]></timestamp>\n"
if "custom_id" in data:
module_xml += "\t<custom_id><![CDATA[" + str(data["custom_id"]) + "]]></custom_id>\n"
if "critical_instructions" in data:
module_xml += "\t<critical_instructions><![CDATA[" + str(data["critical_instructions"]) + "]]></critical_instructions>\n"
if "warning_instructions" in data:
module_xml += "\t<warning_instructions><![CDATA[" + str(data["warning_instructions"]) + "]]></warning_instructions>\n"
if "unknown_instructions" in data:
module_xml += "\t<unknown_instructions><![CDATA[" + str(data["unknown_instructions"]) + "]]></unknown_instructions>\n"
if "quiet" in data:
module_xml += "\t<quiet><![CDATA[" + str(data["quiet"]) + "]]></quiet>\n"
if "module_ff_interval" in data:
module_xml += "\t<module_ff_interval><![CDATA[" + str(data["module_ff_interval"]) + "]]></module_ff_interval>\n"
if "crontab" in data:
module_xml += "\t<crontab><![CDATA[" + str(data["crontab"]) + "]]></crontab>\n"
if "min_ff_event_normal" in data:
module_xml += "\t<min_ff_event_normal><![CDATA[" + str(data["min_ff_event_normal"]) + "]]></min_ff_event_normal>\n"
if "min_ff_event_warning" in data:
module_xml += "\t<min_ff_event_warning><![CDATA[" + str(data["min_ff_event_warning"]) + "]]></min_ff_event_warning>\n"
if "min_ff_event_critical" in data:
module_xml += "\t<min_ff_event_critical><![CDATA[" + str(data["min_ff_event_critical"]) + "]]></min_ff_event_critical>\n"
if "ff_type" in data:
module_xml += "\t<ff_type><![CDATA[" + str(data["ff_type"]) + "]]></ff_type>\n"
if "ff_timeout" in data:
module_xml += "\t<ff_timeout><![CDATA[" + str(data["ff_timeout"]) + "]]></ff_timeout>\n"
if "each_ff" in data:
module_xml += "\t<each_ff><![CDATA[" + str(data["each_ff"]) + "]]></each_ff>\n"
if "module_parent_unlink" in data:
module_xml += "\t<module_parent_unlink><![CDATA[" + str(data["parent_unlink"]) + "]]></module_parent_unlink>\n"
if "global_alerts" in data:
for alert in data["alert"]:
module_xml += "\t<alert_template><![CDATA[" + alert + "]]></alert_template>\n"
module_xml += "</module>\n"
if print_flag:
print (module_xml)
return (module_xml) | bigcode/self-oss-instruct-sc2-concepts |
def flatten(lists):
"""
flattens a list of lists x
"""
result = []
for x in lists:
for elem in x: result.append(elem)
return result | bigcode/self-oss-instruct-sc2-concepts |
import math
def format_memory_size(bytes):
"""Return a humanly readable formatting of 'bytes' using powers of 1024.
"""
units = ('Bytes', 'KB', 'MB', 'GB', 'TB')
if bytes < 1024:
return '%d %s' % (bytes, units[0])
else:
scale = min(math.floor(math.log(bytes, 1024)), len(units)-1)
return "%.2f %s" % (bytes / math.pow(1024, scale), units[scale]) | bigcode/self-oss-instruct-sc2-concepts |
def optimal_summands(n: int):
"""
Gets the maximum number of distinct prizes.
>>> optimal_summands(6)
[1, 2, 3]
>>> optimal_summands(8)
[1, 2, 5]
>>> optimal_summands(2)
[2]
"""
if n <= 2:
return [n]
opt_sum = 0
summands = []
for num in range(1, n):
opt_sum += num
if opt_sum < n:
summands.append(num)
elif opt_sum == n:
summands.append(num)
break
else:
summands[-1] += n - (opt_sum - num)
break
return summands | bigcode/self-oss-instruct-sc2-concepts |
import random
def gen_ran_len_lst(n=500):
"""Returns a random 0, n length list of 0, n random numbers."""
lst = []
for i in range(random.randrange(0, n)):
lst.append(random.randrange(0, n))
return lst | bigcode/self-oss-instruct-sc2-concepts |
def sum_multiples(n):
"""Returns the sum of multiples of three and five below n"""
assert n >= 0
return sum([i for i in range(n) if (not i%3) or (not i%5)]) | bigcode/self-oss-instruct-sc2-concepts |
import collections
def compute_dominators(func, cfg):
"""
Compute the dominators for the CFG, i.e. for each basic block the
set of basic blocks that dominate that block. This means that every path
from the entry block to that block must go through the blocks in the
dominator set.
dominators(root) = {root}
dominators(x) = {x} ∪ (∩ dominators(y) for y ∈ preds(x))
"""
dominators = collections.defaultdict(set) # { block : {dominators} }
# Initialize
dominators[func.startblock] = set([func.startblock])
for block in func.blocks:
dominators[block] = set(func.blocks)
# Solve equation
changed = True
while changed:
changed = False
for block in cfg:
pred_doms = [dominators[pred] for pred in cfg.predecessors(block)]
new_doms = set([block]) | set.intersection(*pred_doms or [set()])
if new_doms != dominators[block]:
dominators[block] = new_doms
changed = True
return dominators | bigcode/self-oss-instruct-sc2-concepts |
def structure_to_composition(series, reduce=False):
"""
Converts a Structure series to a Composition series
Args:
series: a pd.Series with pymatgen.Structure components
reduce: (bool) whether to return a reduced Composition
Returns:
a pd.Series with pymatgen Composition components
"""
if reduce:
return series.map(lambda x: x.composition.reduced_composition)
return series.map(lambda x: x.composition) | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
import json
import warnings
def read_json(file_path, encoding='UTF-8', ordered=True):
"""Read a JSON file.
Wraps the json.load() method.
Arguments:
file_path {str} -- path of file to read
Keyword Arguments:
encoding {str} -- encoding to read the file with
(default: {'UTF-8'})
ordered {bool} -- flag to return the file contents in an OrderedDict
(default: {True})
"""
kwargs = {}
return_dict = {}
try:
kwargs['encoding'] = encoding
if ordered:
kwargs['object_pairs_hook'] = OrderedDict
with open(file_path, 'r') as file_pointer:
return_dict = json.load(file_pointer, **kwargs)
except (IOError, ValueError) as err_msg:
warnings.warn(str(err_msg))
return return_dict | bigcode/self-oss-instruct-sc2-concepts |
def rotate(scale, n):
""" Left-rotate a scale by n positions. """
return scale[n:] + scale[:n] | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def getattrs(obj, attrs, default=None):
"""
Get attrs from obj
:param obj: object
:param attrs: string or iterable object
:param default: default value
:return: obj attr value if existed, otherwise default value
"""
if not attrs:
return obj
if isinstance(attrs, str):
attrs = (attrs,)
try:
return reduce(lambda x, n: getattr(x, n), attrs, obj)
except AttributeError:
return default | bigcode/self-oss-instruct-sc2-concepts |
def get_comparative_word_freq(freqs):
"""
Returns a dictionary of the frequency of words counted relative to each other.
If frequency passed in is zero, returns zero
:param freqs: dictionary
:return: dictionary
>>> from gender_novels import novel
>>> novel_metadata = {'author': 'Hawthorne, Nathaniel', 'title': 'Scarlet Letter',
... 'corpus_name': 'sample_novels', 'date': '1900',
... 'filename': 'hawthorne_scarlet.txt'}
>>> scarlet = novel.Novel(novel_metadata)
>>> d = {'he':scarlet.get_word_freq('he'), 'she':scarlet.get_word_freq('she')}
>>> d
{'he': 0.007329554965683813, 'she': 0.005894731807638042}
>>> x = get_comparative_word_freq(d)
>>> x
{'he': 0.554249547920434, 'she': 0.445750452079566}
>>> d2 = {'he': 0, 'she': 0}
>>> d2
{'he': 0, 'she': 0}
"""
total_freq = sum(freqs.values())
comp_freqs = {}
for k, v in freqs.items():
try:
freq = v / total_freq
except ZeroDivisionError:
freq = 0
comp_freqs[k] = freq
return comp_freqs | bigcode/self-oss-instruct-sc2-concepts |
def triplet_pattern(t):
"""Convert an arbitrary 3-tuple into a string specifying the distinct elements."""
if t[0] == t[1] == t[2]:
return "AAA"
if t[0] == t[1]:
return "AAB"
if t[1] == t[2]:
return "ABB"
return "ABC" | bigcode/self-oss-instruct-sc2-concepts |
def set_emulated_vision_deficiency(type: str) -> dict:
"""Emulates the given vision deficiency.
Parameters
----------
type: str
Vision deficiency to emulate.
**Experimental**
"""
return {"method": "Emulation.setEmulatedVisionDeficiency", "params": {"type": type}} | bigcode/self-oss-instruct-sc2-concepts |
def parse_args(args):
"""
This parses the arguments and returns a tuple containing:
(args, command, command_args)
For example, "--config=bar start --with=baz" would return:
(['--config=bar'], 'start', ['--with=baz'])
"""
index = None
for arg_i, arg in enumerate(args):
if not arg.startswith('-'):
index = arg_i
break
# Unable to parse any arguments
if index is None:
return (args, None, [])
return (args[:index], args[index], args[(index + 1):]) | bigcode/self-oss-instruct-sc2-concepts |
import ssl
import socket
def get_ssl_serversocket(file_certchain, file_privatekey, bindoptions, password_privkey=None):
"""
Create a SSL based server socket. Useage:
conn, addr = ssock.accept()
data = conn.recv()
conn.send(data)
Certificate/private key can be create via:
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
return -- SSL wrapped TCP server socket
"""
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(file_certchain, file_privatekey, password=password_privkey)
socket_simple = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
socket_simple.bind(bindoptions)
socket_simple.listen(5)
return context.wrap_socket(socket_simple, server_side=True) | bigcode/self-oss-instruct-sc2-concepts |
def ParseCodePoint(s):
"""Parses the pua string representation.
The format of the input is either:
- empty string
- hexadecimal integer.
- hexadecimal integer leading '>'.
We're not interested in empty string nor '>'-leading codes, so returns None
for them.
Note that '>'-leading code means it is "secondary" code point to represent
the glyph (in other words, it has alternative (primary) code point, which
doesn't lead '>' and that's why we'll ignore it).
"""
if not s or s[0] == '>':
return None
return int(s, 16) | bigcode/self-oss-instruct-sc2-concepts |
def checksum_min_max(sheet_file):
"""Return the sum of each row's max - min"""
result = 0
with open(sheet_file) as f:
sheet_list = f.readlines()
for row in sheet_list:
int_row = [int(i) for i in row.split('\t')]
result = result + (max(int_row) - min(int_row))
return result | bigcode/self-oss-instruct-sc2-concepts |
def _isCharEnclosed(charIndex, string):
""" Return true if the character at charIndex is enclosed in double quotes (a string) """
numQuotes = 0 # if the number of quotes past this character is odd, than this character lies inside a string
for i in range(charIndex, len(string)):
if string[i] == '"':
numQuotes += 1
return numQuotes % 2 == 1 | bigcode/self-oss-instruct-sc2-concepts |
def soap_auth(client, tenant, username, password):
"""Authenticate to the web services"""
if not tenant:
return client.service.authenticate(
username=username, password=password
)
return client.service.authenticateTenant(
tenantName=tenant, username=username, password=password
) | bigcode/self-oss-instruct-sc2-concepts |
def correct_mag(m0, X, k):
"""Correct magnitude for airmass and extinction.
Parameters
----------
m0 : float
Apparent magnitude.
X : float
Airmass.
k : float
Extinction coefficient.
Returns
-------
m : float
The corrected apparent magnitude.
"""
m = m0 + k * X
return m | bigcode/self-oss-instruct-sc2-concepts |
def split_off_attrib(xpath):
"""
Splits off attribute of the given xpath (part after @)
:param xpath: str of the xpath to split up
"""
split_xpath = xpath.split('/@')
assert len(split_xpath) == 2, f"Splitting off attribute failed for: '{split_xpath}'"
return tuple(split_xpath) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hash_file(path):
"""
Returns the SHA-256 hash of a file.
Parameters
----------
path : `str`
The path of the file to be hashed.
Returns
-------
`str`
SHA-256 hash of the file.
References
----------
* https://stackoverflow.com/a/22058673
"""
BUF_SIZE = 65536
sha256 = hashlib.sha256()
with open(path, 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha256.update(data)
return sha256.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def str2list(v):
"""
Transform user input list(arguments) to be list of string.
Multiple options needs comma(,) between each options.
ex)
--strategies ST01
--strategies ST01,ST02,ST03
:param v: (string) user input
:return: list of option string. (ex - ['ST01', 'ST02', 'ST03')
"""
if isinstance(v, list):
return v
return v.strip().split(",") | bigcode/self-oss-instruct-sc2-concepts |
import json
def retrieve_ecli(ecli, db_session):
"""
Retrieves the ecli from a database
:param ecli: The ECLI identifier
:param db_session: a sqlalchemy session object
"""
res = db_session.execute('select * from cases where ecli=:ecli',
{"ecli":ecli})
field_names = res.keys()
results = res.fetchall()
if len(results)>0:
result = {field_names[i]: results[0][i] for i in range(len(field_names))}
result['articles'] = json.loads(result['articles'])
return result
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
def conjugate_strand(strand):
"""Given a dna strand, re-write it as it's reverse complement."""
basepair = {'a': 't', 't': 'a', 'g': 'c', 'c': 'g'}
rev_strand = ''.join(basepair[s] for s in strand[::-1]
if s in basepair.keys())
return rev_strand | bigcode/self-oss-instruct-sc2-concepts |
def binary(val):
""" validates if the value passed is binary (true/false)"""
if type(val) == bool:
return val
else:
raise ValueError("random seed is a boolean flag") | bigcode/self-oss-instruct-sc2-concepts |
def fixture_to_tables(fixture):
""" convert fixture into *behave* examples
:param fixture: a dictionary in the following form::
{
"test1name":
{
"test1property1": ...,
"test1property2": ...,
...
},
"test2name":
{
"test2property1": ...,
"test2property2": ...,
...
}
}
:return: a list, with each item represent a table: `(caption, rows)`,
each item in `rows` is `(col1, col2,...)`
"""
tables = []
for (title, content) in fixture.iteritems():
rows = []
# header(keyword) row
keys = content.keys()
keys.sort()
rows.append(tuple(keys))
# item(value) row
row1 = []
for col in rows[0]:
row1.append(content[col])
rows.append(tuple(row1))
tables.append((title, tuple(rows)))
return tables | bigcode/self-oss-instruct-sc2-concepts |
def extract_message(result): # pragma: no cover
"""Extracts the original message from a parsing result."""
return result.get('text', {}) | bigcode/self-oss-instruct-sc2-concepts |
import re
def available_space(ctx, device):
"""
Determine the available space on device such as bootflash or stby-bootflash:
:param ctx:
:param device: bootflash / stby-bootflash: / harddisk: / stby-harddisk:
:return: the available space
"""
available = -1
output = ctx.send('dir ' + device)
m = re.search(r'(\d+) bytes free', output)
if m:
available = int(m.group(1))
return available | bigcode/self-oss-instruct-sc2-concepts |
def ssh_host(config, host):
"""Get the full user/host pair for use in SSH commands."""
return '{}@{}'.format(config.user, host) | bigcode/self-oss-instruct-sc2-concepts |
def getKey(spc):
"""
Returns a string of the species that can serve as a key in a dictionary.
"""
return spc.label | bigcode/self-oss-instruct-sc2-concepts |
import operator
def get_ecdf(array, reverse=False):
"""
Generate the empirical distribution function.
:param array: array_like
:param reverse: bool
:return: float -> float
"""
n = len(array)
op = operator.ge if reverse else operator.le
def ecdf(t):
m = sum(op(x, t) for x in array) # x <= t or x >= t if reverse
return float(m) / float(n)
return ecdf | bigcode/self-oss-instruct-sc2-concepts |
import torch
def obb2poly_v1(rboxes):
"""Convert oriented bounding boxes to polygons.
Args:
obbs (torch.Tensor): [x_ctr,y_ctr,w,h,angle]
Returns:
polys (torch.Tensor): [x0,y0,x1,y1,x2,y2,x3,y3]
"""
x = rboxes[:, 0]
y = rboxes[:, 1]
w = rboxes[:, 2]
h = rboxes[:, 3]
a = rboxes[:, 4]
cosa = torch.cos(a)
sina = torch.sin(a)
wx, wy = w / 2 * cosa, w / 2 * sina
hx, hy = -h / 2 * sina, h / 2 * cosa
p1x, p1y = x - wx - hx, y - wy - hy
p2x, p2y = x + wx - hx, y + wy - hy
p3x, p3y = x + wx + hx, y + wy + hy
p4x, p4y = x - wx + hx, y - wy + hy
return torch.stack([p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y], dim=-1) | bigcode/self-oss-instruct-sc2-concepts |
def join_url(*components: str) -> str:
"""Concatenates multiple url components into one url.
Args:
*components:
Multiple url components.
Returns:
A complete url.
"""
clean = [str(comp).strip('/') for comp in components]
return '/'.join(clean) | bigcode/self-oss-instruct-sc2-concepts |
def unique_path(path):
"""
Given a path, determine if all its elements are single-valued predicates. If so, the path is unique,
regardless of length. If any one of the steps in the path has a non single-valued predicated, the path is not
unique.
:param path: a definition path
:return: True if path is unique
:rtype: boolean
"""
unique = True
for elem in path:
if elem['predicate']['single'] != True:
unique = False
break
return unique | bigcode/self-oss-instruct-sc2-concepts |
def _get_requirements_to_disable(old_requirements, new_requirements):
"""
Get the ids of 'CreditRequirement' entries to be disabled that are
deleted from the courseware.
Args:
old_requirements(QuerySet): QuerySet of CreditRequirement
new_requirements(list): List of requirements being added
Returns:
List of ids of CreditRequirement that are not in new_requirements
"""
requirements_to_disable = []
for old_req in old_requirements:
found_flag = False
for req in new_requirements:
# check if an already added requirement is modified
if req["namespace"] == old_req.namespace and req["name"] == old_req.name:
found_flag = True
break
if not found_flag:
requirements_to_disable.append(old_req.id)
return requirements_to_disable | bigcode/self-oss-instruct-sc2-concepts |
def update(cur_aggregate, new_value):
"""For a new value new_value, compute the new count, new mean, the new m_2.
* mean accumulates the mean of the entire dataset.
* m_2 aggregates the squared distance from the mean.
* count aggregates the number of samples seen so far.
"""
(count, mean, m_2) = cur_aggregate
count = count + 1
delta = new_value - mean
mean = mean + delta / count
delta2 = new_value - mean
m_2 = m_2 + delta * delta2
return (count, mean, m_2) | bigcode/self-oss-instruct-sc2-concepts |
def getStringForAndDifferential(a, b, c):
"""
AND = valid(x,y,out) = (x and out) or (y and out) or (not out)
"""
command = "(({0} & {2}) | ({1} & {2}) | (~{2}))".format(a, b, c)
return command | bigcode/self-oss-instruct-sc2-concepts |
def read_data(filename):
"""
Reads raw space image format data file into a string
"""
data = ''
f = open(filename, 'r')
for line in f:
data += line.strip('\n')
f.close()
return data | bigcode/self-oss-instruct-sc2-concepts |
def get_descriptors_text(dl):
"""
Helper function that separates text descriptors from the mixture
of text and uris that is returned from Agritriop
Parameters
----------
dl : list
Descriptor list.
Returns
-------
list
list of text descritors only.
"""
return list(filter(lambda x: not x.startswith('http') , dl)) | 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.