content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_axe_names(image, ext_info):
"""
Derive the name of all aXe products for a given image
"""
# make an empty dictionary
axe_names = {}
# get the root of the image name
pos = image.rfind('.fits')
root = image[:pos]
# FILL the dictionary with names of aXe products
#
# th... | 6c97970149d8eefa35eb3887fc3071f5160c6a53 | 672,382 |
def getSv (self):
"""
Returns the list of flaoting species concentrations
Short-cut sv, eg
print rr.sv()
"""
return self.model.getFloatingSpeciesConcentrations() | d57481fd6f5c2e52d8dce2561dc59e57b62d23f5 | 672,383 |
def filliti(v):
"""
Sets all time bins within a trial to the same choice value v
"""
for x in range(len(v[0])):
if v[0, x] == 0:
v[0, x] = v[0, x - 1]
return v | cb8adf6c150c3cdac10d25347552095b38b4fe68 | 672,384 |
import os
def grab_package_names(path):
"""
Grabs package names from config
"""
package_list = []
for name in os.listdir(path):
if os.path.isdir(path):
package_list.append(name)
return package_list | 1459e10b7ec880a2c0ce7d4d1d9f8afc56b6b498 | 672,387 |
def make_data_dict_for_donut_chart(data_labels_list):
"""Make a data_dictionary to pass through into chart.js donut chart"""
data_dict = {
"labels": data_labels_list[1][0:5], #getting top 5 place types, so slicing from 0 - 5
"datasets": [
{
"data": da... | ba3017a29e0217c4fb026868f6e547e51add5440 | 672,388 |
import math
def Getidcg(length):
"""Get idcg value"""
idcg = 0.0
for i in range(length):
idcg = idcg + math.log(2) / math.log(i + 2)
return idcg | 0fc71efb1e9b0bcc597e5cdb97ddf23605e268e7 | 672,389 |
def color_y_axis(ax, color):
"""Color your axes."""
for t in ax.get_yticklabels():
t.set_color(color)
return None | 32715e39e9d7c09edb145d1fa2f9d5c413a00988 | 672,390 |
from typing import List
def arrayToFloatList(x_array) -> List[float]:
"""Convert array to list of float.
Args:
x_array: array[Any] --
Returns:
List[float]
"""
return [float(x_item) for x_item in x_array] | 617377ae4bf5e55db2882451d91d6839df0bec3d | 672,391 |
import glob
import os
def get_latest(folder, pattern):
"""
Gets the latest file in a folder matching the naming pattern.
"""
files = glob.glob(os.path.join(folder, pattern))
return max(files, key=os.path.getctime) | adbedcfe0c31bdfadd1ff0638ed07c43e758e3d6 | 672,393 |
def fetch_neighbours(matrix, y, x):
"""Find all neigbouring values and add them together"""
neighbours = []
try:
neighbours.append(matrix[y-1][x-1])
except IndexError:
neighbours.append(0)
try:
neighbours.append(matrix[y-1][x])
except IndexError:
neighb... | 7ec775f44b3f12d3693e77e73283fa9783cb5f58 | 672,394 |
def maybe_unsorted(start, end):
"""Tells if a range is big enough to potentially be unsorted."""
return end - start > 1 | 5b7de3e159418a3aa4b3bf0e524e41e11b6455e2 | 672,395 |
import requests
def get_residue_info(name, num_scheme=None, verbose=False):
"""
Gets residue info from the GPCRdb
Parameters
----------
name : str
Name of the protein to download (as in its GPCRdb URL).
num_scheme : str
Alternative numbering scheme to use.... | 0b458cc63da8e0df521727a253a54d06d8548522 | 672,396 |
import os
def get_video_fps(filename):
"""A util function to get the FPS of a video file using ffmpeg.
Args:
filename (str): The file name.
Returns:
int: The FPS of the video.
"""
cmd = f'ffmpeg -i {filename} 2>&1 | sed -n "s/.*, \(.*\) fp.*/\\1/p"'
return round(floa... | ee54f71614333510d1a717864faad198c145d387 | 672,397 |
import re
def get_urls(page):
"""
匹配url
"""
urls, tmp = [], []
#patt = "<a.*?href=.*?<\/a>"
patt = '"((http|ftp|file)s?://.*?)"'
if not page:
return urls
else:
page_tmp = page.replace(" ", "")
re_cpl = re.compile(patt, re.I)
tmp = re_cpl.findall(page_tmp... | 78c73e7f2d3c7e96db3befe1712f313e52938194 | 672,398 |
def is_relevant_event(event):
"""
Filter useful events from the slack webhook stream.
The event stream might contain mixed Slack API data (Events and Blocks)
see more https://api.slack.com/events-api
"""
if event and 'type' in event:
if event['type'] == 'block_actions':
retu... | b0bf7bcc103596784ef80579a6158c172e8a2e38 | 672,399 |
def sample_builder(samples):
"""
Given a dictionary with value: count pairs, build a list.
"""
data = []
for key in samples:
data.extend([key] * samples[key])
data.sort()
return data | 5a33bb4d6b0b363aa99161cc63f195efecfde964 | 672,400 |
def parse_typenet_mapping(file_path):
"""
Parse the TypeNet.
"""
mapping_local = {}
with open(file_path) as file_i:
for row in filter(None, file_i.read().split('\n\n')):
annotations = row.split('\n')
if annotations[0] not in mapping_local:
mapping_loca... | ee69d6caef4b0841dfa759d56db80143804b72ac | 672,401 |
def update_menu_tree_json(d, group_dn, upper_key=''):
"""
传入group_dn,当编辑当前部门上级部门的时候,不能把自己的子部门信息让用户选择,所有当节点到达groupdn后,进行continue操作进行拦截
:param d:
:param group_dn:
:param upper_key:
:return:
"""
result = []
for k, v in d.items():
one_dict = dict()
one_dict['id'] = '{}-{}... | d626b4779f173350fc7a381fa24ffe3bc1f3b598 | 672,402 |
import numpy
def compute_ns(cumulants_sample,axis=0):
"""
axis is the cumulants index axis which will be replaced by the photon number moment axis :
0 : <n>
1 : <n**2>
2 : <dn**2>
"""
cumulants_sample = cumulants_sample.swapaxes(axis,0)
shape = (3,)+cumulants_sample... | 39aa55855e8e59c754f525eebfdf679d686ad0d3 | 672,403 |
import logging
from typing import Any
def _value(record: logging.LogRecord, field_name_or_value: Any) -> Any:
"""
Retrieve value from record if possible. Otherwise use value.
:param record: The record to extract a field named as in field_name_or_value.
:param field_name_or_value: The field name to ext... | 994c306ad15e972817128f70ac61c8de7071e719 | 672,404 |
def is_starter(index, reason=None):
"""Takes index and reason column, returns either S, R or DNP.
Used on boxscore df. Reason is either Nan or 'Did Not Play'.
Keyword arguments:
index -- Used to define if starter or not
reason -- Used to define if DNP or not
"""
# Any reason converted to DN... | d6e7db2da200b43ed2979abbc9390e6274add83d | 672,405 |
def replace_tags(string, from_tag="i", to_tag="italic"):
"""
Replace tags such as <i> to <italic>
<sup> and <sub> are allowed and do not need to be replaced
This does not validate markup
"""
string = string.replace("<" + from_tag + ">", "<" + to_tag + ">")
string = string.replace("</" + from... | dccb4f34d0c26575a9a0c74fdb02c9a3dc4b2cd2 | 672,406 |
def remove_acronyms (dictionary):
"""
`remove_acronyms()` removes every acronyms from the dictionary.
An acronyms is a word such as `word == word.upper()`.
* **dictionary** (*list*) : the input dictionary (while processing)
* **return** (*list*) : the dictionary without acronyms
"""
words_t... | 94e6808dbf784c950f0e77bacb1a1b52e8ff7960 | 672,407 |
from datetime import datetime
def get_datetime(date_string, time_string):
"""
:param date_string: YYYY-MM-DD
:param time_string: HH:MM:SS / HH:MM
:return:
"""
if ' ' in date_string:
date_string = date_string.split(' ')[0]
if len(time_string) == 8:
return datetime.strptime... | 705e2a046efc85622823eba2a8a3185b928608af | 672,408 |
def fourcc_to_string(fourcc):
"""
Convert fourcc integer code into codec string.
Parameters
----------
fourcc : int
Fourcc integer code.
Returns
-------
codec : str
Codec string corresponding to fourcc code.
"""
char1 = str(chr(fourcc & 255))
char2 = str(ch... | 987330ec455e6ff043b4e045af9aa68425597471 | 672,410 |
def poly(a, x, y, order=4):
"""Return polynomial
:param a:
:param x:
:param y:
:param order:
:return:
"""
pol = 0.0
k = 0 # index for coefficients
for i in range(order+1):
for j in range(i+1):
pol = pol + a[k]*x**(i-j)*y**j
k+=1
return pol | 765bc5bf9e5cd031bb96365907e11865e05aee8f | 672,411 |
def shape_of_horizontal_links(shape):
"""Shape of horizontal link grid.
Number of rows and columns of *horizontal* links that connect nodes in a
structured grid of quadrilaterals.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
tuple of i... | 4926b9ed439dec11aff75d4a9554d1b19d3eb20c | 672,412 |
import subprocess
def get_git_commit_hash() -> str:
"""
Returns the hash of the HEAD commit. Or an empty string.
Can be used for logging purposes.
"""
try:
return (
subprocess.check_output(["git", "rev-parse", "HEAD"])
.decode("utf-8")
.strip()
)... | be85c7be7d5e2cd8790bd8bb0f6b421914bf24d7 | 672,413 |
def comparable(a, b):
"""
Tests if two sets of comparable.
Parameters
----------
a : set
One set.
b : set
The other set.
Returns
-------
comp : bool
True if `a` is a subset of `b` or vice versa.
"""
return a < b or b < a | 016020034a953401b5b7740c1050d332461d7a60 | 672,414 |
def max_recur(head, max):
"""Excercise 1.3.28 Find max in linked list recursively."""
if head is None:
return max
if head.item > max:
max = head.item
head = head.next
return max_recur(head, max) | 8ccea9fe2cbd7398eccd73f8452da8cc67bb3ed9 | 672,415 |
def get_false():
"""Always returns false"""
return not True | 0ed8f269bd49ed64d7e3aabaf3832e54a4c3d654 | 672,416 |
def most_common(hist):
"""Makes a list of word-freq pairs in descending order of frequency.
hist: map from word to frequency
returns: list of (frequency, word) pairs
"""
t = []
for key, value in hist.items():
t.append((value, key))
t.sort()
t.reverse()
return t | aa8b757d30d103738c6acc924f1363449d6802cd | 672,418 |
def results_ok(api, utils, packets, check_for_pause=True):
"""
Returns true if stats are as expected, false otherwise.
"""
_, flow_results = utils.get_all_stats(api)
pause = [f.frames_rx for f in flow_results if f.name == "rx_global_pause"][
0
]
un_pause = [
f.frames_rx for f... | 59a9356b25692da17a0d58953e24fcbc4c6b5639 | 672,419 |
from typing import Any
from typing import Optional
def arg_to_int(arg: Any, arg_name: str, required: bool = False) -> Optional[int]:
"""Converts an XSOAR argument to a Python int
This function is used to quickly validate an argument provided to XSOAR
via ``demisto.args()`` into an ``int`` type. It will t... | 2e753b01cf290c90ee4f1607042ef4a6ae3e2c2d | 672,420 |
import random
def populate(num_rats, min_wt, max_wt, mode_wt):
"""Initialize a population with a triangular distribution of weights."""
return [int(random.triangular(min_wt, max_wt, mode_wt))\
for i in range(num_rats)] | e69809b25ea63fba0487794e6d0f4982897461c2 | 672,421 |
def get_sd_prop(all_lines):
"""
The get_sd_prop method interprets the input file
which has a structure comparable to sdf molecular files
"""
# split all the lines according to the keywords
inputs = all_lines.split('> <')
# do not consider the first keyword, this contains the comments
inp... | 9973fe58759c00ed97f7c19fdcc77e18d8b08f1f | 672,422 |
def compare_float( expected, actual, relTol = None, absTol = None ):
"""Fail if the floating point values are not close enough, with
the givem message.
You can specify a relative tolerance, absolute tolerance, or both.
"""
if relTol is None and absTol is None:
exMsg = "You haven't specified a '... | 1a1fe01cd9a5b01dd72f3bd3846fec002b1bcc9b | 672,424 |
def calc_freq_from_interval(interval, unit='msec'):
"""
given an interval in the provided unit, returns the frequency
:param interval:
:param unit: unit of time interval given, valid values include ('msec', 'sec')
:return: frequency in hertz
"""
if interval <= 0:
print('Invalid inter... | cb1862f86128b0b51363d309cf844df5bc02ba85 | 672,425 |
def unganged_me1a_geometry(process):
"""Customise digi/reco geometry to use unganged ME1/a channels
"""
if hasattr(process,"CSCGeometryESModule"):
process.CSCGeometryESModule.useGangedStripsInME1a = False
if hasattr(process,"idealForDigiCSCGeometry"):
process.idealForDigiCSCGeometry.useG... | a22ec5e1c93be2f5f3300f08c211b343b9a7f980 | 672,427 |
import random
import string
def random_string(n):
"""ランダム文字列生成 random string generator
Args:
n (int): 文字数 length
Returns:
str: ランダム文字列 random string
"""
return ''.join(random.choices(string.ascii_letters + string.digits, k=n)) | 9e6c26df098c3cef3b01e2c68409b33ad87d12f0 | 672,428 |
import os
from io import StringIO
import re
def load(path):
""" Returns a StringIO object representing the content of the file at <path>, if any; None otherwise """
if not os.path.isfile(path):
return None
content = StringIO()
with open(path, 'r') as file:
for line in file.readlines()... | 8b15267c4eb77a51a3f6a2d6ae376d698da357e0 | 672,429 |
def convert_timestamp_to_seconds(timestamp):
"""Convert timestamp (hh:mm:ss) to seconds
Args:
timestamp (str): timestamp text in `hh:mm:ss` format
Returns:
float: timestamp converted to seconds
"""
timestamp_split = timestamp.split(":")
hour = int(timestamp_split[0])
minute... | 75c8f6cb6d0e8fd9646c686e8feb3871e1175457 | 672,430 |
import torch
def kpts_2_img_coordinates(kpt_coordinates: torch.Tensor,
img_shape: tuple) -> torch.Tensor:
""" Converts the (h, w) key-point coordinates from video structure format [-1,1]x[-1,1]
to image coordinates in [0,W]x[0,H].
:param kpt_coordinates: Torch tensor in (N,... | 93932bc54402fc105afad2e6b34570d3c83ac0b7 | 672,431 |
def combine(*dep_lists):
"""Combines multiple lists into a single sorted list of distinct items."""
return list(sorted(set(
dep
for dep_list in dep_lists
for dep in dep_list))) | 8eef7e25c93038c008b272dc17e913a61fe0e535 | 672,432 |
def _get_fn_name_key(fn):
"""
Get the name (str) used to hash the function `fn`
Parameters
----------
fn : function
The function to get the hash key for.
Returns
-------
str
"""
name = fn.__name__
if hasattr(fn, '__self__'):
name = fn.__self__.__class__.__na... | 8acdfe38c7f497244d2bf01f343ac241e3af6f6d | 672,433 |
def getPep (site, pos_in_pep, ref_seq):
"""
get the pep seq arount the given site from the reference sequence
Parameters
----------
site : int
pos in protein seq
pos_in_pep : int
position in the peptide (defines the number of aa will get around the site)
ref_seq : str
... | af1760a32f2260f74cac430076f578a0ddf33531 | 672,434 |
def format_time(time):
"""Nicely format a time for console output with correct units.
Args
----
time : float
Time (in seconds) for formatting.
Returns
-------
str
Time formatted with units.
"""
if time >= 1.0:
if time < 60:
return f"{time:.2f}s... | 9a42ddc05e270904274fc5ac53ef7d21f4dd2fbd | 672,435 |
def parse_lines_to_dict(lines):
"""
Parse a list of message into a dictionnary.
Used for command like status and stats.
:param lines: an array of string where each item has the following format
'name: value'
:return: a dictionary with the names (as keys) and values found in the
lines.
"... | ec2246795fccfef79847be76ee013c1ca471b1a6 | 672,436 |
import string
import re
import hashlib
def get_hash(text):
"""Generate a hashkey of text using the MD5 algorithm."""
punctuation = string.punctuation
punctuation = punctuation + "’" + "“" + "?" + "‘"
text = [c if c not in punctuation else ' ' for c in text]
text = ''.join(text)
text = re.sub(... | a20f34cda28c4a5d48799e1e61634da3d67b3da3 | 672,437 |
def exception_str(self, ex): # pylint: disable=unused-argument
"""function used to replace default __str__ method of exception instances"""
return 'in %s\n:: %s' % (ex.file, ', '.join(ex.args)) | 19ea835a3569335a976f67329ced358d91dd3301 | 672,438 |
def std_name(name):
"""
standardize channels name
name:
"""
remove = ['EEG ', '-CLE', '-LER', 'EOG ', 'EMG ', 'ECG ', 'Resp ']
for word in remove:
name = name.replace(word, '')
name = name.lower()
return name | 8117b65eed96054b0a18c1d91018425fd3fbb74a | 672,439 |
def _parse_length(selector):
"""Parse length of route.
Example:
- 5 bis 15m
- bis 10m
- 8m -> 8
- 12-15m -> 15
- None -> 0
Returns 0 if parsing is not working.
"""
if selector:
value = selector.get()
if value == "unbekannt" or value == "m" or... | 7421a37b3c302b29b61aefa9974259ab07d5e78e | 672,440 |
import argparse
def get_args():
"""
method for parsing of arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", required=True, help="Config path.")
parser.add_argument("--parse-folder-config", help="Config for parse_folder.py used when changing heights.")
... | 3b3e6f0ce2f9b9bad382def0e177decaac73fc92 | 672,441 |
def render_input(bound_field, **kwargs):
"""Helper to render a form field input, adding attributes to the element."""
# This logic is copied from BoundField.__str__.
markup = bound_field.as_widget(attrs=kwargs)
if bound_field.field.show_hidden_initial:
markup = markup + bound_field.as_hidden(on... | 9a2eb7c57a3a20f841207d06d9d15923e172386b | 672,442 |
def nameColumn(column, name):
"""Give a column a __name__."""
column.__name__ = name
return column | 047a43fb7b8e3c3a44516dc8a0c13ac4c782aae8 | 672,443 |
import os
def _GetInstalledChromeDriverDirectoryPath() -> str:
"""Returns the absolute filesystem path to the directory where `chromedriver`
that comes with the `inb` repository is installed.
Returns:
Absolute filesystem path the `chromedriver` directory.
"""
dir_path = os.path.dirname(os.path.abspath(... | 6098fce2df94449a57a933241a3a8c5d38334eaf | 672,444 |
def flip_bin_vec(bin_str):
"""
Function flip bit order of binary string. Assumed to
"""
offset = bin_str.find('b') + 1
num_bits = len(bin_str) - offset
ret_val = bin_str[:offset]
for ii in range(num_bits):
ret_val += bin_str[offset + num_bits - ii - 1]
return ret_val | a8b2ca67db2b9350eccada4495f1744b2e39e61e | 672,447 |
def fletcher_reeves(algo):
"""
Fletcher-Reeves descent direction update method.
"""
return algo.current_gradient_norm / algo.last_gradient_norm | 4a4d320f403436f73c92bfeb888eba262b4cae05 | 672,448 |
from typing import Union
def calculate_digital_sum(number: Union[int, str]) -> int:
"""Calculate the digital sum of the number `number`."""
return sum([int(digit) for digit in str(number)]) | b4d8b216473c81e80e1ff5553e7518b0f0a1d760 | 672,450 |
def isStr(obj):
"""
:return bool: True if string or unicode
"""
type_string = str(type(obj))
if 'str' in type_string or 'unicode' in type_string:
return True
else:
return False | 5d9089c8c4a92c96dd5cc5a95cd32bf7e2fcf6a9 | 672,451 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Find PCR primers and Parameters',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('seq', metavar='Target DNA Sequence', help='Target DNA sequence')
... | 358762d445be241fff4e00cf947be7f367ab199b | 672,452 |
import time
def make_clinic_db_query(s_clinic_df, cancer_list):
"""Make a query list for clinic file.
Make a query list for inserting clinic file into graph database.
Args:
s_clinic_df(dataframe): a dataframe of clinic file
cancer_list(list): a list of all cancers in clinic file
... | df9ec0ff51d855fe16a9a21f3031efce1a9254bc | 672,453 |
def split(string, separator):
"""
Return a list of the words in the string, using separator as the delimiter.
"""
if separator == '':
raise ValueError('Empty separator')
if separator is None:
separator = ' '
sequence, word = [], ''
string += separator
for letter in st... | f9819c34fa60e2efa3f663e89fc297d58a987344 | 672,454 |
def update(v):
""" 'Arithmetic logic' from pdf """
return (v * 607) % 990881 | e029d3e355b8b1a47d4a72d6a6f405ec3fb40a8c | 672,455 |
def mySum(L):
"""
(number list) --> number
Returns the sum of the numbers in a given list
mySum([2,3,2])
>>> 7
mySum([])
>>> blank detected
mySum([2])
>>> 2
mySum([1,2,3,4,5])
>>> 15
mySum([-1,-2,-3,-4,-5])
>>> -15
"""
print ()
print ('---Finding sum of... | b71f2288e64c6f847eca4034b5253217a4eda292 | 672,457 |
def printme(o:str):
"""Prints `o` fancily
Parameters
----------
o : str
Some input
"""
return f'{o} is the right answer to "Who wants to be a Millionaire!"' | 3af2e91d071f1e4811a8d456b5d7de5ec16c2601 | 672,458 |
def clean_tag(tag):
"""Clean supercell tag"""
t = tag
t = t.upper()
t = t.replace('O', '0')
t = t.replace('B', '8')
t = t.replace('#', '')
return t | 9c5e74e84da74e68dccfbbf56c846abdc7a3250c | 672,459 |
def tile_type(tile_ref, level, ground_default, sky_default):
"""Returns the tile type at the given column and row in the level.
tile_ref is the column and row of a tile as a 2-item sequence
level is the nested list of tile types representing the level map.
ground_default is the tile type to r... | 25260f8b199b689db1dd74958c15ff3964585678 | 672,460 |
def train_classifier(data, classifier_func):
"""
Trains a support vector machine using the 'X_train' and 'y_train' attributes in :data:. Returns a model.
:classifier_func: should be the function to call to create a new sklearn classifier.
"""
classifier = classifier_func()
classifier.fit(data['X... | 19e837710f3b6df53637b6c1260f997ca5122842 | 672,462 |
def madc(matrix, mean_value):
"""
Calculate the absolute mean deviation of numbers in list.
"""
abs_deviation = 0
for idx in range(len(matrix)):
abs_deviation += (abs(matrix[idx] - mean_value) / len(matrix))
return abs_deviation | 18363d283212283d11833df9bac35b7d6c2e5477 | 672,463 |
def dictfetchone(cursor,sqltext,params=None):
""" Returns query results as list of dictionaries."""
# cursor = conn.cursor()
result = []
cursor.execute(sqltext,params)
cols = [a[0].decode("utf-8") for a in cursor.description]
returnres = cursor.fetchone()
result.append({a:b for a,b in zip(co... | ce811ed2222162a7423304cc9d840a2385c2054b | 672,465 |
import math
def ranged_sine_pulse_integrated(phase: float, lower: float = 0.0, upper: float = 1.0) -> float:
"""Integrated shifted and scaled cosine pulse for derivative range in
[lower, upper].
"""
return .5 * (lower - upper) * math.sin(phase) + .5 * (lower + upper) * phase | 54b184d81b3ffd14568b32a44bb989ece6d4d65a | 672,466 |
import pkg_resources
def case_sensitive_name(package_name):
"""Return case-sensitive package name given any-case package name.
@param project_name: PyPI project name
@type project_name: string
"""
environment = pkg_resources.Environment()
if len(environment[package_name]):
return env... | ee4203e038805424008a98082b1d36456f2ed897 | 672,468 |
def _nd(name):
"""
@return: Returns a named decimal regex
"""
return '(?P<%s>\d+)' % name | fcedfe2219bc308ee40e2dbe9207574a7d2a1545 | 672,469 |
from typing import Optional
def validate_state_of_charge_min(state_of_charge_min: Optional[float]) -> Optional[float]:
"""
Validates the state of charge min of an object.
State of charge min is always optional.
:param state_of_charge_min: The state of charge min of the object.
:return: The valida... | e1d811c7b6636743639e65d58be9c998c54023eb | 672,470 |
import os
import re
def get_file_list():
"""
Return a list of file names and file dates, including all SAFE
directories, found in the current directory, sorted by date.
"""
files = []
filenames = []
filedates = []
# Set up the list of files to process
i = 0
for myfile in os.li... | 151b86dbdfec39a9f76ff1057fffeb012195324c | 672,471 |
def int_to_name(n,hyphen=False,use_and=False,long_scale=False):
"""
Convert an integer to its English name, defaults to short scale (1,000,000 = 'one billion'), returns a string
Args:
n -- int to be named
hyphen --bool, use hyphens for numbers like forty-eight
use_and -- bool, u... | 9eb18f3c2ceabf4e0411ab5591245006e21c930a | 672,472 |
def get_token_types(input, enc):
"""
This method generates toke_type_ids that correspond to the given input_ids.
:param input: Input_ids (tokenised input)
:param enc: Model tokenizer object
:return: A list of toke_type_ids corresponding to the input_ids
"""
meta_dict = {
"genre": {
... | 1b47cb6854388b756e89ff09b962c4dafe2fa649 | 672,473 |
def string_permutation(s1,s2):
"""
Edge case: If the strings are not the same length, they are not permutations of each other.
Count the occurence of each individual character in each string.
If the counts are the same, the strings are permutations of each other.
Counts are stored in array of 128 s... | 45e5fb7e1a4cebc15314e75a48cfd889f4a364b8 | 672,474 |
def get_cdk_context_value(scope, key):
"""
get_cdk_context_value gets the cdk context value for a provided key
:scope: CDK Construct scope
:returns: context value
:Raises: Exception: The context key: {key} is undefined.
"""
value = scope.node.try_get_context(key)
if value is None:
... | 96f0fc440679a3245f517af0bf0aae54a9ca2028 | 672,475 |
def missing_to_default(field, default):
"""
Function to convert missing values into default values.
:param field: the original, missing, value.
:param default: the new, default, value.
:return: field; the new value if field is an empty string, the old value
otherwise.
:rtype: any
... | 3af701c966b95711869def642a1c2f571bc40bfb | 672,476 |
def format_setting_name(token):
"""Returns string in style in upper case
with underscores to separate words"""
token = token.replace(' ', '_')
token = token.replace('-', '_')
bits = token.split('_')
return '_'.join(bits).upper() | 7dd6829ca430ea020bee2e75e21d3f41d9dd2d70 | 672,477 |
def somegen():
"""this is a bad generator"""
if True:
return 1
else:
yield 2 | f89bb8f62b16373748b3865a0fdcdf0dec3c857f | 672,478 |
def simple_request_messages_to_str(messages):
"""
Returns a readable string from a simple request response message
Arguments
messages -- The simple request response message to parse
"""
entries = []
for message in messages:
entries.append(message.get('text'))
return ','.join(ent... | 06a3c564df0405726e0e8b13d7d4d5173fb07530 | 672,479 |
def get_angle_errors(errors):
"""
Takes error vectors computed over full state predictions and picks the
dimensions corresponding to angle predictions. Notice that it is assumed
that the first three dimenions contain angle errors.
"""
return errors[:,:, :3] | b253e1e3b6b98a0d47eb789b3fe01c5fcb782cb2 | 672,480 |
import getpass
import os
def UserDirSearchFileType(Directory, FileExtension):
"""
**Directory: a string of the directory to be checked and created if not found
**FileExtension: a string of the files extension to search for
Checks for the presence of a directory in the Current user folder and creates... | 6d413ff19a01d5682359d8cfa92af13233b7e3d3 | 672,483 |
def apply_filter_list(func, obj):
"""Apply `func` to list or tuple `obj` element-wise and directly otherwise."""
if isinstance(obj, (list, tuple)):
return [func(item) for item in obj]
return func(obj) | ef028323b6161eda45e84e3f95ea55246c32a3aa | 672,484 |
def intensity2color(scale):
"""Interpolate from pale grey to deep red-orange.
Boundaries:
min, 0.0: #cccccc = (204, 204, 204)
max, 1.0: #ff2000 = (255, 32, 0)
"""
assert 0.0 <= scale <= 1.0
baseline = 204
max_rgb = (255, 32, 0)
new_rbg = tuple(baseline + int(round(scale * (... | 338f1266fe4c1be791a026276da7096c7a7b4eb7 | 672,485 |
import argparse
import sys
def parse_args():
"""This function is for a safe command line
input. It should receive the fortran file
name and returns it back to the caller.
Returns:
str: A file name of original fortran script.
"""
parser = argparse.ArgumentParser()
parser.add_argum... | d22e890da9ca0c445bb8925d43711673901a50bc | 672,487 |
def calc_gamma_components(Data_ref, Data):
"""
Calculates the components of Gamma (Gamma0 and delta_Gamma),
assuming that the Data_ref is uncooled data (ideally at 3mbar
for best fitting). It uses the fact that A_prime=A/Gamma0 should
be constant for a particular particle under changes in pressure
... | 873e9ff8fed0f4c8d257b9848bee5c3dbac1efa3 | 672,488 |
import argparse
def get_args():
"""
Parses command line arguments
:return: ArgParser obj - contains all the command line args
"""
parser = argparse.ArgumentParser(description='Find words in a Grid of letters')
parser.add_argument('-default', default=True, help="solve default board stored in g... | 66b66797c0d889a1cae0ebc7eb06fb7b41b75359 | 672,489 |
def append_write(filename="", text=""):
"""string at the end of a text file"""
with open(filename, 'a') as f:
c = f.write(text)
return c | 4e08ddb5a1d69af6099e092c7b926796d56cfee1 | 672,491 |
def split(trajectories_frame, split_ratio, state_size):
"""
Simple train-test data split for a Markov Chain.
:param trajectories_frame: TrajectoriesFrame class object
:param split_ratio: The split ratio for training set
:param state_size: The size of a window (for a Markov Chain algorithm)
:return:
"""
train_fr... | 24e5d5a4e236869d21559f0f29f44a68a42a0a9b | 672,492 |
import time
def message_template():
"""
Return a message template for consistency throughout
"""
message = {
'responded': time.time(),
}
return message | d29d5f3404d33bb77782b51c8ab1a0733abc5901 | 672,494 |
import json
def get_ikhints_json() -> str:
"""Return a test document-config/ikhints.json."""
ikhints = {
"hints":
("[\r\n [\r\n 1.33904457092285,\r\n -1.30520141124725,\r\n"
" 1.83943212032318,\r\n -2.18432211875916,\r\n"
" 4.76191997528076,\r\n -0.29564744... | 8c01d822141a8b662195adfb3695950965e95e63 | 672,495 |
def _backup_path(target):
"""Return a path from the directory this is in to the Bazel root.
Args:
target: File
Returns:
A path of the form "../../.."
"""
n = len(target.dirname.split("/"))
return "/".join([".."] * n) | 9a0826bfbaeae2f22d9885e6bb4d6ef6feef2a78 | 672,496 |
import math
def RE(bigramprob, token2p, token1p):
"""Returns the Relative Entropy.
Relative entropy is P1*log2(P1/P2) where here P1 is P(rightword)
and P2 is P(right word | left word)."""
return token1p * math.log(token1p/(bigramprob/token2p), 2) | 3b2e4a897139b6defe012e928e896d44100e9d32 | 672,497 |
import os
def return_abs_path(directory, path):
"""Unfortunately, Python is not smart enough to return an absolute
path with tilde expansion, so I writing functionality to do this
"""
if directory is None or path is None:
return
directory = os.path.expanduser(directory)
return os.path... | 323ec17bcb78ca87ddc8963ada7cc14c19dd6721 | 672,499 |
import numpy
def motif_id_to_adj_mat(a_motif_id, motif_size):
"""
Returns the adjacency matrix associated with a particular motif id.
Notes:
* In this function it is assumed that the motif id is the number that is formed by flattening its adjacency
matrix in row major form.
* Se... | 12daf4951f084d42458553037a9fd3ef8c51b216 | 672,500 |
import sys
def read_request(protocol, request_file):
""" Reads in the request
Supports:
- Reading request from a file specified by command line argument
- Reading request from a file specified by environment variable
- Reading request from stdin
:param protocol: ProtocolMessage
:param re... | bad1b75e1880f946065307ee369d4d62e1f02e71 | 672,501 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.