content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def sqrt(n: int) -> int:
"""Gets the integer square root of an integer rounded toward zero."""
return int(n ** 0.5) | 380a2516ae77a038469d190e5898ee9fd59f7820 | 662,193 |
def get_hello_user(name):
"""This method does blah blah."""
return 'Hello {}'.format(name) | 4144635bfc0ae705265ab48c8eb7977e234659e4 | 662,194 |
from datetime import datetime
def _filter_pipelines_by_time(con, pipelines, days):
"""
Will return pipelines that are older than the number of days specified.
"""
# for each pipeline in pipelines we should get their builds
# if the most recent build is older than $days old then we should add it to... | 9d62bba2a8b3d69a153f8e816908da3b57d47d74 | 662,195 |
from typing import Dict
from typing import Tuple
from typing import List
import struct
def vox_rgba_content( palette: Dict[ Tuple[int,int,int,int], int ] ) -> bytes:
"""Produces the content for the RGBA chunk, which contains the color palette
for the entire scene.
"""
# While the palette contains at most 255 ... | fcfd58b569187e2ebdf3ef650d530655b65117d5 | 662,196 |
def join_path(a, *p):
"""Join path tokens together similar to os.path.join, but always use
'/' instead of possibly '\' on windows."""
path = a
for b in p:
if len(b) == 0:
continue
if b.startswith('/'):
path += b[1:]
elif path == '' or path.endswith('/'):
path += b
else:
path += '/' + b
# END ... | bd7de83cd96701c716efead5d9c6d9f963a24283 | 662,197 |
import os
def make_video_list_file(root_dir, videos_path_list):
# cSpell:disable
"""create a file for ffmpeg to use as a list of videos
Args:
videos_path_list (list(str)): the list with all the path to the videos
"""
# cSpell:enable
video_list_file = open('video_list.txt', 'w+')
v... | 9f2ec9fe085db74c150bea1acca794bf113fbbf4 | 662,198 |
def evaluate_rm_neg(prediction, ground_truth, none_label_index):
"""
Evaluation matrix.
:param prediction: a dictionary of labels. e.g {0:[1,0],1:[2],2:[3,4],3:[5,6,7]}
:param ground_truth: a dictionary of labels
:return:
"""
# print '[None] label index:', none_label_index
pos_pred = 0.... | fbd66c674b606a75e2f6bc5b6d4ece97b1cfa8b8 | 662,199 |
def convert_diameter_sigma_to_fwhm(diameter):
"""
Converts a beam diameter expressed as the full with at half maximum (FWHM)
to a beam diameter expressed as 2-sigma of a Gaussian distribution
(radius = sigma).
:arg diameter: 2-sigma diameter diameter.
"""
# d_{FWHM} = 1.177411 (2\sigma)
... | 9ff9b8581fdda3f0063a99df340bc5239e296a1f | 662,200 |
def construct_exec_result(result, exec_result):
""" Transform an ImpalaBeeswaxResult object to a QueryResult object.
Args:
result (ImpalaBeeswasResult): Tranfers data from here.
exec_result (QueryResult): Transfers data to here.
Returns:
QueryResult
"""
# Return immedietely if the query failed.... | d6a6ac4f6882e2236d6f8ea585d7c683dbd178af | 662,202 |
import re
def get_row_data(key, row_data, column_names):
"""
Collects row data using column names while cleaning up
anything after the _s
"""
data = [re.sub("_.*", "", key)]
for column in column_names:
data.append(row_data.get(column))
return data | 2c6749bfe9b42f7e4ca3c5d78e99647f069fff31 | 662,203 |
def table_from_fk(fks):
"""Get the table name of the fk constraint, ignoring
the cordis_projects table
Args:
fks (:obj:`list` of SqlAlchemy.ForeignKey): All foreign keys for a given table.
Returns:
tablename (str): The table name corresponding to the non-Project foreign key.
"""... | ffbc61087189a4dc57326a5c91439353a8f0c2dc | 662,204 |
import sys
def bytes_or_string(string):
"""Converts a string to bytes if we're using python3."""
if sys.version_info > (3,):
return bytes(string, "latin-1")
else:
return string | 5537f510408e2aa28a0d0026eab30ed5882d922b | 662,205 |
import gzip
def write_fastq(filename):
"""
return a handle for FASTQ writing, handling gzipped files
"""
if filename:
if filename.endswith('gz'):
filename_fh = gzip.open(filename, mode='wt')
else:
filename_fh = open(filename, mode='w')
else:
filename... | b68d85cf7d551cb2e04df5fae9f1a34837aeffc5 | 662,206 |
def intersection(set1, set2):
"""
Calculates the intersection size between two sets, used to compute overlap
between a word context and a definition's signature.
@param set1 - First set
@param set2 - Second set
@return Intersection size
"""
return len(set(set1) & set(set2)) | 95f3e651d71f217567e9c2e89048f7d1ce5114cd | 662,207 |
def groupby(keys, values):
"""Group values according to their key."""
d = {}
for k, v in zip(keys, values):
d.setdefault(k, []).append(v)
return d | 35f54ecc179971575aaeb8a8a1e86a3dc03556ed | 662,208 |
def square_loss(a, b):
"""
Returns the value of L(a,b)=(1/2)*|a-b|^2
"""
return 0.5 * (a - b)**2 | 6b852ec061273f4d69da64eeee51caee031a5306 | 662,209 |
def is_filetype(filename: str) -> bool:
"""
Return true if fname is ends with .csv, .xlsx, or .xls.
Otherwise return False.
:filename: filename string
Returns bool
"""
cfname = filename.lower()
if cfname.endswith(".csv") and not cfname.startswith("pdappend"):
return True
... | 9dbf867723b474a1e57151ed31e7f358770af25f | 662,210 |
def _calcFrame(parentFrame, posSize, absolutePositioning=False):
"""
Convert a vanilla posSize rect to a Cocoa frame.
"""
(pL, pB), (pW, pH) = parentFrame
(l, t), (w, h) = posSize
if not absolutePositioning:
if l < 0:
l = pW + l
if w <= 0:
w = pW + w - l
... | 5856eab3e8b2dafc531a646d05e05cb74ff6dbaa | 662,211 |
from unittest.mock import call
def send_keepalive(address, port):
"""
Tells the node to send a keepalive packet to address:port.
:param address: http address
:type address: str
:param port: http port
:type port: str or int
:returns: empty dict
:rtype: dict
"""
action = 'keepa... | 6f0508639e2e401bd58536e29802840a71e591c6 | 662,212 |
def fixture_uv_forecast():
"""Return a /forecast response."""
return {
"result": [{
"uv": 0,
"uv_time": "2018-07-30T11:57:49.750Z",
"sun_position": {
"azimuth": -2.0081567900835937,
"altitude": -0.011856950133816461
}
... | 2b6bdc709bad4e3b0a54498baeec4d9ca15a1710 | 662,214 |
from datetime import datetime
def timestamp_to_str(timestamp: float, time_format: str) -> str:
"""转换时间戳为字符串格式
Args:
timestamp: unix时间戳
time_format: 时间格式
Returns:
字符串描述的时间形式
"""
datetime_ = datetime.fromtimestamp(timestamp)
return datetime_.strftime(time_format) | db234d8f84f649ad1b5386c8b44ee37d668408d5 | 662,215 |
def _find_break_pos(txt, break_pos, allow_shift=2):
""" 简单的函数,用来找合适的断行位置
allow_shift << break_len
"""
txt_len = len(txt)
if txt[break_pos] == ' ':
return 0, True
for i in range(allow_shift):
for shift in (i+1, -i-1):
new_break_pos = break_pos + shift
if ne... | 50da661771ffda89436ef3c6ad50433ede462f73 | 662,216 |
def monet_bool(data):
"""
returns "true" or "false"
"""
return ["false", "true"][bool(data)] | c0155ff2ed2c0b19c1c35edaedfb0fa755a8e2b3 | 662,217 |
def image_meta(system_metadata):
"""Format image metadata for use in notifications from the instance
system metadata.
"""
image_meta = {}
for md_key, md_value in system_metadata.items():
if md_key.startswith('image_'):
image_meta[md_key[6:]] = md_value
return image_meta | c76bd0dc4deb26447827bfd1aed9828361a9281e | 662,218 |
def get_tech_installed(enduse, fuel_switches):
"""Read out all technologies which are specifically switched
to of a specific enduse
Parameter
---------
enduse : str
enduse
fuel_switches : dict
All fuel switches where a share of a fuel
of an enduse is switched to a specif... | 4e84c574c9afd08010df653cf00c03daa38bab45 | 662,219 |
def read_voltage_fast(pin):
"""
Returns the voltage of the pin passed in (between 0 and 5 Volts)
It takes a single of measurement
"""
return 5.0 * pin.read() | aaeef61e6e767107d864b1ca271481d7727f561c | 662,220 |
from datetime import datetime
def containsAllData(entry):
""" Ensures ICODrops entry contains all data needed to be stored """
return isinstance(entry["name"], str) \
and isinstance(entry["start"], datetime) \
and isinstance(entry["end"], datetime) \
and isinstance(entry["description"], str) \
and... | 035401754e16d38255bc424aca11c6f33db8282e | 662,221 |
def x_label(epoch_axis):
"""
Get the x axis label depending on the boolean epoch_axis.
Arguments:
epoch_axis (bool): If true, use Epoch, if false use Minibatch
Returns:
str: "Epoch" or "Minibatch"
"""
return "Epoch" if epoch_axis else "Minibatch" | ed6d120e04344ef2a9abf8b0b190f032d6faf763 | 662,222 |
def filter_measurements(measurements, from_measurement, ignore_measurements):
"""Filter the list of measurements."""
if ignore_measurements:
new_list = []
for m in measurements:
if m not in ignore_measurements:
new_list.append(m)
measurements = new_list
... | b1f97085dd304b49b268a7aa5b403c87e06b64ba | 662,223 |
def feature_generation_cont(df, continous, target):
"""Continous Variables"""
for i in range(len(continous)-1):
var_1 = continous[i]
var_2 = continous[i+1]
# ratios
df["ratio_"+str(var_1)+"_"+str(var_2)] = df[var_1].astype("float")/df[var_2].astype("float")
#products
df["prod_"+str(var_1)+"_"+str(var_2)... | f448eceb567466cb1ae24cb479d6ef87ad58d5c5 | 662,224 |
import ast
def count_number_of_functions(filepath):
"""Count number of functions inside a .py file."""
# Taken from: https://stackoverflow.com/a/37514895/1274908
with open(filepath, "r+") as f:
tree = ast.parse(f.read())
return sum(isinstance(exp, ast.FunctionDef) for exp in tree.body) | 4f6ff4d62be9add2b798c73aff3af384646c405f | 662,225 |
import inspect
def parse_comments(func):
"""
parse function comments
First line of comments will be saved as summary, and the rest
will be saved as description.
"""
doc = inspect.getdoc(func)
if doc is None:
return None, None
doc = doc.split('\n', 1)
if len(doc) == 1:
... | ac8c1acccc0fa6a7b2e2f64a8e2df7ce604b9b84 | 662,226 |
import re
def _verify_route_engine_status(output):
""" Attempts to verify that RE0 has the mastership.
Failure indicates either RE0 is missing or another RE has the master role.
"""
masterstatus = re.search(r'Current state.*(Master)',output)
if masterstatus != None:
return True
else:
... | 12c9fd5e90fa89af9ca96196eec2056f71b0af3b | 662,227 |
def __tokenify(number):
"""
生成随机验证字符串
:param number:
:return: 随机验证字符串
"""
token_buf = []
# char map 共64个字符
char_map = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ*$'
remainder = number
while remainder>0:
token_buf.append(char_map[remainder&0x3F])
remainder = remainder // 64
return ''.... | 522c9170a55b9c97bc44e7080ed073e06eae3fca | 662,228 |
import re
def remove_whitespace(text):
"""removes # redundant/additional white space (incl. those from punctuation replacements)"""
return re.sub(r'[\s]+', ' ', text) | c33f2034636595abfab17a071a51e7de31b4146b | 662,229 |
def fix_json_values(json_to_fix):
"""
Function to for making certain unavailable values more readable
"""
for k, v in json_to_fix.items():
if str(v) == "False":
json_to_fix[k] = "No"
if str(v) == "None":
json_to_fix[k] = "Not Available"
if str(v) == "True"... | dc0141bf6b0cfd3414ef259b4280836493b7300b | 662,230 |
def chimie_control(data):
"""check that all needed oxides are there and setup correctly the Pandas datalist.
Parameters
----------
data : Pandas dataframe
the user input list.
Returns
-------
out : Pandas dataframe
the output list with all required oxides.
"""
list_ox... | b99dcd1564efe75bb9513bd385ab957d2b7467d5 | 662,231 |
def remove_at_index(lst, index):
"""
Creates a new list which is a copy of the input one with a single element removed from it
"""
removed = lst[:]
del removed[index]
return removed | 1f5c7dbb32075335a489ee4d2a4857057a4c19dd | 662,232 |
def _limit_stat_length(stat_length, shape):
"""limits the stat_length to current array length along given dimension."""
return tuple((min(stat_pair[0], shape[i]), min(stat_pair[1], shape[i])) for i, stat_pair in enumerate(stat_length)) | 66ab357d8de2537782c85d2c2b705c147a0615a7 | 662,233 |
import sys
def prefix_bits(byte_array, bits):
"""Return the first <bits> bits of a byte array as an integer."""
if sys.version_info < (3,):
b2i = ord # In Python 2, indexing byte_array gives str
else:
b2i = lambda b: b # In Python 3, indexing byte_array gives int
result = 0
... | 83b91b55c18ca585adea8ac57cfa59c0c9f47ab8 | 662,234 |
import cProfile
def profile(func):
"""Decorator for run function profile"""
def wrapper(*args, **kwargs):
profile_filename = func.__name__ + '.prof'
profiler = cProfile.Profile()
result = profiler.runcall(func, *args, **kwargs)
profiler.dump_stats(profile_filename)
retu... | 028369efd3a9f933e211c522d223f4e419592167 | 662,236 |
def early_stop(metrics, steps, min_improvement=0, higher_is_better=False):
"""Early stopping condition.
Args:
metrics: A list of metric values.
steps: Consider the improvement over this many steps.
min_improvement: Continue if the metric improved less than this value:
higher_is_better: Whether a hi... | a5b8f6681989c33f5e8c22698a5ccb82ac49b01b | 662,237 |
def r19o(factor: float = 1) -> float:
"""
The outer size of the mounting rails of a 19-inch
full rack giving it its name.
"""
return 482.6 * factor | 2eeb9be4643dd68d389f06415a3a4c09e8178e99 | 662,238 |
def decode_message(encoded_text, dictionary):
"""Decodes encoded text according to the given dictionary.
Huffman encoded messages can be decoded only if we have the original dictionary
that is used to encode the message. If the encoded message includes an unknown code
function raises an error.
Arg... | 51e05c4685fc4a0a8c2a86c1c019d07bdab25d66 | 662,240 |
def is_valid_variable(X,Y):
"""Given token (X) and variable (Y), make sure token
fits variable's constraints."""
# - Positive constraints: break if mismatch found -
if not(Y.constr_id == [] or (str(X.id) in Y.constr_id)):
return False
if not (Y.constr_lemma == [] or (X.lemma i... | 5b06ef7de764a024afed09218efee475aaeab6f3 | 662,241 |
import collections
def as_namedtuple(d):
"""return dictionary as a named tuple.
"""
return collections.namedtuple('GenericDict', list(d.keys()))(**d) | 3f038232cc70f54337058082121f8966fe8231d1 | 662,242 |
def detail_line(e):
"""Given an expectation, return a readable one-line explanation of it."""
fields = [fname for fname in ('mutable', 'optional', 'volatile')
if getattr(e, fname, None)]
if e.depends_on:
fields.append("depends_on=%s" % e.depends_on)
line = ', '.join(fields)
i... | 53406fc415347b6db8e03b2f68c9de1e0d38cb7a | 662,243 |
def group_by_phrase(docs_df):
""" Takes a Pandas data frame with index=phrase, cols: num_occurrences as input,
calculates the no. of unique and total occurrences of each phrase over
the whole time period (a quarter) by grouping by phrase and aggregating
on the column num_occurrences (sum and count). Th... | 3e88545511494e344ff9877cabd27a25438898c0 | 662,244 |
def clamp(n, maxabs):
"""Clamp a number to be between -maxabs and maxabs"""
return max(-maxabs, min(n, maxabs)) | 619c73b63d12caef58f9e219b2484f20ef569a3f | 662,245 |
def people_simple_raw():
"""A one-person roster defined wrt the `config_simple` fixture."""
return [{
'id': 'a',
'campus': 'Campus',
'cohort': 'People',
'schedule': {
'2020-01-01': ['Block'],
'2020-01-03': ['Block']
},
'site_rank': ['Testin... | e396646fae0768868680ad7f5415e7fc5f618aa9 | 662,246 |
def buildNodeParentDict(nl):
""" Takes a node list and builds a dict
of parents with child names as keys and parent
names as values
"""
npd = {}
for n in nl:
for c in n.children:
npd[c] = n.name
return npd | a4a83c2e611e69dc1431fd0f41450b965290d965 | 662,247 |
import random
def mutation_single_customer_rerouting(vehicle, p1, quality, duration,
setup_time, setup_cost, demand):
"""Re-routing involves randomly selecting one customer, and removing that
customer from the existing route. The customer is then inserted in the
best... | c923b18ed57848a681c2ea6ec14025b6c4213b2b | 662,248 |
import click
def template(func):
"""
Set the value of a config template parameter in the form ``key=value``.
Any instance of ``${key}`` in ``klio-job.yaml`` will be replaced
with ``value``.
"""
return click.option(
"-T",
"--template",
default=[],
multiple=True,
... | f5ceae018c4ff9739e47cb26ff6aac08f466eaa4 | 662,249 |
def parse_context_name(context_obj):
"""Parses context name from Dialogflow's contextsession prefixed context path"""
return context_obj["name"].split("/contexts/")[1] | 95b897395c58d7dac7501778ad968512fbdd4d8e | 662,250 |
def getTypeDict(fullDict, entityType):
"""
Expected Input: Full dictionary. EntityType tag to look up for each transaction_id.
Expected Output: Dictionary filtered by entityType.
"""
typeDict = {}
for key in fullDict.keys():
if(fullDict[key]["entity_type"] == entityType):
typeDict[key] = fullDict[key]
ret... | 5b14fd6f813fc4e6496b3ab1293485ef99dfdaaf | 662,251 |
def options2args(options):
"""Convert a list of command line options to a args and kwargs """
args = list()
kwargs = dict()
for a in options:
if "=" in a:
a = a.split("=", maxsplit=1)
kwargs[a[0].lstrip("-")] = a[1]
else:
args.append(a)
return args... | 3819ba1455d280c22e9f3f124125410781bc2f7a | 662,252 |
def rename_variable(formula, old_name, new_name):
"""
Function that traverses the formula and changes the appearance of one
variable. The renaming is done to the values of the id and field
attributes.
:param formula: Root node of the formula object
:param old_name: Old variable name
:param ... | b76498143e08a07d227ed799d5f74d5ec0e1b731 | 662,253 |
def selectSupportedKeyswitch(switchType):
""" Returns footprint name of the supported switch, returns an error if not supported
Returned object will have this form:
{
"lib_dir":"",
"footprint_ref": "",
}
"""
def selectMXParts():
... | 19c477a3f1165269ca286890b3718579ceecfceb | 662,254 |
def is_number(value):
"""Checks whether a string is a floating point number.
This method checks whether a string is a floating point number by first removing any commas
then attempting to cast the string to a float. If the cast fails, then return false.
:param value: A string to evaluate.
:returns... | 4e81fe5dfd27579f6b71cbe1fd1ac7c9f7cec95a | 662,255 |
import os
def read_file(filename):
"""
Read a file, if it exists. Otherwise return None
"""
if not os.path.exists(filename):
return
with open(filename, 'r') as fd:
content = fd.read()
return content | 45277e6e10010a9852f9386a02148e726837723f | 662,256 |
import re
import os
def replace_all_image_path(text: str, image_path: str) -> str:
"""
# 
"""
pattern = r"\!\[(?P<imgname>.*?)\]\((?P<filepath>.*)\)"
# print(re.findall(pattern, text))
text = re.sub(pattern,
lambda m: '... | 436def064c6aa52b4004a58623bd72bc873290a0 | 662,257 |
def convert_list_to_string(org_list, seperator=' '):
""" Convert list to string, by joining all item in list with given separator.
Returns the concatenated string """
return seperator.join(org_list) | dcc7da366e62b1b638a7f4190aa760a3c4016600 | 662,258 |
import subprocess
import re
def check_cves(check_func=subprocess.check_output):
"""
Query the vulnerability updates available with yum
Header: Loaded plugins...
Columns: Advisory ID, reason/level, package name
Footer: updateinfo list done
"""
update_string = check_func('sudo yum updateinfo list cves'.sp... | d3e3530214a6c40d66f6b86750e44eae6a41587a | 662,259 |
def _pad_with_nulls(data, len_):
""" Pad string with null bytes.
Parameters
----------
data : str/bytes
the string/bytes to pad
len_ : int
the final desired length
"""
return data + (b'\x00' * (len_ - len(data))) | 238cc6c7b883d087cfa09131eec2b463054f791e | 662,260 |
import subprocess
def running_env():
"""
Returns (str) git and (str) env
git contains the git hash of the checked out code
env is the various system information where this app is running
"""
ra_git_version = (
subprocess.run(
["git", "rev-parse", "HEAD"],
captur... | f5fe570fe807dead2f324e8e054fdad2046f67fe | 662,261 |
from pathlib import Path
import sys
def _get_env_flake8_fpath():
"""
Perhaps we are in a virtual environment which hides flake8 from which /
where commands. Worth a try.
"""
bin_path = Path(sys.executable).parent
flake8_fpath = str(bin_path / 'flake8')
return flake8_fpath | a6f7cb62de3daac74acf497ddf42711ecc621614 | 662,263 |
def handle_re(ctx, c1, c2, str1='none'):
""" RegEx-based router, catching goups and named groups """
print("Hello from RE-base route ")
return "Handling RE route %s|%s|%s !" % (c1, c2, str1) | 672739729f7337764123a67e7740c1d0f21ea4b8 | 662,264 |
def generated_tag_data(tags):
"""Convert :obj:`dict` to S3 Tag list.
Args:
tags (dict): Dictonary of tag key and tag value passed.
Returns:
list: List of dictionaries.
"""
generated_tags = []
for key, value in tags.items():
generated_tags.append({
'Key': ke... | 8817d2ab05bd26bb056f3facaadc025b547ef3fc | 662,265 |
def fitness(individual, problem):
"""
Score the fitness of an indivdual based on a MAXSAT problem.
:param individual: An "individual" represented as an array
:param problem: MAXSAT problem to compute fitness in ref to, usually
stored as global MAXSAT_PROBLEM
:return: An int representation of ind... | 410bfd493bf9551f735c0fd6e2f2c5946750490d | 662,266 |
import re
def extract_port_range(address):
""" We additionally allow for setting a port range in rectangular brackets:
tcp://127.0.0.1:[50100:50120]
"""
range_pattern = re.compile(r"(?P<addr>.*?):\[(?P<port_min>\d+):(?P<port_max>\d+)\]")
random_pattern = re.compile(r"(?P<addr>.*?):\*")
por... | 18336267a660d13911cf2bc9ba9678ad7b8e6a18 | 662,267 |
def comp_height_wire(self):
"""Return wire diameter
Parameters
----------
self : CondType12
A CondType12 object
Returns
-------
W: float
Wire diameter [m]
"""
return self.Wwire | 20bb613c66c7b743ecfee91382eb7bba8d2375f8 | 662,268 |
def is_excluded(path, dirs):
"""
if path is excluded in list of dirs/files
:param path: path to check for exclude
:param dirs: list of excludes
:return: Boolean
"""
for directory in dirs:
if path.startswith(directory):
return True
return False | 4bb6e5c5bf38f90252abda7171e949a951baf7a6 | 662,269 |
import random
def greetings():
"""
Returns a random greeting from list
"""
greetings = ["Hello, how are you? ", "Hi, how are you?",
"Hi, lovely day, right? How are you? ",
"Ah, my friend! How are you? ",
"Hey fella, You good? ", "Hey, my old friend, how... | acaf7eb8e9bbe32a558f559a86935b94610c4467 | 662,270 |
def sphere_function(vals):
"""
A very easy test function
Parameters:
vals - a list specifying the point in N-dimensionsla space to be
evaluated
"""
return sum(val**2 for val in vals) | 0f63c980c814f4351b2b9b6dc4e89cb36ef274d0 | 662,272 |
def _filter_statements(stmts_in, ns, ag_id, role=None):
"""Return statements filtered to ones where agent is at given position."""
# Make sure the role is good.
assert role in ['SUBJECT', 'OBJECT', None], \
"The value of role must be either 'SUBJECT', 'OBJECT', or None."
# Map the role to an in... | c89e55bec276aad71ae316546cf58252a58b207d | 662,273 |
import re
def is_domain(domain: str) -> bool:
"""Makes sure domain is valid with proper format."""
# Make sure domain is specified as proper type
if not domain or type(domain) is not str:
return False
# Define regex for domain validation
domain_regex = r'[a-z0-9]+([a-z0-9\-]+\.)+([a-z]+[... | 2f6e75470f55c45c369568b9f564e7c0344210e1 | 662,274 |
def binarySearch(array, target):
""" Devuelve la posicion del elemento "target" si se encuentra en el array, caso contrario devuelve -1 """
left = 0
right = len(array) - 1
while left <= right:
mid = int(left + (right - left) / 2)
if array[mid] == target:
return mid
if array[mid] < target:
... | 2a79e92f977a88a2eeea7369cf8cf09e747a7e36 | 662,275 |
def doubles(source: str) -> str:
"""Returns the source without double characters."""
destination = []
for c in source:
if destination and destination[-1] == c:
destination.pop()
else:
destination.append(c)
return ''.join(destination) | e72c7d822caf2cc64ac6092876a11d876af1fd35 | 662,277 |
import os
def walkfiles(folder, suffix=''):
"""Iterator over files in folder, recursively."""
return (
os.path.join(basename, filename)
for basename, dirnames, filenames in os.walk(folder)
for filename in filenames
if filename.endswith(suffix)
) | e4227508566b2e7b6486d07f292dbcebde8ff959 | 662,278 |
def rearrange_name(s: str) -> str:
"""Converts last, first to first last
Args:
s (str): the original string
Returns:
str: the standardized string
"""
return ' '.join(reversed([i.strip() for i in s.split(', ')])) | 66d734d820ec1836a973e2b8bc658817284503c7 | 662,279 |
def int_pow(x: float, exponent: float) -> int:
"""Finds the nearest integer to ``pow(x, exponent)``.
Args:
x: The number whose power will be found.
exponent: The number to which ``x`` will be raised.
Returns:
The result of rounding ``pow(x, exponent)`` to the nearest integer.
"... | f710adbb0299ec57bc63784fc101b102dadc821d | 662,280 |
def mock_moira(mocker):
"""Return a fake mit_moira.Moira object"""
return mocker.patch("moira_lists.moira_api.Moira") | 91e9c4ba881cbd22780ea7c75e2f9c39c4294af4 | 662,281 |
def _trapz_simps_overlap2(dy, dx):
"""Correction term in the squared error when combining trapezoidal and Simpson's rule.
Only exact for equal spacing *dx* left and right of *dy*.
err^2 = (h/6)^2 ((3 Df0)^2 + ((3+2)Df1)^2 + (8Df2)^2 + (4Df3)^2 + ...)
|-- trapz ---| |--------- Simpson... | 81bd671f27b74d5f4ae3c1ec85bde9e37a0950c5 | 662,282 |
import ast
def _safe_eval(node, default):
"""
Safely evaluate the Boolean expression under the given AST node.
Substitute `default` for all sub-expressions that cannot be
evaluated (because variables or functions are undefined).
We could use eval() to evaluate more sub-expressions. However, this... | e71e320efc330073d355169283b3398eabe56d13 | 662,283 |
def percentage(context, num, total_num):
"""
Works out the percentage of num over total_num and then appends the percentage sign
"""
p = float(num)/float(total_num) * 100
percent = str(p) + "%"
return percent | 66bb8db090a9f9cc01b34fda291055aeae731f1c | 662,284 |
def escape_pw_for_look(string):
""" escape a password for look cmd """
string = string.replace("\\", "\\\\")
string = string.replace('"', '\\"')
string = string.replace("'", "\\'")
return string | 72fb12d89446d38a6d83886860a88ac086299505 | 662,285 |
def get_os_distro():
"""Returns a string of OS distribution.
Since we are using Docker, this function only considers Linux distribution.
Alternative files on Linux: /etc/os-release, /etc/lsb-release
As a matter of fact, "/etc/issue" doesn't exist on Mac OS X. We can use
"sw_vers" command to find it... | 94aa00e94d3ee5d135574000242578eb4ad15b55 | 662,286 |
def mktag(tagname, tagclass='', inner=None, tag_params=None):
""" generates tag:
<tagname * > or if tag_params dict passed <tagname * >inner</tagname>
* tagclass or if tag_params dict passed will be overloaded by tag_params['class']
<tagname param1="value1" param2="value2" ...>
"""
... | 3d44e8af1520f0c2b6561f8cec49795d7da45394 | 662,287 |
def bdev_nvme_set_options(client, action_on_timeout=None, timeout_us=None, timeout_admin_us=None,
keep_alive_timeout_ms=None, retry_count=None, arbitration_burst=None,
low_priority_weight=None, medium_priority_weight=None, high_priority_weight=None,
... | 9191a0e1317de57beefb271859736f42857a2e04 | 662,288 |
import json
def update_json(row, fields):
"""Add data to the taxon_json field."""
taxon_json = json.loads(row.taxon_json)
for field in fields:
if row[field]:
taxon_json[field] = row[field]
return json.dumps(taxon_json, ensure_ascii=False) | cc08e6011a5514212b2a5293350069d789b4df1d | 662,289 |
def fix_ambiguous_cl(column=4):
"""awk command to replace non-N ambiguous REF bases with N.
Some callers include these if present in the reference genome but GATK does
not like them.
"""
return r"""awk -F$'\t' -v OFS='\t' '{if ($0 !~ /^#/) gsub(/[KMRYSWBVHDXkmryswbvhdx]/, "N", $%s) } {print}'""" % ... | 4b7f8de10fce8f9d98d103cd0e3f146d3cca3816 | 662,291 |
def make_list(nb_letters):
"""Makes the list of words.
Args:
nb_letters (int): number of letters in the words of the list
Returns:
list: the list of words
"""
words_list = []
# Open the file that contains the words with the required number of letters
with open(f'data/mots_{nb... | 93982818e55fe46f58b06416fd70dd11b847d8d2 | 662,292 |
def get_travel_requests_of_timetables(timetables):
"""
Retrieve a list containing all the travel_request_documents,
which are included in a list of timetable_documents.
:param timetables: [timetable_documents]
:return: travel_requests: [travel_request_documents]
"""
travel_requests = []
... | 7d825f26799aaaf29521055dab7b07371ffe1cb0 | 662,293 |
def number_vowels(w):
"""
Returns: number of vowels in string w.
Vowels are defined to be 'a','e','i','o', and 'u'. 'y' is a
vowel if it is not at the start of the word.
Repeated vowels are counted separately. Both upper case and
lower case vowels are counted.
Examples:
number... | c5d3003681767b726172547c83c8f44c7a583733 | 662,294 |
import sys
import select
import os
def read_available_bytes(file=sys.stdin, chunk_size=4096):
""" Read all available data from f in chucks of chunk_size returning a byte
array or None if nothing read. """
buffer = b''
while True:
read_list, _, exception_list = select.select([file], [], [file],... | ae6dee78a86997380bb390ff02e354d6e985203a | 662,295 |
import sys
import traceback
def as_string(msg, unixfrom=False):
"""Convert a Message object to a string in a safe-ish way.
In email pkg version 2.5.4 and earlier, msg.as_string() can raise
TypeError for some malformed messages. This catches that and attempts
to return something approximating the ori... | e0ff1eb1fd40311d44d78ba347765cd047bf6858 | 662,296 |
def docker_command(command):
"""Format command as needed to run inside your db docker container.
:param str command: postgres command
:return: Terminal command
:rtype: str
"""
# Template for executing commands inside the db container
command_template = 'docker-compose exec -T db psql ' \
... | 56c02b6e1e0c3fb4ed2430167d7d0ff060ffc9a3 | 662,297 |
def div_by_nums(i, nums):
"""
Test if number (i) is divisible by array of numbers (nums)
:param i:
:param nums:
:return:
"""
for n in nums:
if i % n == 0:
return True
return False | 987bb99f50e4cff8a423ad42cca6692c46a0b4f9 | 662,298 |
from typing import Any
from pydantic import BaseModel # noqa: E0611
from enum import Enum
async def clean_python_types(data: "Any") -> "Any":
"""Turn any types into MongoDB-friendly Python types.
Use `dict()` method for Pydantic models.
Use `value` property for Enums.
Turn tuples and sets into lists... | f67c2be6ada2b528122093c2879f40055dd0f135 | 662,299 |
def temporal_affine_forward(x, w, b):
"""
Inputs:
- x: Input data of shape (N, T, D)
- w: Weights of shape (D, M)
- b: Biases of shape (M,)
Returns a tuple of:
- out: Output data of shape (N, T, M)
- cache: Values needed for the backward pass
"""
N, T, D = x.shape
M = b.shap... | eae8f0dbbea596a4bcc1a7739cfd249e8898df90 | 662,301 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.