seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import re
def to_lowercase_alphanum(text):
"""Remove non-alphanumeric characters and convert text to lowercase.
"""
return re.sub(r'[^a-z0-9]', '', text.lower()) | bigcode/self-oss-instruct-sc2-concepts |
import math
def obliquity_of_ecliptic(t: float) -> float:
"""
Calculate the obliquity of earth's ecliptic around the sun in decimal degrees.
Parameters:
t (float): The time in Julian Centuries (36525 days) since J2000.0
Returns:
float: The obliquity of earth's ecliptic at the given t... | bigcode/self-oss-instruct-sc2-concepts |
def fractional_tune(tune):
""" Returns the fractional tune."""
return tune - int(tune) | bigcode/self-oss-instruct-sc2-concepts |
def euclid(a, b):
"""
Extended Euclidean Algorithm; finds (x,y,z) such that ax + by = gcd(a,b) = z
Written with help from
http://en.literateprograms.org/Extended_Euclidean_algorithm_%28Python%29
Input:
(a,b) two integers
Output:
(x, y, z) integers such that ax + by = gcd(a,b) ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterator
from typing import Dict
from typing import Tuple
from typing import Optional
import logging
def _parse_as_to_org_map_remainder(
f: Iterator[str], org_id_to_country_map: Dict[str, Tuple[str, str]]
) -> Dict[int, Tuple[str, Optional[str], Optional[str]]]:
# pyformat: disable
"""Retur... | bigcode/self-oss-instruct-sc2-concepts |
def is_special(pat):
"""Whether the given pattern string contains match constructs."""
return "*" in pat or "?" in pat or "[" in pat | bigcode/self-oss-instruct-sc2-concepts |
def ReadIDList(infile, delim=None):#{{{
"""
Read a file containing a list of sequence IDs.
"""
try:
fpin = open(infile,"r")
li = fpin.read().split(delim)
fpin.close()
if delim != None:
li = [x.strip() for x in li]
return li
except IOError:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def find_ipv4_with_subnet(string):
"""
Find and return IPv4 address with subnet inside a string.
This function will only return an ipv4 address with a subnet
:param string: (str) The string to search for ipv6 with subnet(i.e. "Successfully added Subnet 10.34.33.20/30")
:return: (str) ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def create_table_dropdown(order_list: List[dict], order_name: str) -> dict:
""" Create the dropdown-options in the context of assembling orders.
Syntax of the returned dictionary is based on dash.
"""
dropdown_options = {
'component': {
'options': []
... | bigcode/self-oss-instruct-sc2-concepts |
def get_values_lengthes(dictionary):
"""returns the sum of the lengthes of values of a dictionary"""
return sum(map(lambda value: len(value), dictionary.values())) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _interp_array(start: torch.Tensor, end: torch.Tensor,
num_steps: int) -> torch.Tensor:
"""Linearly interpolate 2D tensors, returns 3D tensors.
Args:
start: 2D tensor for start point of interpolation of shape [x,y].
end: 2D tensor as end point of interpolation of ... | bigcode/self-oss-instruct-sc2-concepts |
def node_is_shortcuttable(node_i, path, netgraph, rev_netgraph):
"""
Given a index node_i in path and path (list of node numbers) containing node
and the two graph (dict of dicts) structures
where rev_netgraph is just graph with all links reversed, return
True if the node has links only to and from ... | bigcode/self-oss-instruct-sc2-concepts |
def GetRegionFromZone(gce_zone):
"""Parses and returns the region string from the gce_zone string."""
zone_components = gce_zone.split('-')
# The region is the first two components of the zone.
return '-'.join(zone_components[:2]) | bigcode/self-oss-instruct-sc2-concepts |
def key(resource):
"""
Returns key name based on resource
"""
return {
'token': 'address',
'pool': 'address',
'address': 'address',
'allowance': 'hash',
'balance': 'hash',
'claim': 'hash',
'wallet': 'hash',
'transaction': 'hash',
't... | bigcode/self-oss-instruct-sc2-concepts |
def is_first_read(flag):
"""
Interpret bitwise flag from SAM field.
Returns True or False indicating whether the read is the first read in a pair.
"""
IS_FIRST_SEGMENT = 0x40
return (int(flag) & IS_FIRST_SEGMENT) != 0 | bigcode/self-oss-instruct-sc2-concepts |
def comment_code(code_str, line_comment=None, block_comment=None):
"""Adds comments to a snippet of code.
If line_comment is a given string then each line is prepended with the
line_comment string.
If block_comment is a tuple of two strings (begin, end) the code str is
surrounded by the strings.
... | bigcode/self-oss-instruct-sc2-concepts |
def from_image_url(url: str, width: int, height: int) -> str:
"""
Generates GIFT text for a URL.
Parameters
----------
url : str
Input URL.
width : int
Desired width of the image.
height : int
Desired height of the image.
Returns
-------
out: str
GIFT-ready text.
"""
# either both are set or non... | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Optional
def create_src_lengths_mask(batch_size: int, src_lengths: torch.Tensor, max_src_len: Optional[int] = None):
"""
Generate boolean mask to prevent attention beyond the end of source
Inputs:
batch_size : int
src_lengths : [batch_size] of sentence lengths
... | bigcode/self-oss-instruct-sc2-concepts |
import functools
import random
import time
def rare_delay(delay: float, probability: float):
"""
Decorator to add a fixed random delay before executing the function
with a given probability.
:param delay: Delay in seconds.
:param probability: Probability of delaying the function execution.
:re... | bigcode/self-oss-instruct-sc2-concepts |
import random
def rand_index(word):
"""
Returns a random index in a given text.
"""
return random.randint(0, len(word)-1) | bigcode/self-oss-instruct-sc2-concepts |
def get_previous_timestep(timesteps, timestep):
"""Get the timestamp for the timestep previous to the input timestep"""
return timesteps[timesteps.ord(timestep) - 1] | bigcode/self-oss-instruct-sc2-concepts |
import math
def latlon2tms(lat,lon,zoom):
"""
Converts lat/lon (in degrees) to tile x/y coordinates in the given zoomlevel.
Note that it doesn't give integers! If you need integers, truncate
the result yourself.
"""
n = 2**zoom
lat_rad = math.radians(lat)
xtile = (lon+ 180.0) / 360.0 *... | bigcode/self-oss-instruct-sc2-concepts |
def map_values(function, dictionary):
"""Map ``function`` across the values of ``dictionary``.
:return: A dict with the same keys as ``dictionary``, where the value
of each key ``k`` is ``function(dictionary[k])``.
"""
return {k: function(dictionary[k]) for k in dictionary} | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_func_args(func, args, kwargs):
""" 获得函数的所有参数信息,保存在 func_args 中
输入:
func: 函数体
args: 传入的位置参数列表
kwargs: 传入的命名参数列表
"""
# 获得当前函数的所有参数信息
full = inspect.getfullargspec(func) # 含缺省值定义
# FullArgSpec(args=[], varargs='args', varkw='kwargs', defaults=... | bigcode/self-oss-instruct-sc2-concepts |
def clean_cos(value):
"""
Limits the a value between the range C{[-1, 1]}
@type value: float
@param value: The input value
@rtype: float
@return: The limited value in the range C{[-1, 1]}
"""
return min(1, max(value, -1)) | bigcode/self-oss-instruct-sc2-concepts |
def sliding_window(l, n):
"""
Creates a sliding window of given length over a list.
Examples
--------
>>> l = range(5)
>>> sliding_window(l, 2)
[[0, 1], [1, 2], [2, 3], [3, 4]]
"""
rngs = range(0, len(l) - n + 1)
return map(lambda rng: l[rng:rng + n], rngs) | bigcode/self-oss-instruct-sc2-concepts |
import tqdm
def apply_groups(groups, client, func, *args, return_futures=False,
progress_bar=True, **kwargs):
""" Call `func` on each group in `groups`.
Additionally, `args` and `kwargs` are passed to the function call.
Parameters
----------
groups: pandas.DataFrameGroupBy
The re... | bigcode/self-oss-instruct-sc2-concepts |
def refine_digits_set(digits):
"""美化连续数字的输出效果
>>> refine_digits_set([210, 207, 207, 208, 211, 212])
'207,208,210-212'
"""
arr = sorted(list(set(digits))) # 去重
n = len(arr)
res = ''
i = 0
while i < n:
j = i + 2
if j < n and arr[i] + 2 == arr[j]:
while j <... | bigcode/self-oss-instruct-sc2-concepts |
def explode_locations(k):
"""Expands the given key ``k``. ``k``s of the form ``'1--3'`` or
``'1,2,3'`` are both expanded into the list ``['1', '2', '3']``.
Can deal with any combination, e.g. ``'1--3,6,9--11,a'`` results in::
['1', '2', '3', '6', '9', '10', '11', 'a']
Always returns a list, e... | bigcode/self-oss-instruct-sc2-concepts |
def _psd_mp_helper(ooi_hyd_data_obj, win, L, overlap, avg_method, interpolate, scale):
"""
Helper function for compute_psd_welch_mp
"""
ooi_hyd_data_obj.compute_psd_welch(win, L, overlap, avg_method, interpolate, scale)
return ooi_hyd_data_obj.psd | bigcode/self-oss-instruct-sc2-concepts |
def mk_part_uri(uri, idx):
""" Appends fragment part to the uri recording index of the part
"""
return '{}#part={:d}'.format(uri, idx) | bigcode/self-oss-instruct-sc2-concepts |
def formatter(type):
"""Format floating point numbers in scientific notation
(integers use normal integer formatting)."""
if type == int:
return "%d"
elif type == float:
return "%.3e" | bigcode/self-oss-instruct-sc2-concepts |
def linear_y(t0, t_step, slope, y0):
"""
A function to generate y values that satisfied to linear relationship with independent value t_list, slope, and start point of y
Parameters:
-----------
t0: t0, with dependent variable as startpoint_y
t_step: step of t
slope: slope
y0: startpoint... | bigcode/self-oss-instruct-sc2-concepts |
def complexAdd(complex1, complex2):
"""This method is used to add 2 complex numbers
Arguments:
complex1 {tuple} -- tuple of 2 representing the real and imaginary part
complex2 {tuple} -- tuple of 2 representing the real and imaginary part
Returns:
tuple -- tuple... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def collect(input, index, padding_idx=0):
"""
Perform a batched index select where index is given for each example
Args:
input: tensor of shape (B, T_1, dim_2, dim_3, ...)
index: tensor of shape (B, T_2)
Return:
tensor of shape (B, T_2, dim_2, dim_3, ...)
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def ndc_to_camera_space(Xn, P):
"""Transform point(s) from normalised device coordinates to camera space.
Args:
Xn (torch.Tensor): homogeneous point(s) in normalised device coordinates.
P (torch.Tensor): projection matrix.
Returns:
Xc (torch.Tensor): homogeneous poin... | bigcode/self-oss-instruct-sc2-concepts |
import time
def should_refresh(tok):
"""Returns True if the token must be refreshed because it expires soon."""
return time.time() > tok.expiry - 60 | bigcode/self-oss-instruct-sc2-concepts |
def strip_quotes(s):
"""Trim white space and, if necessary, quote characters from s."""
s = s.strip()
# Strip quotation mark characters from quoted strings.
if len(s) >= 3 and s[0] == '"' and s[-1] == '"':
s = s[1:-1]
return s | bigcode/self-oss-instruct-sc2-concepts |
def set_lifecycle_events_enabled(enabled: bool) -> dict:
"""Controls whether page will emit lifecycle events.
Parameters
----------
enabled: bool
If true, starts emitting lifecycle events.
**Experimental**
"""
return {"method": "Page.setLifecycleEventsEnabled", "params": {"enab... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
import re
def parse_dice_string(dice_string: str) -> Tuple[int, int]:
"""parses formatted string to a dice roll, e.g. "2D6" for rolling two
six-sided dice.
Args:
dice_string: formatted string for roll.
Returns:
tuple of the count and sides for the roll.
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_county_variants(county: str) -> list:
"""
Given a county, returns a list of the possible variants of the county name.
Args:
county: A string literal that represents the county name.
Returns:
A list of the possible variants of the county name.
"""
county = county.replac... | bigcode/self-oss-instruct-sc2-concepts |
def sniff_appendix_id_type(paragraphs):
"""
Detect whether an appendix follows the section paragraph indentation
scheme (a-1-i-A-1-i) or the appendix scheme (1-a)
The sniffer should return 'section', 'appendix', or None.
"""
for graph in paragraphs[:10]:
if graph.text.startswith('(a)'):... | bigcode/self-oss-instruct-sc2-concepts |
def obj_func(xl, arg):
"""Wraps a spreadsheet computation as a Python function."""
# Copy argument values to input range
xl.Range('Inputs').Value = [(float(x), ) for x in arg]
# Calculate after changing the inputs
xl.Calculate()
# Return the value of the output cell
result = xl.Range("Outp... | bigcode/self-oss-instruct-sc2-concepts |
def is_tree(character):
""" A tree character is defined as "#" """
return character == "#" | bigcode/self-oss-instruct-sc2-concepts |
def testset_single(paths, rgen):
"""
Returns a test set where each test corresponds to a single probing path.
This function is reproducible: iteration proceeds through the probing-path dictionary
in sorted order, and a random shuffle is applied before returning.
"""
testset = list()
for src... | bigcode/self-oss-instruct-sc2-concepts |
import getpass
def input_api_key() -> str:
"""Get the Meaki dashboard API key from the user's input.
-> Return the API key (string) with the leading & trailing whitespace
removed if the key is not a blank value.
"""
input_message = "Enter your Meraki's dashboard API Key: "
api_key = getpass.... | bigcode/self-oss-instruct-sc2-concepts |
import pkg_resources
def dump_env() -> list[str]:
"""
Get all packages and versions from the current environment.
conda list is slow, use pkg_resources instead
this might miss dev overrides
"""
return sorted(str(pkg) for pkg in pkg_resources.working_set) | bigcode/self-oss-instruct-sc2-concepts |
def body(expr):
"""Gets the body of a parsed lambda (represented as 2-tuples)"""
assert type(expr) == tuple
return expr[1] | bigcode/self-oss-instruct-sc2-concepts |
def key2param(key):
"""Converts key names into parameter names.
For example, converting "max-results" -> "max_results"
Args:
key: string, the method key name.
Returns:
A safe method name based on the key name.
"""
result = []
key = list(key)
if not key[0].isalpha():
result.append('x')
f... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def timestamp_to_ms(groups: Sequence[str]):
"""
Convert groups from :data:`pysubs2.time.TIMESTAMP` match to milliseconds.
Example:
>>> timestamp_to_ms(TIMESTAMP.match("0:00:00.42").groups())
420
"""
h, m, s, frac = map(int, groups)
ms = fra... | bigcode/self-oss-instruct-sc2-concepts |
def box_sz(b):
""" Returns the box size"""
return ((b[:, 2]-b[:, 0]) * (b[:, 3]-b[:, 1])) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import List
from typing import Any
def get_value(dictionary: Dict) -> List[Any]:
"""Return a list of values in a given dictionary."""
return list(dictionary.values()) | bigcode/self-oss-instruct-sc2-concepts |
import random
def split_test_from_training_data(network, ratio=0.1):
"""
Splits a given network into two networks with disjoint edges randomly.
"""
test_edges = random.sample(list(network.edges()), int(len(network.edges()) * ratio))
training_network = network.copy()
training_network.remove_edg... | bigcode/self-oss-instruct-sc2-concepts |
def invert_dictionary(aDict):
"""Transforms a dict so that keys become values and values become keys"""
return {v: k for k, v in aDict.items()} | bigcode/self-oss-instruct-sc2-concepts |
def expectation_value(state, operator):
"""
Calculates the expectation value of a superoperator for a quantum state.
Parameters
----------
state: np.ndarray
Vectorised density matrix of a quantum state.
operator: list of np.array
Quantum superoperator.
"""
return sum((s... | bigcode/self-oss-instruct-sc2-concepts |
def find_block_from_timestamp(
w3,
timestamp: int,
low: int = 0,
high: int = 0,
search_range: int = 150_000,
accuracy_range_seconds: int = 180):
"""
A basic algorithm to find a block number from a timestamp.
Args:
w3: web3 instance
timestamp: Target block timestamp
... | bigcode/self-oss-instruct-sc2-concepts |
def percentile(N, P):
"""
Find the percentile of a list of values
@parameter N - A list of values. N must be sorted.
@parameter P - A float value from 0.0 to 1.0
@return - The percentile of the values.
"""
if len(N)==0:
return 0.0
n = int(round(P * len(N) + 0.5))
return N[n-... | bigcode/self-oss-instruct-sc2-concepts |
def problem1(individual):
"""
Implements the first test problem ("bi-objetive Sphere Model").
Variables = 2
Objetives = 2
f(x) = (x'x, (x - a)'(x - a))' with a = (0, 1)' and a, x element of R^2.
Bounds [0, 1]
@author Cesar Revelo
"""
a = [0,1]
f1 = (individual[0] ** 2) + (... | bigcode/self-oss-instruct-sc2-concepts |
def get_team(teams, team_input):
"""
Returns desired Team from Teams
:type teams: Teams
:type team_input: string
:rtype: Team
"""
for team in teams:
if team_input.lower() in team.name.lower():
return team | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def _parse_online_cpus_string(raw_string) -> List[int]:
"""
Parses string returned by /sys/devices/system/cpu/online
and returns a list of online cores
"""
parsed_cpus_info = []
for nr in raw_string.split(','):
if '-' not in nr:
parsed_cpus_info.appe... | bigcode/self-oss-instruct-sc2-concepts |
def mimebundle_to_html(bundle):
"""
Converts a MIME bundle into HTML.
"""
if isinstance(bundle, tuple):
data, metadata = bundle
else:
data = bundle
html = data.get('text/html', '')
if 'application/javascript' in data:
js = data['application/javascript']
html +... | bigcode/self-oss-instruct-sc2-concepts |
def wrapM(monad):
"""
Takes a monad and wraps it so that any attribute that is not
in the monad is automaticall forwarded to the monad value.
Complexity: O(1)
params:
monad: the monad to wrap
returns: the proxy object
"""
class Proxy():
"""The monad proxy object"""
... | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def get_runner_constructor(suite_tag):
""" Returns the function to run for the test runner.
Args:
suite_tag: A str, locates the test runner for an API.
Returns:
A function to run the tests.
"""
module_name = "api_tests." + suite_tag.lower()
module = importlib.import_module(modul... | bigcode/self-oss-instruct-sc2-concepts |
def set_or_check_min(x, min_x, var_name):
""" If x is None, set its value to min_x; also check that it is at least min_x.
:param int|float x: the value to check
:param int|float min_x: minimum required value for x
:param str var_name: name of the variable (for error logging)
:return: set/checked val... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def batch(action, card_dir: Path, max_backup: int = 1):
"""Performs an `action` repeatedly across a given `region` and
`card_slot`.
Before using this function, ensure all parameters are valid.
Args:
action (function): the function to run in batch
card_dir (Pa... | bigcode/self-oss-instruct-sc2-concepts |
def numberOfUniqueTranscripts(transcripts):
""" Given a list of transcripts, return the number of unique names.
"""
names = set()
for t in transcripts:
if t not in names:
names.add(t)
return len(names) | bigcode/self-oss-instruct-sc2-concepts |
def _break(bitstring,groupsize):
"""
Break a binary string into groups of groupsize digits.
For example, _break('1100001111',4) returns '11 0000 1111'
:param bitstring: The ASCII binary string to break into groups
:param groupsize: The number of bits to group together in each group
:return: A st... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _is_file_exists(path: str) -> bool:
"""Whether the path is a file.
Args:
path: The file path.
Returns:
True if the path is a file, otherwise returns False.
"""
return Path(path).is_file() | bigcode/self-oss-instruct-sc2-concepts |
def get_alternated_ys(ys_count, low, high):
"""
A helper function generating y-positions for x-axis annotations, useful when some annotations positioned along the
x axis are too crowded.
:param ys_count: integer from 1 to 3.
:param low: lower bound of the area designated for annotations
:param h... | bigcode/self-oss-instruct-sc2-concepts |
def height2rate(height_of_rainfall, duration):
"""
calculate the specific rain flow rate in [l/(s*ha)]
if 2 array-like parameters are give, a element-wise calculation will be made.
So the length of the array must be the same.
Args:
height_of_rainfall (float | np.ndarray | pd.Series): height... | bigcode/self-oss-instruct-sc2-concepts |
import math
def round_up(number, precision=10.0):
"""Round a number up to the given precision.
Precision = 1.0 means 12345.6 gets rounded to 12346,
precision = 10.0 means 12345.6 gets rounded to 12350,
precision = 100.0 means 12345.6 gets rounded to 12400,
and so on.
"""
return math.ceil(number / precision... | bigcode/self-oss-instruct-sc2-concepts |
import math
def is_NaN(value):
"""
check value is nan or not
:param value:
:return: bool
"""
if isinstance(value, float):
return math.isnan(value)
else:
return value != value | bigcode/self-oss-instruct-sc2-concepts |
def wordCount(wordListDF):
"""Creates a DataFrame with word counts.
Args:
wordListDF (DataFrame of str): A DataFrame consisting of one string column called 'word'.
Returns:
DataFrame of (str, int): A DataFrame containing 'word' and 'count' columns.
"""
return (wordListDF.group... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Pattern
from typing import Tuple
import re
def parse_vector(s: str, *, num_re: Pattern = re.compile(r"[\d.-]+")) -> Tuple[float, ...]:
"""Convert a vector string into a tuple."""
return tuple(map(float, num_re.findall(s))) | bigcode/self-oss-instruct-sc2-concepts |
def param_name(p):
"""Extract parameter name from attributes.
Examples
--------
- ``fix_x`` -> ``x``
- ``error_x`` -> ``x``
- ``limit_x`` -> ``x``
"""
prefix = ["limit_", "error_", "fix_"]
for prf in prefix:
if p.startswith(prf):
i = len(prf)
return ... | bigcode/self-oss-instruct-sc2-concepts |
def get_datafile_save_path(direc):
"""
get_datafile_save_path(direc)
Returns directory path amended with data file subdirectory.
Required args:
- direc (Path): directory path
Returns:
- direc (Path): amended directory path
"""
direc = direc.joinpath("data_files")
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def is_valid_rule_one(character_count_range: List[int], character: str, password: str) -> bool:
"""
Return True if a password is abides to its asscoiated policy else return False
The policy is represented as follows: [1-3] a --> the character a should occur at least 1 time and at m... | bigcode/self-oss-instruct-sc2-concepts |
def sanitize_name(name: str) -> str:
"""Make a name safe for use as a keyspace name."""
# For now just change dashes to underscores. Fix this more in the future
return name.replace("-", "_") | bigcode/self-oss-instruct-sc2-concepts |
def dna_to_rna(seq):
"""
Converts DNA sequences to RNA sequences.
"""
rs = []
for s in seq:
if s == 'T':
rs.append('U')
else:
rs.append(s)
return "".join(rs) | bigcode/self-oss-instruct-sc2-concepts |
def problem_5_5(a, b):
""" Write a function to determine the number of bits required to convert
integer A to integer B.
Input: 31, 14
Output: 2
Solution: compute (a XOR b) and produce the number of 1 bits in the result.
"""
def num_set_bits(n):
count = 0
while n != 0:
... | bigcode/self-oss-instruct-sc2-concepts |
def is_aa_by_target_atoms(res):
"""Tell if a Residue object is AA
Args:
res: a Bio.PDB.Residue object representing the residue.
Return:
Bool. Wheather or not the residue is AA.
"""
target_atoms = ["N", "CA", "C", "O"]
for atom in target_atoms:
try:
res[atom]
... | bigcode/self-oss-instruct-sc2-concepts |
def extract_tags(lexicon):
"""Extract the set of all tags that are used in a lexicon.
The input lexicon should be a dict:
- lexicon = {wordform: {annotation: set(possible tags)}}
"""
tags = set()
for annotations in list(lexicon.values()):
tags.update(*list(annotations.values()))
r... | bigcode/self-oss-instruct-sc2-concepts |
def get_index_lm(l, m):
"""
return the index of an array ordered as
[l=0 m=0, l=1 m=-1, l=1 m=0, l=1 m=1, ....]
"""
return (l+1)**2 -1 -l + m | bigcode/self-oss-instruct-sc2-concepts |
def has_overflow(grad_norm):
"""
Detect inf and NaN in grad_norm.
"""
if grad_norm == float('inf') or grad_norm != grad_norm:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def mac_to_oid(mac):
"""
Converts a MAC address to an OID string
"""
return '.'.join([ str(int(x,16)) for x in mac.split(':') ]) | bigcode/self-oss-instruct-sc2-concepts |
def stuhlinger_velocity(total_efficiency, t_m, specific_mass):
"""Stuhlinger velocity, a characteristic velocity for electric propulsion missions.
The Stuhlinger velocity is a characteristic velocity for electric propulsion missions,
and is used in calculation of optimal specific impulse. It is defined as:... | bigcode/self-oss-instruct-sc2-concepts |
def real_part_of_complex_image(image_complex):
""" Returns a matrix of only the real parts of the elements of the input matrix """
return image_complex.real | bigcode/self-oss-instruct-sc2-concepts |
def is_solution(cnf, assignment):
"""Test whether the given assignment is a solution to the CNF.
assignment is a dictionary from variable names to truth values.
It is not required that all variables in the CNF are assigned.
"""
for clause in cnf:
satisfied = False
for lit in clause... | bigcode/self-oss-instruct-sc2-concepts |
import random
def weighted_choice(choices):
"""
Provides a weighted version of random.choice
:param choices: A dictionary of choices, with the choice as the key and weight the value
:type choices: list of tuple of (str, int)
"""
total = sum(weight for choice, weight in choices)
rand = ran... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_crashes_by_location(df):
"""
Calculates total number of crashes that occurred at each unique lat/lng pair and
generates a comma-separated string of the dates that crashes occurred at that location
Inputs:
- a dataframe where each row represents one unique crash incident
Outpu... | bigcode/self-oss-instruct-sc2-concepts |
def get_loopbacks(yaml):
"""Return a list of all loopbacks."""
ret = []
if "loopbacks" in yaml:
for ifname, _iface in yaml["loopbacks"].items():
ret.append(ifname)
return ret | bigcode/self-oss-instruct-sc2-concepts |
def mara_db_alias() -> str:
"""The database alias for mara internal data"""
return 'mara' | bigcode/self-oss-instruct-sc2-concepts |
def prod_boiler(info):
"""
Boiler plate text for On-Demand Info for products breakdown
:param info: values to insert into the boiler plate
:param info: dict
:return: formatted string
"""
boiler = ('\n==========================================\n'
' {title}\n'
'===... | bigcode/self-oss-instruct-sc2-concepts |
def _unpad_img(padded_img, window_size, subdivisions):
"""
Undo what's done in the `_pad_img` function.
Image is an np array of shape (x, y, nb_channels).
"""
aug = int(round(window_size * (1 - 1.0/subdivisions)))
ret = padded_img[
aug:-aug,
aug:-aug,
:
]
# gc.col... | bigcode/self-oss-instruct-sc2-concepts |
def _conv_edges(x, y, fx, fy, sx, sy, n_in, n_out, g=1):
"""Number of edges in convolution."""
nx = (x - fx) / sx + 1
ny = (y - fy) / sy + 1
return (fx * fy * nx * ny * n_in * n_out) / g | bigcode/self-oss-instruct-sc2-concepts |
def return_group1(code_check):
"""
Input : L/G/R 6 character
Return : First digits of barcode
"""
if code_check == 'LLLLLL':
return 0
elif code_check == 'LLGLGG':
return 1
elif code_check == 'LLGGLG':
return 2
elif code_check == 'LLGGGL':
return 3
elif... | bigcode/self-oss-instruct-sc2-concepts |
def fdtfile2fieldstring(fdtfile):
"""Make a string of field definitions separated by % (percent sign)
reading from a fdtfile or just take the string and bring into shape:
e.g. 1,AA,20,A,NC,NN%1,F4,4,F,NU,DT=E(UNIXTIME)
:param fdtfile: fdtfile or field string
:return: tuple (number of fields... | bigcode/self-oss-instruct-sc2-concepts |
import json
def retrieve_history(dataset):
"""
Retrieve history_json field from NetCDF dataset, if it exists
Parameters
----------
dataset : netCDF4.Dataset
NetCDF Dataset representing a single granule
Returns
-------
dict
history_json field
"""
if 'history_js... | bigcode/self-oss-instruct-sc2-concepts |
def get_traces_as_tokens(traces_df, col_ref="Activity"):
"""
Groups activities executions into traces
as a string of tokens
Ex:
Activity | Timestamp
-----------------------
START | 2019-09-01
A | 2019-09-01
B ... | bigcode/self-oss-instruct-sc2-concepts |
def str_to_disp(s):
"""Convert a string to a user-friendly, displayable string by replacing
underscores with spaces and trimming outer whitespace.
Args:
s: String to make displayable.
Returns:
New, converted string.
"""
return s.replace("_", " ").strip() | 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.