content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _r_long(int_bytes):
"""Convert 4 bytes in little-endian to an integer."""
return int.from_bytes(int_bytes, 'little') | 160a4fcf1acb9831baed8f9ee9307359a9690965 | 38,977 |
def search_for_transcript(edge_IDs, transcript_dict):
""" Given the edge IDs (in set data structure) that make up a query
transcript, look for a match in the transcript dict.
Return gene ID and transcript ID if found, and None if not. """
try:
transcript = transcript_dict[edge_IDs]
... | bbbf54e7a1c6c47d5fec7d2fcd424bd885b710bc | 38,978 |
def coinify(atoms):
"""
Convert the smallest unit of a coin into its coin value.
Args:
atoms (int): 1e8 division of a coin.
Returns:
float: The coin value.
"""
return round(atoms / 1e8, 8) | 3acc1771168ba7b990282ccfe3bb6ce3adfbdd7b | 38,979 |
def transform_input_data(data):
"""Transform input data dictionary into format ready to use with
model.predict"""
return {key: [value] for key, value in data.items()} | 8edf2d47f0bc009896950d6c78edbf3c9e8a5b37 | 38,980 |
import requests
import configparser
def conf_from_url(url):
"""Read conf file from an URL.
Parameters
----------
url : str
conf file url (in a repo, make sure the "raw" url is passed)
Returns
-------
conf object
"""
text = requests.get(url).text
config = configparser.... | 94eda1351b0ff38593bcc0ad485a8b43ad41fb09 | 38,987 |
import hashlib
def _fingerprint(path):
"""Fingerprint a file."""
with open(path) as fil:
return hashlib.md5(fil.read().encode('utf-8')).hexdigest() | 65d200af8f8e2425f44cff5deeb60656ff572eb9 | 38,996 |
def movieTitle_to_id(movies_titles_list,movies):
"""
Convert a list of movie titles to a list of movie ids
"""
movies_list = []
for i in movies_titles_list:
id = list(movies['movieId'][movies['title'] == i])[0]
movies_list.append(id)
return movies_list | 9e594f8bc590b29b9a09b68b197477ca66df918e | 38,997 |
def validate_submission(y_pred_file):
"""
Validate that y_pred file is a valid prediction file.
Args:
y_pred_file: Predicted values object in sample_submission format
Returns:
bool: Validation succeeded, if false a detailed error message will be
supplied
Raises:
... | b4795ea086ce493f15ca6453dbdefca53d36ad05 | 38,999 |
def extract_indices_from_dependencies(dependencies):
""" Extract all tokens from dependencies
Input example:
[[8, 'cop', 7], [8, 'nsubj', 6]]
Output example:
[6, 7, 8]
"""
word_positions = set()
for governor_pos, _, dependent_pos in dependencies:
word_positions.ad... | ed171902f6d5b9d3f28a56d866ff6a3011f2ec4e | 39,006 |
def dfdb(B, E):
"""
B is the base
E is the exponent
f = B^E
partial df/dB = E * B**(E-1)
"""
out = E * (B**(E-1))
return out | 89047a198028320ecd2cbfac26064db6af8a784b | 39,008 |
def insert_doc(doc, new_items):
"""Insert ``new_items`` into the beginning of the ``doc``
Docstrings in ``new_items`` will be inserted right after the
*Parameters* header but before the existing docs.
Parameters
----------
doc : str
The existing docstring we're inserting docmentation i... | 6b729e9066c2690801d7a749fd366e828bc8cd18 | 39,012 |
def _get_encoder_dimension(encoder):
"""Find dimensionality of encoded vectors.
Args:
encoder: Object implementing the encode() method which takes
a list of strings as input and returns a list of
numpy vectors as output.
Returns:
dimension: Integer size of the encoded vectors.
"""
vector... | cef789252f4dd9975f1e1bddc5175bbdd49d9220 | 39,013 |
def change_current_lang_and_return(lang):
"""Change current language of text/speech recognition and return it"""
global CURRENT_LANG
CURRENT_LANG = lang
return CURRENT_LANG | 3f4b377ad9eab98622890cff5296436e08926f38 | 39,033 |
def create_ngrams(kw_iterable, max_n=False):
"""takes a list of keywords and computes all possible ngrams e.g.
in> ['nice', 'red', 'wine']
out> [
('nice',),
('red',),
('wine',),
('nice', 'red'),
('red', 'wine'),
('nice', 'red', 'wine')
]
"""
kwCount = len(kw_iterable)
output = []
for n in ... | 16a2dab3240214162e1b386e30e912a38e564458 | 39,041 |
def arr_to_json_fixturen(array):
"""Convert given iterable to dict for json transformation.
Desired Format for djangod
{
"id" : None,
"model" : "ocdb.Sector",
"fields" : {
"name" : <mandatory>
"fk_sector" : <optional> *
}
... | 45956ae37638342c3929adda3952f16d87f02025 | 39,042 |
def get_station_daily_path(station_id):
"""
Get path to a station daily file.
:param station_id:
:return:
"""
return "/pub/data/ghcn/daily/all/{0}.dly".format(station_id) | 24060b3e6393318b6d7ad8a7dfe2d2d32d934079 | 39,050 |
def sites_difference(site1, site2):
"""Return minimal sequence of nucleotides that should be added at the end
of site1 to make site2 appear."""
for i in range(len(site2), -1, -1):
if site2[:i] == site1[-i:]:
return site2[i:]
return site2 | 3bcd7d4eda4fd23d253b3a5f77255663c13c2ab1 | 39,055 |
def format_includes(includes):
"""
Format includes for the api query (to {'include' : <foo>,<bar>,<bat>})
:param includes: str or list: can be None, related resources to include
:return: dict: the formatted includes
"""
result = None
if isinstance(includes, str):
result = includes
... | 9f15ac9b767b6612794bec7b14427b6f90d4a734 | 39,067 |
def top_k_predictions(model, probs, k: int):
""" Returns the top `k` most probable classes from our model
After training a fastai Learner on a multi-label classification problem,
return the label and probabilities associated with the top `k` most
probable classes.
Args:
model [Learner]: ... | abedd8ac1b5d90f4485dda8d7c0bae966d57d328 | 39,071 |
def sparse_batch_mm(m1, m2):
"""
https://github.com/pytorch/pytorch/issues/14489
m1: sparse matrix of size N x M
m2: dense matrix of size B x M x K
returns m1@m2 matrix of size B x N x K
"""
batch_size = m2.shape[0]
# stack m2 into columns: (B x N x K) -> (N, B, K) -> (N, B * K)
m2... | 6fe7a5f4b407d27b71b646872d43a78154c594e8 | 39,073 |
def summarizekeys(d, counts={}, base=''):
"""Summarizes keys in the given dict, recursively.
This means counting how many fields exist at each level.
Returns keys of the form ``key0.key1`` and values of ints.
Checks if `d` is instance of dict before doing anything.
"""
if not isinstance(d, dict)... | 714fc56cba1d63178902987623aa0a246c20aa6d | 39,075 |
import hashlib
def hash_password(pw_in):
"""Take password as input, hash it in SHA-1, and split it for use later on"""
hash = hashlib.sha1()
hash.update(str.encode(pw_in))
digest = hash.hexdigest()
return [digest[:5], digest[5:]] | f3950dcda6053f5be3aaa05e11fb8b147abf5eb5 | 39,077 |
def NumGems(gems):
"""Returns the number of gems in the defaultdict(int)."""
return sum(gems.values()) | 60afed06af7c45daa1f8ef4f1097658cfc31e74d | 39,078 |
def tree_attribute(identifier):
"""
Predicate that returns True for custom attributes added to AttrTrees
that are not methods, properties or internal attributes.
These custom attributes start with a capitalized character when
applicable (not applicable to underscore or certain unicode characters)
... | a2e55597dc6df6a897f87a819e6d1dce2580923f | 39,081 |
def get_sim_name(obj):
"""
Get an in-simulation object name: if ``obj`` has attribute
``__sim_name__``, it will be returned, otherwise ``__name__``
standard attribute.
Args:
obj: an object to get name of
Returns: object name
"""
if hasattr(obj, '__sim_name__') and obj.__sim_nam... | 80c7b29047f09d5ca1f3cdb2d326d1f2e75d996b | 39,082 |
def scoreSorter(order):
"""Sort by score value
"""
if order == 'asc':
return "_score"
return {"_score": {"order": "asc"}} | 142e532bd744d7bbcd6568c8e027a441ab7a4e04 | 39,084 |
def braced(s):
"""Wrap the given string in braces, which is awkward with str.format"""
return '{' + s + '}' | 360bfd93ab70ae8393563e25de3d437e1aebfb85 | 39,087 |
import math
def __get_views(views):
"""Convert viewcount to human readable format"""
if int(views) == 0:
return '0'
millnames = ['', 'k', 'M', 'Billion', 'Trillion']
millidx = max(0, min(len(millnames) - 1,
int(math.floor(math.log10(abs(views)) / 3.0))))
return '%... | 6229801d09a703f860a1ba5e285d76b199cfdffb | 39,096 |
def EXACT(string1, string2):
"""
Tests whether two strings are identical. Same as `string2 == string2`.
>>> EXACT("word", "word")
True
>>> EXACT("Word", "word")
False
>>> EXACT("w ord", "word")
False
"""
return string1 == string2 | d6feb4c40bc93fa1ec5426f394a47c5d42c21dfd | 39,097 |
import json
def putTableAll(obj):
"""
Returns table as string showing standings of league with all data
Parameters:
-----------
obj: dict
JSON object of league standings obtained from API/cache
Returns:
--------
str
Standings as a text code block (to get monospaced t... | ae46f33be6200363ab2876fd4d95a1217d719305 | 39,098 |
def _fully_qualified_name(t: type) -> str:
"""Retrieves the fully qualified name of the provided type.
Args:
t (type): The type whose fully qualified name shall be retrieved.
Returns:
str: The fully qualified name of ``t``.
Raises:
TypeError: If ``t`` is not an instance of ``t... | 9a3a6795231b36184ce175c37224aa27e7c6b665 | 39,101 |
def version_string(version):
"""Returns a string from version tuple or list"""
if isinstance(version, str):
return version
return ".".join([f"{v}" for v in version]) | 8688b70a940febebeb16ee2e1f389968aea5a6ea | 39,108 |
def spritecollideany(sprite, group, collided=None):
"""finds any sprites in a group that collide with the given sprite
pygame.sprite.spritecollideany(sprite, group): return sprite
Given a sprite and a group of sprites, this will return return any single
sprite that collides with with the given sprite.... | 4f80e045cec8e8641bc74de15f82adc65394da1a | 39,113 |
import re
def fixture_readme_code_result(readme_content: str) -> str:
"""Get the README.md example result content.
:param readme_content: plain text content of README.md
:return: example result
"""
match = re.search(r"```text([^`]*)```", readme_content, flags=re.DOTALL)
assert match
retur... | ca8fb13bb5013409c91d0ab979848f4745ae6246 | 39,115 |
def divide_list(list, perc=0.5):
"""
Divide a list into two new lists. perc is the first list's share. If perc=0.6 then the first new list will have 60 percent of the original list.
example : f,s = divide_list([1,2,3,4,5,6,7], perc=0.7)
"""
origLen = len(list)
lim = int(perc*origLen)
firstLi... | afe1068a0cdc4f3125df26b821527838d5ef189e | 39,116 |
def out_path(tmp_path):
"""Create a temporary output folder"""
out_dir = tmp_path / "output"
out_dir.mkdir()
return out_dir | dcd9cadc0d11ba3bb7bd415feaa45bcf093b551f | 39,124 |
def _get_ftrack_secure_key(hostname, key):
"""Secure item key for entered hostname."""
return "/".join(("ftrack", hostname, key)) | 7513cd5807b1c1697e6c055de40f7873b2bf9d0a | 39,125 |
def dec_hex(val):
"""
Format inteegr to hex
:param val: integer value
:return: string of hexadecimal representation
"""
return '0x%X' % val | fbccb1fa66ffef7746e365e1448d164ba9c3a4e6 | 39,131 |
import random
def powerRandomInt(max_val):
"""Returns a random integer from the interval [0, max_val],
using a power-law distribution.
The underlying probability distribution is given by:
P(X >= n) = (c/(n+c))^4, for n>=0 an integer, and where we use c=20.
But if X > max_val is generated then max_val is r... | b003a0ae90e254afa5bd2afe4f44e8369131bb6e | 39,134 |
from typing import List
from typing import Union
def _parse_field_names(fields: List[Union[str, dict]]) -> List[str]:
"""Parse field names.
Args:
fields: Either field names or field descriptors with a `name` key.
Returns:
Field names.
"""
return [field if isinstance(field, str) e... | 28ab3032c747ffdc6f2197c62374baf4f94e2ce5 | 39,136 |
from typing import Dict
from typing import Any
def check_action(reply: Dict[str, Any]) -> Dict[str, Any]:
"""Check that the reply contains a message of success."""
if not reply["success"]:
raise RuntimeError(f"Error communicating with the large object storage:\n{reply['error']}")
return reply | 21170d0fb0d417e1ca525cf8540e630aa79a7e72 | 39,141 |
import json
def _parseNative(logs, needle):
"""Parse console logs from Chrome and get decoded JSON.
Args:
logs: Chrome log object
needle (str): the string leading the actual JSON.
Example:
>>> _parseNative([{'message':'a=b'},{'message':'ac={"a":[1,2]}'}],'c=')
{u'a': [1, 2]}
"""
ret = None... | 2d6af33aaecf4e2d41e83540c337b79475ba3c4c | 39,142 |
def add_round_key(block, key):
"""Performs a bitwise XOR between a state block and the key.
Parameters
----------
block : np.ndarray
4x4 column major block matrix.
key : np.ndarray
4x4 column major block matrix.
Returns
-------
np.ndarray
4x4 result block matri... | 1edcf1a28777099a3f7c8bc641606b4297ab8704 | 39,143 |
import requests
def check_status(address, text):
"""Sends request to address and checks if text is present in reponse
Args:
address (str): site address
text (str): text to be checked in responce
Returns:
(status, elapsed): (tuple (str, int)) with status, and responce time
"""... | 0c15e75f35f3ac65dad66b9ac45f09d2a043e2d0 | 39,145 |
def get_passed_tests(log_file_path):
"""Gets passed tests with OK status"""
ok_test_line_pattern = "[ OK ] "
ok_tests = []
with open(log_file_path) as log_file_obj:
for line in log_file_obj.readlines():
if ok_test_line_pattern in line:
ok_tests.append(line.split... | 97fdeab4a2330864f57cd7ac70e8d5f81eaeaa78 | 39,146 |
import json
def safeJson(result, path=[]):
"""Take the result of a requests call and format it into a structured dict."""
if result.status_code != 200:
output = {'code': result.status_code, 'content': result.text}
print("ConfigManager: get secret failed (token expired?)")
print(json.du... | 1a5af140ef8d517a0236eaebfc9c676260a76a14 | 39,152 |
def reference_value_for_covariate_mean_all_values(cov_df):
"""
Strategy for choosing reference value for country covariate.
This one takes the mean of all incoming covariate values.
"""
return float(cov_df["mean_value"].mean()) | 57935c7b39e2f02f059e7f4b4a835bbe84a67081 | 39,153 |
def determine(hand):
"""Returns a list of values, a set of values, a list of suits, and a list of cards within a hand."""
values, vset, suits, all_cards = [], set(), [], []
for x in range(len(hand)):
values.append(int(hand[x]))
vset.add(int(hand[x]))
suits.append(hand[x].suit)
... | 60318bf9c9259f0741caaadb0246d2d8d66ca4f5 | 39,155 |
def osm_zoom_level_to_pixels_per_meter(
zoom_level: float, equator_length: float
) -> float:
"""
Convert OSM zoom level to pixels per meter on Equator. See
https://wiki.openstreetmap.org/wiki/Zoom_levels
:param zoom_level: integer number usually not bigger than 20, but this
function allows ... | 7351c289dde4bc42a46e343efcd3e750841b2c8c | 39,157 |
def subtract(minuend, subtrahend):
"""Subtracts minuend from subtrahend
This function subtracts minuend from subtrahend only when they are
either integers or floats
Args:
minuend(int/float): The quantity or number from which another
is to be subtracted
subtrahend(int/float)... | cdd43cd65cef485f929093cf8c5e481b6cc91148 | 39,159 |
import operator
def strip(listed):
"""Strip a list of string"""
return map(operator.methodcaller("strip"), listed) | 503c7a745c34f211160f45aa7234e96875ddd8fb | 39,162 |
import hashlib
def get_email_id(row):
"""
Creates a unique identifier for each email based on the
date received and a header ID
"""
text = row['X-GM-THRID'] + str(row['Date'])
return hashlib.md5(text.encode('utf-8')).hexdigest() | eddcea303947ef6d1b14b7b0dfb912fcc267f9f1 | 39,164 |
def split_by_unescaped_sep(text, sep=':'):
"""Split string at sep but only if not escaped."""
def remerge(s):
# s is a list of strings.
for i in range(len(s) - 1):
n_esc = len(s[i]) - len(s[i].rstrip('\\'))
if n_esc % 2 == 0:
continue
else:
... | 6eb360787a3ba5e08f499d2a3352d1170d2fcf89 | 39,166 |
def sovatoms_to_tokens(sovatoms: int) -> float:
"""Convert sovatoms to tokens."""
return sovatoms / 100000000 | 5a683213ccc916396af9e7424e315d640fdaf3a3 | 39,171 |
def get_seqname(
locus_text: str) -> str:
"""
Args:
locus_text:
The LOCUS (i.e. header section) of genbank file
Returns:
The seqname of chromosome
"""
line1 = locus_text[:locus_text.find('\n')]
return line1[len('LOCUS'):].lstrip().split(' '*3)[0] | d97939f43ac8937a5fdd694f3575ebe28333718d | 39,177 |
def overlap(interval1, interval2):
"""
Returns the total amount of overlap between two intervals in the format of (x,y)
Example:
input: (0,10) , (5,10)
returns: 5
"""
return max(0, min(interval1[1], interval2[1]) - max(interval1[0], interval2[0])) | 3a859fd12181cbfe278f298c8dcf7133eadd59e3 | 39,180 |
def filt_dct(dct):
"""Filter None values from dict."""
return dict((k,v) for k,v in dct.items() \
if v is not None) | 1d2803a9c7fd143b53206e7e5ac63a955d38b0c9 | 39,182 |
from typing import Sequence
def is_same_shape(a: Sequence, b: Sequence) -> bool:
"""
Compares two shapes a and b, returning True if they are the same
(their ranks and corresponding lengths match) and False otherwise.
"""
return tuple(a) == tuple(b) | 27dbacaa36d600631f89081bb8085d9b2b7f9f58 | 39,183 |
def has_n_leading_zeroes(num_zeroes, digest):
"""Check if the given digest has the required number of leading zeroes."""
return digest[:num_zeroes] == '0'*num_zeroes | fe96941bbeb6325a36452e7b0730face0af54c54 | 39,192 |
import torch
def tangent_vectors(normals):
"""Returns a pair of vector fields u and v to complete the orthonormal basis [n,u,v].
normals -> uv
(N, 3) or (N, S, 3) -> (N, 2, 3) or (N, S, 2, 3)
This routine assumes that the 3D "normal" vectors are normalized.
It is based... | 60282a0f1efc63e0ab04e12685f35337b8185f3a | 39,195 |
from typing import List
from typing import Dict
def _tags_as_dict(tags: List[Dict]) -> Dict[str, str]:
"""
Convert a list of tags to a dictionary
:param tags: the list of tags
:return: the dictionary of tags
"""
return {tag["Key"]: tag.get("Value", "") for tag in tags} | f909f1f4fb6773cf3b1e32067d963738b6e7023d | 39,196 |
def select_color_marker(i):
""" Return index-based marker/color format for plotting """
colors = ['b', 'g', 'r', 'c', 'y', 'k']
style = ['-', '--', '-.', ':']
ci = i % len(colors)
si = (i // len(colors)) % len(style)
return '%s%s' % (colors[ci], style[si]) | 9b06ecc6de31e8c2a0dbf423233640752fe09110 | 39,198 |
import pickle
def get_mct_frame(site):
"""Serves up a dataframe of micro-CT SSA data for a given site"""
# Load a dictionary of dataframes stored as a pickle file
# The pickle file itself is generated by notebook: CheckOutCT.ipynb
frames = pickle.load(open('../data/microCT/processed_mCT.p', 'rb'))
... | ace2697ff9833ca0392815e16741b77d416de3ef | 39,200 |
def get_memory_limit(component_limit, overall_limit):
"""
Return the minimum of the component and overall limits or None if neither is set.
"""
limits = [limit for limit in [component_limit, overall_limit] if limit is not None]
return min(limits) if limits else None | 50c8372dca1bacaa3e408abaf5e03659d01e1eea | 39,203 |
def is_tag(t):
"""Is `t` a tag?
"""
return t.strip().startswith('{%') | a7e4f55925844d8e6e881dcad8d20bfc2f5968bf | 39,208 |
def parse_cdr_annotations_pubtator(entity_type, subset):
"""Get each annotation in the BC5CDR corpus with documents in PubTator format.
Requires:
entity_type: is str, either "Chemical" or "Disease"
subset: is str, either "train", "dev", "test" or "all"
Ensures:
annotations: is ... | 0476628a01db6cd936132838d025ceb3838a9c30 | 39,219 |
import copy
def deeplist(x: list) -> list:
"""
Deep copy a list. This is needed because list() by itself only makes a shallow copy.
See https://stackoverflow.com/questions/5105517/deep-copy-of-a-dict-in-python
Convenience function.
:param x: List to copy
:return: Deep copy of the list provide... | c4161510ddf150e7b57c4d9681a8221b8325b312 | 39,222 |
def get_layer_index(model, name):
"""Get index of layer by name"""
for idx, layer in enumerate(model.layers):
if layer.name == name:
return idx | 5c57fad4cbb28ab8b6605be669e4cb75024ee977 | 39,224 |
import gzip
def encode_gzip(data, compresslevel=6):
"""Encode the passed in data with gzip."""
return gzip.compress(data, compresslevel=compresslevel) | 2693956c15924194e1151d2c04eadf97167cc08b | 39,226 |
def isImage(url):
"""Check if url is related to an image
Args:
url (string): string
Returns:
boolean: return true if url is referring to an image
"""
return \
url.endswith(".png") or \
url.endswith(".jpg") or \
url.endswith(".jpeg") or \
url.endswith(".... | f55b0ba05fa115b8a7d8d85219bd05e465b18854 | 39,228 |
def _get_separator(num, sep_title, sep_character, sep_length):
"""Get a row separator for row *num*."""
left_divider_length = right_divider_length = sep_length
if isinstance(sep_length, tuple):
left_divider_length, right_divider_length = sep_length
left_divider = sep_character * left_divider_len... | 0e10658e11580264a7722f59390a9dfcfaf0a71b | 39,229 |
def parse_pages(pages):
"""
Give a string possibly containing a start and end page, return the start and end page if any
:param pages:
:return: list with start and end pages
"""
if '-' in pages:
k = pages.find('-')
start = pages[0:k]
end = pages[k + 1:]
else:
... | 4ccf0dd8409d50c89dde3951eadd679e3009ffd8 | 39,230 |
def _ll_subvoxel_overlap(xs, x1, x2):
"""For an interval [x1, x2], return the index of the lower limit of the
overlapping subvoxels whose borders are defined by the elements of xs."""
xmin = min(x1, x2)
if xmin <= xs[0]:
return 0
elif xmin >= xs[-1]:
ll = len(xs) - 1
return l... | 5563642767d626f9bc516b90930432b2d5692442 | 39,238 |
import json
def _read_notebook_data_dict(notebook_path: str) -> dict:
"""
Read a dictionary of notebook data.
Parameters
----------
notebook_path : str
Path of target notebook.
Returns
-------
notebook_data_dict : dict
A dictionary of notebook data.
"""
with o... | c74fabb3ad1ff7d0e5d002791b1aef08a353199a | 39,241 |
import itertools
def _binary_count(n):
"""Count `n` binary digits from [0...0] to [1...1]."""
return list(itertools.product([0, 1], repeat=n)) | 0b21fc49763a7c09bd1ac84c4c823a0239a31db9 | 39,246 |
def bdev_compress_get_orphans(client, name=None):
"""Get a list of comp bdevs that do not have a pmem file (aka orphaned).
Args:
name: comp bdev name to query (optional; if omitted, query all comp bdevs)
Returns:
List of comp bdev names.
"""
params = {}
if name:
params[... | 4723929303c27388870ed7d9a2339e7e832b41d1 | 39,248 |
import json
def message_to_json(message):
"""
This function tranforms the string message to a json
string, this is to make all REST responses
to be in JSON format and easier to implement
in a consistent way.
"""
#if message is alreay in json then do not do anything
mesage_dict = {... | bf20d028068d2716c5b40807e6b17a6ffb8b1073 | 39,249 |
def recursive_replace(steps: int, to_expand: str, rules: dict) -> str:
""" Replace the given string with a new replacement string, according to the rules.
Args:
steps (int): How many iterations. Decremented with each recursion. Recursion ends when step=0.
input (str): Input str. The str to be r... | 2104ccfbc89d60aa09235a2933aee0bf15dea0a3 | 39,251 |
def nonzeros(u):
"""Return number of non-zero items in list `u`."""
return len([val for val in u if val != 0]) | 77180e06c9e82bcb4ca19a289514a92334ad62cd | 39,254 |
def match_fields(exp_fields, fields):
"""
Check field names and values match the expected ones.
- exp_fields:
A list of dictionaries with field name/value pairs.
- fields:
SPARKL event fields as returned by the listener.
[
{'attr': {'name':'n',... | 1a260f344ca42c480069b6951e037320fb6a63aa | 39,255 |
def merge_xml(xmls,output_file):
"""
merge xml files
Parameters:
-----------
xmls: list
List of paths of the xml files
output_file: str
Path of the merged xml
"""
if len(xmls) <2 :
raise Exception("Need two or more xml files to merge")
xmls = " ".join(xmls)
... | b574f3edb777f4a48f5209173baf7f74a465377e | 39,261 |
def isNewPhase(ds1, ds2):
"""
Check if two dynamicsState have the same contacts
:param ds1:
:param ds2:
:return: True if they have the same contacts, False otherwise
"""
assert ds1.effNum() == ds2.effNum(), "The two dynamic states do not comes from the same model."
for i in range(ds1.ef... | b6bf21106024991256a3a53b887bf73f83e7c037 | 39,264 |
def create_events_model(areas, virus_states):
"""Create events for the model.
Parameters
----------
virus_states : list of strings
List containing the names of all virus variants.
Returns
-------
events: dict
Dictionary that contains the event names as keys
and dici... | b1e8394f2a57e89372844cbb2b456d702d7b5c59 | 39,266 |
def is_valid(box):
"""Check that a bounding box has valid coordinates"""
return (box[..., 2] > box[..., 0]) and (box[..., 3] > box[..., 1]) | ca622196ac6710494fc052682dca5c2dde4af4ee | 39,277 |
def mask_last_dim(tensor, binary_mask):
"""Pick the elements of tensor in the last dimension according to binary_mask."""
return tensor[..., 0] * binary_mask + tensor[..., 1] * (1 - binary_mask) | ca1b40d8b90184c18979443483361987e49ec370 | 39,280 |
def minimum(ints):
"""
Return the minimum in a list of integers. If the list is empty,
return None.
"""
if ints == ():
return None
else:
head, tail = ints
min = minimum(tail)
if min is None or head <= min:
return head
else:
return ... | ff4e4eab86e2efa0a01b7e254e7d10556284a6d3 | 39,281 |
def clean_name(name: str):
"""Clean name by stripping whitespace and newline."""
return name.splitlines()[0].strip() | 1df5c654bc52ecbe33b98fe9a32eb812abec4e0f | 39,282 |
def datetime_to_list(date):
"""
convert a datetime object into a list [year,month,day,hour,minute,second]
Arguments
---------
date: datetime object
"""
return [date.year,date.month,date.day,date.hour,date.minute,date.second] | 5a581680793172bede720aa9c144203e843beb31 | 39,286 |
def ignore_formatter(error):
"""
Formatter that emits nothing, regardless of the error.
"""
return '' | 1d2d3b145e43d9d5840ad5dc3851331d5d67a23d | 39,288 |
import six
def _encode_metadata(metadata):
"""
UTF8 encode any unicode keys or values in given metadata dict.
:param metadata: a dict
"""
def encode_str(item):
if isinstance(item, six.text_type):
return item.encode('utf8')
return item
return dict(((encode_str(k), ... | 4b953a42b714f9729ae3ca41c413b295f012d72e | 39,292 |
import torch
def get_means(tensors_list):
"""
Calculate the mean of a list of tensors for each tensor in the list. In our case the list typically contains
a tensor for each class, such as the per class z values.
Parameters:
tensors_list (list): List of Tensors
Returns:
list: List... | b99b0dc2f0ab19c5ae55170d59b69b6f714f3db2 | 39,297 |
def deltatime_format(a, b):
""" Compute and format the time elapsed between two points in time.
Args:
a Earlier point-in-time
b Later point-in-time
Returns:
Elapsed time integer (in s),
Formatted elapsed time string (human-readable way)
"""
# Elapsed time (in seconds)
t = b - a
# Elapsed t... | 0478dd50d7d8e4673058b4096cb0247352a80f6f | 39,299 |
def pks_from_iterable(iterable, unique_output=False):
"""
Return pks list based on iterable
:param iterable: list of django model objects OR django queryset
:param unique_output: if True returned list will be unique
:return: list of int
"""
pks = list()
for obj in iterable:
try:
... | 7112b2da95d09fb7fc54626b0aa374d3304af87d | 39,302 |
import hashlib
def sha1_hash_from_text(text: str) -> str:
"""Return sha1 hex digest as string for text.
Parameters
----------
text: str
The text to be hashed
Returns
-------
str
the hash of the text
"""
return hashlib.sha1(text.encode()).hexdigest() | 999a00131adbc207af990a80404887694845da86 | 39,303 |
import click
def os_options(f):
"""Aggregate multiple common options into one.
This decorator should be used by CLI commands that need an
Openstack client."""
f = click.option('--os-username', help='Openstack Username', required=True,
envvar='OS_USERNAME')(f)
f = click.optio... | f38a646a45055d4b23e22d887b9d703fb804c868 | 39,305 |
def is_ob_site_html(html):
"""Check if some HTML looks like it is from the overcomingbias site.
Parameters
----------
html : bs4.BeautifulSoup
An HTML page, possibly from the overcomingbias site.
Returns
-------
is_ob_site_html : bool
True if the input HTML "looks like" it ... | ae3e21320858044772532e74fe94d0cfd0e1cb1b | 39,307 |
def _2DprintInxRow(inxRow, lSpacesIndR):
"""
Function prints one index of a row of a 2D array
Input:
- 1 **inxCol** (*int*) Index of the row to be printed
- 2 **lSpacesIndR** (*list*) A list with spaces which should be added
to indices of row... | f108007a9fcb25a6aa32e22297a654d6d262e247 | 39,312 |
import math
def SSphere(r):
"""
Surface of a sphere of radius r.
"""
return 4. * math.pi * r * r | 161b43f95ccf02349b66ac5035457dd962e3ba11 | 39,315 |
def create(hdf5, name, dtype, shape=(None,), compression=None,
fillvalue=0, attrs=None):
"""
:param hdf5: a h5py.File object
:param name: an hdf5 key string
:param dtype: dtype of the dataset (usually composite)
:param shape: shape of the dataset (can be extendable)
:param compression... | b9000aa26a0f1ebcb86ba61704e8634e081d29c6 | 39,316 |
def retrieve_positions(position_file):
"""
This function returns a list of strings in the right format representing
the positions that will be read out. [spatialfrequency,xi,xf,y].
Args:
position_file (str): The path of the position file.
Returns:
positions (list,str): List representing the positio... | 832d77e894c92b70edbcf330ad37bbaaf0cc3ed2 | 39,318 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.