content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def invalid_idx(idx, affinity):
"""Return position index of positive sample in idx.
Inputs:
idx: [num_sample]
affinity: a list of neighbours' idx
Returns:
invalid: [num_sample], 1 means this sample is invalid
"""
invalid = (idx == affinity[0])
for j in range(1, len(affini... | 2a8029e3d114dd422ccfdc3b875e68d64716d2a2 | 605,382 |
import re
def sanitise_m_starfile_name(starfile_name: str) -> str:
"""
Makes sure STAR filename is properly formatted for import into M (requires _data.star)
:param starfile_name:
:return:
"""
if starfile_name.endswith('_data.star'):
return starfile_name
elif starfile_name.endswith... | 120be13283b90b30205d5c0e4fda52f9250662c7 | 605,383 |
def argsort(numbers):
"""Returns the indices that would sort an array of numbers.
The function is similar to NumPy's *argsort* function.
Note
----
For a large list of numbers reconsider using NumPy's *argsort* function,
since this function might take too long.
"""
return [i[0] for i in... | d7f9b964113f7670f2270b1a511529e68eebb176 | 605,384 |
def predict_fn(input_object, model):
"""
SageMaker XGBoost model server invokes `predict_fn` on the return value of `input_fn`.
"""
return model.predict(input_object)[0] | 553b8bb813ffa83afbd400adc376ff9afe4f0f32 | 605,392 |
def write_uleb128(num: int) -> bytearray:
""" Write `num` into an unsigned LEB128. """
if num == 0:
return bytearray(b'\x00')
ret = bytearray()
length = 0
while num > 0:
ret.append(num & 0b01111111)
num >>= 7
if num != 0:
ret[length] |= 0b10000000
... | fb13878a0c5e984cb1447dfad4536c6f9dcb9ed3 | 605,401 |
def get_has_feature(sentences, features):
"""
Parameters
----------
sentences: list of strs,
The info text of a mushroom species split into sentences.
features: list of strs
Key words ["bruis", "bleed"] for attribute does-bruise-or-bleed
Return
------
list of str,
['t'] if o... | c2d53e59b21573ea0b95009d34640e86f66c8a6a | 605,403 |
def neighbors(node, test_set):
""" Return the neighbors of this node that are within test_set."""
result = set()
for neighbor in node.neighbors:
if neighbor in test_set:
result.add(neighbor)
return result | 047abde15277a10434c39fe37426d94853fb5357 | 605,405 |
def separate_time(undivided_time, is_seconds = False):
""" Given the time in hours or seconds, returns the time in common divisions,
i.e. days, hours, minutes, seconds
"""
if is_seconds is True:
_undivided_time = undivided_time
else:
_undivided_time = undivided_time * 3600
d... | f1bc4be44205664c670fe42358247e34aec2662d | 605,407 |
def weights_linear_time_1d(weights_linear_time):
"""Timeseries of weights_linear_time"""
return weights_linear_time.isel(lon=0, lat=0, drop=True) | 42d196552fa48272e57851fd7849af99becb791e | 605,411 |
def limit_offset_query(query, limit=None, offset=None):
"""Apply limit and offset to the query.
:param query: SQLAlchemy Query
:type query: sqlalchemy.orm.Query
:param limit: Limit number of Items returned, defaults to None
:type limit: int, optional
:param offset: Specify the offset of the fir... | c9140bd63988654628caac5cfa6d450eb8bd831c | 605,414 |
def gray(s):
"""Color text gray in a terminal."""
return "\033[1;30m" + s + "\033[0m" | 4b482ce771ad3b39f5f275767f2fe351e403f1ba | 605,415 |
from pathlib import Path
def read(*, day: int, year: int, test: bool = False) -> str:
"""Read the input data from a file for the respective day and year.
If test is `True`, read the test input file. Raises `FileNotFoundError`
if the file does not exists.
"""
datafile = Path(__file__).parent.paren... | e2df0aff72400b3629d864d4d63433b6ce10973f | 605,417 |
import json
def json_to_fns_and_samples(fn):
"""
Input json must contain a list of tuples [(a0, b0), (a1, b1), ...], where (a, b) represents a filename `a`
and its sample tag `b`.
return ([a0, a1, ...], [b0, b1, ...])
fn -- json file containing a list of tuples, e.g., [(a0, b0), ...,]
...doct... | 546a6e03d821c33ed922892d26434cc56d54cb25 | 605,418 |
def hash_distance(sim_hash_one, sim_hash_two):
"""
Calculates hamming distance between two sim hashes.
:param sim_hash_one: long - sim hash
:param sim_hash_two: long - sim hash
:return: (int) returns hamming distance.
"""
f = 128
x = (sim_hash_one ^ sim_hash_two) & ((1 << f) - 1)
ans... | 4862f5d231146417b227210f080d121043feb349 | 605,420 |
import requests
def display_people_in_space() -> bool:
"""The number of people in space at this moment. List of names when known.
:return: function executed correctly
:rtype: bool
"""
res = requests.get("http://api.open-notify.org/astros.json").json()
number: int = res.get("number")
craf... | d415561865049478cb06f3aaaa89184987c41d48 | 605,425 |
def hexToBitStr(hexStr):
"""
provide the hex string in format 'ab ab ab....
Returns the bits in string format, as list of bytes
"""
b = [int(hexStr[i*3:i*3+2],16) for i in range(int((len(hexStr)+1)/3))]
bytesequence = ['{0:08b}'.format(g) for g in b]
return bytesequence | 1d8229ca290288b4c3487f83895db8d1c18eaca5 | 605,426 |
def buffer_with_count(self, count, skip=None):
"""Projects each element of an observable sequence into zero or more
buffers which are produced based on element count information.
Example:
res = xs.buffer_with_count(10)
res = xs.buffer_with_count(10, 1)
Keyword parameters:
count -- {Number}... | 69aa66975bc41fba293eddc9a167be735f8b00fc | 605,432 |
def uriunsplit(uri):
"""
Reverse of urisplit()
>>> uriunsplit(('scheme','authority','path','query','fragment'))
"scheme://authority/path?query#fragment"
"""
(scheme, authority, path, query, fragment) = uri
result = ''
if scheme:
result += scheme + ':'
if authority:
... | 43f5a826ed62838af9fb59c034bf07b695a1b8e0 | 605,433 |
def format_tags(tags):
"""Formats tags as comma-separated list of urls to tags index."""
return ", ".join([f'<a href="tags.html#{tag}">{tag}</a>' for tag in tags]) | 5371cc166650eb51bc94a23fcb4b2e2709c7d9d8 | 605,435 |
def joinDockerInstruction(input_instruction: str, input_params: list[str]) -> str:
"""
Reverse operation to splitDockerInstruction
:param input_instruction: docker instruction, e.g. FROM
:param input_params: list of parameters, e.g. [ubuntu]
:return: string representation of a docker instruction, e... | eaed2441aa58b34fbd9b220e46d9d25026d7b122 | 605,446 |
def remove_add_mode_entry(log_entries):
"""libtrace creates an "Add Mode:..." message when logging is enabled.
Strip this out of results since our test subjects don't create it."""
return [entry for entry in log_entries
if "message" in entry and
not entry["message"].startswith("Add M... | fb403f7723424bbb67b5021b7dba677b20e64d40 | 605,452 |
def ignore(process, longname, flag, value):
""" ignore inputs, return None """
return None | 83ef5f71415f695389a04208f41574228eaab647 | 605,453 |
from pathlib import Path
from datetime import datetime
def _valid_cache(path: Path, expired_days=30):
"""Return True if the file exists and is younger than `expired_days`."""
if not path.is_file():
return False
days_old = (datetime.now() - datetime.fromtimestamp(path.stat().st_mtime)).days
ret... | ee8e1f1bae5afbb261fcc13c9863c7ca959dd6a4 | 605,459 |
import re
def sanitize_worksheet_name(
name,
max_width = 31):
"""
Sanitizes XLSX worksheet name.
See https://support.office.com/en-us/article/Rename-a-worksheet-3F1F7148-EE83-404D-8EF0-9FF99FBAD1F9.
"""
if name.startswith('\''):
name = name[1:]
name = re.sub(
r'\0|\*... | 41f12446ee0101c5fe3795ac5ee553b7af94f7bf | 605,468 |
def summarize_lane(lane_lines, column_mapping):
"""Given a list of lines, summarize what they contain, returning
a dict of { project: { pool: [ list of libs ] } }
The caller is presumed to have filtered the lines by lane already.
"""
#Make a dict of dicts keyed on all the projects seen
res... | a4100d0b65762a2859e0f775f48326b42fa78b68 | 605,471 |
def ymd2night(year, month, day):
"""
convert year, month, day integers into cannonical YEARMMDD night string
"""
return "{:04d}{:02d}{:02d}".format(year, month, day) | 9ee2b77fee66f930363ddb2ae8322edc7c7d17e5 | 605,474 |
def scale(x, range, drange):
"""
From real coordinates get rendered coordinates.
:param x: source value
:param range: (min,max) of x
:param drange: (min,max) of sx
:return: scaled x (sx)
"""
(rx1, rx2) = float(range[0]), float(range[1])
(sx1, sx2) = float(drange[0]), float(drange[1]... | c7cdb5a38f7c7869d7cdaa7f4aed778199b1de36 | 605,479 |
def file_length(file_obj):
"""
Returns the length in bytes of a given file object.
Necessary because os.fstat only works on real files and not file-like
objects. This works on more types of streams, primarily StringIO.
"""
file_obj.seek(0, 2)
length = file_obj.tell()
file_obj.seek(0)
... | 052254469e4a20e4b510cec52434ec88614d92c1 | 605,480 |
from typing import List
from pathlib import Path
def _filter_unused_builds(used_build_paths: List[Path], build_path: Path) -> bool:
"""Return whether a build is not used."""
return build_path.name not in used_build_paths | f2218f23feb4e17b7d3e16abea4d83a420fc5d89 | 605,483 |
def find_resource(platform, id):
"""
Search for a resource in a platform and raise an error if the resource is
not found.
:param platform: The Platform object to search in
:param id: Name of the resource to search for
"""
resource = platform.find_communication_resource(id)
if resource is... | 1d152cec6491d481d5f19c6985fc6bf1a104cbb9 | 605,484 |
def centerify(text, width=-1):
"""Center multiline text."""
lines = text.split(" ")
width = max(map(len, lines)) if width == -1 else width
return "\n".join(line.center(width) for line in lines) | 0c24a19fd16b0fde1588c9108fa39be989e36ad5 | 605,486 |
def get_run_mode(settings):
"""Extract run mode from settings."""
run_mode = None
if settings.is_gruneisen:
run_mode = "gruneisen"
elif settings.is_joint_dos:
run_mode = "jdos"
elif settings.is_isotope and not (settings.is_bterta or settings.is_lbte):
run_mode = "isotope"
... | 3ce178502b2a764c4aff10c8b82e210b5c9122f9 | 605,487 |
def url_direction(
direction_int # type: int
):
"""Parse InMon-defined URL direction"""
if direction_int == 1:
return "Source"
elif direction_int == 2:
return "Destination"
else:
return "Unknown" | 35825a6b21b23750ae0c2593a463424e9e0ae192 | 605,491 |
def column(value, *columns, **kwargs):
"""
Extract one or more columns from a tab-separated format. If more than one
index is provided, a list is returned; if only one index is provided, only
the value is returned.
The value of `sep` is used to split the columns, so for example, to parse
CSV fi... | 71282fe22ab1ce7c6ad8e4f40b17140cc1bdabde | 605,492 |
def all_items_have_attrs(items, attrs):
"""Return True if all items has all attributes, otherwise, False"""
for item in items:
for attr in attrs:
if not hasattr(item, attr):
return False
return True | 69881eb03726137655974c183b8509eed59160e4 | 605,493 |
def stemmer_fun(stemmer, token):
"""stemming token by porter one algoritm
Arguments:
stemmer {obj} -- instance of PorterStemmer
token {str} -- token
Returns:
str -- stemmed token
"""
return stemmer.stem(token) | a29e3859d736c469b556de9f26c2c86749a135df | 605,501 |
def sort_pvalue(val):
""" Sort p-values by value """
return val[1] | 3370591dc87d3a714605fe03d711185ba1ff96f4 | 605,502 |
async def healthz():
"""No-op basic health check."""
return {"status": "ok"} | c59017d2bfc42a804598747d3523ceab4050b29e | 605,506 |
def _to_str(t) -> str:
"""
Transform binary into string.
"""
return t.decode("utf-8") | f7812afad3813c4f8d20310968ee47c0f9120232 | 605,507 |
def _snat_rule_format(dnat_rule):
"""Format a SNATRule as a iptables rule.
:param ``SNATRule`` dnat_rule:
SNAT rule to insert
:returns:
``str`` -- Iptables SNAT rule.
"""
rule = '-s {src_ip} -d {dst_ip} -p {proto} -m {proto}'.format(
proto=dnat_rule.proto,
src_ip=(dn... | 6b590375d5c72eff2c878856fb1fe9acc51df2a7 | 605,508 |
def to_dec_deg(dms):
"""Convert to decimal degrees."""
if not dms:
return 0.
deg, minutes = dms.split()
side = minutes[-1]
minutes = minutes[:2]
float_deg = int(deg) + int(minutes) / 60.
return float_deg if side in ('N', 'E') else -float_deg | cda4f30290bd39622ac84ba201354dcc98725723 | 605,514 |
def _flatten(orig):
"""
Converts the contents of list containing strings, lists of strings *(,lists of lists of strings,...)* to a flat
list of strings.
:param orig: the list to flatten
:return: the flattened list
"""
if isinstance(orig, str):
return [orig, ]
elif not hasattr(o... | 61ae7d225dcc97b8a1b1522971750da6dc0dbfcb | 605,515 |
from typing import Union
def resolve_size(size: Union[float, int]) -> str:
"""
Resolve memory size in human readable format.
Args:
size: Memory size to resolve.
Note: This function currently supports size resolution upto TB, any
size beyond it would return `Memory Exceeded`. To resolve this,
... | ca114554492104518107020c504488299c727b87 | 605,516 |
def check_choice(choice):
"""Validate choice for yes or no"""
return choice == 'y' or choice == 'n' | 4c393533b83600f622133aff999b2c3830c82655 | 605,518 |
def iterable(obj):
""" Return True if obj is iterable with a well-defined len()."""
if hasattr(obj, "__iter__"):
return True
try:
len(obj)
except:
return False
return True | 955b3be33965f998bac8579eb9cff87351a037ae | 605,522 |
def hex_distance(a, b):
"""Returns the distance between two hexagons in a grid"""
return (abs(a[0] - b[0])
+ abs(a[0] + a[1] - b[0] - b[1])
+ abs(a[1] - b[1])) / 2 | ef31445d6108558aa03727ac1577944bf83fc2a2 | 605,523 |
import re
def _sanitize_label(label):
"""
Clean up a label by removing non-letter, non-space characters and
putting in all lowercase with underscores replacing spaces.
Parameters:
- label: The text you want to fix.
Returns:
The sanitized label.
"""
return re.sub(r'[^\w\s]... | 85da5af75ab8c5f8e0d6ae162771e5f397a0ca73 | 605,530 |
def remap(x, oldmin, oldmax, newmin, newmax):
"""Remap the float x from the range oldmin-oldmax to the range newmin-newmax
Does not clamp values that exceed min or max.
For example, to make a sine wave that goes between 0 and 256:
remap(math.sin(time.time()), -1, 1, 0, 256)
"""
zero_to_one... | 3d5812d108f807b75e56bddda6edbe61177c17b4 | 605,536 |
def toVName(name, stripNum=0, upper=False):
"""
Turn a Python name into an iCalendar style name,
optionally uppercase and with characters stripped off.
"""
if upper:
name = name.upper()
if stripNum != 0:
name = name[:-stripNum]
return name.replace('_', '-') | 2c1af88647b2207bf6c88826e0b1c668ae697de1 | 605,543 |
import torch
def euler2mat(angle):
"""Convert euler angles to rotation matrix.
:param angle: [3] or [b, 3]
:return
rotmat: [3] or [b, 3, 3]
source
https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py
"""
if len(angle.size()) == 1:
x, y, z = ang... | 2b125cd1ad3430f1beaf628da9a1aa45a2f4f783 | 605,547 |
def _trim_columns(columns, max_columns):
"""Prints a warning and returns trimmed columns if necessary."""
if len(columns) <= max_columns:
return columns
print(('Warning: Total number of columns (%d) exceeds max_columns (%d)'
' limiting to first max_columns ') % (len(columns), max_columns))
return c... | 5019c575085f972087166acb1da134d96457ccf7 | 605,553 |
def is_staticmethod(kls: object, method: str) -> bool:
""" Determines if the method of the class is a staticmethod.
Args:
kls: The class to test for the staticmethod.
method: The name of the method to be checked. This method does not need
to exist; if it does not exist, this function ... | 6b430a503916991e308d225311f9bee445cc00ba | 605,557 |
def strUnpad(text_as_bytes, pad=0):
"""Convert a bytes or bytearray
to a str removing trailing bytes matching int pad."""
text_b = bytes(text_as_bytes) # bytes type has the useful methods
if pad is not None:
text_b = text_b.rstrip(bytes([pad]))
return text_b.decode("utf-8") | 3e072d7c0b3510186c66762032ab6e904f3f4753 | 605,558 |
from typing import ByteString
import base64
def encode_bytes(b: ByteString) -> str:
"""Encode the binary data to a string.
Args:
b: Binary data to encode.
Returns:
WAMP JSON string representation of the binary data.
"""
e = b"\0" + base64.b64encode(b)
return e.decode() | 036b57d45466fffad30c42b906c1cb94bddcf965 | 605,560 |
def bubble_sort(arrayParam):
"""
Sort a list using bubble sort algorithm. Run time: O(n**2)
"""
done = True
array = arrayParam[:]
for l in range(1, len(array)):
if array[l] < array[l - 1]:
done = False
if done == True:
return array
while done == False:
... | 7a18b04df7748becb23044195a845223429d198d | 605,561 |
def nextpow2(i):
"""
Find the next power of 2 for number i
"""
n = 1
while n < i:
n *= 2
return n | 1420664ccbe194e198520bcb3bf309c71615ccda | 605,562 |
def phred_to_prob(q):
"""Convert a phred score (Sanger or modern Illumina) in probabilty
Given a phred score q, return the probabilty p
of the call being right
Args:
q (int): phred score
Returns:
float: probabilty of basecall being right
"""
p = 10 ** (-q / 10)
return ... | 8d1c0304c0058650f4ac613b6dde958ca22faa7f | 605,565 |
def create_connect_request_message(source_peer_id, target_peer_id, timeout):
"""
creates a connect request message
:param source_peer_id: peer id of source peer
:param target_peer_id: peer id of target peer
:param timeout: timeout in seconds
:return: connect request message as string (formatted ... | 1204dba8e76857ff34d483139a4cc82f39444385 | 605,566 |
def get_file_content(file):
"""
get the content of a given file
:param file: the file to get the content of
"""
content = ''
with open(file, 'r') as f:
content= f.read()
return content | fc15ae1b0021f57c97a27184104b83933bcbecb4 | 605,569 |
from pathlib import Path
def GetTestsPath() -> Path:
"""path to the "tests" folder"""
return Path(__file__).parent.absolute() | 2223ae9f0af57f7beeac3bc1f1edc54fc652f202 | 605,571 |
def count_file_lines(file_path):
"""Count how many lines the given file has.
Args:
file_path (str): Path to the target file.
Returns:
int: Number of lines in the file.
"""
file = open(file_path, "r")
total_lines = 0
for _ in file:
total_lines += 1
file.close()
... | 7ae659ebcebbc323d101e0ae4880bd322675d4a7 | 605,572 |
def __first_line(string: str, delimiter: str = "\n") -> str:
"""Returns only first line up to next delimiter item occurred.
Args:
string (str): given string item
delimiter (str): separator string
"""
return string.split(delimiter)[0] | afc38d14da3e7d0cce4008829d5bc20f9888d059 | 605,576 |
def remove_build_suffix(version):
"""Remove build suffix (if exists) from a version."""
if version.find("-dev") >= 0:
return version[:version.find("-dev")]
if version.find(".dev") >= 0:
return version[:version.find(".dev")]
if version.find("dev") >= 0:
return version[:version.find("dev")]
return v... | 75c084a7f18bc6bf97f5e8af178a25656d9318d1 | 605,582 |
def inc(ia, incr):
"""create a copy of an int[]. The values of the copy are the original values incremented by a fixed number"""
iaC = [None] * 9
for i in range(9):
iaC[i] = ia[i] + incr
return iaC | 2f1b03c102d66229ebad7386bd84a8c2e6cb3618 | 605,586 |
def _service(request):
""" Returns service host URL as derived from request """
return ('http://', 'https://')[request.is_secure()] + request.get_host() | 89a185af7886dd1e7294304de399de1f0e771277 | 605,587 |
def inputs(request):
"""
Served at host/job/inputs
:param request:
:return: JSON response with all job inputs
"""
resp = help(request)
return resp | 6e09b7bdb2d9dd93e952cae3a5c8f7cad5a24266 | 605,590 |
def silent(obj):
""" Mark view method or class as "silent" so events won't be fired.
Should be used as decorator on view classes or methods.
:param obj: Any object that allows attributes assignment. Should be
either view method or view class.
"""
obj._silent = True
return obj | 916a66634eeaa78f3223590cbb2ec2c88748ad9b | 605,592 |
from typing import List
def get_topic_names() -> List:
"""Return list of topic names to use in the tests."""
return ["test.t1", "test.t2", "test.t3"] | 1d9ed55d7c6f47201a77b88e05f7c4cb9f568c51 | 605,596 |
def _is_int(x):
"""Checker function for Integer required inputs."""
return isinstance(x, int) or x.isdigit() | 8db0f8336c49edf456cd1d0451770dea13dd432a | 605,597 |
def _validate_pv(module, vg, pvs):
"""
Function to validate if the physical volume (PV) is not already in use by
another volume group or Oracle ASM.
:param module: Ansible module argument spec.
:param vg: Volume group name.
:param pvs: Physical volume list.
:return: [bool, message] or modul... | 4a8d13ae97a3ce2747b5cf08bdafad42ae514893 | 605,598 |
def bin_stats(arr) -> str:
"""Return a string basic statistics for a binary array of either {0,1} or {True,False}"""
n = len(arr)
k = sum(arr)
p = 100. * k / n if n != 0 else 0.
return f"{k}/{n} ({p:.2f}%)" | 388f2a3351e6958cd57b2db5ea2c6d47c7801cec | 605,599 |
import hashlib
def get_sha256(file):
"""
Generates a sha256 checksum from file
:param file: absolute path to file
:return: sha256 checksum
"""
sha = hashlib.sha256()
with open(file, 'rb') as f:
while True:
data = f.read(0x100000)
if not data:
... | 888b95d00a4bd7331ce3b24a5b9d397b24732e5b | 605,601 |
def rgb2cmyk(r, g, b):
"""
Convert rgb color to cmyk color.
"""
c = 1 - r
m = 1 - g
y = 1 - b
k = min(c,m,y)
c = min(1, max(0,c-k))
m = min(1, max(0,m-k))
y = min(1, max(0,y-k))
k = min(1, max(0,k))
return c, m, y, k | 4b74af9ce8eb6719ce31336b86c0c57f2ab50442 | 605,602 |
def can_pack(data_list):
"""
Converts list of tuples and combines them into an array
rendition. Each val is broken into individual byte values
and appended to bytearr output (LSB first)
Args:
List of tuples in form ((int) val, (int) len_in_bytes). val must be
in range [0, 2**len_in_b... | cc628da790f97879f9959b5f8b266d92423d0e91 | 605,603 |
def could_be_mongo_object_id(test_id:str = "") -> bool:
"""
Tests if passed-in string is 24 lower-case hexadecimal characters.
Parameters
----------
test_id : str
String representing a possible mongodb objectId
Returns
-------
test_val : bool
True if test_id is 24 l... | fd6e0118d0558a1f4fc0835f1ba226331faf86ec | 605,606 |
def doit(f,arg):
"""
Returns the result of the call f(arg)
Parameter f: the function to call
Precondition: f a function that takes one argument
Parameter arg: the function argument
Precondition: arg satisfies the precondition of f
"""
return f(arg) | 971de178e285377dd2f57b1d3dc965f84b368464 | 605,607 |
import logging
import requests
import hashlib
def fetch_tarball_sha256(url):
""" Get the sha256 of a tarball """
logging.info("Fetching tarball from {}...".format(url))
response = requests.get(url, stream=True)
sha256 = hashlib.sha256()
for chunk in response.iter_content(chunk_size=1024 * 1024):
... | 71d3a71c1b66a599c13ac29731049d6d39087a08 | 605,608 |
def isFloat(string):
""" Return a true is string is convertable to a float, otherwise false.
"""
try:
float(string)
return True
except ValueError:
return False | f37156b167a20aa80c600be56c65ed2945c99648 | 605,609 |
from datetime import datetime
def datetime_string_to_datetime(datetime_string):
"""
This function converts ISO 8601 time string with timezone info to a datetime object
preserving the original timezone.
"""
try:
dt = datetime.strptime(datetime_string, '%Y-%m-%dT%H:%M:%S%z')
return d... | 4a820a749b6a2b4bda67ce926bb1404c16e56e94 | 605,612 |
def IsPosInt( x ):
"""Test if a number is an integer"""
try:
val = int(x)
return val > 0
except ValueError: return False | c207457d05f8df5132eb70917872f831bcb72139 | 605,613 |
def read_list(path: str):
"""
Read UTF-8 encoded word list from path.
Example file:
house
play
train
...
:param path str: file path to utf-8 word list
"""
with open(path, 'r') as file:
word_list = []
for line in file:
word_list.append(line.strip())
... | 8c170a78e15b9905552e2b2f752b74819761dfd2 | 605,614 |
def collapsebins(hist, bin, func=lambda b: b>bin):
"""Collapses bins of a histogram into one, based on the given function.
The function is given all bins (keys) and for every bin that tests positive,
it will collapse it to the chosen bin.
This function copies the given histogram, rather than modifying... | fda79376aef228abc72d02f0ec2111f5bd8fe288 | 605,616 |
def print_pauli_list_grouped(pauli_list_grouped):
"""Print a list of Pauli operators which has been grouped into tensor
product basis (tpb) sets.
Args:
pauli_list_grouped (list of lists of (coeff, pauli) tuples): the
list of Pauli operators grouped into tpb sets
Returns:
None
... | cc58f5a9dce2ee77fdf46d9801f617ca85cf6306 | 605,617 |
def vsub(v, w):
"""Subtract a vector from another."""
try:
return tuple(i - j for i, j in zip(v, w))
except TypeError:
return v - w | 743a182a05d38e5aca7fa2c16e9c64e8a483f5a8 | 605,618 |
def predict_proba(model, test_X):
"""Get the prediction_proba scores of a model given some test data"""
return model.predict_proba(test_X) | acc0b934c63ff597bd6168ee4dd3444a79e4f75d | 605,619 |
def is_multi_instance_task(conf):
# type: (dict) -> bool
"""Determines if task is multi-isntance
:param dict conf: task configuration object
:rtype: bool
:return: task is multi-instance
"""
return 'multi_instance' in conf | 11262a4ac738916f84a82fd82404002b334586ca | 605,622 |
def optional_arg_decorator(fn):
"""
A decorator which _optionally_ accepts arguments.
So a decorator like this:
@optional_arg_decorator
def register_something(fn, optional_arg = 'Default Value'):
...
return fn
will work in both of these usage scenarios:
@register_somethin... | 67d24393838c9349b07d622f9a39c28761dab855 | 605,628 |
def meanSunEl(xmlroot):
"""Get the mean sun elevation angle from the xml."""
return float(xmlroot.find('IMD/IMAGE/MEANSUNEL').text) | 0d9865afdfc5729a1d39b1a091e845c508a35f12 | 605,629 |
def remove_none_args(args):
"""Remove the `None` from the `argparse` argument object
Parameters
----------
args : `argparse.Namespace`, required
`argparse` argument object
Returns
-------
`argparse.Namespace` : `argparse` argument object without `None`
"""
a... | afd971e46b83dde15e99e7bae1fbf63414b6b346 | 605,631 |
def restrictGender(mp, category, gender):
""" Selects the minimal pairs that have a given gender
For example, allows one to only keep pairs with masculine entries """
dropouts_1 = list(mp.loc[(mp.cgram_1 == category) & (~mp.genre_1.str.contains(gender,na=True))].index)
dropouts_2 = list(mp.loc[(mp.cgram... | ab3254e6edfa8ce158c0ea7b89b6af9229385c50 | 605,632 |
def preprocess_value_with_position(values, position):
"""check value is valid and compatible with position, and turn integer into list"""
if isinstance(values, (list, tuple)):
if len(values) != len(position):
raise ValueError(
"Length of values is not compatible with positio... | 2320f5af4457771b619ded8993822b1c2ae12695 | 605,633 |
def startswith_word(phrase, startswith):
"""Check if a string starts with a word
Basic startswith method doesn't separate into words, so checking if a string
starts with '$foo' will return true for both '$foo' and '$fooooooo'.
Parameters
==========
phrase : str
Phrase to check startswi... | 5c0e0ad79bf53ffc8489b167f4b8d8e331c786dd | 605,638 |
def route_value(to_route_value, count, default=None):
"""
Routes only a single `name` - `value` pair.
Parameters
----------
to_route_value : `Any`
The respective value to route
count : `int`
The expected amount of copies to generate.
default : `Any`, Optional
Opt... | 8ccdd9edd3b8ba1b09438158ed8f54559aed7564 | 605,643 |
def direction_to_tuple(direction):
"""Returns the tuple coordinate offset from the start
hexagon given a certain direction"""
return {
'n' : (0, -1),
'ne' : (1, -1),
'se' : (1, 0),
's' : (0, 1),
'sw' : (-1, 1),
'nw' : (-1, 0)
}[direction] | bcddbc24e8c3b1bdf2e0c13f0d28e4286e8f05be | 605,651 |
def GetAdminKeyName(email):
"""Returns a str used to uniquely identify an administrator.
Args:
email: str user email.
Returns:
A str that can be used to uniquely identify a given administrator.
"""
return 'Admin_' + email.lower() | cef9af7a32d6f4de5e4ddebb418c47f3893819aa | 605,654 |
import json
def isJson(tstr):
""" if tstr is valid JSON, return object created from the string, else, return None """
ret = None
try:
ret = json.loads(tstr)
except ValueError:
pass
return ret | 0dd369cdbdd1e2a5c6e83b18e8777ad686e6000d | 605,655 |
def msb(n):
"""Extract the most significant bytes from n."""
return n >> 8 | f0f9336e4348634a584e517cb54ac482b23cbe80 | 605,656 |
def count_nines(loss_rate):
"""
Returns the number of nines after the decimal point before some other digit happens.
"""
nines = 0
power_of_ten = 0.1
while True:
if power_of_ten < loss_rate:
return nines
power_of_ten /= 10.0
nines += 1
if power_of_ten ... | e95894f03b5d976a12537517cfaea02b41520fee | 605,657 |
def modify_filter(record):
""" A filter function to modify records.
"""
# Input filters can safely modify record.
record["int"] *= 2
return record | bd9ec4ddae91203b8c9d25281d6c875426a05130 | 605,658 |
def to_bool(value):
""" Converts value to a bool """
return value.lower() in ['true', 'yes', 'on'] | 839996c37167fd8f816a9f081a83fd2a58777ef7 | 605,660 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.