content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def drop_duplicates(df):
"""
PASTA produces some duplicate change records, usually deletes. At last
count there were 9 duiplicates in the JRN records. This removes those.
"""
df_dd = df.drop_duplicates()
n_dupdeletes = df.shape[0] - df_dd.shape[0]
print('{0} duplicate records were removed.'.... | b90d9b1b5bdf8097eab37aae531d0b2d532dbe03 | 667,442 |
def validate_certificateauthority_type(certificateauthority_type):
"""
CertificateAuthority Type validation rule.
Property: CertificateAuthority.Type
"""
VALID_CERTIFICATEAUTHORITY_TYPE = ("ROOT", "SUBORDINATE")
if certificateauthority_type not in VALID_CERTIFICATEAUTHORITY_TYPE:
raise... | 2f9229092d02851a9bd9dd75eeeedb65d8f4e4b0 | 667,443 |
def writeweight(alloc, content_w, g_w, g_a):
"""Return write weighting `ww`
Parameters
----------
alloc : `[batch_size, mem_size]`.
content_w : `[batch_size, mem_size]`.
g_w : `[batch_size, 1]`.
g_a : `[batch_size, 1]`.
Returns
-------
ww : `[batch_size, mem_size]`.
"""
... | d63849cad870644466edd2f11b1d686000ae9456 | 667,444 |
import os
def find_runs(benchmark_results_dir):
"""This function finds all runs and their associated results files
paths that need standard analysis reports generated.
This function assumes that files for a run-ID are only found in a
single folder.
Args:
benchmark_results_dir (str) - Pat... | a9f53c6b8f5c22366f7a40a6d682538f0d622186 | 667,445 |
def comp_joule_losses(self, out_dict, machine):
"""Compute the electrical Joule losses
Parameters
----------
self : EEC_PMSM
an EEC_PMSM object
out_dict : dict
Dict containing all magnetic quantities that have been calculated in comp_parameters of EEC
machine : Machine
a... | 1414263267cd46527a4c6acc2967976795990ccd | 667,446 |
def get_value(roi, frame):
"""add-on method for getting the value of ROI in the frame"""
return frame[(roi.x):(roi.x + roi.w), (roi.y):(roi.y + roi.h), :].mean() | 945eb4a7e44d10fd29c2e1ac0416ce32c3d505ec | 667,447 |
def get_fold_val(fold_test, fold_list):
""" Get the validation fold given the test fold.
Useful for cross-validation evaluation mode.
Return the next fold in a circular way.
e.g. if the fold_list is ['fold1', 'fold2',...,'fold10'] and
the fold_test is 'fold1', then return 'fold2'.
If the fold_... | 352a1c372d7a559dacd9d4dc0572d1e3eb1500b9 | 667,448 |
import shutil
def width():
"""width."""
return shutil.get_terminal_size((80, 20)).columns | 29742b51b4814c11e359b1776ef42a643f994c20 | 667,450 |
import torch
def model5D(X5D: torch.Tensor) -> torch.nn.Module:
"""Simple fake linear model
"""
return torch.nn.Sequential(torch.nn.AdaptiveAvgPool3d(1), torch.nn.Flatten(), torch.nn.Linear(X5D.shape[1], 1)) | f4e4d9908d18e0bc0af6b373c210f00b85d4fa23 | 667,451 |
def find_values(obj, keys, key=None, val_type=list):
"""Find dictionary values of a certain type specified with certain keys.
Args:
obj (obj): a python object; initailly the dictionary to search
keys (list): list of keys to find their matching list values
key (str, optional): key to che... | 98e25b181a4aaf7b16caba0dfea9aec27b1fdb5a | 667,452 |
def map_segs_xsens2ergowear(xsens_segs):
"""Map segments from xsens (23) to ergowear (9)."""
return xsens_segs[..., [0, 4, 5,
8, 9, 10,
12, 13, 14], :] | 3f98317595efeb097a21d9f31bb67887ed97b642 | 667,453 |
def todep(name):
"""Convert a library name to an archive path or object file name."""
if name.startswith("-l"):
name = name.replace("-l","",1)
if name.startswith('toaru'):
return (True, "%s/lib%s.so" % ('base/lib', name))
elif name.startswith('kuroko'):
return (Tr... | 1294eb790ae235d84f75bbc67dcacbaf45617fd8 | 667,454 |
def transform_center(pos_x, pos_y, pos_z):
"""
re-center
:return: posx, posy, posz [arrays]
"""
posx = pos_x - (min(pos_x) + max(pos_x)) / 2.0
posy = pos_y - (min(pos_y) + max(pos_y)) / 2.0
posz = pos_z - (min(pos_z) + max(pos_z)) / 2.0
return posx, posy, posz | 2d1908827ab550e8ce42a960cce77fbb1ee13a09 | 667,455 |
import subprocess
def is_excel_file_2007(maldoc):
"""
Check to see if the given file is a 2007+ Excel file.
@param name (str) The name of the file to check.
@return (bool) True if the file is an Excel file, False if not.
"""
typ = subprocess.check_output(["file", maldoc])
if (b"Excel 200... | 101f24609256fdc343df8fd73097b74486840e91 | 667,456 |
def sort_select(list):
"""
参数
list: 待排序的队列
返回值
list:经过选择排序的队列,默认升序排列,降序排列将小于号改为大于号即可
"""
size = len(list)
for i in range(0, size - 1):
minindex = i
for j in range(i + 1, size):
if list[j] < list[minindex]:
minindex = j
if not mi... | dbb62473f2f1d5149f40fbd3f8112244e2b48839 | 667,457 |
def lin_closure(s, implications):
"""
Input: A set of implications and an attribute set s
Output: The closure of s with respect to implications
NB: This implementation is not linear-time.
Use lists instead of dicts to get a liner-time implementation.
Examples
========
>>> ... | 54cdb60ac7376efa2fe651c74103fc2acd275120 | 667,458 |
from pathlib import Path
def create_data_dir(run_dir):
"""
Create initial files for HADDOCK3 run.
Returns
-------
pathlib.Path
A path referring only to 'data'.
"""
data_dir = Path(run_dir, 'data')
data_dir.mkdir(parents=True, exist_ok=True)
return data_dir | 28945efcd3e50b91375d087e12178f855d0e3056 | 667,459 |
def translate(value, left_min, left_max, right_min, right_max):
"""This maps a value from one range to another. TY to the guy on stackoverflow"""
# Figure out how 'wide' each range is
left_span = left_max - left_min
right_span = right_max - right_min
# Convert the left range into a 0-1 range (float... | c7edd2bc7a103889376860763a373e65f75138d2 | 667,460 |
def str_warp(str_):
"""Change input string."""
if isinstance(str_, str) and not (
str_.startswith('\'') and str_.endswith('\'')):
return "'{}'".format(str_)
else:
return str_ | 5da4b37450677953981b376a3f032467937841e1 | 667,461 |
def split_key_value(key_value_str, delimiter='='):
"""
splits given string into key and value based on delimiter
:param key_value_str: example string `someKey=somevalue`
:param delimiter: default delimiter is `=`
:return: [ key, value]
"""
key, value = key_value_str.split(delimiter)
key... | 53a6c51afc01ae487bb1d9cafe9fa3f0ab544a90 | 667,464 |
def phantomjs():
"""Return the phantomjs page"""
return "Welcome to lab 8!" | 155142b24f642e55b9aa1dfae4de770ce8b62482 | 667,465 |
def parse_labels_and_features(dataset):
"""Extracts labels and features.
This is a good place to scale or transform the features if needed.
Args:
dataset: A Pandas `Dataframe`, containing the label on the first column and
monochrome pixel values on the remaining columns, in row major order.
Retu... | 60fb74b9b309fdbb7928406fe7213d18299b69ab | 667,466 |
def filter_used_routes(transfers_pair, routes):
"""This function makes sure we filter routes that have already been used.
So in a setup like this, we want to make sure that node 2, having tried to
route the transfer through 3 will also try 5 before sending it backwards to 1
1 -> 2 -> 3 -> 4
v... | ec6957cc4ce908771481a4baf7a9ca1f61f2c8b2 | 667,467 |
def marker_source(session, Type='Int32', RepCap='', AttrID=1150065, buffsize=0, action=['Get', '']):
"""[Get/Set Marker Source <int32>]
Sets/Gets the marker source. Markers may be output on the four marker output connectors.
"""
return session, Type, RepCap, AttrID, buffsize, action | 847fe72b54814be77f34b8914a6e3abab4457f71 | 667,468 |
def gen_file_name(rank: int, file_ext: str) -> str:
"""
generate filename to write a DataFrame partition
"""
if rank < 10:
numeric_ext = "000" + str(rank)
elif rank < 100:
numeric_ext = "00" + str(rank)
elif rank < 1000:
numeric_ext = "0" + str(rank)
else:
num... | d04286b6af7e9a4ee7d80ab45c1f41748b1385cd | 667,469 |
import os
def _OSError(err, path):
"""Return an OSError with an appropriate error string"""
return OSError(err, os.strerror(err) + ": '%s'" % path) | 9e772c9b333ce7392b6c73e5f6f4de845795ff1e | 667,470 |
def test_items_must_be_in_array_type(open_discovery_document, name, version):
""" Test that all array types in disc docs have an attribute called "items".
aiogoogle.validate.validate assumes all arrays has an "items" property and it will
fail if it didn't find one """
disc_doc = open_discovery_document... | 20ea6ab951c09f9d67918d2117f6ca6a980acefe | 667,471 |
def valid_year(entry, minimum, maximum):
"""Validate four digit year entries."""
if len(entry) > 4:
return False
elif int(entry) >= minimum and int(entry) <= maximum:
return True
else:
return False | 12491b406daa3c6d2eceb0929a2a72becca3cb42 | 667,472 |
def refreshAllSymbol(command, mySymbols):
""" Check if command is to refresh all stock symbols. """
return (len(mySymbols) > 0 and (command.strip().lower() == "r" or command.strip().lower() == "refresh") and len(command) == 1) | e5a397e3b2c4d4aaf8dc868702ba3b812531fdac | 667,474 |
def clamp(val, min, max):
""" Clamp value between min/max values """
if val > max:
return max
if val < min:
return min
return val | 1d0a80be15bcce8619d087086af3aefb4562155b | 667,475 |
def split_line(line):
"""
Converts a single input line into its elements.
Result is a dict containing the keys low, high, letter and passwd.
"""
parts = line.split()
numbers = parts[0].split("-")
d = dict()
d["low"] = int(numbers[0])
d["high"] = int(numbers[1])
d["letter"] =... | 5d7afd29e2b61747f73d00a27646a5936a22ea85 | 667,476 |
def heaps(arr: list) -> list:
"""
Pure python implementation of the iterative Heap's algorithm,
returning all permutations of a list.
>>> heaps([])
[()]
>>> heaps([0])
[(0,)]
>>> heaps([-1, 1])
[(-1, 1), (1, -1)]
>>> heaps([1, 2, 3])
[(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2... | 1bbf1b7bb70dc650852b8f02841eaf0643f59512 | 667,477 |
def get_concordance(text,
keyword,
idx,
window):
"""
For a given keyword (and its position in an article), return
the concordance of words (before and after) using a window.
:param text: text
:type text: string
:param keyword: keyword... | 508a989a8d59c4877fe40291bd24be406374962a | 667,478 |
def find_subj_verb_prep_obj_chunk(doc):
"""
Returns a dictionary representing a simple verb chunk
with a subject, verb, perp, object.
"""
for noun_chunk in doc.noun_chunks:
if noun_chunk.root.dep_ != 'nsubj':
continue
subj = noun_chunk.root
verb = subj.head
for child in verb.children:
if child.dep_ =... | 563993959a4e8ffef7b3fe84023327d5c7060274 | 667,479 |
import time
def decode_date(date):
"""Decodes a datetime from TiddlyWiki format."""
return time.strptime(date, '%Y%m%d%H%M') | a992e6ececb3495efef9b144024938c3aac7bb85 | 667,481 |
def no_op(*_, **__) -> None:
"""A function that does nothing, regardless of inputs"""
return None | 0c113e667d7f26d1f22e6a48030ae5f311e4481a | 667,482 |
from typing import OrderedDict
import sys
def read_file(filename):
"""Reads in sequences from fasta or multifasta file formats"""
seqs_in_file = OrderedDict()
strings = []
name = ''
with open (filename, 'r') as F:
for line in F:
if line.startswith('>'):
if st... | e2d31029abd731ddd3b2f18fbec74c81a71e1ea2 | 667,483 |
import math
def my_softmax(z):
""" Just an example of how softmax works for my own edification
Don't use this in any production code, stricky informational / educational.
"""
# math.exp() = e**x where:
# The value of e (Euler's Number - the base of the natural log) is raised to
# the power of ... | a0839a6c7511bf5e748efd3d939ab8e076bd7e30 | 667,484 |
def shift_augment(is_training=True, **kwargs):
"""Applies resize and random shift augmentation."""
size, pad_size = kwargs['size'], int(0.125 * kwargs['size'])
if is_training:
return [
('resize', {
'size': size
}),
('shift', {
'pad': pad_size
}),
]
... | ab2312c5f2c47c32680946a0316e40349892b298 | 667,485 |
def synergy_rows_list(ws, signal_names):
"""
Params
- ws: openpyxl worksheet object
- signal_names: name given to the signal by the user, i.e., "CFP"
Returns
- rows: list of tuples, each containing ('signal', signal_row_position)
"""
rows = [(celda.value, celda.row)
for... | 69f117a50e0682f50a6b0d84f235910cd657e223 | 667,486 |
import os
def get_checkpoint_dir(checkpoint_path):
"""Gets the checkpoint_dir containing the given checkpoint_path."""
return os.path.dirname(checkpoint_path) | 0b7303f171654c5f621bb781a99f773a3d5d27fa | 667,487 |
def write(*args, **kwargs):
"""
Wrapper for print function or print to ensure compatibility with python 2
The arguments are used similarly as the print_function
They can also be generalized to python 2 cases
"""
return print(*args, **kwargs) | f6bfcc9f72bf1fcfad0dbec56f4bce185df1fa04 | 667,489 |
def total_variation_distance(u_values, v_values):
"""Compute the total variation distance between two 1D distributions.
:param u_values: probability distribution
:param v_values: probability distrbution
:return: total variation distance between u_values and v_values
"""
dist = sum([abs(p-q) for... | 9c7d5a09431471d4ed605b96702375ad93a056cc | 667,490 |
def sfl(L):
""" (list) -> bool
Precondition: len(L) >= 2
Return True if and only if first item of the list is same as last.
>>> sfl([3, 4, 2, 8, 3])
True
>>> sfl([a, b, c])
False
"""
return (L[0] == L[-1]) | e89e3a6b8aa3c17ebfee553b044d536227eeabe5 | 667,491 |
def flatten_dict(input_dict, parent_key='', sep='.'):
"""Recursive function to convert multi-level dictionary to flat dictionary.
Args:
input_dict (dict): Dictionary to be flattened.
parent_key (str): Key under which `input_dict` is stored in the higher-level dictionary.
sep (str): Sepa... | fa3faee48455ea7e227c77b09bee2702fee5440f | 667,492 |
def partition(list, start, end):
"""Partition helper function for quicksort."""
sorted = False
pivot = list[start]
left = start + 1
right = end
while not sorted:
while left <= right and list[left] <= pivot:
left = left + 1
while list[right] >= pivot and right >= lef... | d4747284f79e6662a73b322a783996c7232600c9 | 667,493 |
def mean(vals):
"""Calculate the mean of a list of values."""
return sum([v for v in vals])/len(vals) | 31fa90a32ca10f42511c439954ef545a386d647f | 667,494 |
def get_raffles_for_date_expanded(db, date, user_id, conf):
"""Get raffles for a specific date
Args:
db (psycopg2.connection): The db to generate a cursor
date (datetime.date): The date to search for
user_id (int): User id
conf (Config): Configurations
Returns:
psyc... | f65573674d852e90e50f36e0e65d3c79efa64f01 | 667,495 |
from typing import Tuple
def footprint_transpose(x: float, y: float) -> Tuple[float, float]:
"""A transform function to swap the coordinates of a shapely geometry
Arguments:
x {float} -- The original x-coordinate
y {float} -- The original y-coordinate
Returns:
Tuple[float, float]... | c1b5ce2239913e99a306eeae67515481235ed4f2 | 667,496 |
import random
def randint(start: int, end: int) -> int:
"""Returns a random integer"""
return random.randint(start, end) | 0f0f7a8fda9287c6260ad5e201de1bd16065bbb1 | 667,497 |
import json
def return_assoc_edges(st,dict_name):
"""
Function to join co-occurring words with edges to create the contextual graph
"""
with open(dict_name+'.json','r+') as fp:
edge_dict = json.load(fp)
stlist = st.split(' ')
local_ids={}
for ind,w in en... | 656190c010182f60a162a663da9d7625402eccb6 | 667,498 |
def _is_income_level(code):
"""
"""
return code in ["NOC","OEC","HIC","HPC","LIC","LMC","LMY","MIC","UMC",
"Z4","Z7","XD","ZJ","XM","XN","XO","ZQ","XP","XR",
"XS","ZG","XT", "XE"] | 44f7f5a457211abb66be265794527bdc74a28e42 | 667,499 |
def helper_properties_def(properties):
"""
Convert properties from a Fiona datasource to a definition that is usable by
`dict_reader_as_geojson` and utilizes the helper functions for better value
handling.
Sample input:
{
'float_field': 'float:14',
'int_field': 'in... | 07e368026842eae5bb59b3fc4fe3860672c0daf9 | 667,500 |
def growth(t):
"""
Calculate grain size growth
From IPW albedo > growth
"""
a = 4.0
b = 3.
c = 2.0
d = 1.0
factor = (a+(b*t)+(t*t))/(c+(d*t)+(t*t)) - 1.0
return(1.0 - factor) | 77426dee005037e0045922cac0ac302f18383183 | 667,501 |
from pathlib import Path
import shutil
def copy_to_tmp(origin: Path, dest: Path) -> Path:
"""
Copy `origin` to temp `dest`
"""
shutil.copy(origin.as_posix(), dest.as_posix())
return dest / origin.name | 82929c88109889a9af8802ff154b70237b3ce1cc | 667,503 |
import random
def init_neurons(count):
"""
Initialize the weights of the neurons
:param count: number of neurons to initialize
:return: list of neurons as weight vectors (x,y)
"""
return [[random.uniform(0.0, 1.0),
random.uniform(0.0, 1.0)] for i in range(count)] | 98be8fc1f621e2c768af3c93d1a0254ac42a4ffc | 667,504 |
def custom_name_func(testcase_func, param_num, param):
"""Generates friendly names such as `test_syntax_while`."""
return "%s_%s" % (testcase_func.__name__, param.args[0]) | a2800267987bdafb82636e4391f95db2e4872edb | 667,505 |
def arg_preprocessing(arg_v):
"""Return the values of an argument after preprocessing"""
# check if arg is list and convert it to comma-separated string
if isinstance(arg_v, list):
arg_v = ','.join(arg_v)
# check if arg is boolean and convert it to string
elif isinstance(arg_v, bool):
... | 9be2511d4254c2f350c0ca236c1eda941e8e7913 | 667,506 |
def iodineIndex (Na2S2O3_molarity, Na2S2O3_fc, Na2S2O3_volume_spent, blank_volume, sample_weight):
"""
Function to calculate the iodine index in grams of iodine per 100g
"""
V_Na2S2O3 = blank_volume - Na2S2O3_volume_spent
iodine_mols = (Na2S2O3_molarity * Na2S2O3_fc * V_Na2S2O3) / 2
iodine_mg = ... | 9af3c55d90228f43c16885b6e2f828ffae195296 | 667,508 |
def time_to_seconds(time):
"""Convert timestamp string of the form 'hh:mm:ss' to seconds."""
return int(sum(abs(int(x)) * 60 ** i for i, x in enumerate(reversed(time.replace(',', '').split(':')))) * (-1 if time[0] == '-' else 1)) | 55dbf2f8a57f3a57c593afda908c984910bcb659 | 667,509 |
def detect(input_tensor,detection_model):
"""Run detection on an input image.
Args:
input_tensor: A [1, height, width, 3] Tensor of type tf.float32.
Note that height and width can be anything since the image will be
immediately resized according to the needs of the model within this
function.
... | f69daf1b88fc688b345eae0e77af8d24f0aa31e3 | 667,510 |
def build_idef_regexp( curr_idef ):
""" build regexp quering collection """
level_num= curr_idef.count('-')
# build regexp for the given idef plus it's context (siblings and full parental branch)
if level_num > 0: # deeper than 'a'
idef_srch= curr_idef.rsplit('-', 1)[0]
lookup_idef= r'^... | cd76170f70d1f18d87565a634a995ddd423a16a5 | 667,511 |
import functools
def check_prerequisites(prerequisites, checker, msg_tmpl='Prerequisites "{}" are required in method "{}" '
'but not found, please install them first.'): # yapf: disable
"""A decorator factory to check if prerequisites are satisfied.
Ar... | 49ccacede097c3bfbabf4d69bb788786d8df05c6 | 667,512 |
def value2Tuple4(v):
"""Answers a tuple of 4 values. Can be used for colors and rectangles.
>>> value2Tuple4(123)
(123, 123, 123, 123)
>>> value2Tuple4((2,3))
(2, 3, 2, 3)
>>> value2Tuple4((2,3,4,5))
(2, 3, 4, 5)
"""
if not isinstance(v, (list, tuple)):
v = [v]
if len(v)... | ed8a7c49e0198d2867f4d00fb52a3206b5850b9b | 667,513 |
def CustomCMakeLinesTestHoldingProject(project):
""" Line to enable testing. """
return "\n# Enable CMake Testing\nENABLE_TESTING()\n" | ae82e926ca2ab7a9e2e68a1fea3169c46f9b0005 | 667,514 |
def extend(oneMers,kmer):
"""Extends a given kmer.
INPUT :
oneMers: array-like. A list of amino acids that will be used to extend the given kmer.
kmer: string. The given kmer required to extend.
OUTPUT:
.: List. A list of extended kmers.
"""
extentions = []
for oneMe... | 077d714a62be222459189fc623e81fa9b38bf3ab | 667,515 |
def calc_players_dangerously(level, honor):
"""
Returns a float between 0 and 1
honor influences this calculation:
Min honor = 0
Max honor = 5000
honor_index is a value between 0.003 and 0.00469
and represents the honor in this calc
the courve works fine for levels 5-60
""... | c20dd2345e81b77d85b7cb61c36c96a897984b76 | 667,517 |
def fetch_bricks(repo, start_date, end_date):
"""
"""
return repo.get_commits(since=start_date, until=end_date) | 5280819fd5c10fd0530dfdce089f64e842897142 | 667,518 |
import os
def get_project_file(path, target):
"""
Get a Visual Studio project file for a specific target.
:param str path: The path of the directory project files
:param str target: The name of the target
:returns: The path of the project file if it exists, otherwise None
:rtype: str
"""
... | d6ed4103afcda6dcfd186ece3a94afe0c651b79d | 667,519 |
import math
def glow(radius=40):
"""Overlay a Gaussian blur with given radius (default 40)"""
stdDev = math.floor(radius/2)
return lambda g: f"""
<filter id="glow">
<feGaussianBlur stdDeviation="{stdDev}" />
<feMerge>
<feMergeNode />
<feMergeNode in="SourceGraphic" />
</feM... | 2b70b0485276049aacae30fb8f06d9bda7d16173 | 667,521 |
def parked_vehicles(psvList):
""" Get number of successfully parked vehicles.
Args:
psvList (list): List of parking search vehicle objects
Returns:
int: Number of parked vehicles
"""
return sum(1 for psv in psvList if psv.is_parked()) | 8bfeeb3ceacb8697df76021bc1206d2e4d1a26f5 | 667,522 |
def computeBalanceTriads(G, signs):
"""
:param - G: graph
:param - signs: Dictionary of signs (key = node pair (a,b), value = sign)
return type: List, each position representing count of t0, t1, t2, and t3, respectively.
return: Return the counts for t0, t1, t2, and t3 triad types. Count each triad... | 133213f44bd9cb2f1ef80639458e9988507d586f | 667,523 |
def false_discovery_rate(cm):
"""
false discovery rate (FDR)
FDR = FP / (FP + TP) = 1 - PPV
"""
return cm[0][1] / float(cm[0][1] + cm[1][1]) | 90316c7648ee9993764eb88f0de12b7fcd1914c7 | 667,524 |
def __get_movie_strings(full_name: str):
"""
Function that, given a full name on the movielens dataset: Initially, the string is separated by " (" string to
exclude the year, than the first step is to extract the first and eventually second and third names. Finally, the
articles of the pt, en, es, it, f... | 48b10ef95a473aea0796cba3cf3a219d2cfe3602 | 667,525 |
def _get_iterator_device(job_name, task_id):
""" Returns the iterator device to use """
if job_name != 'learner':
return None
return '/job:%s/task:%d' % (job_name, task_id) | 336b06f0fa15c662765e867afc43b87fdd400ed3 | 667,526 |
def unicode_to_c_ustring(string):
"""Converts a Python unicode string to a C++ u16-string literal.
>>> unicode_to_c_ustring(u'b\u00fccher.de')
'u"b\\\\u00fccher.de"'
"""
result = ['u"']
for c in string:
if (ord(c) > 0xffff):
escaped = '\\U%08x' % ord(c)
elif (ord(c) > 0x7f):
escap... | 2498487aa424ebf7da1825284be054d2699a5e6e | 667,527 |
def get_label(StateMachineName, StateIdx, SuccessfulOriginalStateMachineID=None):
"""
(1) StateIdx != None
jump label for state machine state entry
(2) StateIdx == None: terminal state
(1a) SuccessfulOriginalStateMachineID == None: not acceptance terminal state
... | 438632677c9fdce8816ddbc67672150051d8e8f9 | 667,528 |
import torch
def masked_mean(x, m=None, dim=-1):
"""
mean pooling when there're paddings
input: tensor: batch x time x h
mask: batch x time
output: tensor: batch x h
"""
if m is None:
return torch.mean(x, dim=dim)
mask_sum = torch.sum(m, dim=-1) # ba... | 0e222b49aac03e12befd4da7bafefe12c9c80980 | 667,529 |
def dictify(gen):
"""Decorator that converts a generator into a function which returns a dict
Use it in the case where a generator is easier to write but you want
to enforce returning a dict::
@listify
def counter(max_no):
i = 0
while i <= max_no:
yi... | 6feb9cff9a89af3bf733c805510e8228f269bbb9 | 667,530 |
def gFont(fontname="Times", fontsize=12, fontface='normal'):
""" Returns a font specification to use with the draw text routines
fontname must be a string, fontsize and integer
fontface is also a string normal, bold or italic; for bold and italic,
make fontface "bold italic"
"""
ret... | 96e27bea0838acda94ec64a1bb691e0641632bc5 | 667,531 |
def Get_FigWidth_Inches(FigSizeFormat="default"):
"""
This function gets the figure width in inches for different formats
Args:
FigSizeFormat: the figure size format according to journal for which the figure is intended
values are geomorphology,ESURF, ESPL, EPSL, JGR, big
de... | 2d07f39256ce628f7e8922421c8d6ec69e9d78f3 | 667,532 |
def _is_int(v):
"""int testing"""
return isinstance(v, int) | f8417bbc4fec1278a5a29a2882392d052dffcad9 | 667,533 |
def acrostic(items):
"""
Take the acrostic of a list of words -- the first letter of each word.
"""
return ''.join([item[0] for item in items]) | c42fd9645d3129f2792d9c3347a6a908126dfa83 | 667,534 |
def mean_soft_prediction(y_true, y_score):
"""Compute the mean predicted probability."""
return y_score.mean() | 8bf5af4b8ab9562a015e5a58af3929f0e24167bb | 667,535 |
import argparse
def parse_arguments():
"""
Get parameter to train.
"""
parser = argparse.ArgumentParser(description="Training / Evaluating RetinaNet")
parser.add_argument("--ds_test", type=str, required=True)
parser.add_argument("--ds_test_json", type=str, required=True)
parser.add_argumen... | 25f15de188a79c9473a508040e61c4c0a7756b98 | 667,536 |
def build_ticker_url(ticker_identifier_list):
"""
Queries the url using the desired ticker identifier and token.
Trims the data set by start date. All values are being benchmarked
against 4/10/2007, which is the latest inception date for all of
the funds for apples-to-apples since-inception compari... | 2760d38eda718eba1d6818423a90c5669668596a | 667,537 |
def _get_file_name_from_uri(uri):
"""Gets filename from URI
Args:
uri (str): URI
"""
return uri.split("/")[-1] | c7b99ef3646c1df4a651c1ad78c08802847ffb31 | 667,538 |
import argparse
def parse_args():
"""Parse argument values from command-line"""
parser = argparse.ArgumentParser(description='Arguments required for script.')
parser.add_argument('-s', '--state-machine', required=True,
choices=['EMR-Demo-Process', 'EMR-Demo-Analysis'],
... | f94690effd4d8b3dd24626457a81d0338bca3604 | 667,539 |
def copy_state_dict(state_dict_1, state_dict_2):
"""Manual copy of state dict.
Why ? Because when copying a state dict to another with load_state_dict, the values of weight are copied only
when keys are the same in both state_dict, even if strict=False.
"""
state1_keys = list(state_dict_1.keys())
... | 2c66e3de9c13fc1b668c121dc307d8320679de36 | 667,540 |
def get_status_code(status,short = False):
"""Converts status code phrase to a simplified code if it isn't already simplified.
Examples: 'Registered' => 'R' or 'Web Drop' => 'DROP'
"""
if short:
status_codes = {'Registered': 'R','Web Registered': 'R','(Add(ed) to Waitlist)': 'WL', 'Web Drop'... | 3b9345e9739afd1a9b08150e60a58ebaf24ebddb | 667,541 |
import sys
def IsLinuxPlatform():
""" Returns true if the python script is running on Unix or Unix like. """
return sys.platform == "linux2" | e7ef00ec8312b38021ab9580acb9f781c7dd606d | 667,543 |
def sql_get_columns_postgres(schemas: list) -> str:
"""Generates an SQL command that gives the list of columns of every table
in a specific schema from a postgres database"""
sql_schemas = ', '.join(f"'{schema}'" for schema in schemas)
return f"""
SELECT table_name, STRING_AGG(CONCAT(column_name, '... | 02d739024836485b89ec73fe01fd71cb4f541d4e | 667,544 |
def cachedproperty(f):
"""returns a cached property that is calculated by function f"""
def get(self):
try:
return self._property_cache[f]
except AttributeError:
self._property_cache = {}
x = self._property_cache[f] = f(self)
return x
excep... | 84dc9ff928dc114b58b529d9f31e159bfe1bea1c | 667,545 |
def add(a, b, fill_value=0.0):
"""Sum of *a* and *b*."""
return a.add(b, fill_value=fill_value).dropna() | 1ddea91c9b1e50bcfd877f32dd01e478ab4cdc82 | 667,546 |
def is_repo_image(image):
"""
Checks whether the given image has a name, i.e. is a repository image. This does not imply that it is
assigned to an external repository.
:param image: Image structure from the Docker Remote API.
:type image: dict
:return: ``False`` if the only image name and tag i... | 75aa72fac2d1a99870b72b59b1f9e8861c82fd79 | 667,547 |
import ast
import json
def parse_json(infile):
""" Read a json file to a dict """
with open(infile) as f:
return ast.literal_eval(json.dumps(json.load(f))) | 25310150ee7e2770dbaa6926d9ef332e3ff54936 | 667,548 |
def find(word, lexicon):
""" Look up and return features of a given word in the lexicon. """
# Define pronoun categories.
pronouns = lexicon["pronouns"]
subject_pros = pronouns["subject"]
object_pros = pronouns["object"]
possessive_pros = pronouns["possessive"]
dep_possessives = possessive_... | 76a00896f8a283e08fa94a0e81abd1df3cedd641 | 667,549 |
def sum_of_two(arrayA,arrayB,value):
"""verify if the difference of A elements minus value is in B"""
flag = False
for a in arrayA:
diff = value - a
if diff in arrayB:
flag = True
return flag
return flag | 3ec3de2e4ada418da99d61e1b2c8d9285be35797 | 667,550 |
def summary_example(field):
"""Returns an example of a value in the summary of the field
"""
distribution_keys = ["categories", "counts", "bins", "tag_cloud", "items"]
for key in distribution_keys:
if key in field["summary"]:
return repr(field["summary"][key][0][0]) | a18fa2d3dc763a4429ed41d628dc84fce1476acd | 667,551 |
def invert_pitches(pitches, inversion):
"""Inverts a list of pitches, wrapping the top pitches an octave below the root
:param pitches: list
:param inversion: int
:return: list
"""
for i in range(1, (inversion % (len(pitches)))+1):
pitches[-i] = pitches[-i] - 12
pitches.sort()
... | 256f303ec67cdd2d07bb611c6bebc7a2bfb1f67b | 667,552 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.