code stringlengths 15 1.19k | docstring stringlengths 13 400 |
|---|---|
def print_properties(nodes, prop):
for node_id, node in nodes.items():
if prop in node.properties:
print(node.properties[prop])
| Prints the value of the property prop of each node that has that property. |
def hash_labels_only(**data):
labels = data["labels"]
node_label_hash = data["node_label_hash"]
hash_value = 0
for label in labels:
hash_value += node_label_hash[label]
return hash_value
| Computes a hash value only based on a list of labels. |
def copy_dir_contents(src, dest):
src_files = os.listdir(src)
for file_name in src_files:
full_file_name = os.path.join(src, file_name)
if os.path.isfile(full_file_name):
shutil.copy(full_file_name, dest)
| Copy contents of one directory to another |
def make_list_to_condition_on(index_var, all_vars, top_vars):
window_top_vars = set(all_vars).intersection(set(top_vars))
cond_list = list(window_top_vars - set([index_var]))
return cond_list
| Makes a list of variants on which to condition on |
def skewness(s):
return (((s - s.mean()) / s.std(ddof=0)) ** 3).mean()
| Computes the Skewness of the input Series or Dataframe.
There is also the function scipy.stats.skew(). |
def kurtosis(s):
return (((s - s.mean()) / s.std(ddof=0)) ** 4).mean()
| Computes the Kurtosis of the input Series or Dataframe.
There is also the function scipy.stats.kurtosis() which, however,
computes the "Excess Kurtosis", i.e., Kurtosis minus 3 |
def semivolatility(s):
return s[s < 0].std(ddof=0)
| Returns the semivolatility of a series, i.e., the volatility of
negative returns |
def tracking_error(r_a, r_b):
return (((r_a - r_b) ** 2).sum()) ** (0.5)
| Returns the tracking error between two return series.
This method is used in Sharpe Analysis minimization problem. |
def weight_cw(r, cap_ws, **kwargs):
return cap_ws.loc[r.index[0]]
| Returns the weights of the Cap-Weigthed (CW) portfolio based on the time series of capweights |
def enc(weigths):
return (weigths**2).sum() ** (-1)
| Computes the Effective Number of Constituents (ENC) given an input
vector of weights of a portfolio. |
def encb(risk_contrib):
return (risk_contrib**2).sum() ** (-1)
| Computes the Effective Number of Correlated Bets (ENBC) given an input
vector of portfolio risk contributions. |
def insert_first_row_df(df, row):
df.loc[-1] = row
df.index = df.index + 1
return df.sort_index()
| The method inserts a row at the beginning of a given dataframe and shift by one existing rows.
The input row has to be either a single element (in case of 1-column dataframe) or
a dictionary in case of multi-column dataframe. |
def mkdir(path):
try:
os.mkdir(path)
except FileExistsError:
pass
return None
| Create the DIRECTORY, if they do not already exist |
def remove(flist):
flist = [f for f in flist if f is not None]
for f in flist:
try:
os.remove(f)
except FileNotFoundError:
pass
return None
| Remove file if it exists. |
def find_by_username(cls, name):
for user in cls.users:
if user.user_name == name:
return user
| Method that takes in username and returns a user that matches the username |
def user_exist(cls, name):
for user in cls.users:
if user.user_name == name:
return True
return False
| Method that checks if a contact exists form the contact list |
def find_by_account(cls, accountName):
for password in cls.passwords:
if password.account == accountName:
return password
| Method that takes in account and returns the password that matches the account |
def password_exist(cls, accountName):
for password in cls.passwords:
if password.account == accountName:
return True
return False
| Method that checks if a password exists from the password list |
def display_passwords(cls):
return cls.passwords
| Method that displays the passwords list |
def s(data):
return hex(ord(data))
| Serialize data into a string representing a hex code.
ex. |
def _binary_search(f, xmin, xmax, eps=1e-9):
middle = (xmax + xmin) / 2.0
while xmax - xmin > eps:
assert xmin < xmax
middle = (xmax + xmin) / 2.0
if f(xmax):
return xmax
if not f(xmin):
return xmin
if f(middle):
xmin = middle
e... | Return the largest x such f(x) is True. |
def conn2str(a_conn):
return "_".join(itok for ipart in a_conn for itok in ipart)
| Convert connective tuple to string. |
def writeHTMLFile(htmlText, filename):
import codecs
with codecs.open(filename, "w", "utf8") as htmlFile:
htmlFile.write(htmlText)
| Helper file to write the HTML file from the given text. It uses the
codecs module, which can deal correctly with UTF8 encoding. |
def args_from_user_params(user_params):
return {}
| Get keyword arguments for this plugin based on values in user params.
Plugin runners will set these automatically for all plugins. |
def pt(title=None, text=None):
if text is None:
text = title
title = "-------------------------------------"
else:
title += ":"
print(str(title) + " \n " + str(text))
| Use the print function to print a title and an object coverted to string |
def update_arc_modify_based_on_arc_node(sender, instance, created, *args, **kwargs):
if not created:
arc = instance.arc
arc.modified = instance.modified
arc.save()
| If an ArcElement Node is edited after the initial addition to the arc, update
the arc's last modified timestamp. |
def update_outline_modify_based_on_story_node(
sender, instance, created, *args, **kwargs
):
if not created:
outline = instance.outline
outline.modified = instance.modified
outline.save()
| If a StoryElementNode is edited after the initial addition to the outline, update the outline's
last modified timestamp. |
def rows(matrix):
if type(matrix) != list:
return 1
return len(matrix)
| Returns the no. of rows of a matrix |
def cols(matrix):
if type(matrix[0]) != list:
return 1
return len(matrix[0])
| Returns the no. of columns of a matrix |
def pivot_index(row):
counter = 0
for element in row:
if element != float(0):
return counter
counter += 1
return counter
| Returns the index of pivot in a row |
def pivot_value(row):
for element in row:
if element > math.exp(-8):
return element
return 0
| Returns the value of pivot in a row |
def mat_splice(matrix, r, c):
result = list()
for i in range(r):
row = matrix[i]
result.append(row[:c])
return result
| Function which returns a matrix with the first r rows and first c
columns of the original matrix |
def _detect_dataframe_cell_type(df):
if df.v_call.str.contains("IG\wV").all():
return "B cell"
elif df.v_call.str.contains("TR\wV").all():
return "T cell"
else:
raise ValueError(
"Mixed / unknown cell types found in dataframe: "
"{}".format(df.v_call.str.slice... | Detects whether cell type being analyzed is B or T cells |
def _replace_Ns_with_ref(ref, seq):
assert len(ref) == len(seq)
if "N" not in seq and "n" not in seq:
return seq
else:
replaced = ""
for r, s in zip(ref, seq):
if s == "N" or s == "n":
replaced += r
else:
replaced += s
a... | Replace Ns in a sequence given an aligned reference |
def _fill_missing_nt(ref_seq_aln, seq_aln):
if seq_aln.startswith("-"):
filled = ""
for pos, (char_ref, char_seq) in enumerate(zip(ref_seq_aln, seq_aln)):
if char_seq == "-":
filled += char_ref
else:
break
return filled + seq_aln[pos:]
... | Fill in nucleotides missing from the beginning of a sequence with
respect to a reference sequence |
def _trim_extra_nt(ref_seq_aln, seq_aln):
if ref_seq_aln.startswith("-"):
for pos, (char_ref, char_seq) in enumerate(zip(ref_seq_aln, seq_aln)):
if char_ref != "-":
break
return seq_aln[pos:]
else:
return seq_aln
| Trim extra nucleotides from the beginning of a sequence with respect to
a reference sequence |
def _no_stop_codon(aa_seq):
if "*" not in aa_seq:
return True
else:
return False
| Returns True if a sequence does not contain a stop codon,
otherwise returns False |
def _no_Ns(nt_seq):
if "N" not in nt_seq:
return True
else:
return False
| Returns True if a sequence does not have any N's |
def _check_vdj_len(nt_seq):
if len(nt_seq) % 3 == 1:
return True
else:
return False
| Verifies the length of a VDJ nucleotide sequence mod 3 equals 1
(The constant region continues the reading frame) |
def appointAddPeople(infoJson, name):
for i in infoJson["people"]:
if i["name"] == name:
i["appoint_people"] = i["appoint_people"] + 1
break
return infoJson
| search name And add 1 to appoint_people |
def build_id_table(artifact_cursor):
mapping = dict(
[
(row[0], str(row[1]) + str(row[2]))
for row in artifact_cursor.execute(
"SELECT obj_id, parent_path, name FROM tsk_files"
)
]
)
return mapping
| Build the map of object ids to file paths. |
def wait_for_element_to_load(driver, xpath):
while len(driver.find_elements_by_xpath(xpath)) == 0:
time.sleep(0.1)
| Checks if an element is loaded on a page |
def is_element_loaded(driver, element):
is_image_loaded = driver.execute_script(
"return arguments[0].complete && typeof arguments[0].naturalWidth != 'undefined' && arguments[0].naturalWidth > 0;",
element,
)
return is_image_loaded or False
| Check if image element is loaded and ready in the DOM. |
def _reindex_spatial_data_to_regions(ds, df):
res = ds.sel_points("reshape_index", lat=df.lat.values, lon=df.lon.values)
return res
| Reindexes spatial and segment weight data to regions
Enables region index-based math operations
Parameters
xarray Dataset
df: pandas DataFrame
Returns
|
def tasmin_under_32F(ds):
return ds.tasmin.where((ds.tasmin - 273.15) < 0).count(dim="time")
| Count of days with tasmin under 32F/0C |
def tasmax_over_95F(ds):
return ds.tasmax.where((ds.tasmax - 273.15) > 35).count(dim="time")
| Count of days with tasmax over 95F/35C |
def tasmax_over_27C(ds):
ds["gte_27"] = ds.tasmax.where((ds.tasmax - 273.15) >= 27.0).count(dim="time")
ds["gt_0_lte_27"] = ds.tasmax.where(0 < ds.tasmax - 273.15 < 27).count(dim="time")
return ds
| Count of days with tasmax gte 27C |
def _is_lua_comment(line):
return re.match(r"^--\s+", line)
| Checks if a line of text is a Lua comment.
line : str
A line from some Lua source code. |
def _convert_bool(b):
return str(b).lower()
| Converts Python bool values to Lua's.
For simplicity's sake, you can use Python's bool values for everything in
the codebase. Before it can go in the XML it has to be turned into a string,
and it must also be lowercased to match Lua's bool values, otherwise ROBLOX
won't recognize them. |
def transpose(records):
for page in records:
for row in zip(*(column.split() for column in page)):
yield row
| tranpose data from interpreted table columns
Args:
records: list of data per page, where each item comtains sublists of
data for various columns.
data per row |
def by_sample_id(de_novos):
samples = {}
for x in de_novos:
if x.person_id not in samples:
samples[x.person_id] = []
samples[x.person_id].append(x)
return samples
| collect de novos by sample for a cohort |
def count_sample_matches(first, second):
first = set((x.chrom, x.pos, x.ref, x.alt) for x in first if x.chrom != "X")
second = set((x.chrom, x.pos, x.ref, x.alt) for x in second if x.chrom != "X")
intersect = len(first & second)
union = len(first | second)
return intersect, intersect / union
| count variant matches between samples from two different cohorts |
def random_id(size=12):
def is_number(string):
try:
number = float(string)
return True
except ValueError:
return False
string = None
while string is None or is_number(string) or len(string) != size:
string = f"{random.getrandbits(size*4):x}"
... | make a random character string for semi-unique IDs
Args:
size: length of string to return. 12 characters should mean a 50% chance
of string collisions only after 20 million random strings.
random character string |
def tidy_complex_alts(alts):
alts = alts.copy()
alts[60] = "S"
alts[77] = "1D, -G"
alts[115] = "1I, +C"
alts[132] = "R"
alts[184] = "1D, -G"
return alts
| sort out the "complex" allele events |
def valid_allocation_request_data(application_round):
return {
"application_round_id": application_round.id,
"application_round_basket_ids": [],
}
| Valid JSON data for creating a new Reservation |
def extract_concept_entities(data):
all_entities = list(data.entity_to_idx.keys())
concept_entities = []
for ent in all_entities:
if ent[:9] == "concept__":
concept_entities += [ent]
return concept_entities
| This function takes the augmented training data and extracts all concept entities present.
If we are doing sampling, it is possible that not all of the concept entities are added. |
def run_length_decode(integers):
x = []
for index, val in enumerate(integers[::2]):
x += [val] * integers[1::2][index]
return x
| Expands a list of integers where every second integer is a count of the
integer before it. |
def delta_decode(integers):
array, last = [], 0
for i in integers:
last += i
array.append(last)
return array
| Turns a list of integers into a new list of integers where the values in
the first are treated as deltas to be applied to the previous value. |
def readFile(filePath):
with open(filePath, "r") as f:
fileData = f.read()
return fileData
| Returns data presend in a file |
def writeFile(filePath, writeData):
if type(writeData) != type("str"):
raise TypeError(f"Write Content Must Be Str Not {type(writeData)}")
with open(filePath, "r+") as file:
file.truncate(0)
file.write(writeData)
file.close()
return True
| Writes given data to given file |
def randfloat(start, end):
start = int(start * 10000000)
end = int(end * 10000000)
resultList = [i / 10000000 for i in range(start, end)]
return random.choice(resultList)
| Returns a random float between `start` and `end` |
def create_bytearray_str(b):
if b is None:
return None
s = ""
for item in b:
s += str(int(item))
s += " "
return s[:-1]
| Converts a bytearray into a string of ints. Elements are space delimited |
def ensure_dir(directory):
if not os.path.exists(directory):
os.makedirs(directory)
return directory
| Make sure the directory exists. If not, create it. |
def enforce_copy(disabled_ids, allowed_wids, kp_pred_unfinished, vocab_size):
for batch in range(len(allowed_wids)):
if kp_pred_unfinished[batch]:
indices_to_remove = [
i for i in range(vocab_size) if i not in allowed_wids[batch]
]
disabled_ids[batch].upda... | Update disabled_ids to satisfy constraints of KP vocabulary. |
def _boundaries_overflow(index, radius, length):
return ((index + radius) >= length) or ((index - radius) < 0)
| Checks boundaries defined by the index of the center and the radius are
inside the sequence of given length.
Returns True if boundaries are already outside the sequence,
False otherwise. |
def format_coordinate(number):
return "{:.2f}".format(number).rstrip("0").rstrip(".")
| Returns decimal in the format required by task. |
def count_groups(seqids, supergroups, unique=True):
group_counts = {g: 0 for g in set(supergroups.values())}
species = [seqid[:4] for seqid in seqids]
if unique:
species = set(species)
for spec in species:
group_counts[supergroups[spec]] += 1
return group_counts
| Counts the number of species in each supergroup covered. |
def traverse_json_entries(data, callback):
entries_count = 0
if isinstance(data, dict):
for k, v in data.items():
entries_count += 1
callback(k, v)
elif isinstance(data, list):
for v in data:
entries_count += 1
callback(None, v)
return entr... | Traverse json and execute callback for each top-level entry
Could later be optimized by accepting json uri instead of the full object
and using streaming request/parse APIs to exit early on validation error
Returns entries count if succeeded |
def validate_min_repeats(cls, v, values):
if values["request_type"] == "image_label_multiple_choice":
return max(v, 4)
return v
| min repeats are required to be at least 4 if ilmc |
def count_params(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
| Returns total number of model's trainable parameters. |
def dynamodb_item_to_json(item, indent=None):
result = {}
for key in item.keys():
if type(item[key]) is decimal.Decimal:
result[key] = float(item[key])
else:
result[key] = item[key]
return json.dumps(result, indent=indent)
| Function to serialize items retrieved from DynamoDB as JSON strings.
Amazon's DynamoDB API for Python returns numbers as decimal.Decimal
instances instead of ints or floats. This makes it so that you can't
just call json.dumps on an item retrieved from DynamoDB. If you want to
serialize a DynamoDB item to JSON, you can... |
def _fixup(d):
return {(k[1:] if k.startswith("_") else k): v for k, v in d.items()} if d else None
| Convenience method to let the protocol implementation use the key '_class'
instead of 'class', which is a reserved word, as an argument to the dict
constructor
|
def _padString(strIn, padding=None):
if padding is None:
return strIn
if not (isinstance(padding, int) and padding >= 0):
raise ValueError("Invalid padding argument {} ".format(padding))
pad = " " * padding
return pad + strIn.replace("\n", "\n" + pad)
| Replace every endline with endline + (#padding) spaces, for indent formatting |
def describe(description):
yield
| noop, just used to provide structure to test classes |
def stringify_arg_value(obj, arg):
value = getattr(obj, arg.lower())
value_prettified = pprint.pformat(value)
if type(value) is str and value_prettified.startswith("("):
value_prettified = value_prettified.replace("\n", "\\\n")[1:-1]
return value_prettified
| Prettifying the value argument's value at the given object. |
def lane_lines_directixes(lane_info):
def directrix(coefficients):
a, b, c = coefficients
return (b**2 - 4 * a * c + 1) / 4 * a
return directrix(lane_info.left_fit), directrix(lane_info.right_fit)
| Computes the parabola directrix for both curves. |
def load_pickle_from_file(file_name):
if not os.path.isfile(file_name):
return None
with open(file_name, "rb") as handle:
return pickle.load(handle)
| Loads a pickled object from a file |
def create_user_dir(path):
try:
os.mkdir(path)
except OSError:
print("Failed to create User Directory with " + path)
else:
print("Created directory {path_to_dir}".format(path_to_dir=path))
return path
| Creates a unique directory based on a path including a unique user_id |
def file_exist(filename):
try:
with open(filename) as f:
f.close()
return True
except IOError:
return False
| checks if a given file exist or not |
def resolve_token_auth(obj, info, **kwargs):
print(info.context)
user = info.context.get("request").user
return {"user": user}
| Gets current current user from context and returns a user, token and refresh token |
def load_flight_file(infile):
with open(infile, "rb") as readfile:
flightplan = pickle.load(readfile)
return flightplan
| loads a flight file from disk. |
def pyllbc_foreach(func, iterable):
for elem in iterable:
func(elem)
| Traverse the iterable value to execute function, mo matter the func return. |
def normalize_reference_name(name):
return name.strip().lower().replace("-", "_").replace(" ", "_")
| Simplify potentially variable ways to write out a reference name
by lowercasing it and replacing all dashes and spaces with underscores.
Parameters
name : str
Returns
str |
def most_recent_assembly_name(assembly_names):
match_recency = [
int(re.search(r"\d+", assembly_name).group())
for assembly_name in assembly_names
]
sorted_list_of_names = [
assembly
for (number, assembly) in sorted(
zip(match_recency, assembly_names), reverse=Tru... | Given list of (in this case, matched) assemblies, identify the most recent,
where "recency" is determined by sorting based on the numeric element of
the assembly name. |
def build_info_pair(key, val):
if val is True:
return key
if type(val) == list:
val = ",".join(map(str, val))
else:
val = str(val)
return "{}={}".format(key, val)
| Build key/val pair for info field. |
def build_sample_val(sample_val):
if type(sample_val) is list:
return ",".join(map(str, sample_val))
elif sample_val is not None:
return str(sample_val)
else:
return "."
| Build a specific value for a sample . |
def variant_ascending_position_sort_key(variant):
return (variant.contig, variant.start)
| Sort key function used to sort variants in ascending order by
chromosomal position.
This is a function rather than method to make it easier to serialize.
Returns
tuple of (str, int) |
def trim_shared_prefix(ref, alt):
n_ref = len(ref)
n_alt = len(alt)
n_min = min(n_ref, n_alt)
i = 0
while i < n_min and ref[i] == alt[i]:
i += 1
prefix = ref[:i]
ref_suffix = ref[i:]
alt_suffix = alt[i:]
return ref_suffix, alt_suffix, prefix
| Sometimes mutations are given with a shared prefix between the reference
and alternate strings. Examples: C>CT (nucleotides) or GYFP>G (amino acids).
This function trims the common prefix and returns the disjoint ref
and alt strings, along with the shared prefix. |
def trim_shared_suffix(ref, alt):
n_ref = len(ref)
n_alt = len(alt)
n_min = min(n_ref, n_alt)
i = 0
while i < n_min and ref[-i - 1] == alt[-i - 1]:
i += 1
if i == 0:
return (ref, alt, "")
return (ref[:-i], alt[:-i], ref[-i:])
| Reuse the `trim_shared_prefix` function above to implement similar
functionality for string suffixes.
|
def stream_gzip_decompress_lines(stream):
dec = zlib.decompressobj(zlib.MAX_WBITS | 16)
previous = ""
for compressed_chunk in stream:
chunk = dec.decompress(compressed_chunk).decode()
if chunk:
lines = (previous + chunk).split("\n")
previous = lines.pop()
... | Uncompress a gzip stream into lines of text.
Parameters
Generator of chunks of gzip compressed text.
Returns
Generator of uncompressed lines. |
def str_to_int(s):
if s.startswith("0x"):
return int(s, 16)
elif s.startswith("0b"):
return int(s, 2)
else:
return int(s)
| Convert binary strings (starting with 0b), hex strings (starting with 0x), decimal strings to int |
def deserialize(cls, object_dict):
return cls(
x=object_dict["x"],
y=object_dict["y"],
)
| Creates a new Obstacle model instance from a dictionary. The object
returned by this method can be used to create a new database entry.
Notably, *id* is not set by this method. Likewise the map relationship
is expected to be created from the view method. |
def ultima(palavra):
return palavra[-1]
| Exibe a ultima parte da string |
def write_file(path, content):
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
elif os.path.exists(path):
logging.warning("The file %s will be overwritten.", path)
with open(path, "w") as f:
f.write(content)
| Write string into local file. |
def parse_azure_url(azure_url):
re_pattern = r"^wasbs{0,1}://(?P<container>[^@]+)@(?P<account>[^@.]+).blob.core.windows.net/(?P<blob>.+$)"
match = re.match(re_pattern, azure_url)
if match:
return (match.group("container"), match.group("blob"), match.group("account"))
else:
raise Exceptio... | Parse out and return the container and blob names from an azure wasb url. |
def parse_s3_url(s3_url):
s3_url = s3_url.split("/")
bucket_txt = s3_url[2]
key_txt = "/".join(s3_url[3:])
return bucket_txt, key_txt
| Parse out and return the bucket name and key path of an s3 url. |
def ipynb2markdown(ipynb):
j = json.loads(ipynb)
markdown = ""
for cell in j["cells"]:
if cell["cell_type"] == "markdown":
markdown += "".join(cell["source"]) + "\n"
return markdown
| Extract Markdown cells from iPython Notebook |
def transifexjson2txt(jsondata):
data = json.loads(jsondata)
text = ""
for category, content in data.items():
for key, value in content.items():
text += value + "\n"
return text
| extract translations from Transifex JSON file |
def _interleave(lon, lat):
lon_lat = []
for c in range(len(lon)):
lon_lat.append(lon[c])
if c >= len(lat):
continue
lon_lat.append(lat[c])
return "".join(lon_lat)
| Interleaves a lon and lat array and joins the result
into a binary string. |
def _split(geohash, chars=None):
lon, lat = [], []
for i, c in enumerate(geohash):
if chars is not None and i >= chars:
break
lon.append(c) if i % 2 == 0 else lat.append(c)
return lon, lat
| Splits an interleaved binary string into lon and lat arrays. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.