content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def meters_to_feet(n):
"""
Convert a length from meters to feet.
"""
return float(n) * 3.28084 | 280c5bd6b310fbd29d9542fa425d26a5c8901508 | 618,663 |
def _find_missing_and_invalid_fields( required_fields, json_data ):
"""
Look for missing or invalid fields, and return them.
"""
missing = []
invalid = []
for req, types in required_fields.items():
if req not in json_data.keys():
missing.append( req )
if... | 62de326eb793c251d6e1b42009ceba208072897b | 618,666 |
def listSubset(requiredList, suppliedList):
"""Returns true if the requiredList is a subset of the suppliedList."""
return set(requiredList).issubset(set(suppliedList)) | 6603e5a5b23cdbd9c8e9f99217dc913bd5e14e8e | 618,668 |
def all_equal(*args):
"""
Returns True if all of the provided args are equal to each other
Args:
*args (hashable): Arguments of any hashable type
Returns:
bool: True if all of the provided args are equal, or if the args are empty
"""
return len(set(args)) <= 1 | 0b99d6408014f7e69b19e895aad43f568af19d88 | 618,670 |
import json
def loads(string, **kwargs):
"""Load object from JSON string."""
return json.loads(string, **kwargs) | 349b41b141ee97263fb69f0d23c1c3bfe756f698 | 618,675 |
from datetime import datetime
def _utcnow(now):
"""Returns the given time if not None, or datetime.utcnow() otherwise."""
if now is None:
return datetime.utcnow()
return now | a5f7c03c3c3b4f2cdbb9c5d841c12b52264ee4e0 | 618,677 |
def _FormatHumanReadable(number):
"""Formats a float into three significant figures, using metric suffixes.
Only m, k, and M prefixes (for 1/1000, 1000, and 1,000,000) are used.
Examples:
0.0387 => 38.7m
1.1234 => 1.12
10866 => 10.8k
682851200 => 683M
"""
metric_prefixes = {-3: 'm',... | d5d2927d144156e822f0931626473cee9bc7135b | 618,684 |
def _pair(s: str, i: int, i1: int, j: int, j1: int) -> str:
"""Return a stack representation, a key for the NN maps
Args:
s: Sequence being folded
i: leftmost index
i1: index to right of i
j: rightmost index
j1: index to left of j
Returns:
str: string re... | b647c247c87834f86d48b4ad68a509be2869acaf | 618,685 |
def find_cuds_object(criterion, root, rel, find_all, max_depth=float("inf"),
current_depth=0, visited=None):
"""Recursively finds an element inside a container.
Use the given relationship for traversal.
Args:
criterion (Callable): Function that returns True on the Cuds object
... | 78e227f425ba386aaa26577a1b0f9900a552cde4 | 618,689 |
import re
def condense_zero_units(css: str) -> str:
"""Replace `0(px, em, %, etc)` with `0`."""
return re.sub(r"([\s:])(0)(px|em|%|in|q|ch|cm|mm|pc|pt|ex|rem|s|ms|"
r"deg|grad|rad|turn|vw|vh|vmin|vmax|fr)", r"\1\2", css) | 5617762d45c3dfd01ec560c7cd3f882dbb13b1e6 | 618,695 |
def common_data(list1, list2):
""" returns true if both lists have something in common
"""
result = False
# traverse in the 1st list
for x in list1:
# traverse in the 2nd list
for y in list2:
# if one common
if x == y:
result = True
return result
return result | fc4ca20c44f4af38b796a3e219b43e0917a2cc2e | 618,697 |
def dict2bibtex(data):
"""
Convert a single BibTeX entry dict to a BibTeX string.
:param data: A dict representing BibTeX entry, as the ones from \
``bibtexparser.BibDatabase.entries`` output.
:return: A formatted BibTeX string.
"""
bibtex = '@' + data['ENTRYTYPE'] + '{' + data['ID'... | 82a9889c2da730e13ecd49d3a26750e398a09aec | 618,701 |
def translate_to_hsv(in_color):
"""
Standard algorithm to switch from one color system (**RGB**) to another (**HSV**).
:param tuple(float,float,float) in_color: The RGB tuple list that gets translated to HSV system. The values of each element of the tuple is between **0** and **1**.
:return: The transl... | b315907f3858046c6a422f097921d3ac3c2098d9 | 618,702 |
import fnmatch
def getGlobValue(globs, path):
""" Returns the value of the glob, where path matches
:Parameters:
- `globs`: The glob list (``[(glob, associated value)]``)
- `path`: The path to match
:Types:
- `globs`: sequence
- `path`: ``str``
:retur... | ca5a6569549905b1167dd0a8f17bdf380d34dc8d | 618,704 |
from typing import Callable
def preprocess_check_and_replace(old: str, new: str) -> Callable[[str], str]:
"""
Create a preprocess function that replaces `old` with `new` (and fails when there is no `old`).
"""
def preprocess(orig: str) -> str:
assert old in orig
return orig.replace(ol... | d952ffecb397009933f3bd89c44a35d5b12a6c61 | 618,705 |
def get_info_fields(record_info, info_fields):
"""
Get info fields from pyvcf record_info
Args:
record_info (pyvcf record infos): info fields from vcf record
info_fields (list): info to get from record_info
Returns:
info (dict): Info dictionary containing requested info fields
... | a1728f5176ae3376e129a84bee013e3a68e62baf | 618,709 |
def index_(iterable, x) -> int:
"""Return zero-based index of the first item whose value is equal to x.
Raises a ValueError if there is no such item.
We need a custom implementation instead of the built-in list .index() to
be compatible with NumPy array and Pandas Series.
Parameters
----------... | 6ad47ffa118e90f954a85b1784bb40a80f053306 | 618,713 |
from functools import reduce
def compose(*funcs):
"""
chained function composition wrapper
creates function f, where f(x) = arg0(arg1(arg2(...argN(x))))
if *funcs is empty, an identity function is returned.
Args:
*funcs: list of functions to chain
Returns:
a new functio... | bfe2e59d8c479bc1ee1d89d4c43c5568db180eb3 | 618,714 |
def str_or_none(val):
"""Like str, but allows a value of None to pass through as-is."""
return str(val) if val is not None else None | b39c665aca86c3370848407991283d5639190b62 | 618,716 |
def fibonacci(i):
"""
This function finds the ith number in the Fibonaci series, -1 otherwise.
"""
if i <= 0:
return -1
#Fixing the code to see if test cases go through
if i <= 2:
return 1
prev = 1
curr = 1
for k in range(i-2):
temp = curr
curr += prev
prev = temp
return curr | 223b5cdeea2e94623317304ae1fafd8921772e13 | 618,718 |
import math
def set_angle(angle: float) -> float:
"""
Ensure the angle is within the range of [-pi, pi] radian convention
"""
return math.atan2(math.sin(angle), math.cos(angle)) | 9731d1053d9f5c5a2977cf6db03a3c0310c8dd40 | 618,719 |
def only_1st_and_lst(items):
"""Return (at most) the first and last items from a list.
"""
# print(str(items[0]) + '-' + str(items[len(items) - 1]))
items_len = len(items)
if items_len == 0:
return False
# Plot only 1st and last.
return items if items_len == 1 else items[::items_len... | 5634da677da60755746690ed3dabc413826520e4 | 618,724 |
def b(string):
"""
convert string (unicode, str or bytes) to binary representation
"""
if isinstance(string, bytes):
return string
return string.encode('utf-8') | 4090ec8cd1274122ffc1d8744b59c33c8145d8b2 | 618,725 |
def getSep(path, pattern='/\\'):
"""
Get path separator or indicator.
:param path: relative or absolute path (str).
:param pattern: guess characters to compare path (str).
:return: sep (str).
.. note:: It is equivalent to os.path.sep but obtained from the given path and patterns.
"""
i... | dcbc9c28e9fb18f50377d1184a1432c24fadfadf | 618,726 |
def widget_type(field):
"""
Template filter that returns field widget class name (in lower case).
E.g. if field's widget is TextInput then {{ field|widget_type }} will
return 'textinput'.
"""
if hasattr(field, 'field') and hasattr(field.field, 'widget') and field.field.widget:
return fie... | 3683d94c4e7e43a1ddd5cbeeacc6bbddaea537bd | 618,727 |
def csv2json(csvdata, header=True): #----------------------------------------<<<
"""Convert CSV data to JSON (i.e., list of dictionaries).
csvdata = string containing a CSV file
e.g., open('filename.csv').read()
header = whether the data contains a header row (if not, output fields
... | 123c9bd862a265a07549f49bf2c969186cbb6d1a | 618,741 |
def range_check(low, high):
"""\
Verifies that that given range has a low lower than the high.
>>> range_check(10, 11)
(10.0, 11.0)
>>> range_check(6.4, 30)
(6.4, 30.0)
>>> try:
... range_check(7, 2)
... except ValueError as e:
... print(e)
... | 0fb2281e77bf8b4447629f0628bb28001c31a38d | 618,744 |
import pytz
def utc_to_local(user, utc_dt):
"""
Turn a date into a date matching use timezone. It's useful when you need
to display a date.
"""
local_tz = pytz.timezone(user["timezone"])
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
return local_tz.normalize(local_dt) | 1b8dd759515aaae722666dd1dac4babeb686ec2a | 618,748 |
from datetime import datetime
def add_day_month(df):
"""Creates columns for the Day, Day int value, and the Month
Args:
df (pandas.DataFrame): The original pandas dataframe
Returns:
df (pandas.DataFrame): The pandas dataframe with the DAY, DAY_NUM, and MONTH columns
"""
df['DAY'... | 387428a6c3e8a8c75c634e18eb84afd3211b6d2a | 618,749 |
def newalpha(img, alpha):
"""
Multiplication of image alpha channel and alpha
:param img: PIL.Image
:param alpha: float
:return: PIL.Image
"""
out = img.copy()
a = img.getchannel('A')
a = a.point(lambda i: i * alpha)
out.putalpha(a)
return out | a24e40e101edc6fe44921ff03d66394a0a252e58 | 618,753 |
from typing import List
import random
def load_paragraphs_from_files(file_name_list: List[str], shuffled: bool=True):
"""
This function loads paragraphs from multiple files.
A paragraph is just a string.
It can, but does not need to contain multiple sentences.
The function takes a list of file nam... | 792860a9f2859899a118642f70d234594e673af2 | 618,758 |
def start_new_game(player1, player2):
"""
Creates and returns a new game configuration.
"""
board = [['-']*3 for _ in range(3)]
game = {
'player1': player1,
'player2': player2,
'board': board,
'next_turn': player1,
'winner': None
}
return game | 3e43cfe73298f34f4c544ba48cbeea8158a4ff33 | 618,760 |
def key_for_value(dictionary, value):
"""finds the key for a given value in a dict."""
return list(dictionary.keys())[list(dictionary.values()).index(value)] | 1928ee59649b8505f49b567293f886a4ab7f03fa | 618,765 |
import re
def natural_sort(lst):
"""Sort a list in natural order."""
def key(s):
return [int(t) if t.isdigit() else t.lower() for t in re.split(r'(\d+)', str(s))]
return sorted(lst, key=key) | 9d723fe3334fccdd55b67ddbad3b16e472e54ec8 | 618,768 |
def split_semicolon(text):
"""Split lines by semicolon
Useful to manage path in windows or email names
>>> split_semicolon('Jean;Jane; John')
'Jean\\nJane\\nJohn'
"""
return text.replace("; ", "\n").replace(";", "\n") | a4bb8262fd589e46e1f08f61589808e2badb6ca8 | 618,773 |
import re
def is_canonical(version):
"""Check if a version string is in canonical format of PEP 440."""
# Source: https://www.python.org/dev/peps/pep-0440
pattern = (
r'^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))'
r'*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))'
r'?(\.d... | 7930d4210fd82b4eb210895854fbfba7e244e470 | 618,774 |
def dasherize(text):
"""Replace underscores with hyphens."""
return text.replace('_', '-') | 7c442dc1342a5e12987719c03c68a694b46b052d | 618,775 |
from typing import List
from typing import Tuple
def read_data() -> List[Tuple[str, int]]:
"""
Read list of people and how much did they pay
:return: List[name, how much money did he / she gave]
"""
print('Enter names and amounts of money in format of "Jack: 1984"'
'If man didn\'t pay an... | f05764dd5114bdf231a1e7182df0fe7319258de7 | 618,779 |
import typing
def atoi(text: str) -> typing.Union[int, str]:
"""returns numeric representation of text if possible else original text
Parameters
----------
text: str
text whose numeric representation is needed
Returns
-------
typing.Union[int, str]
the integer representat... | b6677ddad4e4f6655c08aabdf93c09800b6427f8 | 618,781 |
import yaml
import collections
def ParseMappingAsOrderedDict(enable=True,
loader=yaml.Loader,
dumper=yaml.Dumper):
"""Treat OrderedDict as the default mapping instance.
While we load a yaml file to a object, modify the object, and dump to a yaml
file,... | 6145d9737e9a11b2cc65c24e271917dd0f9a46a0 | 618,797 |
def lerp(x, x0, x1, y0, y1):
"""
Linearly interpolate between points (x0, y0) and (x1, y1) to
get the value of y at x.
:param x:
:param x0:
:param x1:
:param y0:
:param y1:
:return:
"""
t = (x - x0) / (x1 - x0)
return (1 - t) * y0 + t * y1 | 0fb707ab2d066177642108fc64655b5ca2115256 | 618,799 |
def container_to_string(cont):
"""Convert a container to a command line string.
Elements of the container are joined with a space between them,
suitable for a command line parameter.
If the container `cont` is only a sequence, like a string and not a
container, it is returned unmodified.
Para... | f92115bb0aeb0dfef69d277cef7f612600cf2d6a | 618,800 |
def verifyRasterNum(alg, parameters, context, rasters, mini, maxi=None):
"""Verify that we have at least n rasters in multipleInput"""
num = len(alg.parameterAsLayerList(parameters, rasters, context))
if num < mini:
return False, 'You need to set at least {} input rasters for this algorithm!'.format... | 70b9125e79262453db66768fa17023d86cfeb571 | 618,801 |
import pathlib
def grab_files_from_dir(input_path, file_types=("*.jpg", "*.png", "*.tif")):
"""Grab file paths specified by file extensions.
Args:
input_path (str or pathlib.Path):
Path to the directory where files
need to be searched.
file_types (str or tuple(str)):
... | 67998747acf59aa7e48102a7b5ceb719f6cb91a5 | 618,809 |
import json
def loadjson(filepath, field=None):
"""load a json file
Parameters
----------
filepath : str
The file path string.
field : None, optional
The string of field that want to be loaded.
"""
with open(filepath, 'r', encoding='utf-8') as f:
if field is None:... | 6a2e755d2d0523df8b1606e1152432b83faf1068 | 618,813 |
def list_datasets(print_list=True):
"""Print available datasets in the cptac.pancan module.
Parameters:
print_list (bool, optional): Whether to print the list. Default is True. Otherwise, it's returned as a string.
"""
datasets = [
"PancanBrca",
"PancanCcrcc",
"PancanCoad",... | 037e101a9c907fbb0a773c845a1a2b4af3ff2504 | 618,820 |
def initial_check(filename):
"""
Check the first 4 bytes of a file for the 'magic number' and return the
file endianness. If the 'magic number' is not found, the file is probably
not a PSU-WOPWOP file and an error is raised.
"""
endianness_flag = 'little'
# read first four bytes to check f... | 2031eda8df6c97492db4ece540d4eed9352be15d | 618,826 |
def strip_base_dir(filename, base_dir):
"""Strip base directory from filename if it starts there.
>>> strip_base_dir('/path/to/base/relpath/to/file',
... '/path/to/base/')
'relpath/to/file'
>>> strip_base_dir('/path/to/somewhere/else/relpath/to/file',
... '/path/t... | fb383f355f30f20179dcefa8facb0dc5b24bf0f7 | 618,827 |
import base64
def btoa(a):
"""Jinja filter to mimic JavaScript's ``btoa`` function."""
return base64.b64encode(a.encode()).decode() | 75576b4da07834fd28f9c8f1ddaf9ca7acbc2f74 | 618,831 |
from typing import Tuple
from typing import Callable
from typing import Dict
from typing import Any
def runner(args: Tuple[Callable, Dict[Any, Any]]) -> Any:
"""Runner function for process pool
Args:
args: A pair where the first element is the function to run and
the second element is a d... | 2ae3ed9301ada5cb5e860db43ec3860c2390ffdc | 618,834 |
def format_key_list(keys_str):
"""
Format the key list
:param keys_str: a string containing the keys separated by spaces
:return: a string containing the keys ordered and separated by a coma and a space
"""
key_list = keys_str.split(" ")
key_list.sort()
return ", ".join(key_list) | 66780979c2f8f2a50f9db720d021c7857857a929 | 618,835 |
def HealthCheckName(deployment):
"""Returns the name of the health check.
A consistent name is required to define references and dependencies.
Assumes that only one health check will be used for the entire deployment.
Args:
deployment: the name of this deployment.
Returns:
The name of the health ch... | 37c124819afa61370ae5841d691e1d40ce06fe25 | 618,836 |
import math
def jd_to_weekday(jd):
"""Return weekday of Julian Day
Return:
int - weekday [1..7] where 1 is Ahad/Sunday
"""
return int(math.floor(jd + 1.5) % 7) + 1 | 87fc9bf7f1604b234222884d3c7ff2784b5db6db | 618,837 |
def _branch_error_analyzer(output):
"""Checks if there is an error in `output` for branch creation.
"""
if len(output["error"]) > 0:
l = output["error"][0]
return "Switched to a new branch" not in l
else:
return False | 8e8dc6b155735825ceae226680aa2c2caec358c2 | 618,839 |
def _parse_book_links(dom):
"""
Parse links to the details about publications from page with book list.
Args:
dom (obj): HTMLElement container of the page with book list.
Returns:
list: List of strings / absolute links to book details.
"""
links = []
picker = lambda x: x.pa... | 868ad793c7c9c9674785d30dcd63f387e7a1e1f9 | 618,841 |
import socket
import logging
def GetHostName(fully_qualified=False):
"""Return hostname of current machine, with domain if |fully_qualified|."""
hostname = socket.gethostname()
try:
hostname = socket.gethostbyaddr(hostname)[0]
except (socket.gaierror, socket.herror) as e:
logging.warning('please check... | 0d388d0087732ec312f738f12b59c89cc8bde888 | 618,842 |
def get_armature_modifier_rig_object(mesh_object):
"""
This function gets the armature associated with a mesh via its armature modifier.
:param object mesh_object: A object of type mesh.
:return object: A object of type armature.
"""
for modifier in mesh_object.modifiers:
if modifier.ty... | 2634ec055df2ee7933d42cc0792abe0033b9536c | 618,843 |
import decimal
def _decimal(value):
"""Return env var cast as Decimal."""
return decimal.Decimal(value) | 70adfcdbd09c00829f510d8d84bcfb5deba13a75 | 618,847 |
import jinja2
def read_template(template):
""" Returns a jinja template
Parameters
---------
template: str
template file that is to be stored as variable.
Returns
-------
output_template: jinja template object
output template that can be 'jinja.render' -ed.
"""
... | b093fca578f4601a279ac4dde44cf584f3508b6f | 618,848 |
def is_tie_bar(a_character: str) -> bool:
"""
Whether a character is used to tie two characters in the
international phonetic alphabet together. The tie bar is
usually used to indicate an affricate, or double-articulation.
"""
return a_character in ["͜", "͡"] | 0c76bc2dbda31a27b2bcfb7a19feaf55d309199e | 618,854 |
def max_key(dic):
"""
Based on https://stackoverflow.com/questions/42044090/return-the-maximum-value-from-a-dictionary
Returns the key of the max value in a dictionairy
"""
return [k for k, v in dic.items() if v == max(dic.values())][0] | 0e228494a876e0b94be319fd29b383e2c548504b | 618,855 |
def strToSet(string):
"""
Convert a string into a set
"""
ens = set()
for char in string:
ens.add(char)
return ens | c16c5f48eb51ede206929e6af37d7699e9c15c1e | 618,856 |
def read64str(f):
"""Read 8 bytes from a file and return as an ASCII string.
"""
return f.read(8).decode("latin1") | 532dd21f33d5935b3aa9fc329747f3edd468a6aa | 618,860 |
from warnings import warn
def add_attrs(remember_added_attrs=True, if_attr_exists="raise", **attrs):
"""Make a function that will add attributes to an obj.
Originally meant to be used as a decorator of a function, to inject
>>> from on.util import add_attrs
>>> @add_attrs(bar='bituate', hello='world')... | 220573f813e569dea8e4dae43bbd6b6eac05bb91 | 618,861 |
import math
def ToVVU(AxorRh):
"""
Convert to van Vleck Units (vvu = m3/3.77 10-35)
@param AxorRh: Axial or Rhombic component
@type AxorRh : float
"""
return AxorRh*(1./((12*math.pi))*10000) | fdd26282914b3156fd38eb4f5c6af8edfea1127c | 618,864 |
def parseTR(trCode):
"""요청 TR 코드 파싱
:param trCode: TR 코드
:type trCode: str
:return: TR코드 내역을 반환
::
parseTR("t0425") # 주식체결/미체결
"""
ht = {
"t0424" : "주식잔고",
"t0425" : "주식체결/미체결",
"t8407" : "멀티현재가조회",
"t8412" : "주식챠트(N분)",
... | 7670ef3fc112311fc56e974548106493c8659eb9 | 618,867 |
def pd_train_eval_split(df, eval_split=0.0, seed=None, reset_index=False):
"""Splits pandas dataframe into train/eval sets.
Uses pandas DataFrame.sample to create the split.
Args:
df: Dataframe of examples to be split.
eval_split: Float in range (0, 1), fraction of dataset to split out as eval
set... | e8183a60529b7f8209886389cbd63762c0c80b79 | 618,869 |
def find_bounds(f, y):
"""
Find approximate bounds for binomial search.
"""
x = 1
while((f(x) < y) and (x<1000483646) ):
x = x * 2
lo = -100
if (x ==1):
lo = -100
else:
lo = x/2
if(x > 1000):
x = min(x,2047483646)
return lo, x | c0cbf9f9867d028f8d83da5ae05860613946e987 | 618,870 |
def get_seq(query_filepath):
"""
Get a sequence from a single-entry FASTA file.
"""
f = open(query_filepath,'r')
lines = f.readlines()
lines = [row.strip() for row in lines] # restituisce una copia della stringa con i caratteri iniziali e finali rimossi per le righe in fila
lines = [row.repl... | fd77760a389e192d60ecc592e1a3ca8fa1c9b17e | 618,876 |
def remap_clocks(ports, clock_map):
"""
Remaps clock dependencies of all ports and returns a new port map.
Does not remap clocks for "P1" and "P2" ports.
"""
new_ports = {
"input": set(),
"clock": set(),
"output": set(),
}
for key in ["input", "clock", "output"]:
... | 3dc49429b7d4da660473223d3265aa52fddc0d78 | 618,880 |
def get_string_names(elems, names, label):
"""
Transform the list of values into a string to write
elems is a dictionary with the values
names is the selected keys we want for the output
label is the model label
"""
# Start to write the output string
ss = ""
for name in names:
... | ce37f96ab6d436e85791f300a31a5e24d889bf7b | 618,881 |
import _pickle
def unpickle(fname):
"""Load pickled object from `fname`"""
with open(fname) as f:
return _pickle.loads(f.read()) | f9483a16a70e2eee325da4c7de29e7a90e9094f6 | 618,882 |
def check_inv_exists(v, phi):
"""
Given a vertex id u and a set of partial isomorphisms phi.
Returns True if an inverse transformation exists for v
"""
for _phi in phi:
if _phi[1] == v:
return True
return False | b62cc46f4dd9a123bfb980d99c739b9871a35fbd | 618,884 |
import requests
def post_file(input_filepath, input_format, output_format):
"""Posts a file to the REST API and converts between the given formats."""
with open(input_filepath) as input_file:
input_text = input_file.read()
url = 'http://localhost:5000/convert/{}/{}'.format(
input_f... | ebf29734719ec379bf1759ebdec03fe53c25636b | 618,885 |
def filter_by_speaker_id(queryset, speaker_id):
"""Filter a Quip-based queryset by Quote's Speaker's id."""
queryset = queryset.filter(quotes__speaker_id=speaker_id)
return queryset | 0a6ad6cf4f3ce20799941b56b08e7ad6283925b1 | 618,887 |
def convert_flat_stitch_id_to_pubchem_cid(stitch_flat_id: str) -> str:
"""Convert a flattened STITCH identifier (no stereochemistry) to PubChem compound identifier."""
return str(abs(int(stitch_flat_id[3:])) - 100000000) | 419cf8a93ace03ce8942ca23ce06360339218ba9 | 618,888 |
def load_loglikelihood_from_hdf5_group(group):
"""
Loads a loglikelihood from the given hdf5 group.
group: the hdf5 file group from which to load the Loglikelihood
returns: Loglikelihood object of the correct type
"""
try:
class_name = group.attrs['class']
cls = eval(cl... | c96e9cfff710c49dd850d64aa3a187589ac1dac9 | 618,889 |
def int_to_bitstring(n: int, desired_len=None) -> str:
"""Converts an integer into a bitstring (unicode representation) of desired length. MSB leftmost, LSB rightmost"""
bitstring = bin(n)[2:]
if desired_len:
current_len = len(bitstring)
assert current_len <= desired_len, 'Desired length to... | 566c7129b3ff8d515dc13f5a79add9b95d8501ed | 618,890 |
def q_liq_top(rho_top_liq, L_septum, L_top):
"""
Calculates the specific flow rate of the liquid for 1 m of drain septum
Parameters
----------
rho_top_liq : float
The destiny of liquid at top of column, [kg/m**3]
L_top : float
The flow rate of liquid at top of column, [kg/s]
... | 5aaf515f2c932ddec67c20734f7bf711b67025b8 | 618,892 |
def make_dict(in_text):
"""
Create a counter of the string
"""
my_dict = dict()
for c in in_text:
if c in [' ', '\n']:
continue
if c not in my_dict.keys():
my_dict[c] = 1
else:
my_dict[c] += 1
return my_dict | 37abe722499f1eabdc4c52356ea60e54df458c8e | 618,899 |
from typing import Union
def to_string(byte_array: Union[bytes, bytearray]) -> str:
"""
convert a byte array into string
:param byte_array: a latin1 encoded byte array
:return: a decoded string
"""
string = []
for byte in byte_array:
string.append(chr(byte))
return "".join(str... | 29bda53940a4cc465418f7885c76b562d40286f5 | 618,900 |
def get_user_input(prompt: str) -> str:
""" Get user answer given prompt
Args:
prompt (str): String with to confirm action by user
Returns:
str: "y" or "n" strings
"""
response = input(prompt)
assert response in ['y', 'n'], 'Invalid input entered by user'
return response | 90ae9a5a6b8e8c7f9de689be96c852882cb04c54 | 618,901 |
def combine_dicts(dict1, dict2):
""" Combine two dicts into one, respecting common keys
If dict1 and dict2 both have key a, then x[a] and y[a] must both
be dictionaries to recursively merge.
Args:
dictionary1 : dict
dictionary2 : dict
Returns:
output : dict
"""
outpu... | 380042beb913b8ad8bf46b30e3acf1d1d372e104 | 618,905 |
def examine_categoricals(df, columns=None):
""" Returns (to driver memory) a list of tuples consisting of every unique value
for each column in `columns` or for every categorical column in the source
data if no columns are specified """
default_columns = [
"SeniorCitizen",
"Par... | c056f0d753225c4825d77ba660d572c30b6656fb | 618,906 |
def represent(instance: object, *args, **kwargs) -> str:
""" Return an appropriate representation string for the instance.
>>> class Cat(object):
... def __init__(self, name, *, age=0):
... self.name, self.age = name, age
... def __repr__(self):
... return represent(self... | 3356cfa496057b57e0b1b5075ba9aa455bb28f37 | 618,907 |
def numberp(thing):
"""
NUMBERP thing
NUMBER? thing
outputs TRUE if the input is a number, FALSE otherwise.
"""
return type(thing) is int or type(thing) is float | 654882a5a6620176d3723b195f09e995d7abf614 | 618,911 |
def get_ordered_values_from_table_by_key(table, reverse=False):
"""
Get value list where the value orders are determined by their keys.
Args:
table: a table of data
reverse: value list in a reversed order
Returns:
- an ordered list of values
"""
keys = [_ for _ in table... | 21c3dcef91b3a8e5fb7d9a36aa2acba87e508432 | 618,914 |
def get_backends_url(config):
"""Return the URL for a backend."""
hub = config.get('hub', None)
group = config.get('group', None)
project = config.get('project', None)
if hub and group and project:
return '/Network/{}/Groups/{}/Projects/{}/devices/v/1'.format(hub, group,
... | 6f51ab43d61c1692bb92274a4ae3f723e2999822 | 618,915 |
def depth_first_search(grid, start, target):
"""
Search a 2d grid for a given target starting at start.
Args:
grid: the input grid as a List[List]
start: the start grid in format (x,y) zero index
target: the target value to find in the grid
Returns:
Coordinate of the tar... | 1bd8c5c5c5a3b44df97e9ff899576bfab44ad4e4 | 618,917 |
def _exam_score(review):
"""Returns an HTML-formatted exam score, if applicable."""
if review.type_ == "Evaluation":
return u""
return u"<p>Scored %s on written exam." % review.exam_score | d0102ee3be47cef9bd3a72ad615bbbd8f692f982 | 618,920 |
def is_unweighted(matrix):
"""Quick function to determine if a Matrix is likely an unweighted adjacency matrix"""
return matrix[matrix.nonzero()].min() == 1 and matrix.max() == 1 | 37fe5491aa13da8bf48236fa351ba5b58c74ab21 | 618,923 |
def to_iso_8601_format(dt):
"""
Convert the supplied datetime instance to the ISO 8601 format as per API specs.
:param dt: The datetime instance to convert.
:return: Supplied datetime as timestamp in ISO 8601 format.
"""
if not dt:
return
if isinstance(dt, str):
return dt
... | 87f2de31302c4b60cb44118955b6d0cdffcaf71c | 618,924 |
def getNamedNode(node, nodename):
"""
Return first named subnode of the supplied node
"""
subnodes = node.getElementsByTagName(nodename)
if len(subnodes) > 0:
return subnodes[0]
return None | df716df94b1a7554a0c047253b34ffe04b61c102 | 618,929 |
def get_lname(request):
"""
Returns the name of the label which has been changed
:param request: incomming request
:return: label name from request (String)
"""
return request.json['label']['name'] | 0514051be4495d4108508a9ae0b2f1a651745907 | 618,932 |
def indent(code, level):
"""
indent code to the given level
"""
return code.replace("\n", "\n" + (" "*level)) | 71e1584165cac2ea76ac7a28c2b3368bf6ae9ef1 | 618,935 |
def keys(dictionary: dict) -> tuple:
"""Return a tuple of keys in a dictionary."""
return tuple(dictionary.keys()) | 064d4a0156a8a0f97a3210d7daf3eaebb42a5e0f | 618,937 |
def is_benign(ba, bs_terms):
"""Check if criterias for Benign are fullfilled
The following are descriptions of Benign clasification from ACMG paper:
Benign
(i) 1 Stand-alone (BA1) OR
(ii) ≥2 Strong (BS1–BS4)
Args:
ba(bool): Stand Alone term for evidence of benign impact
bs... | 25497b21d4b68bcdc655836414046c28ffc4086e | 618,938 |
import zlib
def undeflate(data):
"""Decompresses data for Content-Encoding: deflate.
(the zlib compression is used.)
"""
decompressobj = zlib.decompressobj(-zlib.MAX_WBITS)
return decompressobj.decompress(data)+decompressobj.flush() | 077f13e8ce7c22181a10ba9de843f2f05d292565 | 618,941 |
def output_modal(func, output: set):
"""Updates output with the result of func, a modal which returns a set.
Cheap way to monitor the modal result of a bpy.Operator."""
def wrap(self, context, event):
result = func(self, context, event)
output.update(result)
return result
return... | a8cd9a2b2d05621ce37f6cff08a3845b83005724 | 618,946 |
import re
def find_ipv6_with_subnet(string):
"""
Find and return IPv6 address with subnet inside a string.
This function will only return an ipv6 address with a subnet
:param string: (str) The string to search for ipv6 with subnet
(i.e. "Successfully added Subnet 2001:420:30a:200::a10/127")
... | eb9fdf088727e4d5e3ebb8e361c60846656f8bdc | 618,948 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.