content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_filename_safe_string(string, max_length=146):
"""
Converts a string to a string that is safe for a filename
Args:
string (str): A string to make safe for a filename
max_length (int): Truncate strings longer than this length
Warning:
Windows has a 260 character length limit on file paths
Returns:
str: A string safe for a filename
"""
invalid_filename_chars = ['\\', '/', ':', '"', '*', '?',
'<', '>', '|', '\n', '\r']
if string is None:
string = "None"
for char in invalid_filename_chars:
string = string.replace(char, "")
string = string.rstrip(".")
string = (string[:max_length]) if len(string) > max_length else string
return string | 5b7815c092d566e875cdda4466f716d48ed62671 | 691,295 |
def is_user_active(user_obj):
"""
Helps to find user is active or not.
Returns boolean value True or False
:param user_obj: user queryset of User model
:return: boolean value
"""
if user_obj.is_active:
return True
return False | 1008ab560600803988b32b40ca9c861df0b15ce3 | 691,297 |
from datetime import datetime
def format_datetime(timestamp):
"""Format a timestamp for display."""
return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M') | f841d74e381f4524a7fc428feb4111eb5f282538 | 691,298 |
def read_monoisotopic_mass_table(input_file):
"""
Given a tab-separatedd input file with amino acids (as capital letters)
in the first column, and molecular weights (as floating point numbers)
in the second column - create a dictionary with the amino acids as keys
and their respective weights as values.
"""
mass_dict = {}
with open(input_file, "r") as read_file:
for line in read_file:
elements = line.split()
amino_acid = str(elements[0])
weight = float(elements[1])
mass_dict[amino_acid] = weight
return mass_dict | b14c3353a4a71b23e540f041abc170dc6b2f6942 | 691,299 |
from typing import Mapping
def _mapping2list(map: Mapping):
"""Converts a mapping to a list of k1.lower():v1.lower(), k2:v2, ..."""
return [f"{str(key).lower()}:{str(value).lower()}" for key, value in map.items()] | 7cee135c883ce1ff8dcb48103d1718e4bc76ab25 | 691,301 |
def GetBlockIDs(fp):
"""
Get the information about each basic block which is stored at the end
of BBV frequency files.
Extract the values for fields 'block id' and 'static instructions' from
each block. Here's an example block id entry:
Block id: 2233 0x69297ff1:0x69297ff5 static instructions: 2 block count: 1 block size: 5
@return list of the basic block info, elements are (block_id, icount of block)
"""
block_id = []
line = fp.readline()
while not line.startswith('Block id:') and line != '':
line = fp.readline()
if line == '': return []
while line.startswith('Block id:'):
bb = int(line.split('Block id:')[1].split()[0])
bb -= 1 # Change BBs to use 0 based numbering instead of 1 based
icount = int(line.split('static instructions:')[1].split()[0])
block_id.append((bb, icount))
line = fp.readline()
# import pdb; pdb.set_trace()
return block_id | 7434d30db1dfb4ce34469e9c900a6a80cb487bd7 | 691,306 |
import functools
def lcm(l):
"""least common multiple of numbers in a list"""
def _lcm(a, b):
if a > b:
greater = a
else:
greater = b
while True:
if greater % a == 0 and greater % b == 0:
lcm_ = greater
break
greater += 1
return lcm_
return functools.reduce(lambda x, y: _lcm(x, y), l) | 219eb5bbb50ec6f23979db489f42a86b4feef3cc | 691,307 |
def map_value(value, inmin, inmax, outmin, outmax):
"""Map the value to a given min and max.
Args:
value (number): input value.
min (number): min input value.
max (number): max input value.
outmin (number): min output value.
outmax (number): max output value.
Returns:
number: output value.
"""
if value < inmin:
value = inmin
elif value > inmax:
value = inmax
return ((outmax - outmin) * (value - inmin)) / (inmax - inmin) + outmin | c44e1c16589e86835321ae883724e514f0a043d1 | 691,312 |
from datetime import datetime
def to_timestamp(date):
"""Convert string to UNIX timestamp."""
ts = datetime.strptime(date, '%Y-%m-%dT%H:%M:%SZ').timestamp()
return ts | b33e3297739acb4b5ed73ab4a09526f7b2bf8778 | 691,316 |
from pathlib import Path
def get_n_bytes(file: Path, n):
"""
Return the first n bytes of filename in a bytes object. If n is -1 or
greater than size of the file, return all of the file's bytes.
"""
with file.open("rb") as in_file:
return in_file.read(n) | 4f791ef60393190b6d367271d21b2f07cdd007c1 | 691,317 |
def _partial_fn(fn, *args, **kwargs):
"""Partial apply *args and **kwargs after the shape, dtype, key args."""
# Dummy value here is so that we can use lax.switch directly.
def f(shape, dtype, key, _):
return fn(shape, dtype, key, *args, **kwargs)
return f | a0f1d0fa86f7dd4a1ad6c7241a03895966b6725a | 691,320 |
def accuracy(y_hat, y):
"""Get accuracy."""
return (y_hat.argmax(axis=1) == y).mean().asscalar() | 9c63e1d8b7e06dc278b2965abb3931cd0f6208c7 | 691,321 |
def get_velocity_line(pt, vx, vy):
"""get line slope and bias from a start point and x, y change velocity,
y = slope*x + bias
"""
slope, bias = None, None
if vx != 0:
slope = vy / vx
bias = pt[1] - slope * pt[0]
return slope, bias | 4b32259c245f056881743f108ff617c2c49ac49c | 691,331 |
def omrs_datetime_to_date(value):
"""
Converts an OpenMRS datetime to a CommCare date
>>> omrs_datetime_to_date('2017-06-27T00:00:00.000+0000') == '2017-06-27'
True
"""
if value and 'T' in value:
return value.split('T')[0]
return value | f3728a47b64781842ce353aacec70b0cfe104f2c | 691,333 |
def default(default_value, force=False):
"""
Creates a function which allows a field to fallback to a given default
value.
:param Any default_value: The default value to set
:param bool force: Whether or not to force the default value regardless of a
value already being present
:rtype: function
"""
def default_setter(value):
"""
Sets the value to the given default value, assuming the original value
is not set or the default value is set to forced.
:param Any value: Injected by CKAN core
:rtype: Any
"""
return value if value and not force else default_value
return default_setter | c6a56d976131e9d712e63b73ac09ddb6b0acedc6 | 691,334 |
def filter_d(mzs, rts, ccss, data):
"""
filter_d
description:
a helper function for filtering data
given M/Z, RT, CCS ranges and a DataFrame containing data,
find and returns all data within that range.
* CCS tolerance is absolute in this case, NOT a percentage *
parameters:
mzs (list(flaot)) -- mz [0] and tolerance [1]
rts (list(float)) -- rt [0] and tolerance [1]
ccss (list(float)) -- ccs [0] and tolerance [1]
data (pandas.DataFrame) -- DataFrame representation of the data
"""
# removed all of the casts to float, that should happen at input time not here
filtered = data[(data[0] < mzs[0] + mzs[1]) & (data[0] > mzs[0] - mzs[1]) &
(data[1] < rts[0] + rts[1]) & (data[1] > rts[0] - rts[1]) &
(data[2] < ccss[0] + ccss[1]) & (data[2] > ccss[0] - ccss[1])]
return filtered | 065f27bed9d5b04dcd1eaa6b48b8466c6847d540 | 691,335 |
from typing import List
def flatten(lst: List) -> List:
"""Flatten a list.
"""
return [item for sublist in lst for item in sublist] | 58ce2d954bd80b9a8a60f2eb20803761a5ef8052 | 691,337 |
def make_hit(card, cards, deck):
"""
Adds a card to player's hand
"""
if card in deck:
cards.append(card)
deck.remove(card)
return cards | 2420676fa793d07ee2674d2870428eeb6d580a97 | 691,338 |
import math
def Expectation(Ra, Rb):
""" Calculates the 'Expectation' value following the original formula """
return 1.0 / (1 + math.pow(10, -((Ra - Rb) / 8))) | c7675790f49155e29fe857ee1ea7924e7227d5fd | 691,340 |
from typing import Optional
import pathlib
def _log_figure_path(path: Optional[pathlib.Path]) -> Optional[pathlib.Path]:
"""Adds a suffix to a figure path to indicate the use of a logarithmic axis.
If the path is None (since figure should not be saved), it will stay None.
Args:
path (Optional[pathlib.Path]): original path to figure, or None if figure should
not be saved
Returns:
Optional[pathlib.Path]: new path to figure including _log suffix, or None if
original path is None
"""
if path is not None:
return path.with_name(path.stem + "_log" + path.suffix)
return None | 381bde67a89f0f61d7bdb9a9f2ea033664e6fab0 | 691,342 |
def label(self):
"""
Returns:
label (string): name for the hazard category
"""
try:
value = self._label
except AttributeError:
value = None
return value | 0cc08e0b62420f9eb92da64b4636191c72306091 | 691,344 |
def group(n, lst, discard_underfull = False):
"""Split sequence into subsequences of given size. Optionally discard or
include last subsequence if it is underfull
"""
out = []
for i in range(0, len(lst), n):
out.append(lst[i:i+n])
if discard_underfull and len(out[-1]) < n:
out.pop()
return out | 5d96885b92b0f470239723554eed14fe276644c0 | 691,348 |
from typing import Optional
def fancy_archetype_name(position: str, archetype: str) -> Optional[str]:
"""
If given a non-goalie position and a string 'passer', 'shooter', or 'deker' (case insensitive), returns a string corresponding
to proper name per rulebook. Returns None otherwise.
"""
position, archetype = position.upper(), archetype.upper()
if position == "FORWARD":
return {"PASSER": "Playmaker", "SHOOTER": "Sniper", "DEKER": "Dangler"}[archetype]
if position == "DEFENSEMAN":
return {"PASSER": "Enforcer", "SHOOTER": "Offensive Defenseman", "DEKER": "Finesser"}[archetype]
return None | fcca0505f722856037274a22ac0c47e6c8baff4f | 691,349 |
from bs4 import BeautifulSoup
def is_single_media(text):
"""
Judge whether the paragraph is an single media.
:param text: one paragraph string.
:return: bool.
"""
soup = BeautifulSoup(text, 'lxml')
# ONE <a> tag here, return True
if soup.select('a'):
anchor = soup.select('a')[0]
if anchor.getText() == '[Media]':
if text.replace(str(anchor), '') == '':
return True
# ONE media plain stmbol here, return True
elif text.strip() == '[Media]':
return True
return False | 3256778f9668ad432b8f0a6e0e620ac49761dafc | 691,350 |
def center_low_freq_2d(x):
"""Be x a multidimensional tensor. Along the last two dimensions reorder the
vector.That is, for the last dimension assume we have
[x_0, x_1, ..., x_{n-1}]. Reorder the tensor along the given
dimesion as:
- if n is even:
[x_{n/2}, x_{n/2+ 1}, ..., x_{n-1}, x_0, x_2, ..., x_{n/2-1}]
- if n is odd:
[x_{(n+1)/2}, x_{(n+3)/2}, ..., x_{n-1}, x_0, x_2, ..., x_{(n-1)/2}]
It does the same for the dimension before the last.
If `x` is the FFT of a signal, this can be understood as centering the frequencies.
"""
shape = x.shape
m, n = shape[-2:]
n_index = list(range(n))[n//2:] + list(range(n))[:n//2]
m_index = list(range(m))[m//2:] + list(range(m))[:m//2]
return x[...,n_index][..., m_index, :] | 918b23a407dc76d3743160559ded64528e5b29c0 | 691,351 |
from typing import Dict
from typing import Any
def validObject(object_: Dict[str, Any]) -> bool:
"""
Check if the Dict passed in POST is of valid format or not.
(if there's an "@type" key in the dict)
:param object_ - Object to be checked
"""
if "@type" in object_:
return True
return False | 6c40ad1cef0a8f056d2e00c9a7632108bfd2f506 | 691,353 |
def none_if_invalid(item):
"""
Takes advantage of python's 'falsiness' check by
turning 'falsy' data (like [], "", and 0) into None.
:param item: The item for which to check falsiness.
:return: None if the item is falsy, otherwise the item.
"""
return item if bool(item) else None | d19476af100d85590d6357ad8677cbaca18e26b4 | 691,356 |
def makeIterable(item):
"""
Takes as argument or an iterable and if it's not an iterable object then it
will return a listiterator.
"""
try:
iterable = iter(item)
except TypeError:
iterable = iter([item])
return iterable | 5ec952ed2f1c9b0761aa5396a57da6271c7cd6dd | 691,359 |
def geometrical_spreading(freq, dist, model="REA99"):
"""
Effect of geometrical spreading.
Args:
freq (array):
Numpy array of frequencies for computing spectra (Hz).
dist (float):
Distance (km).
model (str):
Name of model for geometric attenuation. Currently only supported
value:
- 'REA99' for Raoof et al. (1999)
Returns:
Array of anelastic attenuation factor.
"""
if model == 'REA99':
dist_cross = 40.0
if dist <= dist_cross:
geom = dist**(-1.0)
else:
geom = (dist / dist_cross)**(-0.5)
else:
raise ValueError('Unsupported anelastic attenuation model.')
return geom | cb03585fc855b8ec565bcc25c37073ec9fd0f1c8 | 691,360 |
import unicodedata
def _is_punctuation(char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, for
# consistency.
if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
(cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
return True
cat = unicodedata.category(char)
if cat.startswith("P"):
return True
return False | ac4eeeeceba447f85cb61d792237c930d9c131f9 | 691,361 |
def glue_pair(code1, code2):
"""Glue two pieces of code."""
return code1 + code2 | 030af6fdb333fd8927c3af192e7563d1e285eaad | 691,364 |
def cleanList(aList):
"""
Returns aList with any duplicates removed
"""
return list(set(aList)) | ab8eaa8556bf868beb32100ad5897302d9551eda | 691,365 |
def collapse_list(the_list):
""" Collapses a list of list into a single list."""
return [s for i in the_list for s in i] | 4a693970ce2bf7baa4a43bef6c3778d2381a2487 | 691,367 |
from functools import reduce
def bytes_to_int(bytes):
"""
Convert bytes to integer
Args:
bytes(bytes): bytes to be converted
Returns:
int
Examples:
>>> bytes_to_int(b'\xde')
222
"""
return reduce(lambda s, x: (s << 8) + x, bytearray(bytes)) | e771a3ebd4d90d524e48f34ab0fe51e7f6babf90 | 691,368 |
def format_git_describe(git_str, pep440=False):
"""format the result of calling 'git describe' as a python version"""
if git_str is None:
return None
if "-" not in git_str: # currently at a tag
return git_str
else:
# formatted as version-N-githash
# want to convert to version.postN-githash
git_str = git_str.replace("-", ".post", 1)
if pep440: # does not allow git hash afterwards
return git_str.split("-")[0]
else:
return git_str.replace("-g", "+git") | 38f5c4787d91e4abc2771499e9f62703fa2a3150 | 691,375 |
import requests
def image_metrics(ID, filename):
"""
GET image metrics from server
Args:
ID (str): user name
Returns:
r7.json() (dict): Dictionary containing the image metrics
example: outdict = {
"timestamp": ...,
"size": [100, 100],
"latency": 1,
"process": 'Reverse Video'}
"""
mjson = {
"username": ID,
"filename": filename
}
r8 = requests.get("http://vcm-9030.vm.duke.edu:5000/api/image_metrics",
json=mjson)
return r8.json() | 9d3f6ea202006f9c53f54e242a805f07eb34e35e | 691,376 |
import re
def email_finder(text):
"""returns emails found inside a given text"""
email_finder = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}')
mo = re.findall(email_finder, text)
return mo | c3a7b04a80936db59a78eec44c146e410ba00124 | 691,377 |
def getservbyname(servicename, protocolname=None): # real signature unknown; restored from __doc__
"""
getservbyname(servicename[, protocolname]) -> integer
Return a port number from a service name and protocol name.
The optional protocol name, if given, should be 'tcp' or 'udp',
otherwise any protocol will match.
"""
return 0 | b0e583205ee1954c7a9b178f0f3e68f05511144c | 691,378 |
def _isValidOpcodeByte(sOpcode):
"""
Checks if sOpcode is a valid lower case opcode byte.
Returns true/false.
"""
if len(sOpcode) == 4:
if sOpcode[:2] == '0x':
if sOpcode[2] in '0123456789abcdef':
if sOpcode[3] in '0123456789abcdef':
return True;
return False; | dee516c1765aedfc9f7c0044cde29495d54f81f5 | 691,379 |
import six
import re
def is_valid_mac(address):
"""Return whether given value is a valid MAC."""
m = "[0-9a-f]{2}(:[0-9a-f]{2}){5}$"
return (isinstance(address, six.string_types)
and re.match(m, address.lower())) | 12d84e3e18bf51a48270639e59a3c4ce39d58e84 | 691,388 |
def group_by_clauses(selectable):
"""Extract the GROUP BY clause list from a select/query"""
return selectable._group_by_clauses | ce639e2acf78ead54f7f43ec91298dc95cfd0f27 | 691,390 |
def format_nmmpmat(denmat):
"""
Format a given 7x7 complex numpy array into the format for the n_mmp_mat file
Results in list of 14 strings. Every 2 lines correspond to one row in array
Real and imaginary parts are formatted with 20.13f in alternating order
:param denmat: numpy array (7x7) and complex for formatting
:raises ValueError: If denmat has wrong shape or datatype
:returns: list of str formatted in lines for the n_mmp_mat file
"""
if denmat.shape != (7, 7):
raise ValueError(f'Matrix has wrong shape for formatting: {denmat.shape}')
if denmat.dtype != complex:
raise ValueError(f'Matrix has wrong dtype for formatting: {denmat.dtype}')
#Now we generate the text in the format expected in the n_mmp_mat file
nmmp_lines = []
for row in denmat:
nmmp_lines.append(''.join([f'{x.real:20.13f}{x.imag:20.13f}' for x in row[:3]]) + f'{row[3].real:20.13f}')
nmmp_lines.append(f'{row[3].imag:20.13f}' + ''.join([f'{x.real:20.13f}{x.imag:20.13f}' for x in row[4:]]))
return nmmp_lines | a39dfac693e4acd7632deebef416d27cf18df71e | 691,392 |
def _set_default_application(application_id: int, type_id: int) -> int:
"""Set the default application for mechanical relays.
:param application_id: the current application ID.
:param type_id: the type ID of the relay with missing defaults.
:return: _application_id
:rtype: int
"""
if application_id > 0:
return application_id
return {1: 1, 2: 1, 3: 8, 4: 1, 5: 6, 6: 3}[type_id] | 5a162670c144cd37299caf728ca8cb4da87d9426 | 691,395 |
def arb_func(arg):
"""Arbitrary function just returns input."""
return arg | e09e2bc688d0d9c2c2f0cc5cfa8ae6ec4e5eadfb | 691,396 |
def str2bool(str):
"""
Converts a string to a boolean value. The conversion is case insensitive.
:param str: string to convert.
:type str: string
:returns: True if str is one of: "yes", "y", "true", "t" or "1".
:rtype: bool
"""
return str.lower() in ("yes", "y", "true", "t", "1") | 95ad6a99e004e304a160e4edb9bc57bec22bf3d8 | 691,398 |
def get_pixel_info(local_info, d_behind, obs_range, image_size):
"""
Transform local vehicle info to pixel info, with ego placed at lower center of image.
Here the ego local coordinate is left-handed, the pixel coordinate is also left-handed,
with its origin at the left bottom.
:param local_info: local vehicle info in ego coordinate
:param d_behind: distance from ego to bottom of FOV
:param obs_range: length of edge of FOV
:param image_size: size of edge of image
:return: tuple of pixel level info, including (x, y, yaw, l, w) all in pixels
"""
x, y, yaw, l, w = local_info
x_pixel = (x + d_behind) / obs_range * image_size
y_pixel = y / obs_range * image_size + image_size / 2
yaw_pixel = yaw
l_pixel = l / obs_range * image_size
w_pixel = w / obs_range * image_size
pixel_tuple = (x_pixel, y_pixel, yaw_pixel, l_pixel, w_pixel)
return pixel_tuple | a0aaa8accdbb9bab6102b9f8e9895986376c594e | 691,402 |
def _joinNamePath(prefix=None, name=None, index=None):
"""
Utility function for generating nested configuration names
"""
if not prefix and not name:
raise ValueError("Invalid name: cannot be None")
elif not name:
name = prefix
elif prefix and name:
name = prefix + "." + name
if index is not None:
return "%s[%r]" % (name, index)
else:
return name | fb26dc39ded907cefc1a319d6d0692e67f8c5007 | 691,404 |
import datetime
import time
def convert_to_seconds(minutes):
"""
Return minutes elapsed in time format to seconds elapsed
:param minutes: time elapsed
:return: time elapsed in seconds
"""
if minutes == '-16:0-':
return '1200' # Sometimes in the html at the end of the game the time is -16:0-
x = time.strptime(minutes.strip(' '), '%M:%S')
return datetime.timedelta(hours=x.tm_hour, minutes=x.tm_min, seconds=x.tm_sec).total_seconds() | 5d841de245cc6790a9a9d15c998406927ffda5a6 | 691,407 |
def parse_typename(typename):
"""
Parse a TypeName string into a namespace, type pair.
:param typename: a string of the form <namespace>/<type>
:return: a tuple of a namespace type.
"""
if typename is None:
raise ValueError("function type must be provided")
idx = typename.rfind("/")
if idx < 0:
raise ValueError("function type must be of the from namespace/name")
namespace = typename[:idx]
if not namespace:
raise ValueError("function type's namespace must not be empty")
type = typename[idx + 1:]
if not type:
raise ValueError("function type's name must not be empty")
return namespace, type | 7770939cbe7d6e7afabb8e0679380836977f17aa | 691,412 |
from typing import Tuple
def min_or_max_index(L: list, minimum: bool) -> Tuple[int, int]:
""" If the Boolean parameter refers to True
the function returns a tuple containing the minimum and its index;
if it refers to False,
it returns a tuple containing the maximum and its index
>>> min_or_max_index([5, 4, 3, 2, 8, 9], True)
(2, 3)
>>> min_or_max_index([5, 4, 3, 2, 8, 9], False)
(9, 5)
"""
# find both the minimum value in a list and that value’s index
# and the maximum value in a list and that value’s index
# in one pass through the list
smallest = L[0]
smallest_pos = 0
biggest = L[0]
biggest_pos = 0
for element in L:
if element < smallest:
smallest = element
smallest_pos = L.index(element)
if element > biggest:
biggest = element
biggest_pos = L.index(element)
if minimum:
return (smallest, smallest_pos)
else:
return (biggest, biggest_pos) | e2f0f572f248fec946690cc586bd4faf326aa699 | 691,414 |
def get_from_cache(key, default_value=None, ctx=None):
"""Returns value from the context cache.
:param str key: String with the key.
:param obj default_value: Optional default value, if the
key is not found inside the cache this value will be
returned, defaults to None.
:param obj ctx: The context object.
:returns: The value in the cache that corresponds to the provided key.
"""
if not ctx:
return default_value
return ctx.get(key, default_value) | 4a63525802b7076e5b196269c3fc43fd198039ff | 691,416 |
def is_number(word):
""" Function that returns 'NUM' if a shipo word is a number or False if not
:param word: a word to be evaluated
:type word: str
:returns: 'NUM' if a shipo word is a number or False if not
:rtype: str
:Example:
>>> import chana.ner
>>> chana.ner.is_number('kimisha')
'NUM'
"""
numbers=['westiora','rabé','kimisha','chosko','pichika','sokota','kanchis','posaka','iskon','chonka','pacha','waranka']
if word.lower() in numbers:
return 'NUM'
else:
return False | 45daa79eff17c93e201b03082bbea3c05c383d33 | 691,418 |
from typing import Dict
from typing import Any
import uuid
def make_test_experiment_config(config: Dict[str, Any]) -> Dict[str, Any]:
"""
Create a short experiment that based on a modified version of the
experiment config of the request and monitors its progress for success.
The short experiment is created as archived to be not user-visible by
default.
The experiment configuration is modified such that:
1. The training step takes a minimum amount of time.
2. All checkpoints are GC'd after experiment finishes.
3. The experiment does not attempt restarts on failure.
"""
config_test = config.copy()
config_test.update(
{
"description": "[test-mode] {}".format(
config_test.get("description", str(uuid.uuid4()))
),
"batches_per_step": 1,
"min_validation_period": 1,
"checkpoint_storage": {
**config_test.get("checkpoint_storage", {}),
"save_experiment_best": 0,
"save_trial_best": 0,
"save_trial_latest": 0,
},
"searcher": {
"name": "single",
"metric": config_test["searcher"]["metric"],
"max_steps": 1,
},
"resources": {**config_test.get("resources", {"slots_per_trial": 1})},
"max_restarts": 0,
}
)
config.setdefault(
"data_layer", {"type": "shared_fs", "container_storage_path": "/tmp/determined"}
)
return config_test | 72ee62a9b6fa977aaff6f0621e18e0cdb0a8a0bb | 691,419 |
def operation_jnz(register, register_check, jump_by):
"""Jump operation. Jump if register_check is not 0."""
if register.get(register_check, register_check) != 0:
return jump_by | bfeca2efbb7389c21749497db73e624d37faef62 | 691,420 |
from typing import List
def increment_index(index: List[int], dims: List[int]) -> bool:
"""Increments an index.
Args:
index: The index to be incremented.
dims: The dimensions of the block this index is in.
Returns:
True iff the index overflowed and is now all zeros again.
"""
cur = len(index) - 1
index[cur] += 1
while index[cur] == dims[cur]:
index[cur] = 0
if cur == 0:
return True
cur -= 1
index[cur] += 1
return False | 833e0baa9c29348067102ef6fe530e45b91ff988 | 691,421 |
def add_up_errors(list_keyerror):
"""
#################################################################################
Description:
Adds in one string the given keyerrors from the list of keyerrors
#################################################################################
:param list_keyerror: list of string
list of keyerrors (strings or None) listing encountered errors
:return keyerror: string
string of all encountered errors concatenated
"""
keyerror = ''
for key in list_keyerror:
if len(keyerror) > 0 and key is not None:
keyerror += " ; "
if key is not None:
keyerror += str(key)
if keyerror == '':
keyerror = None
return keyerror | 62e61fa97dc3bfcd5f62d312d3f573a730479dde | 691,424 |
import random
def _create_list_of_floats(n):
"""Create a list of n floats."""
list = []
for _ in range(n):
list.append(random.random() * 100)
return list | bbade853b1fd091aa157ac81d6ee3b636f723a7b | 691,425 |
def counts_in_out_packets(packets):
"""
Counts the number of packets in & out in the array packets
@param packets is a list of packets, structured as follows: `[(time, direction)]`
@return tuple `(num_packets_in, num_packets_out)`
"""
packets_in, packets_out = [], []
for val in packets:
if val[1] < 0:
packets_in.append(val)
elif val[1] > 0:
packets_out.append(val)
return (len(packets_in), len(packets_out)) | c60186ba48764e019204d2088ea554fffb999f7b | 691,426 |
from typing import Tuple
from datetime import datetime
def getStartDatetime(start: str, days: Tuple) -> datetime:
""" obtain starting datetime from json input
:param start: string representation of the day and time
:param days: a tuple of 3 characters representation of day
:return : datetime instance
"""
day, time = start.split(' ')
day = days.index(day.lower())
hour, minute = int(time[:2]), int(time[2:])
return datetime(1, 1, day, hour, minute, 0, 0) | e4ffdc7743700914fbb3bd677ddc8ecef0fe16a4 | 691,428 |
def mod(a,b):
"""Return the modulus of a with respect to b."""
c = int(a/b)
result = a - b*c
return result | 7f0b961fcd6b83071d66e2cdbb8f5e1f08e0542a | 691,432 |
from typing import Sized
from typing import Iterable
from typing import Mapping
import six
def is_listy(x):
"""Return True if `x` is "listy", i.e. a list-like object.
"Listy" is defined as a sized iterable which is neither a map nor a string:
>>> is_listy(["a", "b"])
True
>>> is_listy(set())
True
>>> is_listy(iter(["a", "b"]))
False
>>> is_listy({"a": "b"})
False
>>> is_listy("a regular string")
False
Note:
Iterables and generators fail the "listy" test because they
are not sized.
Args:
x (any value): The object to test.
Returns:
bool: True if `x` is "listy", False otherwise.
"""
return (isinstance(x, Sized) and
isinstance(x, Iterable) and
not isinstance(x, Mapping) and
not isinstance(x, six.string_types)) | ca8f1d6b025990e9083f94ecf0f9e4ec9b168876 | 691,433 |
import pickle
def read_pickle(relnm):
""" Read serialized object from pickle on disk at relnm
Args:
relnm (str) : Relative name/path to pickled object
Returns:
obj (`:obj: unpickled object`)
"""
with open(relnm, 'rb') as f:
obj = pickle.load(f)
print('Loaded object from disk at {}'.format(relnm))
return obj | ee9572c38c0c5c18d308c07ef4bad9410ce4048a | 691,434 |
def parse_key_value_config(config_value):
""" Parses out key-value pairs from a string that has the following format:
key: value, key2: value, key3: value
:param string config_value: a string to parse key-value pairs from
:returns dict:
"""
if not config_value:
return {}
key_values_unparsed = config_value.split(',')
key_values = {}
for key_value_pair in key_values_unparsed:
key, value = key_value_pair.strip().split(':')
key_values[key.strip()] = value.strip()
return key_values | f00c79d85e71364db58bfb5b91fb2b8654ebe75c | 691,436 |
def fileno(fil):
"""Return the file descriptor representation of the file.
If int is passed in, it is returned unchanged. Otherwise fileno()
is called and its value is returned as long as it is an int
object. In all other cases, TypeError is raised.
"""
if isinstance(fil, int):
return fil
elif hasattr(fil, "fileno"):
fileno = fil.fileno()
if not isinstance(fileno, int):
raise TypeError("expected fileno to return an int, not " + type(fileno).__name__)
return fileno
raise TypeError("expected int or an object with a fileno() method, not " + type(fil).__name__) | 983243c11a3264c77752a2da5a1d3d33279814ce | 691,439 |
def _count_submissions(conductors):
""" From array of conductors, accumulate submission count. """
return sum(c.num_cmd_submissions for c in conductors) | 9ae42a47fa0284fe28fff572dafad5f601e6bd56 | 691,445 |
def get_headers(oauth_token: str) -> dict:
"""Common headers for all requests"""
return {
'Authorization': f'OAuth {oauth_token}'
} | 285f88b6268f50209432698a12ba2b4b57ecd1ee | 691,446 |
def find_diff(g, start):
"""
g -> Graph of states of nibbles
start -> Starting configuration
Find all possible differentials given a start configuration. The function
returns a tuple containing:
1. the number of rounds
2. a list of all possible end states (second-last round)
3. a list of all possible end states (last round)
"""
vs = set([start])
states = [vs]
rounds = 0
is_end = False
while len(vs) > 0 and not is_end:
n_vs = set()
for v0 in vs:
for v1 in g[v0]:
if v1 == 4095:
is_end = True
n_vs.add(v1)
vs = n_vs
states.append(vs)
rounds += 1
return (rounds, states) | 74f24be96f057e2810fed6de6bb7753be31092d5 | 691,450 |
def sg_to_plato(sg):
"""
Specific Gravity to Degrees Plato
:param float sg: Specific Gravity
:return: Degrees Plato
:rtype: float
:math:`\\text{Plato} = \\frac{\\big(\\text{SG} - 1\\big) \\times 1000}{4}`
The more precise calculation of Plato is:
:math:`\\text{Plato} = -616.868 + 1111.14 \\times sg - 630.272 \\times sg^2 + 135.997 \\times sg^3`
Source:
* http://www.brewersfriend.com/2012/10/31/on-the-relationship-between-plato-and-specific-gravity/
""" # noqa
# return (sg - 1.0) * 1000 / 4
return ((135.997 * sg - 630.272) * sg + 1111.14) * sg - 616.868 | cf689927fb64d5a9108b28626dd324982c0ce776 | 691,451 |
from typing import List
from typing import Dict
from typing import Tuple
def replace_variables(
sentence: List[str], sentence_variables: Dict[str, str]
) -> Tuple[List[str], List[str]]:
"""
Replaces abstract variables in text with their concrete counterparts.
"""
tokens = []
tags = []
for token in sentence:
if token not in sentence_variables:
tokens.append(token)
tags.append("O")
else:
for word in sentence_variables[token].split():
tokens.append(word)
tags.append(token)
return tokens, tags | 4a5111c209a4faf03b96c920af113d086d0c970f | 691,452 |
def num_patches(output_img_dim=(3, 256, 256), sub_patch_dim=(64, 64)):
"""
Creates non-overlaping patches to feed to the PATCH GAN
(Section 2.2.2 in paper)
The paper provides 3 options.
Pixel GAN = 1x1 patches (aka each pixel)
PatchGAN = nxn patches (non-overlaping blocks of the image)
ImageGAN = im_size x im_size (full image)
Ex: 4x4 image with patch_size of 2 means 4 non-overlaping patches
:param output_img_dim:
:param sub_patch_dim:
:return:
"""
# num of non-overlaping patches
nb_non_overlaping_patches = (output_img_dim[1] / sub_patch_dim[0]) * (output_img_dim[2] / sub_patch_dim[1])
# dimensions for the patch discriminator
patch_disc_img_dim = (output_img_dim[0], sub_patch_dim[0], sub_patch_dim[1])
return int(nb_non_overlaping_patches), patch_disc_img_dim | 612fc2a5de8e560d6b6d79a4db27484e3ea36de0 | 691,456 |
def poly2(x,C0,C1,C2):
"""
Calculate a polynomial function of degree 2 with a single variable 'x'.
Parameters
----------
x : numeric
Input variable.
C0, C1, C2 : numeric
Polynomial coefficients
Returns
-------
numeric
Result of the polynomial function.
"""
return C0+C1*x+C2*x**2 | a37c6bfa7bedef4f24791e802a5a50b651956094 | 691,460 |
import csv
def load_data(dataset_path):
"""
Extracts the relevant data from the dataset given.
Returns {lang: {gloss: [transcription,]}}.
Asserts that there are no entries with unknown or no transcriptions.
"""
data = {} # lang: {gloss: [transcription,]}
with open(dataset_path) as f:
reader = csv.reader(f, delimiter='\t')
next(reader)
for line in reader:
if line[0] not in data:
data[line[0]] = {}
if line[3] not in data[line[0]]:
data[line[0]][line[3]] = []
assert line[5] not in ('', 'XXX')
data[line[0]][line[3]].append(line[5])
return data | d7bd2fa760dbb8ec70135eca0e27473baef69213 | 691,461 |
def get_bonds_of_molecule(molecule):
"""
It returns the atom's indexes for all bonds of a molecule.
:param molecule: Mol object with the ligand (Rdkit)
:return: list of tuples with the indexes for each bond
"""
bonding_idx = []
for bond in molecule.GetBonds():
bonding_idx.append((bond.GetEndAtomIdx() + 1, bond.GetBeginAtomIdx() + 1))
return bonding_idx | 5eecdb40b31c1bd32f966594999a029ac75a6347 | 691,465 |
def fahr_to_celsius(fahr):
""" Convert Fahrenheit to Celsius (F-32) + 5/9 """
result_in_celsius = (fahr - 32) + 5/9
return result_in_celsius | 09601a064da209e64d9652be0e7b5fab01cd0038 | 691,466 |
def format_stats(stats: dict) -> str:
"""Prepares stats for logging."""
return ", ".join([f"{k}: {v} commits" for k, v in stats.items()]) | 8c554012e7ff2db2ba6394dcb87541ab668ed31c | 691,468 |
def grandchildren_with_tag(child,tagnames):
"""Return children of child that have tag names in
the given set of tag names"""
ret=[]
for grandchild in child.iterchildren():
if grandchild.tag in tagnames:
ret.append(grandchild)
pass
pass
return ret | 1121345abab69f67abde0ee2b6e4629e71034c61 | 691,469 |
from typing import Counter
def calculate_gc_content1(sequence):
"""
Receives a DNA sequence (A, G, C, or T)
Returns the percentage of GC content (rounded to the last two digits)
"""
counts = Counter(sequence.upper())
gc_content = counts.get("G", 0) + counts.get("C", 0)
at_content = counts.get("A", 0) + counts.get("T", 0)
return round(gc_content * 100 / (gc_content + at_content), 2) | acebad90e15a69d9ab52c32826e132e466f926b6 | 691,471 |
def bfalist(self, area="", lab="", **kwargs):
"""Lists the body force loads on an area.
APDL Command: BFALIST
Parameters
----------
area
Area at which body load is to be listed. If ALL (or blank), list
for all selected areas [ASEL]. If AREA = P, graphical picking is
enabled and all remaining command fields are ignored (valid only in
the GUI). A component name may also be substituted for AREA.
lab
Valid body load label. If ALL, use all appropriate labels. Load
labels are listed under "Body Loads" in the input table for each
element type in the Element Reference. See the BFA command for
labels.
Notes
-----
Lists the body force loads for the specified area and label. Body
loads may be defined on an area with the BFA command.
This command is valid in any processor.
"""
command = f"BFALIST,{area},{lab}"
return self.run(command, **kwargs) | acecc25b0f337fae3e39d93682b2c9233630b354 | 691,472 |
from typing import Optional
def parse_float(value: bytes) -> Optional[float]:
"""
Convert bytes to a float.
Args:
value: A bytes value to be converted to a float.
Returns:
A float if the bytes value is a valid numeric value, but
``None`` otherwise.
"""
try:
return float(value)
except ValueError:
return None | 2ccf0e19e3b2168750892ef7a675dced438ce4a6 | 691,473 |
def trim_to_peak(peaks, troughs):
"""
Trims the peaks and troughs arrays such that they have the same length
and the first peak comes first.
Args:
peaks (numpy array): list of peak indices or times
troughs (numpy array): list of trough indices or times
Returns:
peaks (numpy array): list of peak indices or times
troughs (numpy array): list of trough indices or times
"""
# start index for troughs:
tidx = 0
if len(peaks) > 0 and len(troughs) > 0 and troughs[0] < peaks[0]:
tidx = 1
# common len:
n = min(len(peaks), len(troughs[tidx:]))
# align arrays:
return peaks[:n], troughs[tidx:tidx + n] | 908547e34238fb68576481414df98183b329553e | 691,475 |
def find_all_conditions(path: str) -> set:
"""
Find all unique conditions in given training data file.
:param path: Path to training data.
:return: Set of all the unique available conditions in the file.
"""
cond = set()
with open(path) as f:
for line in f:
split = line.split(",")
if len(split) >= 1: # Don't have to be strict about the format
try: # If it's a number, don't add to the set
float(split[0])
except ValueError:
# Not a number, add to set if not already in it
if split[0] not in cond:
cond.add(split[0])
return cond | 0e3b355342b1f1a5e95f5fa6d2c6c6fa67f1231f | 691,477 |
def body_mass_index(weight: float, height: float) -> float:
"""Returns body mass index
Parameters
----------
weight
weight in kg
height
height in cm
Returns
-------
float
body mass index
"""
return round(weight / (height / 100) ** 2, 1) | bd05ae4accd4dee5c9839ca950df0c1da5a646db | 691,481 |
def separate_files_and_options(args):
"""
Take a list of arguments and separate out files and options. An option is
any string starting with a '-'. File arguments are relative to the current
working directory and they can be incomplete.
Returns:
a tuple (file_list, option_list)
"""
file_args = []
opt_args = []
for arg in args:
if arg and arg[0] != "-":
file_args.append(arg)
else:
opt_args.append(arg)
return file_args, opt_args | eae2de9cb93308b78ddf279304a73c6c5e1070e2 | 691,482 |
def search_fields_to_dict(fields):
"""
In ``SearchableQuerySet`` and ``SearchableManager``, search fields
can either be a sequence, or a dict of fields mapped to weights.
This function converts sequences to a dict mapped to even weights,
so that we're consistently dealing with a dict of fields mapped to
weights, eg: ("title", "content") -> {"title": 1, "content": 1}
"""
if not fields:
return {}
try:
int(list(dict(fields).values())[0])
except (TypeError, ValueError):
fields = dict(zip(fields, [1] * len(fields)))
return fields | ee2150aa62b0897c77e20e99b15ee6d0138e293b | 691,489 |
import functools
import time
def to_timestamp_property(func_to_decorate):
""" A decorator for properties to convert the property value from a
datetime to a timestamp. """
@functools.wraps(func_to_decorate)
def wrapper(instance, value):
""" Closure that converts from datetime to timestamp. """
if value:
value = time.mktime(value.timetuple())
func_to_decorate(instance, value)
return wrapper | 04a6776284b739d06fbff9620072c91e8ba84c64 | 691,494 |
def format_kmer(seqid, start):
"""
prints out a header with 1-based indexing.
>>> format_kmer('chr3', 1000)
'chr3_1001'
"""
return "%s_%i" % (seqid, start + 1) | 2d2dcd2c00b14e68f5f7a095120ec9c1b4c45a20 | 691,496 |
def find_undefined_value(cbf_handle):
"""Given a cbf handle, get the value for the undefined pixel."""
cbf_handle.find_category(b"array_intensities")
cbf_handle.find_column(b"undefined_value")
return cbf_handle.get_doublevalue() | 9e53dd7ebac6f711e02e1cf77f1d2553a09d9c3b | 691,498 |
import inspect
def args_to_kwargs(tool, args):
"""Use inspection to convert a list of args to a dictionary of kwargs.
"""
argnames = list(inspect.signature(tool).parameters.keys())[1:] # get list of argsnames and remove self
kwargs = {argnames[i]: arg for i, arg in enumerate(args)}
return kwargs | 7b3a8c022bb504348b2564d7ae4f683aa891604e | 691,499 |
from typing import Optional
import re
def guess_wapi_version(endpoint: str) -> Optional[float]:
"""Guess WAPI version given endpoint URL"""
match = re.match(r".+\/wapi\/v(\d+\.\d+)$", endpoint)
return float(match.group(1)) if match else None | 8bc35926d2317916c10e71f1997a9f2dbac047de | 691,500 |
def message_prefix(file_format, run_type):
"""Text describing saved case file format and run results type."""
format_str = ' format' if file_format == 'mat' else ' format'
if run_type == ['PF run']:
run_str = run_type + ': '
else:
run_str = run_type + ':'
return 'Savecase: ' + file_format + format_str + ' - ' + run_str | 4e08d6aa39f2dc7eeee80250219887c03751fc72 | 691,501 |
from pathlib import Path
def modified_after(first_path: Path, second_path: Path):
"""Returns ``True`` if first_path's mtime is higher than second_path's mtime.
If one of the files doesn't exist or is ``None``, it is considered "never modified".
"""
try:
first_mtime = first_path.stat().st_mtime
except (EnvironmentError, AttributeError):
return False
try:
second_mtime = second_path.stat().st_mtime
except (EnvironmentError, AttributeError):
return True
return first_mtime > second_mtime | e3628e63f0ed1d220702aa618cf18732077942cf | 691,502 |
import math
def get_from_decomposition(decomposition):
"""Returns a number from a prime decomposition"""
result = 1
for key in decomposition:
result *= math.pow(key, decomposition[key])
return result | ed66dda787f22306643fda8e2ff497b4f2e820cb | 691,510 |
def compute_tolerance(baseline: float, abstol: float, reltol: float) -> float:
""" Computes effective tolerance from a baseline value and relative and absolute tolerances.
:param baseline: the input value
:param abstol: absolute tolerance
:param reltol: relative tolerance
:return: tolerance to use for th einput value
Example:
>> compute_tolerance(1000, 3, 0.01)
>> 10
>> compute_tolerance(1000, 1, 0.002)
>> 2
"""
assert abstol >= 0
assert reltol >= 0
assert reltol < 1
return max(abstol, reltol * abs(baseline)) | 35c8ccef3b1c330d59aa3e55940f390b414fccca | 691,511 |
def vhdl_bit_name(reg_name, bit_name, number):
"""
Returns a string with a VHDL constant delaration of a bit name and it's
associted number.
"""
return "constant {}_{} : integer := {};\n".format(reg_name, bit_name, number) | f31585c9b019a2398a5d10620af5137f5aeb3de2 | 691,517 |
def getClikedPos(pos, rows, width):
""" Get the col and row of the cliked Spot """
gap = width // rows
y, x = pos
row = y // gap
col = x // gap
return row, col | bf2aaf95bcbce3d71ae6e51b02e2a7f7f694b49f | 691,521 |
def sum2(n):
"""
Take an input of n and return the sum of the numbers from 0 to n
"""
return (n * (n + 1)) / 2 | 10a10f276eaed6894470624c4d7460cdbf057906 | 691,522 |
def find_unique(lst: list) -> list:
"""Find the unique numbers in a list."""
return [i for i in lst if lst.count(i) < 2] | 3a40cf7caa076238a128cee2292d5ddde5970edb | 691,525 |
def generate_placeholder(length, width):
"""
Generate "(%s, %s, %s, ...), ..." for placing parameters.
"""
return ','.join('(' + ','.join(['%s'] * width) + ')' for _ in range(length)) | 28ff2ba22f1bcfcef796f724a878c4e2c7764983 | 691,528 |
def get_caption(attributes, feature, label, group=None):
"""Construct caption from plotting attributes for (feature, label) pair.
Parameters
----------
attributes : dict
Plot attributes.
feature : str
Feature.
label : str
Label.
group : str, optional
Group.
Returns
-------
str
Caption.
Raises
------
KeyError
``attributes`` does not include necessary keys.
"""
group_str = '' if group is None else f' ({group})'
if feature not in attributes:
raise KeyError(
f"Attributes do not include necessary key for feature '{feature}'")
if label not in attributes:
raise KeyError(
f"Attributes do not include necessary key for label '{label}'")
feature_attrs = attributes[feature]
label_attrs = attributes[label]
if 'plot_title' not in feature_attrs:
raise KeyError(
f"Attributes for feature '{feature}' does not include necessary "
f"key 'plot_title'")
if 'plot_xlabel' not in feature_attrs:
raise KeyError(
f"Attributes for feature '{feature}' does not include necessary "
f"key 'plot_xlabel'")
if 'plot_ylabel' not in label_attrs:
raise KeyError(
f"Attributes for label '{label}' does not include necessary "
f"key 'plot_ylabel'")
caption = (f"{attributes[feature]['plot_title']}: "
f"{attributes[label]['plot_ylabel']} vs. "
f"{attributes[feature]['plot_xlabel']}{group_str}.")
return caption | 5597ff8ab392a3a2db89752f87c4228a49c6069e | 691,531 |
def get_user_email(user_profile):
"""Get user e-mail address or the default address if user profile does not exist."""
# fallback address
default_email = 'bayesian@redhat.com'
if user_profile is not None:
return user_profile.get('email', default_email)
else:
return default_email | ded1e83507d979751ffb26cf2b0f272e5540c234 | 691,532 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.