content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def load_template(config):
"""Return text of template file specified in config"""
with open(config['template'], 'r') as template_file:
return template_file.read() | 273ec44bc951889d5d5b4f33e3238b60d7df1143 | 669,030 |
def norm_shape(shape):
"""
Normalize numpy array shapes so they're always expressed as a tuple,
even for one-dimensional shapes.
Parameters
shape - an int, or a tuple of ints
Returns
a shape tuple
"""
try:
i = int(shape)
return (i,)
except TypeError:
... | fd27472b059276db6e632f461442d35917bff2ba | 669,031 |
def batch_size(y_true, y_pred):
"""Count the number of items in the current batch."""
return y_true.shape[0] | b8390da3cc98ad49d03f3dfc830c1695b19cc593 | 669,032 |
import time
def convert_atom_timestamp_to_epoch(text):
"""Helper function to convert a timestamp string, for instance
from atom:updated or atom:published, to milliseconds since Unix epoch
(a.k.a. POSIX time).
`2007-07-22T00:45:10.000Z' ->
"""
return str(int(time.mktime(time.strptime(text.spli... | 0795d3eac9e7d71f669112f435c88925f7ed10e3 | 669,035 |
def find_field(d, candidates):
"""
Given a dict and a list of possible keys, find the first key
which is included into this dict. Throws ValueError if not found.
"""
for c in candidates:
if c in d:
return c
raise ValueError(f"Can't find any of: {candidates}") | 3b716ec557a8477775c5321ecf56fdc2d9d5be3b | 669,037 |
def __renumber(dictionary):
"""Renumber the values of the dictionary from 0 to n
"""
count = 0
ret = dictionary.copy()
new_values = dict([])
for key in dictionary.keys():
value = dictionary[key]
new_value = new_values.get(value, -1)
if new_value == -1:
new_va... | 7f97325f1f9635fe45c3e24e5a3c073ee6e06c30 | 669,038 |
def get_container_type(full_name: str) -> type:
"""
get a new type to be used as a container
Args:
full_name (str): full name to distinguish from other types.
Returns:
type: a new type
"""
cls_name = "".join([name.capitalize() for name in full_name.split(".")])
return type... | d5a0e54836dd362b41dd01683291f29dd8a4b621 | 669,039 |
def leadingzero(number, minlength):
"""
Add leading zeros to a number.
:type number: number
:param number: The number to add the leading zeros to.
:type minlength: integer
:param minlength: If the number is shorter than this length than add leading zeros to make the length correct.
:retur... | b44213cec111c387b2b6670a2ccad363cb7b81a8 | 669,043 |
from pathlib import Path
def _find_json(db_dir):
"""Search with tags.
Args:
db_dir (str): Directory path which has database files.
Returns:
(list): List of json file path.
"""
p = Path(db_dir)
json_list = list(p.glob("**/*.json"))
json_list.sort()
return json_list | e19aec0491625194874aa57b09c1c946bd199941 | 669,045 |
def ConvertToInterval(timestamp):
"""Converts a datetime timestamp to a time interval for a cron job.
Args:
timestamp: a datetime.datetime object
Returns:
A value between 0 and 55 corresponding to the interval the timestamp
falls in. In this calculation, 12am on Monday is interval 0 and each
int... | 95be0fd67d36cb700bbc920b46affa58f26e3356 | 669,050 |
def flops_to_string(flops):
"""Converts flops count to a human-readable form"""
flops_str = ''
if flops // 10 ** 9 > 0:
flops_str = str(round(flops / 10. ** 9, 2)) + 'GMac'
elif flops // 10 ** 6 > 0:
flops_str = str(round(flops / 10. ** 6, 2)) + 'MMac'
elif flops // 10 ** 3 > 0:
... | e34165bbfa4d43416c77a45e440a9addcb39df32 | 669,053 |
def replace_final_line(edited_lines):
"""Replace final line internal tutorial link with external links."""
expected_final_line = (
"For a more thorough introduction,"
" check out the :ref:`tutorial`.\n"
)
new_final_line = (
"You can find the complete documentation"
"\ninc... | a85cd0d64eb7ad0a322c04a2f5056b9882a72aa8 | 669,059 |
def _create_padded_message(message: str) -> str:
"""Create padded message, used for encrypted responses."""
extra = len(message) % 16
return (16 - extra) * "0" + message | 616b36648a1f4d39354fd5978d532a97edd7e156 | 669,064 |
def basic_stats(db):
"""Collect basic statistics to be fed to output functions"""
rps = len(list(db['rp'].keys()))
users = len(list(db['users'].keys()))
logins = db['logins']
return {"rps": rps, "users": users, "logins": logins} | bdb4d93807d078789dfb44f1b47158a67f28165c | 669,065 |
def strip_chrom(chrom):
"""
Remove Chr or chr from the chromosome id
:param chrom: String
:return: String
"""
if 'chr' in chrom.lower():
return chrom[3:]
else:
return chrom | 58cd995d36f35c0b63ad7b1e1cda8210117573a0 | 669,066 |
def _get_user_display_name(user):
"""Return a human-friendly display name for a user."""
# An anonymous user has no display name
if user.is_anonymous:
return ''
# Form display name by concatenating first and last names and stripping whitespace
display_name = user.get_full_name().strip()
... | dfd8572893bb5c491d2b6c16e07975f6a141b235 | 669,067 |
import random
def fragment_list(tot_len, n_frags):
"""
A little function to help trouble shoot list_chunker. Creates a list of lists
by randomly fragmenting range(tot_len) into n_frags list
Args:
tot_len: the total number of elements in the lists
n_frags: the number of lists
Retu... | 0b7229fffd75b4b25d31ae702c0d4c7e4eecd2a5 | 669,069 |
def _time_last_active(cluster_summary, steps):
"""When did something last happen with the given cluster?
Things we look at:
* cluster's ``CreationDateTime`` (always set)
* cluster's ``ReadyDateTime`` (i.e. when bootstrapping finished)
* step's ``CreationDateTime`` for any step
* step's ``Start... | d0c2a77b50ba7380455ab2f2eded72f2b4ff8c31 | 669,072 |
import re
def format_imports(text):
"""
Takes a string of text and formats it based on rule 3 (see docs).
"""
# rule to find consective imports
regex4 = r"^import[\s\w]+?(?=from|^\s*$)"
# this subsitution will happen with a function
def subst4(match_obj):
pattern = r"import (\w+)"... | 2b66fded4660396c1b386daa99666250aa5a3f06 | 669,074 |
def rev_vid(image):
"""
Performs reverse video filter on input image.
:param image: an ndarray for a single-layer greyscale image,
where each element corresponds to a pixel.
:return: An ndarray that is the reverse video of input
"""
inverted = 255 - image
return inverted | d087206dfc9822d08287c84da2623c471e423bb4 | 669,078 |
def get_central_meridian(srs):
"""
Get the central meridian of the projection
Parameters
----------
srs : object
OSR spatial reference system
Returns
-------
: float
central meridian
"""
return srs.GetProjParm('central_meridian', 0.0) | c7b042472de0d4a2f486eabec36eb8ef60967d64 | 669,083 |
from typing import List
from typing import Dict
from typing import Callable
from typing import Any
def _dict_from_terse_tabular(
names: List[str],
inp: str,
transformers: Dict[str, Callable[[str], Any]] = {})\
-> List[Dict[str, Any]]:
""" Parse NMCLI terse tabular output into a lis... | 159a4db05c18ab181526a0e4b574d4859c5d9ad2 | 669,084 |
def snake2pascal(string: str):
"""String Convert: snake_case to PascalCase"""
return (
string
.replace("_", " ")
.title()
.replace(" ", "")
) | 5b0d9687924425d93c9f6611cd27a14dc2473497 | 669,088 |
def taille(arbre):
"""Renvoie la taille de l'arbre"""
if arbre is None:
return 0
else:
return 1 + taille(arbre.get_gauche()) + taille(arbre.get_droite()) | bafc78eaf1d4b3a6e4f272fda6f15d54212af5ce | 669,089 |
def event_callback(callback, **kw):
"""
Add keyword arguments to the event callback.
"""
return lambda evt: callback(evt,**kw) | 69471eb654594794643af6ba2c7ea1e88f083f1e | 669,091 |
def get_safe_filename(title):
"""
Get a safe string to use as a filename
:param title: your target file title
:return: the filename to use
:rtype: str
"""
keep_chars = (' ', '.', '_')
return "".join(c for c in title if c.isalnum() or c in keep_chars).rstrip() | 10a3b274bf166681c79ed05b9651326eb37898fd | 669,102 |
def time_format(num, digits=1, align_unit=False):
# type: (float, int, bool) -> str
"""Format and scale output according to standard time
units.
Example
-------
>>> time_format(0)
'0.0 s'
>>> time_format(0, align_unit=True)
'0.0 s '
>>> time_format(0.002)
'2.0 ms'
>>> t... | 806cefcd7c9ddeff8214031bbbdfee09ad7fa27f | 669,104 |
import torch
def compute_accuracy(dataloader, pred_list, nb_models):
"""
Computes the accuracy across al batches between the true labels in the dataloader and the batch predictions in pred_list
------------------
Input:
dataloader: contains the validation dataset X,y
pred_list: list of of tens... | 10e2eda9a0fce953ba5856cff59ed0520c70d36d | 669,106 |
def get_flood_risk_rating(num):
"""Converts an integer value of a flood risk rating to the rating it
represents - low (0/1), moderate (2), high (3), severe (4)"""
if num == 0 or num == 1:
return "Low"
if num == 2:
return "Moderate"
if num == 3:
return "High"
if num == 4... | 6c75676b58ec970a3c730ba59f6383794ea0438b | 669,110 |
def cross_compile(*args, **kwargs):
"""Compile the source string into a code object
__future__ imports change the behavior of default compile function
This function just provides the 'compile' free of __future__ imports
"""
return compile(*args, **kwargs) | bad06e0b5d1b87ea8b5ec47b92e1a9f92831a58e | 669,114 |
def importobj(modpath, attrname):
"""imports a module, then resolves the attrname on it"""
module = __import__(modpath, None, None, ["__doc__"])
if not attrname:
return module
retval = module
names = attrname.split(".")
for x in names:
retval = getattr(retval, x)
return retv... | e849a363b69195516cff46ff8ab3b6743b5383bb | 669,117 |
def get_channel(version: str) -> str:
"""Find channel based on version number."""
if "dev0" in version:
return "dev"
if "dev" in version:
return "nightly"
if "b" in version:
return "beta"
return "stable" | 38b3ea838c68593b9d9e1a9213d5b45f0886cba2 | 669,119 |
from pathlib import Path
def splitall(path):
"""
Split path into each part, top catalogue on top, filename (if included) last
"""
out = Path(path).parts
return out | 2ff81f9182de04763a43a75cab45c25b2f6fd2e3 | 669,120 |
from typing import Any
from typing import Union
from typing import Tuple
import operator
def _ensure_index(x: Any) -> Union[int, Tuple[int, ...]]:
"""Ensure x is either an index or a tuple of indices."""
try:
return operator.index(x)
except TypeError:
return tuple(map(operator.index, x)) | d47b62855d1cae40959412b6f509e6f76fefefc7 | 669,122 |
def line_pad(linestr, padding=''):
"""
:param linestr: multiple line string with `\n` as line separator.
:param padding: left padding string to add before each line.
It could also be a callable object that returns a string.
This is useful when creating dynamic padding.
:return: multiple line s... | 418e71d9511ef0250fe1e473e7a45b7c0f161b0b | 669,125 |
def mat_var(data, struc, field):
"""Get the 'field' from the 'struc' in the 'data' imported from Matlab"""
return data[struc][field].item() | 96533de8006f1d1760b5235a01bda7a22790033f | 669,126 |
def _cols_if_none(X, self_cols):
"""Since numerous transformers in the preprocessing
and feature selection modules take ``cols`` arguments
(which could end up as ``None`` via the ``validate_is_pd``
method), this will return the columns that should be used.
Parameters
----------
X : Pandas ... | e33d36d8b32cc891115ac6fe18d2779b391a9d05 | 669,127 |
def torch_to_numpy(t):
"""
torch tensor to numpy array
:param t: the torch tensor
:return: numpy array
"""
return t.numpy() | 793232ee73d11fb1d0e3503d907f0290fc09ebb9 | 669,129 |
def gen_target_cfg_items(target_cfg):
"""
Convert target_cfg to list of target configs
"""
if isinstance(target_cfg, list):
# list of templates defined for this target
return target_cfg
elif isinstance(target_cfg, dict):
# only one template defined for this target
ret... | 5ccf6198b44a800061a961d5decfba4701f7ac34 | 669,133 |
def intersection(l1, l2):
"""Return intersection of two lists as a new list::
>>> intersection([1, 2, 3], [2, 3, 4])
[2, 3]
>>> intersection([1, 2, 3], [1, 2, 3, 4])
[1, 2, 3]
>>> intersection([1, 2, 3], [3, 4])
[3]
>>> intersection([1, 2, 3], [4, 5, 6])
... | 98948fe600c1c1dd52d942d875efbb9d1dfdd46a | 669,138 |
def _equiv_topology(top_1, top_2):
"""Compare topologies using string reps of atoms and bonds"""
for (b1, b2) in zip(top_1.bonds(), top_2.bonds()):
if str(b1) != str(b2):
return False
for (a1, a2) in zip(top_1.atoms(), top_2.atoms()):
if str(a1) != str(a2):
return Fa... | efa70e346874745f119377542cf572d48a852504 | 669,141 |
import re
def ProcessGitHubLinks(markup, github):
"""Replaces the GitHub local links by the external variants."""
markup = re.sub(
r'#(\d+)',
r'[#\1](https://github.com/%s/issues/\1)' % github,
markup)
markup = re.sub(
r'\[(.+?)\]\((wiki/.+?)\)',
r'[\1](https://github.com/%s/\2)' %... | 88284abc8fc76f4b24dd1d5040b0156e4eef0cf7 | 669,142 |
def transpose(df):
"""Transpose df, set 'Date' as index, and strip columns."""
df = df.T.reset_index().rename(columns={"index" : "Date"})
return df.set_index("Date") | 0f7fa255880c4e89117ada7471e19dbbdf3037e4 | 669,150 |
def unique_label(operator):
"""Function for generating short name for operator from it's address. It takes first 6 and last 4 symbols and
combines it. """
return operator[:6] + operator[-4:] | 57b845de8af7c0c75479a6151dbe0e7f24898db5 | 669,162 |
import re
def sphinx_escape(value):
""" Escapes SphinxQL search expressions. """
if not isinstance(value, str):
return value
value = re.sub(r"([=<>()|!@~&/^$\-\'\"\\])", r'\\\\\\\1', value)
value = re.sub(r'\b(SENTENCE|PARAGRAPH)\b', r'\\\\\\\1', value)
return value | 12107cd3fac889f15d008a4a7be46ae17e774529 | 669,164 |
import base64
def s2b(s: str) -> bytes:
"""b64 string to bytes."""
return base64.b64decode(s) | d6e5bd6418f551fee207aaf2ed0c9e14b1b9c6cc | 669,168 |
from typing import Union
def constant_schedule(value: Union[float, int]):
"""Constructs a constant schedule.
Args:
value: value to be held constant throughout.
Returns:
schedule: A function that maps step counts to values.
"""
return lambda count: value | 14fc340a21b3b0deb008368a332ae28ab93162e2 | 669,170 |
def parse_lon_lat(grid, lon, lat):
""" Parse lat and lon parameters """
if lat is None:
lat = grid.axes['lat']['data'][0]
if lon is None:
lon = grid.axes['lon']['data'][0]
return lon, lat | 1f0280170c8d2c633c2615a0423d6b671d0dd0f0 | 669,173 |
def get_unique(frame, column_name):
"""
Helper function to get unique count for column
"""
return frame[column_name].value_counts().compute() | 5a32b53897658a6ba4b0aebabc1670c6460c16b8 | 669,174 |
def get_properties(dataset, property_offsets=None):
"""
Extract properties and return values in a dictionary:
{
'properties':
{
'datetime': time,
'odc:creation_datetime': creation_time,
...
}
}
"""
props = dict()
props['datetime'] = dataset.center_ti... | b525a6eb950a1763f1eb591e9b47d18ce3305cb9 | 669,177 |
def get_enduse_regs(
enduse,
fuels_disagg):
"""
Get a specific enduse for all regions
Arguments
---------
enduse : str
Enduse to sum
fuels_disagg : list
Fuels per disaggregated regions
Returns
-------
fuels_enduse : dict
Fuels of an enduse fo... | 17a3468fc795cfa0221cb3efca34246f6ff40f2f | 669,179 |
import random
def next_unused_name_in_group(grp, length):
""" Gives a name that isn't used in a Group.
Generates a name of the desired length that is not a Dataset or
Group in the given group. Note, if length is not large enough and
`grp` is full enough, there may be no available names meaning that
... | 302c55264655ef5d5c011462527ea88565dedebe | 669,180 |
def pluralize(count, singular, plural):
"""Return singular or plural based on count"""
if count == 1:
return singular
else:
return plural | cf9ead8a58728b59ecf485542aa6c9afd399b311 | 669,181 |
import six
def elide(string, max_length, ellipsis="...", position=1.0):
"""
Elides characters to reduce a string to a maximum length.
Replaces elided characters with an ellipsis.
>>> string = "Hello, world. This is a test."
>>> elide(string, 24)
'Hello, world. This i...'
>>> e... | f32662a49990d32fc53df0abad623d5bed890b76 | 669,185 |
def convert_to_hex(input_string: str):
"""Convert input_string into string of hexadecimal values."""
return " ".join([hex(ord(ch))[2:] for ch in input_string]) | d31be0492960c5fc6a49ecacdd3981f3d71fce14 | 669,186 |
def convert_uint32_to_array(value):
""" Convert a number into an array of 4 bytes (LSB). """
return [
(value >> 0 & 0xFF),
(value >> 8 & 0xFF),
(value >> 16 & 0xFF),
(value >> 24 & 0xFF)
] | e578cb3958511339c3df155d599fe00ee5c24f9d | 669,197 |
def solve(v):
""" Sum big numbers and get first digits. """
# no gmp support, pruning table
# int32 support: trunc digits
t = (
37107, #2875339021027,
46376, #9376774900097,
74324, #9861995247410,
91942, #2133635741615,
23067, #5882075393461,
89261, #67069... | aac5928db0281c11174ac7ea94c96e0f0742236f | 669,198 |
def read_data(filename):
""" read the cities data ffrom txt file and store them as a list of tuples of (x, y) """
cities = []
with open(filename) as f:
lines = f.readlines()
n = int(lines[0].split()[0])
for line in lines[1:]:
cities.append((float(line.split()[0]), float(l... | 177760b787b216d6d95a7436c4b4248d88f000cd | 669,199 |
import functools
def Factorial(x):
"""Computes the factorial of an integer number.
"""
# 0) SECURITY CHECK
if not isinstance(x, int):
raise ValueError( "'Factorial' function only accepts integers" )
# 1) COMPUTE THE FACTORIAL
if x == 0 or x == 1:
return 1
else:
ret... | 24d53acfcb6a372025a648b761f12747a5e1fa25 | 669,200 |
def motifPosCmp(motifOcc1, motifOcc2):
"""Compares two motif occurences according to their position on a given
sequence. The occurences must be on the same sequence."""
assert(motifOcc1.getSeqName() == motifOcc2.getSeqName())
motifOcc1Centre = motifOcc1.getCentre()
motifOcc2Centre = motifOcc2.getCe... | ef7fbff4fc40067f1b062841e36c9d6b4abf7390 | 669,204 |
import typing
import pkg_resources
def get_imagenet_classes() -> typing.List[str]:
"""Get the list of ImageNet 2012 classes."""
filepath = pkg_resources.resource_filename("vit_keras", "imagenet2012.txt")
with open(filepath) as f:
classes = [l.strip() for l in f.readlines()]
return classes | 66de4ad997c8002a3c8f82fe7b830d3e1fd1702d | 669,213 |
import math
def pts_near(gt_bbx, pred_bbx, rad): # change name
"""
Determine if two points are within a radius.
Parameters
----------
gt_bbx : dict
[centre_x, centre_y]
pred_bbx : dict
[centre_x, centre_y]
Returns
-------
True or False
"""
# creat... | f3a5b98b2e886aeb6c447591b7464d6a19631106 | 669,214 |
def len4bytes(v1, v2, v3, v4):
"""Return the packet body length when represented on 4 bytes"""
return (v1 << 24) | (v2 << 16) | (v3 << 8) | v4 | 74d503e7b21dbc2c3c14ca968f0a9decec297292 | 669,216 |
def solution(n: int = 1000) -> int:
"""
returns number of fractions containing a numerator with more digits than
the denominator in the first n expansions.
>>> solution(14)
2
>>> solution(100)
15
>>> solution(10000)
1508
"""
prev_numerator, prev_denominator = 1, 1
result ... | 07f07e82642e42232fd8c02b1d607eeaa589a11a | 669,217 |
def create_word_count_dict(word_count_queryset):
"""
This function creates a dictionary where the keys are word names
and the values are word counts from a given queryset.
:param word_count_queryset: A WordCountQueryset containing word names
and their associated word counts.
:return: A dictionar... | d04d66e70927fd12b4a8343ba8fefdb952239c35 | 669,218 |
def unique_list(l):
"""Remove duplicate term from a list
Parameters
----------
l : list
A list potentially contains duplicate terms
Returns
ulist : list
A list without unique terms
"""
ulist = []
for item in l:
if item not in ulist:
u... | 3ff78c11a7b62ec48e53333ee274b293fc09939b | 669,219 |
import random
def mutUniform(individual, expr, pset):
"""Randomly select a point in the tree *individual*, then replace the
subtree at that point as a root by the expression generated using method
:func:`expr`.
:param individual: The tree to be mutated.
:param expr: A function object that can gen... | c389b942c8b11508dee92fd4d003bbc528623dcf | 669,229 |
import random
def randomize(applicants):
"""
Random permutation of applicant list. Typical usage is before
prioritization.
"""
return random.sample(applicants, k = len(applicants)) | 4dceff66041e1881df2c064bc56b8f2b0663fb0c | 669,230 |
def _arithmetic_mean(nums) -> float:
"""Return arithmetic mean of nums : (a1 + a2 + ... + an)/n"""
return sum(nums) / len(nums) | 4917bbccc5f3e960dbedd57489cb148c207dd962 | 669,239 |
def tag(tag, url_name=None):
"""
Render a tag and a URL to filter by it if the base URL is provided.
"""
return {"tag": tag, "url_name": url_name} | 8434bcbf80202978e8c09229d2b6eb411f6a4ddd | 669,242 |
def get_reference_id(url: str):
"""
Return the reference id from a URL
For example:
>>> get_reference_id("https://github.com/advisories/GHSA-c9hw-wf7x-jp9j")
'GHSA-c9hw-wf7x-jp9j'
"""
_url, _, ref_id = url.strip("/").rpartition("/")
return ref_id | 370af3938b88b9c704e4777358a4c57bd66a20f0 | 669,243 |
def centroid_of_points(pts):
"""Returns the centroid of a cluster of points. Automatically
works with either 2D or 3D point tuples."""
xs, ys, zs = 0, 0, 0
for pt in pts:
xs += pt[0]
ys += pt[1]
if len(pt) > 2:
zs += pt[2]
if len(pts) > 0:
xs /= len(pts)
... | a274583a09d7272c9a680f44d44b9b58d2f5a346 | 669,244 |
from typing import Callable
from typing import Tuple
def _get_callable_info(callable: Callable) -> Tuple[str, str]:
"""Returns type and name of a callable.
Parameters
----------
callable
The callable
Returns
-------
Tuple[str, str]
The type and name of the callable. Type ... | f6e913f16556cc8ae078fd8562c2070bda8046a3 | 669,248 |
import re
def uncamel(phrase, sep='-'):
"""
converts camelcase phrase into seperated lower-case phrase
Parameters
---
phrase : str
phrase to convert
Examples
---
>>> uncamel('HTTPRequestHeader')
'http-request-header'
>>> uncamel('StatusCode404', sep=' ')
'... | bceea017e31258a6768e5197aee86c168e683303 | 669,252 |
def load_data_and_labels(filename, encoding="utf-8"):
"""Loads data and label from a file.
Args:
filename (str): path to the file.
encoding (str): file encoding format.
The file format is tab-separated values.
A blank line is required at the end of a sentence.
For exam... | 8d69c0cf28053fefacad5a2ff549e25cccb52f5a | 669,255 |
def trim_middle(arbitrary_string: str, max_length: int) -> str:
"""
Trim down strings to max_length by cutting out the middle.
This assumes that the most "interesting" bits are toward
the beginning and the end.
Adds a highly unusual '✂✂✂' in the middle where characters
were stripped out, to avo... | 00da48df252e6304d9f5a1faf1ef9848d63b5a02 | 669,258 |
def _get_categorization_parameters_for_extract_study(extract_study_id, dict_cur):
"""
returns a dictionary keyed by (vocabulary_id, concept_code) of lists of rows.
The rows are dictionaries as those returned by a dict_cur.
param extract_study_id
Returns dictionary keyed by (vocabu... | c6ed4ea3dc410f187cbd92661d1c093881bc781c | 669,263 |
def float_or_none(arg):
"""Returns None or float from a `float_or_none` input argument.
"""
if arg is None or str(arg).lower() == 'none':
return None
return float(arg) | ee4c835f0dae4e01d388e1f6c30677315dbfd1d9 | 669,266 |
def get_position_left(original_position):
"""
Given a position (x,y) returns the position to the left of the original position, defined as (x-1,y)
"""
(x,y) = original_position
return(x-1,y) | c4b928d90bea3a06322cb0b3631904df0c3eea3e | 669,267 |
def get_fields(fields, response):
"""Extracts desired fields from the API response"""
results = {}
for field in fields:
results[field] = response.get(field)
return results | 1ee509723f66de1dd95b60b7b5bbba069c3020fb | 669,269 |
def withdraw_money(amount, card_balance):
"""Withdraw given amount of money from the account."""
card_balance -= amount
# save new balnace to the database
return card_balance | da538bf9f99e04dc8717854d04566dcd83a9d652 | 669,270 |
def convert_batch_idx_to_window_idx(batch_idx, ws_multiplier):
"""return absolute_window_idx that batch_idx is in"""
return int(batch_idx/ws_multiplier) | 654925153e7724c64865c918e364b5a1e86fc145 | 669,281 |
import pickle
def read_object(filename):
"""Convenience function for retrieving object from file using pickle.
Arguments:
filename {str} -- path to file
Returns:
object -- object in file (uses pickle)
"""
with open(filename, 'rb') as file:
obj = pickle.load(file)
... | c6b53d5cb7260a397eb197fa84ed2b8802410bb4 | 669,283 |
def match_content_type(filename: str) -> str:
"""
Match file extensions to content-type. A quick lightweight list.
This is needed so s3 vends the right MIME type when the file is downloaded
directly from the bucket.
"""
content_type_match = {
'json': 'application/json',
'js': 'ap... | ff4ef5d752a96a39845baad8516e3057408c1b27 | 669,286 |
def duplicate(my_list):
"""Return a new list that repeats the input twice"""
return my_list + my_list | 738aa7301ec26532f1162ff062c2ccc7b54918e3 | 669,290 |
def filter_providers_by_type(providers, type):
"""
helper function to filter a list of providers by type
:param providers: ``list``
:param type: str
:returns: filtered ``dict`` provider
"""
providers_ = {provider['type']: provider for provider in providers}
return providers_.get(type,... | 7cf3204907b9cf9e6ee0fddf33ec10fb321c8a03 | 669,291 |
def get_full_module_name(o, lower=False):
"""
Returns the full module and class name of an object o.
For example, for our :class: OntonotesReader, returns
'nlp.forte.data.readers.ontonotes_reader.OntonotesReader'.
"""
if not isinstance(o, type):
o = o.__class__
module = o.__module__
... | a5e5d8fa54124f103f66f8a3cb0678325d0932ee | 669,295 |
def expression_polynomial(cobj, prop, T):
"""
Create expressions for CoolProp rational polynomial forms
Args:
cobj: Component object that will contain the parameters
prop: name of property parameters are associated with
T: temperature to use in expression
Returns:
Pyomo... | 8aa677b22c5239e95b962204049eed48941e36e6 | 669,296 |
def any_ga(geoawi):
"""
GEOAWI: GA W/I GRID
0=None
1=Quest
2=<I2
3=<O2
4=<1/2 DA
5=<1DA
6=<2DA
7=>2DA
8=CG
Returns:
0, 1, 88
"""
if geoawi == 0:
return 0
elif 1 <= geoawi <= 7:
return 1
elif geo... | 1db941f44a23f8ec99fb27efd395cc12c8902544 | 669,299 |
def _merge_weights(spin_d1, spin_d2):
"""Sum the weights stored in two dictionaries with keys being the spins"""
if len(spin_d1) != len(spin_d2):
raise RuntimeError("Critical - mismatch spin-dict length")
out = {}
for spin in spin_d1:
out[spin] = spin_d1[spin] + spin_d2[spin]
return ... | 6e99afd66192954db1eae9d4f958dd2ca2b23c59 | 669,300 |
def read(path, open_flags='r'):
"""Opens file at |path| with |open_flags| reads it and then returns the
result."""
with open(path, open_flags) as file_handle:
return file_handle.read() | 4eaee0fe9e5467388104644b535500df1210eca8 | 669,303 |
def valueToString(v):
"""
>>> valueToString(0)
'0'
>>> valueToString(10)
'10'
>>> valueToString(-10)
'-10'
>>> valueToString(0.1)
'0.1'
>>> valueToString(0.0001)
'0.0001'
>>> valueToString(0.00001)
'0'
>>> valueToString(10.0001)
'10.0001'
>>> valueToString... | 74026c993ac2510c075a34d6b2568f8b8f6efcf5 | 669,305 |
def period_starts(counter, period):
"""
Utility function to test whether we are at the beginning of a cycle
of length `period`.
If the period is non positive, this always return False, otherwise
it returns True when `counter` is 0, cycle, 2*cycle, etc.
@param counter typically an epoch index, o... | 6691dc2e35ea74086a43c1d9a0cd4a3be5022afb | 669,308 |
def get_vararg_name(varargs_name, i):
# type: (str, int) -> str
""" Given some integer i, return the name of the ith vararg.
Note that the given internal names to these parameters are
impossible to be assigned by the user because they are invalid
Python variable names, as they start with a star
... | b8a2566ab611c2fdefff584383808e224aad2f00 | 669,313 |
def get_options(options, names):
"""Returns a dictionary with options for the given keys.
Args:
options: dict
names: list of keys
Returns:
dict
"""
new = {}
for name in names:
if name in options:
new[name] = options[name]
return new | 1b4df1967cf73b56d5ae2ed998daf7c49ce76a7a | 669,315 |
import hashlib
def list_digest(inp_list):
"""Return a digest to uniquely identify a list."""
if type(inp_list) is not list:
raise TypeError("list_digest only works on lists!")
if not inp_list:
raise ValueError("input must be a non-empty list!")
# If we can rely on python >= 3.8, shlex.... | e63a52bd1d4356c437a16d8a16101a8c9ac852c1 | 669,319 |
def create_api_auth_refresh_parms(_client_id, _api_secret, _refresh_token):
"""
Creates the request parameters necessary to refresh an authentication token.
@param _client_id: Client ID magic string from the API setup.
@param _api_secret: Super secret API secret from the API setup that you are never allowed to see ... | db71d5b06f60f71690cf016fc0e4f58969f8fa00 | 669,321 |
def quote_title(title):
"""Quote an article name of a MediaWiki page."""
return title.replace(" ", "_") | 806ab68a809c9d6bd82304e474ed88b074169a23 | 669,324 |
import random
def max_weight_paths(k, weight_paths_dict, paths_to_edges, overlap=True, norev=False, rgen=None):
"""
Returns k largest-weight paths. The function proceeds in order through descending weight values to select paths,
and if an entire weight class of paths is not to be included, applies a pred... | 50264effde7c0f7f97c6e5a4c6c34899ad5462db | 669,326 |
def load_processed_data(processed_path, parsed_reader):
""" Load parsed results from disk
:param processed_path: the file name to a file that stores parsed results
:type processed_path: str
:param parsed_reader: the parsed reader to load parsed results
:type parsed_reader: ParsedReader
:return:... | c4ef54e5967c5952d86cc4b6748580914fee3ad4 | 669,328 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.