content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import tempfile
def PacklfwRoImage(rorw_file, loader_file, image_size):
"""Create a temp file with the
first image_size bytes from the loader file and append bytes
from the rorw file.
return the filename"""
fo=tempfile.NamedTemporaryFile(delete=False) # Need to keep file around
with open(loader_file,'rb')... | f8a952ce78fd2c6d53f9ac9febd896f4432b199a | 574,552 |
import math
def xyz_to_lab(xyz, reference=(95.047, 100.0, 108.883)):
"""Convert CIE-XYZ color to CIE-Lab."""
delta = 6 / 29
f = [xyz[k] / reference[k] for k in range(3)]
x, y, z = [math.pow(t, 1 / 3) if t > math.pow(delta, 3)
else (t / (3 * delta * delta) + 4 / 29)
for t ... | 23c4041534420b079dd021b8e6799bad4f55e48e | 574,553 |
def toTable(config):
"""Transforms a two-level dictionary of configuration options into a
list-of-dictionaries, each with the following fields:
* section
* field
* value
"""
table = []
for section in config.keys():
for k, v in config[section].items():
tabl... | e5f57d522aeff228979a693213ad61d485502d9e | 574,554 |
def format_metric(metric, form):
"""Returns a string representation for metric-format combinations"""
if callable(metric):
metric_string = metric.__name__
else:
metric_string = str(metric)
return "{}-{}".format(metric_string, form.__name__) | 3256daf5cab0210170df4d997d1e8aab94cf2fe5 | 574,558 |
def get_bit(data, bit_index):
"""
Get bit as integer at index bit_index from bytes array.
Order is from left to right, so bit_index=0 is MSB.
"""
if bit_index < 8 * len(data):
cur_byte = data[bit_index // 8]
return (cur_byte >> (7 - bit_index % 8)) & 0x1
raise RuntimeError("Out o... | 9d21b2ad712c31a7fe729e6c010f24f24cf9e6bc | 574,562 |
def minimum_of(*column_names, **extra_columns):
"""
Return the minimum value over the supplied columns e.g
min_value=patients.minimum_of("some_column", "another_column")
Note: this ignores "empty values" (i.e. the values used if there is no data
for a particular column, such as 0.0 for numeric v... | 28df01737b9e97d5ddd59fa63668a56ebbb6ff1c | 574,564 |
def predictXVal(y, params):
"""
Predicts the x-axis value of a given y-axis value
that belongs to a curve given its parameters
@param y: y-axis value of the points to be estimated
@param params: (tuple) of the lane line fitted parameters
"""
a, b, c = params
return a*y**2 + b*y + c | 6e92ca7e8ea837d19ce5bdd577bda9062ddedbd7 | 574,565 |
def bit_not(n: int, numbits: int = 64):
""" Python's ints are signed, so use this instead of tilda """
return (1 << numbits) - 1 - n | 1af5e87d638300f7648e15a63780d938b8489770 | 574,566 |
def getLast(text, signs):
"""
Returns a position of the sign which occurs the last.
@param {string} text.
@param {Array.<string>} signs.
@return {number} Position.
"""
positions = [text.rfind(sign) for sign in signs if text.rfind(sign) != -1]
if positions:
retur... | 7acdcc0007c1977c16f21635a681ab4654a6015c | 574,567 |
def replace_token(spacy_doc, idx, replacement):
"""Replace token in position idx with replacement."""
return " ".join([spacy_doc[:idx].text, replacement, spacy_doc[1 + idx:].text]) | 51d082bc98845ad763c2cf92fa75e224ef3b0768 | 574,569 |
import re
def remove_escape_chars(s, chars):
"""Removes escapes from any escaped occurances of the given characters in
the given string.
Args:
s: a string
chars: the iterable (e.g., string or list) of characters to unescape
Returns:
the unescaped string
"""
return re.... | a7b105f5044500d08c44da18600c42129c073ac5 | 574,570 |
import torch
def mat2euler(rot_mat, seq='xyz'):
"""
convert rotation matrix to euler angle
:param rot_mat: rotation matrix rx*ry*rz [B, 3, 3]
:param seq: seq is xyz(rotate along z first) or zyx
:return: three angles, x, y, z
"""
r11 = rot_mat[:, 0, 0]
r12 = rot_mat[:, 0, 1]
r13 = r... | d06397aaa3ecd15211a2fb20483aef0ef4223568 | 574,573 |
def read_generic_file(filepath):
""" reads any generic text file into
list containing one line as element
"""
text = []
with open(filepath, 'r') as f:
for line in f.read().splitlines():
text.append(line.strip())
return text | 236a142629a1ced710fdb7710e7b9fa84fd05a4b | 574,576 |
def precip_to_energy(prec):
"""Convert precip to W/m2
Parameters
---------
prec : (mm/day)
"""
density_water = 1000
Lv = 2.51e6
coef = density_water / 1000 / 86400 * Lv
return coef * prec | d264eb741df893b70ec48826fae13787c1394221 | 574,579 |
import shutil
def task_clean_up(*args, **kwargs):
"""
Cleans up after tasks. By default, this involves removing a temporary directory,
but more can be done on a per-app basis based on the `task_model` kwarg.
Note that some parameters are kwarg-only due to Celery mechanics rather than convenience.
... | e49a67e7ad6281131522b233b833517487b4412e | 574,581 |
def get_ternary_dict(mode="bin"):
"""Returns map from floating values to bit encoding."""
if mode == "bin":
return {-1.0: "11", 0.0: "00", 1.0: "01"}
else:
return {-1.0: "-1", 0.0: "0", 1.0: "1"} | 6b6dee328d7fc3b375c7a9bf7a18e9a70763f562 | 574,583 |
def f(i, j, k, affine):
"""
Returns affine transformed coordinates (i,j,k) -> (x,y,z) Use to set correct coordinates and size for the mesh.
Parameters
----------
i,j,k : int
Integer coordinates of points in 3D space to be transformed.
affine : array
4x4 matrix containing affine transformation information of... | 93f9ba585c3fffdf53ac4021d85f93b30ff88bba | 574,586 |
def getGeneaDeviceId(binFile):
"""Get serial number of GENEActiv device
Parses the unique serial code from the header of a GENEActiv accelerometer file
:param str binFile: Input raw .bin accelerometer file
:return: Device ID
:rtype: int
"""
f = open(binFile, 'r') # 'Universal' newline m... | a6f6e65a7fd7d8697fe9984b0433a84f1b739ae3 | 574,591 |
def posterior_samples(
read_variable, metafile=False, default_analysis=None,
print_parameters=True, samples_variable="posterior_samples", text=(
"The posterior samples can be extracted through the `samples_dict` "
"property. These posterior samples are stored in a custom "
"table structu... | bb58fe264e54e6a44d8517eb8bb8394cc93ee3b2 | 574,596 |
import zlib
def complexity(s):
"""Compress string and return the size of the compression."""
s = s.encode("utf-8") # Python 3 fix.
compr = zlib.compress(s)
c = float(len(compr))
return c | 11986b3f56761fa50e90005093d1b205bd2841f5 | 574,599 |
def ex3_pickle_name(n):
"""build name for pickle file
Parameters
------
n, prop : float
`n` population and `proportion` observed
Returns
------
f_name : str
return `f_name` file name to save pickle as
"""
f_name = f"ueg_ukf_agents_{n}... | 5d48e52cb8d96f5cd4c3079318f21f255172f763 | 574,600 |
def get_digit(text: str) -> str:
"""
Get digit output from a given text
"""
return "".join([c for c in text if c.isdigit()]) | 8081cf699fe5c2e274a1ac217dc31545a2192912 | 574,603 |
def unravel_index(index, shape):
""" Analog of numpy.unravel_index. """
out = []
for dim in reversed(shape):
out.append(index % dim)
index = index // dim
return tuple(reversed(out)) | 94e7e58811b165ca470009c7e6d48efcccd4869e | 574,604 |
def verification_storage_location(l1_block_id: str, level_received_from: int, chain_id: str) -> str:
""" Format the path for the storage of a verification object
Args:
l1_block_id: the id of the L1 block which this verification verifies
level_received_from: the level from which this verification... | 1c7e7872ee265edb85f1a1cfd1a7be36fd37b921 | 574,605 |
def split_overlapping(signal, freq=257, time=2, shift=0.5):
"""
Splits the signal data into segments. Expects signal with dim-0 samples, dim-1 leads (12)
:param signal: the signal
:param freq: frequency rate of the signal
:param time: time length of the segments
:param shift: time shift in takin... | ba72e6315f1bf9dec12655f459bcd3d6e4b42a7e | 574,606 |
def f_pitch(p):
"""Compute center frequency for (single or array of) MIDI note numbers
Notebook: C1/C1S3_FrequencyPitch.ipynb
Args:
p (float or np.ndarray): MIDI note numbers
Returns:
freq_center (float or np.ndarray): Center frequency
"""
freq_center = 2 ** ((p - 69) / 12) * ... | e8ee1b764865da6ff4c300ea5bd7333670cdf28e | 574,609 |
def _is_encodable(value: str) -> bool:
"""
We need to filter out environment variables that can't
be unicode-encoded to avoid a "surrogates not allowed"
error in jsonnet.
"""
# Idiomatically you'd like to not check the != b""
# but mypy doesn't like that.
return (value == "") or (value.e... | a3ebee12af32139e8f60ad8e3b498cfcb9d45f1f | 574,610 |
import six
def binary_encode(text, encoding='utf-8'):
"""Converts a string of into a binary type using given encoding.
Does nothing if text not unicode string.
"""
if isinstance(text, six.binary_type):
return text
elif isinstance(text, six.text_type):
return text.encode(encoding)
... | 185132f36f10a78db4d7a935aa3010eb0c8f29bc | 574,613 |
def get_permutations_1(sequence, permutation_curr = [], permutations = []):
"""
Returns all the possible permutations of the given sequence
O(n^2 * n!) time
O(n * n!) space
"""
# base case, when sequence is empty current permutation is the only one possible
if not len(sequence) and len(per... | bd9b2013e4c88441a18609a918584d461078c740 | 574,618 |
import requests
def send_binary_image_data(image_file_name, image_file_binary, printer_name="printi", auth=None):
"""Sends a binary image file to the printi API
:param str image_file_name: Must include the right file type (e.g. cat.png)
:param file image_file_binary: A file-like object, *opened in binary mode*
:... | 1abc0c111c7d9dafbd2f15fe8a5f16dc7daeb0e0 | 574,630 |
async def present(
hub,
ctx,
name,
address_prefix,
next_hop_type,
route_table,
resource_group,
next_hop_ip_address=None,
connection_auth=None,
**kwargs,
):
"""
.. versionadded:: 1.0.0
Ensure a route exists within a route table.
:param name:
Name of the r... | 5e4aff2737882d7efa0b1522739af6697d6197a9 | 574,631 |
def to_upper_case(given: str) -> str:
"""Returns 'given' in upper-case.
>>> to_upper_case("foo")
'FOO'
>>> to_upper_case("Foo")
'FOO'
>>> to_upper_case("FOO")
'FOO'
>>> to_upper_case(" ") == " "
True
"""
return given.upper() | ef135c9293f59babdf6462846c073c37d0976c3e | 574,637 |
def coleman_liau_index(n_chars, n_words, n_sents):
"""
Readability score whose value estimates the number of years of education
required to understand a text, similar to :func:`flesch_kincaid_grade_level()`
and :func:`smog_index()`, but using characters instead of syllables.
Higher value => more dif... | 991af9c14555beaf4886e667661bb45f0f72017d | 574,640 |
import math
def FindScaleBarLengths(ax, frac=0.25):
"""
Find reasonable scale bar lengths as a fraction `frac` of current x- and y-ranges
`ax` = axis object
`frac` = fraction of axis (in data coordinates) that scale bar will represent
"""
def IntegerScale(s):
# extract from tuple... | 40af7daf5f65743f835ed339fb28cd7d3d749045 | 574,642 |
def insettion_sort(arr):
"""
time complexity: O(n^2)
space complexity: O(1)
:prarm arr: list
:return: list
"""
if not isinstance(arr, list):
raise TypeError
for i in range(1, len(arr)):
for j in range(i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] ... | e68539033f484aef14cbf5866deda254d47f7bce | 574,647 |
def get_column_names(inspector, table_name):
"""
Return the actual columns that are in the database table,
and not just the columns that our SQLAlchemy model expects.
"""
return sorted([col["name"] for col in inspector.get_columns(table_name)]) | f231e4ce4d6d6b905515a5cc78479dfe465faf8b | 574,657 |
def get_locs(r1, c1, r2, c2):
"""Get ndarray locations of given bounds."""
rs = []
cs = []
for r in range(r1, r2 + 1):
for c in range(c1, c2 + 1):
rs.append(r)
cs.append(c)
return rs, cs | 853b154196c39901e0b51272dc6ab69c2eaee52a | 574,658 |
from typing import Any
def validate_ndim(ndim: Any) -> int:
"""Make sure that the number of dimensions makes sense
Args:
ndim (Any): number of dimensions
Raises:
ValueError: If the number of dimensions is not an integer
ValueError: If the number of dimensions is not greater than ... | bb83d946fd4f913250f06ee6d8fba68889c5dd54 | 574,660 |
def Ids2Words(ids_list, vocab):
"""Get words from ids.
Args:
ids_list: list of int32
vocab: TextVocabulary object
Returns:
List of words corresponding to ids.
"""
assert isinstance(ids_list, list), '%s is not a list' % ids_list
return [vocab.IdToWord(i) for i in ids_list] | 4e2fbd016b607838698b2e1d3f1daddec3f5dac0 | 574,664 |
def th_flatten(a):
"""Flatten tensor"""
return a.contiguous().view(a.nelement()) | d6243aee949cb84652a7a3a007476d32e7be165b | 574,671 |
def construct_xml_global_options(url, username):
"""This function constructs the global options portion of the XML file.
Inputs:
- url: URL of the Collaborator server [string]
- username: Username for the Collaborator user [string]
Outputs:
- global_options_string: A string contain... | 27a0c38dafa254a20b8bfaa770b63e38ad381452 | 574,673 |
def from_3d_numpy_to_2d_array(X):
"""Converts 3d NumPy array (n_instances, n_columns, n_timepoints) to
a 2d NumPy array with shape (n_instances, n_columns*n_timepoints)
Parameters
----------
X : np.ndarray
The input 3d-NumPy array with shape
(n_instances, n_columns, n_timepoints)
... | eea339473f2c2268148f9a75b36e552ed5f87a7b | 574,675 |
import requests
import time
def _fetch_url(url, attempt=1, session=requests.Session()):
"""
Attempt to fetch the specified url. If the request fails, retry it with an
exponential backoff up to 5 times.
"""
try:
# Without this, citybureau.org throttles the first request.
headers = {... | 4cab0620ce4a74ab11b0d49241eb963b7065e22a | 574,677 |
def make_tqdm_progress_bar_fn(description='', leave=True):
"""Make a `progress_bar_fn` that uses `tqdm`.
Args:
description: `str` to display next to the progress bar, default is "".
leave: Boolean whether to leave the progress bar up after finished.
Returns:
tqdm_progress_bar_fn: A function that tak... | e47534b0391ae1c537b3be999987498a51b08100 | 574,678 |
from datetime import datetime
def create_grib_idx_url_path(
baseurl: str,
url: str,
product: str,
file: str,
timestamp: datetime,
forecast_hour: int,
):
"""
Given a date and forecast hour return the expected grib.idx filepath
"""
url = url.format(
timestamp=timestamp, p... | e667a57c947076ed9412abf30b4261a53e5b4d69 | 574,679 |
from typing import Mapping
from typing import Any
from typing import Callable
from typing import Dict
def map_keys(dikt: Mapping[Any, Any], func: Callable[[Any], Any]) -> Dict[Any, Any]:
"""Map dictionary keys."""
return {func(key): value for key, value in dikt.items()} | ed98788720d8a98c8324551b1a3af1dea0bc43ce | 574,680 |
def comp_diff_emerge(result, loc1, loc2, time, obs='sstopo'):
"""Compute differential glacial isostatic adjustment between locs 1 and 2.
Parameters
----------
result : GiaSimOutput
loc1, loc2 : tuples of (lon, lat)
time : the time for comparison
obs : str
The type of observation, de... | 69c2dd7b0396132c86d02cb72d5d1b02c545ce75 | 574,681 |
import re
def string_like_int( s ):
""" Given a string, return test if it contains only digits. """
if re.search( r'\D', s ):
return False
return True | 2911208f884f909d267677f66f1c54c14a21046c | 574,683 |
def canonize2(twos, threes, fives, horogram="JI"):
"""
Reduce a pitch given in powers of two, three and five into a canonical form that has the same frequency based on the temperament.
"""
# pylint: disable=invalid-name
if horogram == "meantone":
return (twos - 4*fives, threes + 4*fives, 0)
... | 14152b1fb466326b6be57a5de34c144de239f039 | 574,684 |
def get_lr(optimizer):
""" Returns the current learning rate of the optimizer. """
return optimizer.param_groups[0]['lr'] | acd21aa58ff06ebd8e6cc5425a02d898e8c89594 | 574,685 |
from datetime import datetime
def extract_time(time):
"""
Convert the string into datetime format.
:param time: string of time need to be converted. Example: '2017-01-16T15:09:28Z'
:return: the time in datetime format
"""
result = datetime.strptime(time[11: 19], '%H:%M:%S')
return res... | a568b335de94ac424f7752ca2ffe713c7630e011 | 574,688 |
import re
def _contains_chord_definition(word: str) -> bool:
"""
Check if this word contains a chord definition
:param word: Word for which we want to check if it contains a chord definition
:return: Boolean indicating if word contains a chord definition
"""
if re.search(r'(^|.*\D)[0-9]{6}($|... | 98cd7118d522de90c135bb1f626d2f3cf5f3d744 | 574,692 |
def oauth2_client_id() -> str:
"""The Oauth client id obtained from the Adwords API center"""
return '123456789-abcdefghijklmnopqrstuvwxyz.apps.googleusercontent.com' | 0e4655b198cc8147b09663fa458ef771744ee4a2 | 574,695 |
def _split_joins(join_string, only_join=False):
"""
Split a string into the field and it's joins, separated by __ as per
Django convention
"""
split = join_string.split('__')
field = split.pop(0) # the first field
join = '__'.join(split) # the rest of the fields
# return single join o... | f2fdbf0bd4a9c350a42536bf5e36283018bb69e4 | 574,698 |
def branch_exists(nametag, branches):
"""
Checks whether the given nametag is indeed labelling a branch.
:param nametag: The nametag to check the accessibility of.
:param branches: The list of branches.
:return: True if the nametag exists, False otherwise.
"""
for branch in branches:
... | efc97cda140e32c3d0c8215f5deb013cdf5d9d8e | 574,699 |
def fixture_case_id() -> str:
"""Return name of a case"""
return "handsomepig" | 6624e180021a5c559949c85e46dc821a2294207a | 574,700 |
def mem_empty_payload(mem_default_payload):
"""Provide a membership payload with no action."""
empty_payload = mem_default_payload
empty_payload["action"] = ""
return empty_payload | 4a8f5ec3505a3b40b424edbfc6a9e83618292224 | 574,705 |
def shorten(msg: str, max_len: int=100) -> str:
"""
Shorten this string, if longer than max_len, truncate and add "..."
:param msg: the message to shorten
:param max_len: the maximum length for this string
:return: the shortened string
"""
msg = str(msg)
return msg if len(msg) < max... | 21dd0d757cfc26643b44198630e4a00a0c923eb7 | 574,711 |
import csv
def save_file(path, content, mode='w', format_='json'):
"""
Save exported items to a file
"""
# Save to file
try:
file = open(path, mode)
if format_ == 'json':
file.write(content)
file.close()
else:
writer = csv.writer(fi... | cff274a05da36292e61ab91b10cf71acdf085083 | 574,713 |
def inner_nodes_recursive(root):
"""
Return a list of all inner nodes of the tree, from left to right.
"""
if root.is_leaf():
return []
return inner_nodes_recursive(root.left) + [root] + inner_nodes_recursive(root.right) | 879275d7ffc6f2d24295fb318943339503d20d23 | 574,718 |
def Int2Bin(integer: int,n_bits: int):
"""Turn an integer into a binary string.
Args:
integer (int): Integer to convert.
n_bits (int): Minimum number of bits to represent the integer with.
Returns:
str: binary_str
"""
formatstr = '0' + str(n_bits) + 'b'
return format(integer,formatstr) | 8a4868861e9d390595f073a4606aaf6ec5786ec9 | 574,722 |
def ternary_search(f, lo, hi, gap=1e-10):
"""Ternary maximum search for a bitonic function
:param f: boolean bitonic function (increasing then decreasing,
not necessarily strictly)
:param int lo:
:param int hi: with hi >= lo
:param float gap:
:returns: value x in [lo,hi] maximizing f(x),
... | f57d011608b26e1154de7e1de74abfb6792bfb10 | 574,724 |
import time
def measure(func):
"""
@measure
def test():
for i in range(1000000000):
pass
if __name__ == '__main__':
print("start")
test()
print("end")
"""
def wrapper(*args, **kwargs):
def display_formatted_time(elapsed_time, msg=""):
... | 95a703cdd0858f45f279608844a444a774c21c46 | 574,726 |
def remove_prefix_and_suffix(s, prefix, suffix):
"""Try and remove the prefix and suffix from the given string.
This function will try and remove the given prefix and suffix to the given string.
If it succeeds, it returns the resulting string.
If the string doesn't start or end with the prefix or suffix respective... | 55d018248b4b75ab13c99665cfda5c97454d8e62 | 574,728 |
from typing import Optional
from typing import List
def compact(array: Optional[List]) -> Optional[List]:
"""Compact an list by removing `None` elements. If the result is an empty list, return `None`
:param array: Inital list to compact
:type array: List
:return: Final compacted list or None
... | 20271464dd9b1c312be6bd12f7df40dfc10076d5 | 574,731 |
def compile_report_dict(tp, fp, fn, precision, recall, f1):
"""
Generate a dictionary of all the metrics, to be used to generate a report.
"""
sorting_remark = """
Your score is calculated as (F1*0.9).
If you had a perfect F1 score, this means that you returned all tuples
perfectly, but for... | 4d90334d1eba2362bb9483922ce2746ba4f4d950 | 574,735 |
from contextlib import suppress
def _create_column(data, col, value):
"""
Create column in dataframe
Helper method meant to deal with problematic
column values. e.g When the series index does
not match that of the data.
Parameters
----------
data : pandas.DataFrame
dataframe ... | 48679ae327edb9771a64ac5931db3bac0c6866bd | 574,736 |
import torch
def rotMat_to_quat(rotMat):
"""Convert rotation matrices back to quaternions.
Ported from Matlab:
https://github.com/asheshjain399/RNNexp/blob/srnn/structural_rnn/CRFProblems/H3.6m/mhmublv/Motion/rotmat2quat.m#L4
Args:
rotMat (torch.Tensor): rotation matrix or matrices to conve... | 2577c625d026f85db3ec28d42bbe71f347036f0b | 574,740 |
def compare_txt(set1,
set2
):
"""
compare two sets of words
return the ratio R of common words over the the length of the second set
return also the rounded R
(which is the floor of R if R is equally close to two integers,
e.g the rounded 0.5 is... | b216cda6f8c68137b520f20e92d9fd46c03ad205 | 574,742 |
def is_in_map(pos, grid_dim):
"""
Parameters
----------
pos : tuple of 2 ints
x, y coordinates in the grid system of current position
grid_dim : tuple of ints
x, y dimension of the grid system
Returns
true if pos in map
false if not in map
"""
(max_x, max... | 6259194877dfbb4a84a67f969700d8d3473f74a4 | 574,744 |
from datetime import datetime
def hour_start(src_time):
"""Return the beginning of the hour of the specified datetime"""
return datetime(src_time.year, src_time.month, src_time.day, src_time.hour) | 101be49d48526f5c2e6b1b35046e02eb8493dc49 | 574,748 |
def flatten(lists):
"""
flatten a list of lists
"""
result = []
for sublist in lists:
result += sublist
return result | 0bbec6241b1cd673a142b8ab46ccfdc15b133077 | 574,749 |
def square(number):
"""
This function returns the square of a given number
"""
return number ** 2 | 61b78b66b54e844ca64320362f625b06fb854cd4 | 574,750 |
import json
def input_data(client, headers):
"""Input data (as coming from the view layer)."""
data = {
"metadata": {"title": "Test"},
}
res = client.post("/mocks", headers=headers, data=json.dumps(data))
assert res.status_code == 201
return res.json | 5a02ddf1e9244b6c67549e27980a08635ac72e83 | 574,751 |
from typing import Dict
from typing import Set
def gmt_to_dict(gmt_fp: str) -> Dict[str, Set[str]]:
"""Read GMT format, return dict: geneset name -> set of gene identifiers"""
# Read GMT: get a list of geneset names, and a list of the genes in each geneset
with open(gmt_fp) as fin:
geneset_lines =... | 4068c60eb778666527dd4a182ecde341c8d83e78 | 574,753 |
def significance_level(value_to_check, string_to_print):
""" This function attaches ***/**/* to float if float meets conditions.
Designed to be used in ttest(), reg_tab and reg_tab_ext to indicate statistical significance.
:param (float) value_to_check: value to check
:param (str) string_to... | bfb27b7fd36d5044e4fd5f73b92b2002436ed618 | 574,757 |
import json
def adjust_properties(properties):
"""Adjust properties to Siren protocol.
:param properties: dictionary or iterable with dictionary items.
:returns: dictionary with strings as values (property names) and json serializable values.
:raises: :class:ValueError.
"""
try:
prope... | 3f8b47a7d85719efb49d89f8b63fb7949bb1d2a9 | 574,758 |
def get_match_files(git_pattern: str) -> bool:
"""
If there is a separator at the end of the pattern
then the pattern will match directories and their contents,
otherwise the pattern can match both files and directories.
>>> assert get_match_files('')
>>> assert get_match_files('/something')
... | 722c7a0ece40f31b1da0beccb51733c4ba7139ce | 574,766 |
def convert_row_to_nd_slices(slice_, shape):
""" Convert from 1d slice to nd slices
When first n rows are required, need to convert to
closest suitable nd-slices that contain them.
Parameters
----------
slice_ : slice
desired on the data
shape : tuple
the shape of the data
... | 3af0aa00f97748a09e9e507d8d9e04fcc20011e4 | 574,769 |
def oneD_quadratic_interpolation(desired_x, known):
"""
utility function that performs 1D linear interpolation with a known energy value
:param desired_x: integer value of the desired attribute/argument
:param known: list of dictionary [{x: <value>, y: <energy>}]
:return energy value with desired a... | 733ac8f16a32c7f6cab361db51b58bf907f12166 | 574,772 |
def get_simplified_tpmatrices(tpmats):
"""Return copy of tpmats list, where diagonal matrices have been
simplified and placed in scale arrays.
Parameters
----------
tpmats
Instances of :class:`.TPMatrix`
Returns
-------
List[TPMatrix]
List of :class:`.TPMatrix`'es, that... | fde27736a5eb0159a85df80850f6eff166d4482b | 574,776 |
def __getItemIndex__(testObj, firstElementValue):
"""
Returns the index of list testObj whose first element is equal to firstElementValue.
If it cannot be found, then the next free index is returned.
"""
assert isinstance(testObj, list), 'The provided object is not a list!'
for itemIndex in ran... | 2cc76c0fd7ca67bddd8d850c6e2e55be8f3e6be1 | 574,779 |
def str2hex(str):
"""Convert a string to hex encoded format"""
result = str.encode('hex')
return result | 85a9dcfd6016bc785c9168378e5adf714c24d194 | 574,781 |
import torch
def pretty_size(size):
"""Pretty prints a torch.Size object
Args:
size: tensor size
"""
assert (isinstance(size, torch.Size))
return " × ".join(map(str, size)) | f7b6ca29ad9be561f424dda92f355f79a6d238b5 | 574,783 |
import dis
def instructions_are_the_same(instr: dis.Instruction, target_instr: dis.Instruction,
frame=None):
"""Check if the disassembled instructions *instr* and *target_instr* are (basically) the same.
Mainly this checks if the *opname* and *argval* of the two instructions are... | 791322a4658c244b4be0f776cb2b2297246c31ea | 574,784 |
import queue
def drain_queue(q, close_queue=False):
"""Get all items from a queue until an `Empty` exception is raised.
Args:
q: `Queue`, the queue to drain.
close_queue: bool, whether to close the queue, such that no other object can be put in. Default is False.
Returns:
List of... | 99ed0d22f8948a94f4428d5ab292b2ed1c1ae75c | 574,785 |
def network(site_client, attributes):
"""Return a Network object."""
return site_client.sites(site_client.default_site).networks.post(
{
'cidr': '10.20.30.0/24',
'attributes': {
'foo': 'test_network'
}
}
) | 9c906dce4091d488d546263af46c629df1b2e526 | 574,787 |
def ConvertLotType(aLotType,aIncludePossible):
"""
Returns a list of strings to query LotType on
Keyword arguments:
aLotType -- integer value representing Lot Type -- 0 = both, 1 = Vacant Lot, 2 = Vacant Building
aIncludePossible -- boolean value, if true will include possible vacant lot or possibl... | 36ce0e4d3d53dcd7d395582493b8bfc51bdc73e5 | 574,788 |
def ageRange(row):
"""Gives the age range label for histogram
-----------
row : pandas Series
row of a dataset
Returns
-----------
label : str
the corresponding label
"""
if row.Age == 100:
label = '100-104'
else:
label = str(row.Age) + '-' +... | f159ecc9ffa4bcd63cf164e07b154026a8805529 | 574,789 |
import click
def _click_resolve_command(root, parts):
"""Return the click command and the left over text given some vargs."""
location = root
incomplete = ''
for part in parts:
incomplete = part
if not part[0:2].isalnum():
continue
try:
next_location =... | 4eaece099ba9c8087e31fda60ac2e5ef626ca843 | 574,790 |
from typing import FrozenSet
def _vocabulary_overlap(vocabulary1: FrozenSet[str],
vocabulary2: FrozenSet[str]):
"""
Vocabulary overlap as calculated by the Jaccard coefficient.
"""
intersection_length = len(vocabulary1 & vocabulary2)
if intersection_length == 0:
ret... | 563d61a9eaa3b15fb002cbf823c94cbba3d1c5a1 | 574,792 |
from functools import reduce
import operator
def get_by_path(root, items):
"""Access a nested object in root by item sequence"""
return reduce(operator.getitem, items, root) | 72e7ae8792fdaf1182a393f4c52bc9c929482107 | 574,793 |
def accounts(web3_eth): # pylint: disable=redefined-outer-name
"""Get the accounts associated with the test web3_eth instance."""
return web3_eth.accounts | b17834630697a958ad963e364a5a682a8c1eb0e8 | 574,801 |
def rankkern(x):
""" The kernel for the rank transformation, measures the fraction of the neighbors that
take on a value less than the middle value """
n = x.size
mid = n // 2
better = ((x >= 0) & (x < x[mid])).sum()
return better / ((x >= 0).sum() - 1.0) | 06b85bd962460c378eb09bb9f964adb5261a5590 | 574,802 |
def camelcase_css_name(css_name):
"""Convert hyphen-separated-name to UpperCamelCase.
E.g., '-foo-bar' becomes 'FooBar'.
"""
return ''.join(word.capitalize() for word in css_name.split('-')) | e2b90aa80be9bb464f5d6999897aaa025b3b56ec | 574,803 |
def from_string(key: str, ghs_dict: dict) -> int:
"""Get status value by key from dictionary."""
for string_val, return_val in ghs_dict.items():
if key == string_val:
return return_val
return 0 | 0ada609f6324702ee8bafc1f0d0acaf94ef68c11 | 574,804 |
def lag_autocov(v, lag):
""" Compute lag autocovariance of a vector
"""
tmp = 0
N = len(v)-lag
for j in range(N):
tmp += v[j]*v[j+lag]
return tmp/N | 4804216db765713cb549b3b537d2d42a09554bab | 574,809 |
def _shape_repr(shape):
"""Return a platform independent reprensentation of an array shape
Under Python 2, the `long` type introduces an 'L' suffix when using the
default %r format for tuples of integers (typically used to store the shape
of an array).
Under Windows 64 bit (and Python 2), the `long`... | fc12559a86d1bdf56553208e3afbb623fea732c6 | 574,810 |
def f2p(f):
"""
浮点转转为百分比字符串
>>> f2p(0.003)
'0.3%'
:param f:
:return:
"""
return str(round(f * 100, 2)) + "%" | ea347b0b12e67dc85cb9c0704985b7f3004078dc | 574,811 |
def left(value, len):
"""
return the `len` left-most characters in value
:param value:
:param len:
:return:
"""
if len <= 0:
return u""
return value[0:len] | 652bae823c8aec2f7d49a7fa12938dca4cb762b2 | 574,817 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.