seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_longest_repeating_substring(input_string: str) -> str:
"""
Algorithm for getting the longest repeating substring from a string
Complexity --> O(N)
:param input_string: str
:return longest_substring: str
"""
longest_substring = ""
local_longest_substring = input_string[0]
for i in range(1, len(input_string)):
if local_longest_substring[0] == input_string[i]:
local_longest_substring += input_string[i]
else:
local_longest_substring = input_string[i]
if len(local_longest_substring) > len(longest_substring):
longest_substring = local_longest_substring
return longest_substring | bigcode/self-oss-instruct-sc2-concepts |
def count_mol_weights(mol_weights):
"""
Count the number of weights in each bin, and
return a list of counts.
"""
counts = [0 for _ in range(9)]
for mol_weight in mol_weights:
if mol_weight < 250:
counts[0] += 1
elif 250 <= mol_weight < 300:
counts[1] += 1
elif 300 <= mol_weight < 325:
counts[2] += 1
elif 325 <= mol_weight < 350:
counts[3] += 1
elif 350 <= mol_weight < 375:
counts[4] += 1
elif 375 <= mol_weight < 400:
counts[5] += 1
elif 400 <= mol_weight < 425:
counts[6] += 1
elif 425 <= mol_weight < 450:
counts[7] += 1
else:
counts[8] += 1
return counts | bigcode/self-oss-instruct-sc2-concepts |
import bisect
def bottom_values(values, period=None, num=1):
"""Returns list of bottom num items.
:param values: list of values to iterate and compute stat.
:param period: (optional) # of values included in computation.
* None - includes all values in computation.
:param num: the num in the bottom num items.
:rtype: list of windowed bottom num items.
Examples:
>>> values = [34, 30, 29, 34, 38, 25, 35]
>>> bottom_values(values, 3, 2) #3 period window and top 2 items.
[[34], [30, 34], [29, 30], [29, 30], [29, 34], [25, 34], [25, 35]]
"""
if period:
if period < 1:
raise ValueError("period must be 1 or greater")
period = int(period)
if num:
num = int(num)
results = []
recs = []
_additem = bisect.insort
_search = bisect.bisect_left
for bar, newx in enumerate(values):
if period and (bar >= period):
item = values[bar - period]
idx = _search(recs, item)
del recs[idx]
_additem(recs, newx)
endidx = num
if bar < num - 1:
endidx = bar + 1
lastval = recs[0:endidx]
results.append(lastval)
return results | bigcode/self-oss-instruct-sc2-concepts |
def safemax(data, default=0):
""" Return maximum of array with default value for empty array
Args:
data (array or list ): data to return the maximum
default (obj): default value
Returns:
object: maximum value in the array or the default value
"""
if isinstance(data, list):
if len(data) == 0:
maximum_value = default
else:
maximum_value = max(data)
return maximum_value
if data.size == 0:
maximum_value = default
else:
maximum_value = data.max()
return maximum_value | bigcode/self-oss-instruct-sc2-concepts |
import tqdm
def _pbar(x):
"""Create a tqdm progress bar"""
return tqdm.tqdm(x, ascii=True, unit=" scans") | bigcode/self-oss-instruct-sc2-concepts |
def is_yaml(file_path: str) -> bool:
"""Returns True if file_path is YAML, else False
Args:
file_path: Path to YAML file.
Returns:
True if is yaml, else False.
"""
if file_path.endswith("yaml") or file_path.endswith("yml"):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sha256_file(filename):
"""Calculate sha256 hash of file
"""
buf_size = 65536 # lets read stuff in 64kb chunks!
sha256 = hashlib.sha256()
with open(filename, '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 |
import re
def extract_thread_list(trace_data):
"""Removes the thread list from the given trace data.
Args:
trace_data: The raw trace data (before decompression).
Returns:
A tuple containing the trace data and a map of thread ids to thread names.
"""
threads = {}
parts = re.split('USER +PID +PPID +VSIZE +RSS +WCHAN +PC +NAME',
trace_data, 1)
if len(parts) == 2:
trace_data = parts[0]
for line in parts[1].splitlines():
cols = line.split(None, 8)
if len(cols) == 9:
tid = int(cols[1])
name = cols[8]
threads[tid] = name
return (trace_data, threads) | bigcode/self-oss-instruct-sc2-concepts |
def getDuration(timesarr):
"""
gets the duration of the input time array
:param timesarr: array of times as returned by readCSV
:returns: Duration for which there are times
"""
dur = max(timesarr)-min(timesarr)
return dur | bigcode/self-oss-instruct-sc2-concepts |
def landsat_ts_norm_diff(collection, bands=['Green', 'SWIR1'], threshold=0):
"""Computes a normalized difference index based on a Landsat timeseries.
Args:
collection (ee.ImageCollection): A Landsat timeseries.
bands (list, optional): The bands to use for computing normalized difference. Defaults to ['Green', 'SWIR1'].
threshold (float, optional): The threshold to extract features. Defaults to 0.
Returns:
ee.ImageCollection: An ImageCollection containing images with values greater than the specified threshold.
"""
nd_images = collection.map(lambda img: img.normalizedDifference(
bands).gt(threshold).copyProperties(img, img.propertyNames()))
return nd_images | bigcode/self-oss-instruct-sc2-concepts |
import json
def fromJSON(json_file):
"""load json with utf8 encoding"""
with open(str(json_file),"r", encoding='utf8') as fp:
return json.load(fp) | bigcode/self-oss-instruct-sc2-concepts |
def get_node_attributes(G, name):
"""Get node attributes from graph
Parameters
----------
G : NetworkX Graph
name : string
Attribute name
Returns
-------
Dictionary of attributes keyed by node.
Examples
--------
>>> G=nx.Graph()
>>> G.add_nodes_from([1,2,3],color='red')
>>> color=nx.get_node_attributes(G,'color')
>>> color[1]
'red'
"""
return dict( (n,d[name]) for n,d in G.node.items() if name in d) | bigcode/self-oss-instruct-sc2-concepts |
def calc_downsample(w, h, target=400):
"""Calculate downsampling value."""
if w > h:
return h / target
elif h >= w:
return w / target | bigcode/self-oss-instruct-sc2-concepts |
import re
def camel_case_split(text: str) -> list:
"""camel_case_split splits strings if they're in CamelCase and need to be not Camel Case.
Args:
str (str): The target string to be split.
Returns:
list: A list of the words split up on account of being Camel Cased.
"""
return re.findall(r"[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))", text) | bigcode/self-oss-instruct-sc2-concepts |
def hex_to_bytes(data):
"""Convert an hex string to bytes"""
return bytes.fromhex(data) | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def multiline_fix(s):
"""Remove indentation from a multi-line string."""
return textwrap.dedent(s).lstrip() | bigcode/self-oss-instruct-sc2-concepts |
def oc2_pair(actuator_nsid, action_name, target_name):
"""Decorator for your Consumer/Actuator functions.
Use on functions you implement when inheriting
from OpenC2CmdDispatchBase.
Example:
class MyDispatch(OOpenC2CmdDispatchBase):
...
@oc2_pair('slpf', 'deny', 'ipv4_connection')
def some_function(oc2_cmd):
return OC2Response()
"""
def _register(method):
method.is_oc2_pair = True
method.actuator_nsid = actuator_nsid
method.action_name = action_name
method.target_name = target_name
return method
return _register | bigcode/self-oss-instruct-sc2-concepts |
def round_next (x,step):
"""Rounds x up or down to the next multiple of step."""
if step == 0: return x
return round(x/step)*step | bigcode/self-oss-instruct-sc2-concepts |
def trim_seq(seq):
"""
Remove 'N's and non-ATCG from beginning and ends
"""
good = ['A','T','C','G']
seq = seq.upper()
n = len(seq)
i = 0
while i < n and seq[i] not in good: i += 1
j = len(seq)-1
while j >= 0 and seq[j] not in good: j -= 1
return seq[i:j+1] | bigcode/self-oss-instruct-sc2-concepts |
def _extract_patch(img_b, coord, patch_size):
""" Extract a single patch """
x_start = int(coord[0])
x_end = x_start + int(patch_size[0])
y_start = int(coord[1])
y_end = y_start + int(patch_size[1])
patch = img_b[:, x_start:x_end, y_start:y_end]
return patch | bigcode/self-oss-instruct-sc2-concepts |
def do_sql(conn, sql, *vals):
"""
issue an sql query on conn
"""
# print(sql, vals)
return conn.execute(sql, vals) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def sigma(a: Iterable[int]) -> int:
"""Returns sum of the list of int"""
return sum(a) | bigcode/self-oss-instruct-sc2-concepts |
def merge(d1, d2):
"""
Merge two dictionaries. In case of duplicate keys, this function will return values from the 2nd dictionary
:return dict: the merged dictionary
"""
d3 = {}
if d1:
d3.update(d1)
if d2:
d3.update(d2)
return d3 | bigcode/self-oss-instruct-sc2-concepts |
def obs_to_dict(obs):
"""
Convert an observation into a dict.
"""
if isinstance(obs, dict):
return obs
return {None: obs} | bigcode/self-oss-instruct-sc2-concepts |
import math
def convert_state_to_hex(state: str) -> str:
"""
This assumes that state only has "x"s and Us or Ls or Fs or Rs or Bs or Ds
>>> convert_state_to_hex("xxxU")
'1'
>>> convert_state_to_hex("UxUx")
'a'
>>> convert_state_to_hex("UUxUx")
'1a'
"""
state = (
state.replace("x", "0")
.replace("-", "0")
.replace("U", "1")
.replace("L", "1")
.replace("F", "1")
.replace("R", "1")
.replace("B", "1")
.replace("D", "1")
)
hex_width = int(math.ceil(len(state) / 4.0))
hex_state = hex(int(state, 2))[2:]
if hex_state.endswith("L"):
hex_state = hex_state[:-1]
return hex_state.zfill(hex_width) | bigcode/self-oss-instruct-sc2-concepts |
def _lat_hemisphere(latitude):
"""Return the hemisphere (N, S or '' for 0) for the given latitude."""
if latitude > 0:
hemisphere = 'N'
elif latitude < 0:
hemisphere = 'S'
else:
hemisphere = ''
return hemisphere | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
import operator
def _get_longest_palindrome_boundaries(lps_table: List[int]) -> Tuple[int, int]:
"""Returns real text longest palindrome boundaries based from its lps table.
"""
center_index, radius = max(enumerate(lps_table), key=operator.itemgetter(1))
start = (center_index - (radius - 1)) // 2
end = (center_index + radius) // 2
return start, end | bigcode/self-oss-instruct-sc2-concepts |
def parse_word(word):
"""
Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair.
"""
mapping = {'yes': True, 'true': True, 'no': False, 'false': False}
_, key, value = word.split('=', 2)
try:
value = int(value)
except ValueError:
value = mapping.get(value, value)
return (key, value) | bigcode/self-oss-instruct-sc2-concepts |
def merge_sort(nsl: list) -> list:
"""
function sorts an array by a merge method.
:param nsl: type list: non sorted list
:return: type list: list after merge sort
"""
sl = nsl[:]
n = len(nsl)
if n < 2:
return sl
else:
left_arr = merge_sort(nsl=nsl[:n//2])
right_arr = merge_sort(nsl=nsl[n//2:n])
sl = []
i = 0
j = 0
while i < len(left_arr) or j < len(right_arr):
if not (i < len(left_arr)):
sl.append(right_arr[j])
j += 1
elif not (j < len(right_arr)):
sl.append(left_arr[i])
i += 1
elif not (left_arr[i] > right_arr[j]):
sl.append(left_arr[i])
i += 1
else:
sl.append(right_arr[j])
j += 1
return sl | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json(filename):
"""
Deserializes json formatted string from filename (text file) as a dictionary.
:param filename: string
"""
with open(filename) as f:
return json.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def redshift2dist(z, cosmology):
""" Convert redshift to comoving distance in units Mpc/h.
Parameters
----------
z : float array like
cosmology : astropy.cosmology instance
Returns
-------
float array like of comoving distances
"""
return cosmology.comoving_distance(z).to('Mpc').value * cosmology.h | bigcode/self-oss-instruct-sc2-concepts |
def first_half(dayinput):
"""
first half solver:
Starting with a frequency of zero, what is the resulting
frequency after all of the changes in frequency have been applied?
"""
lines = dayinput.split('\n')
result = 0
for freq in lines:
result += int(freq)
return result | bigcode/self-oss-instruct-sc2-concepts |
def reorder(x, indexList=[], indexDict={}):
"""
Reorder a list based upon a list of positional indices and/or a dictionary of fromIndex:toIndex.
>>> l = ['zero', 'one', 'two', 'three', 'four', 'five', 'six']
>>> reorder( l, [1, 4] ) # based on positional indices: 0-->1, 1-->4
['one', 'four', 'zero', 'two', 'three', 'five', 'six']
>>> reorder( l, [1, None, 4] ) # None can be used as a place-holder
['one', 'zero', 'four', 'two', 'three', 'five', 'six']
>>> reorder( l, [1, 4], {5:6} ) # remapping via dictionary: move the value at index 5 to index 6
['one', 'four', 'zero', 'two', 'three', 'six', 'five']
"""
x = list(x)
num = len(x)
popCount = 0
indexValDict = {}
for i, index in enumerate(indexList):
if index is not None:
val = x.pop(index - popCount)
assert index not in indexDict, indexDict
indexValDict[i] = val
popCount += 1
for k, v in indexDict.items():
indexValDict[v] = x.pop(k - popCount)
popCount += 1
newlist = []
for i in range(num):
try:
val = indexValDict[i]
except KeyError:
val = x.pop(0)
newlist.append(val)
return newlist | bigcode/self-oss-instruct-sc2-concepts |
def textarea_to_list(text: str):
"""Converts a textarea into a list of strings, assuming each line is an
item. This is meant to be the inverse of `list_to_textarea`.
"""
res = [x.strip() for x in text.split("\n")]
res = [x for x in res if len(x) > 0]
return res | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def iterdir(path):
"""Return directory listing as generator"""
return Path(path).iterdir() | bigcode/self-oss-instruct-sc2-concepts |
import re
def count_ops_in_hlo_proto(hlo_proto,
ops_regex):
"""Counts specific ops in hlo proto, whose names match the provided pattern.
Args:
hlo_proto: an HloModuleProto object.
ops_regex: a string regex to filter ops with matching names.
Returns:
Count of matching ops.
"""
ops_count = 0
for computation in hlo_proto.computations:
for instr in computation.instructions:
if re.match(ops_regex, instr.name) is not None:
ops_count += 1
return ops_count | bigcode/self-oss-instruct-sc2-concepts |
def list_diff(l1: list, l2: list):
""" Return a list of elements that are present in l1
or in l2 but not in both l1 & l2.
IE: list_diff([1, 2, 3, 4], [2,4]) => [1, 3]
"""
return [i for i in l1 + l2 if i not in l1 or i not in l2] | bigcode/self-oss-instruct-sc2-concepts |
def get_list_sig_variants(file_name):
"""
Parses through the significant variants file
and creates a dictionary of variants and their
information for later parsing
: Param file_name: Name of file being parsed
: Return sig_variants_dict: A dictionary of significant results
"""
sig_variants_dict = {}
sig_variants_file = open(file_name, 'r')
# Skipping the header
for line in sig_variants_file:
if line.startswith('#CHROM'):
continue
# Getting the actual data to create a dictionary
else:
parsed_line = line.rstrip().split('\t')
variant_name = parsed_line[0] + ":" + parsed_line[1]
variant_info = parsed_line[:8]
sig_variants_dict.update({variant_name: variant_info})
# Closing the file
sig_variants_file.close()
return(sig_variants_dict) | bigcode/self-oss-instruct-sc2-concepts |
def attack_successful(prediction, target, targeted):
"""
See whether the underlying attack is successful.
"""
if targeted:
return prediction == target
else:
return prediction != target | bigcode/self-oss-instruct-sc2-concepts |
def merge(elements):
"""Merge Sort algorithm
Uses merge sort recursively to sort a list of elements
Parameters
elements: List of elements to be sorted
Returns
list of sorted elements
"""
def list_merge(a, b):
"""Actual "merge" of two lists
Compares every member of a list and returns a new list with
sorted elements
Parameters
a, b: Lists of elements to be sorted
Returns
list of sorted elements
"""
#initialize some values
len_a = len(a)
len_b = len(b)
a_i = b_i = 0
c = []
for i in range(len_a + len_b):
#check which element is the smaller
#and place it into c list
if a_i < len_a and b_i < len_b:
if a[a_i] < b[b_i]:
c.append(a[a_i])
a_i = a_i+1
else:
c.append(b[b_i])
b_i = b_i+1
else:
#when we are done with one list append pending values of the other one
if a_i == len_a:
# append all pending b values into c
return c + b[b_i:]
if b_i == len_b:
# same as above but with a values
return c + a[a_i:]
length = len(elements)
if length <= 1:
#ending condition
return elements
half = int(length/2)
#recursive call for both halfs of elements
#divide and conquer
return list_merge(merge(elements[:half]), merge(elements[half:])) | bigcode/self-oss-instruct-sc2-concepts |
def map_structure(func, structure, args=(), kwargs={}):
"""apply func to each element in structure
Args:
func (callable): The function
structure (dict, tuple, list): the structure to be mapped.
Kwargs:
args (tuple,list): The args to the function.
kwargs (dict): The kwargs to the function.
Returns: The same structure as input structure.
"""
if structure is None:
return None
if isinstance(structure, (list, tuple)):
return [func(x, *args, **kwargs) for x in structure]
if isinstance(structure, dict):
returns = dict()
for key, value in structure.items():
returns[key] = func(value, *args, **kwargs)
return returns
else:
return func(structure, *args, **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
def is_a_monitoring_request(request):
"""Returns True it the input request is for monitoring or health check
purposes
"""
# does the request begin with /health?
return request.get_full_path()[:7] == '/health' | bigcode/self-oss-instruct-sc2-concepts |
def num2songrandom(num: str) -> int:
"""
将用户输入的随机歌曲范围参数转为发送给 API 的数字
Algorithm: (ratingNumber * 2) + (ratingPlus ? 1 : 0)
Example: '9+' -> 19
"""
return int(num.rstrip('+')) * 2 + (1 if num.endswith('+') else 0) | bigcode/self-oss-instruct-sc2-concepts |
def pad(size, padding):
"""Apply padding to width and height.
:param size: two-tuple of width and height
:param padding: padding to apply to width and height
:returns: two-tuple of width and height with padding applied
"""
width = size[0] + padding.left + padding.right
height = size[1] + padding.top + padding.bottom
return (width, height) | bigcode/self-oss-instruct-sc2-concepts |
def _parse_input_list(input_list: str) -> list[str]:
"""
Converts a CSV list of assets IDs into a list of parsed IDs (but not Asset objects)
"""
return [fqn_id for fqn_id in input_list.split(",") if fqn_id != "" and fqn_id != ":"] | bigcode/self-oss-instruct-sc2-concepts |
def count_where(predicate, iterable):
"""
Count the number of items in iterable that satisfy
the predicate
"""
return sum(1 for x in iterable if predicate(x)) | bigcode/self-oss-instruct-sc2-concepts |
def add_default_value_to(description, default_value):
"""Adds the given default value to the given option description."""
# All descriptions end with a period, so do not add another period.
return '{} Default: {}.'.format(description,
default_value if default_value else '""') | bigcode/self-oss-instruct-sc2-concepts |
def derive_order_id(user_uid: str, cl_order_id: str, ts: int, order_src='a') -> str:
"""
Server order generator based on user info and input.
:param user_uid: user uid
:param cl_order_id: user random digital and number id
:param ts: order timestamp in milliseconds
:param order_src: 'a' for rest api order, 's' for websocket order.
:return: order id of length 32
"""
return (order_src + format(ts, 'x')[-11:] + user_uid[-11:] + cl_order_id[-9:])[:32] | bigcode/self-oss-instruct-sc2-concepts |
def get_edge(source, target, interaction):
"""
Get the edge information in JSON format.
:param source: the id or name of source node.
:param target: the id or name of target node.
:param interaction: the interaction of edge.
:return : the JSON value about edge.
"""
if interaction is None:
itr = '-'
else:
itr = interaction
edge = {
'data': {
'source': source,
'target': target,
'interaction': itr
}
}
return edge | bigcode/self-oss-instruct-sc2-concepts |
def is_invocation(event):
"""Return whether the event is an invocation."""
attachments = event.get("attachments")
if attachments is None or len(attachments) < 1:
return False
footer = attachments[0].get("footer", "")
if footer.startswith("Posted using /giphy"):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def calc_prof(ability, profs, prof_bonus):
"""
Determine if proficiency modifier needs to be applied.
If character has expertise in selected skill, double the proficiency bonus.
If character has proficiency in selected skill/ability/save,
prof_mod = prof_bonus (multiply by 1).
If character has no proficiency in selected skill/ability/save,
prof_mod = 0 (no bonus).
"""
if ability in profs.keys():
prof_mod = profs[ability] * int(prof_bonus)
else:
prof_mod = 0
return prof_mod | bigcode/self-oss-instruct-sc2-concepts |
def inexact(pa, pb, pc, pd):
"""Tests whether pd is in circle defined by the 3 points pa, pb and pc
"""
adx = pa[0] - pd[0]
bdx = pb[0] - pd[0]
cdx = pc[0] - pd[0]
ady = pa[1] - pd[1]
bdy = pb[1] - pd[1]
cdy = pc[1] - pd[1]
bdxcdy = bdx * cdy
cdxbdy = cdx * bdy
alift = adx * adx + ady * ady
cdxady = cdx * ady
adxcdy = adx * cdy
blift = bdx * bdx + bdy * bdy
adxbdy = adx * bdy
bdxady = bdx * ady
clift = cdx * cdx + cdy * cdy
det = alift * (bdxcdy - cdxbdy) + \
blift * (cdxady - adxcdy) + \
clift * (adxbdy - bdxady)
return det | bigcode/self-oss-instruct-sc2-concepts |
def oef_port() -> int:
"""Port of the connection to the OEF Node to use during the tests."""
return 10000 | bigcode/self-oss-instruct-sc2-concepts |
def get_input(filename):
"""returns list of inputs from data file. File should have integer values,
one per line.
Args:
filename: the name of the file with the input data.
Returns:
a list of integers read from the file
"""
text_file = open(filename, "r")
input_strs = text_file.readlines()
text_file.close()
input_ints = list(map(int, input_strs))
return input_ints | bigcode/self-oss-instruct-sc2-concepts |
def tuple_for_testing(model, val, replace_i):
"""this function creates a tuple by changing only one parameter from a list
Positionnal arguments :
model -- a list of valid arguments to pass to the object to test
val -- the value you want to put in the list
replace_i -- the index of the value to be replaced
Returns :
tuple
"""
m_copy = model.copy()
m_copy[replace_i]=val
return tuple(m_copy) | bigcode/self-oss-instruct-sc2-concepts |
def all_entities_on_same_layout(entities):
""" Check if all entities are on the same layout (model space or any paper layout but not block).
"""
owners = set(entity.dxf.owner for entity in entities)
return len(owners) < 2 | bigcode/self-oss-instruct-sc2-concepts |
def merge_dicts(dicts_a, dicts_b):
"""Merges two lists of dictionaries by key attribute.
Example:
da = [{'key': 'a', 'value': 1}, {'key': 'b', 'value': 2}]
db = [{'key': 'b', 'value': 3, 'color':'pink'}, {'key': 'c', 'value': 4}]
merge_dicts(da, db) = [{'key': 'a', 'value': 1}, {'key': 'b', 'value': 3, 'color':'pink'}]
Args:
dicts_a (list of objs): First dictionary.
dicts_b (list of objs): Second dictionary.
Returns:
list of objs: List of merged dicts.
"""
for dict_a in dicts_a:
for dict_b in dicts_b:
if dict_a['key'] == dict_b['key']:
for k, v in dict_b.items():
dict_a[k] = v
return dicts_a | bigcode/self-oss-instruct-sc2-concepts |
def parenthesize(s):
"""
>>> parenthesize('1')
'1'
>>> parenthesize('1 + 2')
'(1 + 2)'
"""
if ' ' in s:
return '(%s)' % s
else:
return s | bigcode/self-oss-instruct-sc2-concepts |
def _PiecewiseConcat(*args):
"""Concatenates strings inside lists, elementwise.
Given ['a', 's'] and ['d', 'f'], returns ['ad', 'sf']
"""
return map(''.join, zip(*args)) | bigcode/self-oss-instruct-sc2-concepts |
def brute_force(s: str) -> int:
"""
Finds the length of the longest substring in s without repeating characters.
Parameters
----------
s : str
Given string.
Returns:
int
Length of the longest substring in s without repeating characters.
Speed Analysis: O(n), no matter how you implement this algorithm, all of the characters will need to be checked.
Memory Analysis: O(n), the initial string is going to be the largest memory element with a possible substring as
large as the initial string, but no greater than that.
"""
substring = set()
max_len = 0
i = 0
while s:
char = s[i]
if char not in substring:
substring.add(char)
i += 1
if i >= len(s):
max_len = max(max_len, len(substring))
break
continue
else:
max_len = max(max_len, len(substring))
s = s[1:]
if max_len > len(s):
break
substring = set()
i = 0
return max_len | bigcode/self-oss-instruct-sc2-concepts |
def get_box(mol, padding=1.0):
"""
Given a molecule, find a minimum orthorhombic box containing it.
Size is calculated using min and max x, y, and z values.
For best results, call oriented_molecule first.
Args:
mol: a pymatgen Molecule object
padding: the extra space to be added in each direction. Double this
amount will be added to each of the x, y, and z directions
Returns:
a list [x1,x2,y1,y2,z1,z2] where x1 is the relative displacement in
the negative x direction, x2 is the displacement in the positive x
direction, and so on
"""
minx, miny, minz, maxx, maxy, maxz = 0.,0.,0.,0.,0.,0.
for i, p in enumerate(mol):
x, y, z = p.coords
if x < minx: minx = x
if y < minx: minx = y
if z < minx: minx = z
if x > maxx: maxx = x
if y > maxx: maxx = y
if z > maxx: maxx = z
return [minx-padding,maxx+padding,miny-padding,maxy+padding,minz-padding,maxz+padding] | bigcode/self-oss-instruct-sc2-concepts |
def is_maximum_local(index, relative_angles, radius):
"""
Determine if a point at index is a maximum local in radius range of relative_angles function
:param index: index of the point to check in relative_angles list
:param relative_angles: list of angles
:param radius: radius used to check neighbors
:return: Boolean
"""
start = max(0, index - radius)
end = min(relative_angles.shape[0] - 1, index + radius)
for i in range(start, end + 1):
if relative_angles[i] > relative_angles[index]:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def get_clean_name(name, char='-'):
"""
Return a string that is lowercase and all whitespaces are replaced
by a specified character.
Args:
name: The string to be cleaned up.
char: The character to replace all whitespaces. The default
character is "-" (hyphen).
Returns:
A string that is fully lowercase and all whitespaces replaced by
the specified character.
>>> get_clean_name('Random teXt')
'random-text'
>>> get_clean_name('Random teXt', '#')
'random#text'
"""
return name.lower().replace(' ', char) | bigcode/self-oss-instruct-sc2-concepts |
def decrement(field):
"""
Decrement a given field in the element.
"""
def transform(element):
element[field] -= 1
return transform | bigcode/self-oss-instruct-sc2-concepts |
def read_list_of_filepaths(list_filepath):
"""
Reads a .txt file of line seperated filepaths and returns them as a list.
"""
return [line.rstrip() for line in open(list_filepath, 'r')] | bigcode/self-oss-instruct-sc2-concepts |
def gatherKeys(data):
"""Gather all the possible keys in a list of dicts.
(Note that voids in a particular row aren't too bad.)
>>> from shared.tools.examples import complexListDict
>>> gatherKeys(complexListDict)
['date', 'double', 'int', 'string']
"""
keys = set()
for row in data:
keys.update(row)
return sorted(list(keys)) | bigcode/self-oss-instruct-sc2-concepts |
def read_file(path):
"""Reads file"""
with open(path) as file:
return file.readlines() | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sigmoid(z):
"""Applies sigmoid to z."""
return 1/(1 + torch.exp(-z)) | bigcode/self-oss-instruct-sc2-concepts |
import base64
def decode64(string):
""" Decode a string from base64 """
return base64.b64decode(string) | bigcode/self-oss-instruct-sc2-concepts |
import threading
import time
def rate_limited(num_calls=1, every=1.0):
"""Rate limit a function on how often it can be called
Source: https://github.com/tomasbasham/ratelimit/tree/0ca5a616fa6d184fa180b9ad0b6fd0cf54c46936 # noqa E501
Args:
num_calls (float, optional): Maximum method invocations within a period.
Must be greater than 0. Defaults to 1
every (float): A dampening factor (in seconds).
Can be any number greater than 0. Defaults to 1.0
Returns:
function: Decorated function that will forward method invocations
if the time window has elapsed.
"""
frequency = abs(every) / float(num_calls)
def decorator(func):
"""
Extend the behavior of the following function,
forwarding method invocations if the time window hes elapsed.
Args:
func (function): The function to decorate
Returns:
function: Decorated function
"""
# To get around issues with function local scope
# and reassigning variables, we wrap the time
# within a list. When updating the value we're
# not reassigning `last_called`, which would not
# work, but instead reassigning the value at a
# particular index.
last_called = [0.0]
# Add thread safety
lock = threading.RLock()
def wrapper(*args, **kwargs):
"""Decorator wrapper function"""
with lock:
elapsed = time.time() - last_called[0]
left_to_wait = frequency - elapsed
if left_to_wait > 0:
time.sleep(left_to_wait)
last_called[0] = time.time()
return func(*args, **kwargs)
return wrapper
return decorator | bigcode/self-oss-instruct-sc2-concepts |
def throttling_mod_func(d, e):
"""Perform the modular function from the throttling array functions.
In the javascript, the modular operation is as follows:
e = (e % d.length + d.length) % d.length
We simply translate this to python here.
"""
return (e % len(d) + len(d)) % len(d) | bigcode/self-oss-instruct-sc2-concepts |
import math
def dimension_of_bounding_square(number):
"""Find the smallest binding square, e.g.
1x1, 3x3, 5x5
Approach is to assume that the number is the largest
that the bounding square can contain.
Hence taking the square root will find the length of the
side of the bounding square.
The actual bounding squares all have integer length that is odd
( due to the wrapping action of forming a spiral)
Hence find the actual length by rounding the square root to the next
integer odd number."""
approximate_dimension = math.ceil((math.sqrt(number)))
return approximate_dimension + (1 - (approximate_dimension % 2)) | bigcode/self-oss-instruct-sc2-concepts |
def key_has_granted_prefix(key, prefixes):
"""
Check that the requested s3 key starts with
one of the granted file prefixes
"""
granted = False
for prefix in prefixes:
if key.startswith(prefix):
granted = True
return granted | bigcode/self-oss-instruct-sc2-concepts |
def add_key(rec, idx):
"""Add a key value to the character records."""
rec["_key"] = idx
return rec | bigcode/self-oss-instruct-sc2-concepts |
def unpack_twist_msg(msg, stamped=False):
""" Get linear and angular velocity from a Twist(Stamped) message. """
if stamped:
v = msg.twist.linear
w = msg.twist.angular
else:
v = msg.linear
w = msg.angular
return (v.x, v.y, v.z), (w.x, w.y, w.z) | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
def get_soup(url):
"""Gets soup object for given URL."""
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
return soup | bigcode/self-oss-instruct-sc2-concepts |
def generate_fake_ping_data(random_state, size):
"""
Generate random ping values (in milliseconds) between 5 and 20,
some of them will be assigned randomly to a low latency between 100 and 200
with direct close values between 40 and 80
"""
values = random_state.random_integers(low=5, high=20, size=size)
picked_low_latency_values_indexes = random_state.choice(
size, round(0.001 * len(values)), replace=False
)
# Sets the picked value to a random low ping (e.g.: [100, 200]),
# and sets the direct close values to a ping between 40 and 80ms
for index in picked_low_latency_values_indexes:
if index - 1 >= 0:
values[index - 1] = random_state.random_integers(40, 80)
values[index] = random_state.random_integers(100, 200)
if index + 1 < size:
values[index + 1] = random_state.random_integers(40, 80)
return values.tolist() | bigcode/self-oss-instruct-sc2-concepts |
def split_cols_with_dot(column: str) -> str:
"""Split column name in data frame columns whenever there is a dot between 2 words.
E.g. price.availableSupply -> priceAvailableSupply.
Parameters
----------
column: str
Pandas dataframe column value
Returns
-------
str:
Value of column with replaced format.
"""
def replace(string: str, char: str, index: int) -> str:
"""Helper method which replaces values with dot as a separator and converts it to camelCase format
Parameters
----------
string: str
String in which we remove dots and convert it to camelcase format.
char: str
First letter of given word.
index:
Index of string element.
Returns
-------
str:
Camel case string with removed dots. E.g. price.availableSupply -> priceAvailableSupply.
"""
return string[:index] + char + string[index + 1 :]
if "." in column:
part1, part2 = column.split(".")
part2 = replace(part2, part2[0].upper(), 0)
return part1 + part2
return column | bigcode/self-oss-instruct-sc2-concepts |
def parse_stat(stat):
"""Parses the stat html text to get rank, code, and count"""
stat_clean = stat.replace('\n', ' ').replace('.', '').strip()
stat_list = stat_clean.split(' ')
rank = stat_list[0]
code = code_orig = ' '.join(stat_list[1:-1])
# remove xx and dd from the end of the code so we can get more matches
# Note: rstrip will remove 'd' even if it doesn't find 'dd' ...
if code.endswith('dd') or code.endswith('xx'):
code = code[:-2]
count = stat_list[-1]
return [rank, code, code_orig, count] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import torch
from typing import List
def collect_flow_outputs_by_suffix(
output_dict: Dict[str, torch.Tensor], suffix: str
) -> List[torch.Tensor]:
"""Return output_dict outputs specified by suffix, ordered by sorted flow_name."""
return [
output_dict[flow_name]
for flow_name in sorted(output_dict.keys())
if flow_name.endswith(suffix)
] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def _counterSubset(list1, list2):
"""
Check if all the elements of list1 are contained in list2.
It counts the quantity of each element (i.e. 3-letter amino acid code)
in the list1 (e.g. two 'HIS' and one 'ASP') and checks if the list2 contains
at least that quantity of every element.
Parameters
----------
list1 : list
List of amino acids in 3-letter code (can be repetitions)
list2 : list
List of amino acids in 3 letter code (can be repetitions)
Returns
-------
bool
True if list2 contains all the elements of list1. False otherwise
"""
#1. Count how many amino acids of each kind
c1, c2 = Counter(list1), Counter(list2)
#2. Check that list2 contains at least the same number of every amino acid
for k, n in c1.items():
if n > c2[k]:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def clean_url(address):
"""Remove unwanted data and provide a default value (127.0.0.1)"""
if address == "":
return '127.0.0.1'
address = address.replace("http://", "")
address = address.replace("https://", "")
address = address.split(":")[0]
return address | bigcode/self-oss-instruct-sc2-concepts |
def string_encode(key):
"""Encodes ``key`` with UTF-8 encoding."""
if isinstance(key, str):
return key.encode("UTF-8")
else:
return key | bigcode/self-oss-instruct-sc2-concepts |
def hasanno(node, key, field_name='__anno'):
"""Returns whether AST node has an annotation."""
return hasattr(node, field_name) and key in getattr(node, field_name) | bigcode/self-oss-instruct-sc2-concepts |
def scale_reader_decrease(provision_decrease_scale, current_value):
"""
:type provision_decrease_scale: dict
:param provision_decrease_scale: dictionary with key being the
scaling threshold and value being scaling amount
:type current_value: float
:param current_value: the current consumed units or throttled events
:returns: (int) The amount to scale provisioning by
"""
scale_value = 0
if provision_decrease_scale:
for limits in sorted(provision_decrease_scale.keys(), reverse=True):
if current_value > limits:
return scale_value
else:
scale_value = provision_decrease_scale.get(limits)
return scale_value
else:
return scale_value | bigcode/self-oss-instruct-sc2-concepts |
import logging
def compareFuzzies(known_fuzz, comparison_fuzz):
"""
The compareFuzzies function compares Fuzzy Hashes
:param known_fuzz: list of hashes from the known file
:param comparison_fuzz: list of hashes from the comparison file
:return: dictionary of formatted results for output
"""
matches = known_fuzz.intersection(comparison_fuzz)
if len(comparison_fuzz):
similarity = (float(len(matches))/len(known_fuzz))*100
else:
logging.error('Comparison file not fuzzed. Please check file size and permissions')
similarity = 0
return {'similarity': similarity, 'matching_segments': len(matches),
'known_file_total_segments': len(known_fuzz)} | bigcode/self-oss-instruct-sc2-concepts |
import typing
def _rounded(d: typing.SupportsFloat) -> float:
"""Rounds argument to 2 decimal places"""
return round(float(d), 2) | bigcode/self-oss-instruct-sc2-concepts |
def ping_parser(line):
"""When Twitch pings, the server ,ust pong back or be dropped."""
if line == 'PING :tmi.twitch.tv':
return 'PONG :tmi.twitch.tv'
return None | bigcode/self-oss-instruct-sc2-concepts |
def _in_matched_range(start_idx, end_idx, matched_ranges):
"""Return True if provided indices overlap any spans in matched_ranges."""
for range_start_idx, range_end_idx in matched_ranges:
if not (end_idx <= range_start_idx or start_idx >= range_end_idx):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def isSubList(largerList, smallerList):
"""returns 1 if smallerList is a sub list of largerList
>>> isSubList([1,2,4,3,2,3], [2,3])
1
>>> isSubList([1,2,3,2,2,2,2], [2])
1
>>> isSubList([1,2,3,2], [2,4])
"""
if not smallerList:
raise ValueError("isSubList: smallerList is empty: %s"% smallerList)
item0 = smallerList[0]
lenSmaller = len(smallerList)
lenLarger = len(largerList)
if lenSmaller > lenLarger:
return # can not be sublist
# get possible relevant indexes for first item
indexes0 = [i for (i,item) in enumerate(largerList) if item == item0 and i <= lenLarger-lenSmaller]
if not indexes0:
return
for start in indexes0:
slice = largerList[start:start+lenSmaller]
if slice == smallerList:
return 1 | bigcode/self-oss-instruct-sc2-concepts |
def merge_sort(arr):
"""
Merge sort repeatedly divides the arr then
recombines the parts in sorted order
"""
l = len(arr)
if l > 1:
mid = l//2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
return arr | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_file_pattern(text):
"""
>>> is_file_pattern('file.java')
True
>>> is_file_pattern('.gitignore')
True
>>> is_file_pattern('file')
False
>>> is_file_pattern('java')
False
>>> is_file_pattern('*.java')
True
>>> is_file_pattern('docs/Makefile')
True
>>> is_file_pattern('**/*.jpg')
True
>>> is_file_pattern('.rubocop.yml')
True
>>> is_file_pattern('Class.{h,cpp}')
True
"""
return bool(re.match(r'''
(?: [.]{0,2}[\-_*\w+]+ /)* # Preceeding directories, if any
[.]?[\-_*\w+]+ # The basename
(?: [.][\-_*\w]+ # An extension
| [.][{][^}*,]+,[^}*]+[}] # An alternation
| (?: file | ignore )) # .gitignore, Makefile
''', text, re.VERBOSE | re.UNICODE)) | bigcode/self-oss-instruct-sc2-concepts |
def gc_percent(seq):
"""
Calculate fraction of GC bases within sequence.
Args:
seq (str): Nucleotide sequence
Examples:
>>> sequtils.gc_percent('AGGATAAG')
0.375
"""
counts = [seq.upper().count(i) for i in 'ACGTN']
total = sum(counts)
if total == 0:
return 0
gc = float(counts[1] + counts[2]) / total
return gc | bigcode/self-oss-instruct-sc2-concepts |
def build_superblock(chanjo_db, block_group):
"""Create a new superblock and add it to the current session.
Args:
chanjo_db (Store): Chanjo store connected to an existing database
block_group (list): group of related database blocks
Returns:
object: new database block
"""
superblock_id, some_block = block_group[0]
# create a brand new superblock
new_superblock = chanjo_db.create(
'superblock',
superblock_id=superblock_id,
contig=some_block.contig,
start=min([payload[1].start for payload in block_group]),
end=max([payload[1].end for payload in block_group]),
strand=some_block.strand
)
# add the new superblock to the current session
chanjo_db.add(new_superblock)
# relate the blocks to the superblock
new_superblock.blocks = [block for _, block in block_group]
return new_superblock | bigcode/self-oss-instruct-sc2-concepts |
def prune_small_terms(hpo_counts, min_samples):
"""
Drop HPO terms with too few samples
"""
filtered_counts = {}
for term, count in hpo_counts.items():
if count >= min_samples:
filtered_counts[term] = count
return filtered_counts | bigcode/self-oss-instruct-sc2-concepts |
import jinja2
def get_jinja_parser(path):
""" Create the jinja2 parser """
return jinja2.Environment(loader=jinja2.FileSystemLoader(path)) | bigcode/self-oss-instruct-sc2-concepts |
def debian_number(major='0', minor='0', patch='0', build='0'):
"""Generate a Debian package version number from components."""
return "{}.{}.{}-{}".format(major, minor, patch, build) | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_request_data(request):
""" Retrieve request data from the request object.
Parameters
----------
request: object
the request object instance
Returns
-------
Dictionary
the request data from the request object.
Raises
------
Exception:
for any uncaught syntax error.
"""
try:
data = request.get_json()
if not data:
data = request.values.to_dict()
return data
except Exception as e:
logging.error(f"""Error ocurred while retrieving \
flask request data: {e}""")
raise e | bigcode/self-oss-instruct-sc2-concepts |
def get_prospective_location(location, velocity, time):
"""Calculate the final location and velocity based on the one at time 0"""
return [l + v * time for l, v in zip(location, velocity)] | bigcode/self-oss-instruct-sc2-concepts |
import json
def pretty_jsonify(data):
"""Returns a prettier JSON output for an object than Flask's default
tojson filter"""
return json.dumps(data, indent=2) | 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.