content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def Int2Digits(i, base):
"""
The next function converts the number into a list of digits
For example:
if base=10, then Int2Digits(126, 10) = [1, 2, 6]
if base=2, then Int2Digits(126, 2) = [1, 1, 1, 1, 1, 1, 0]
(This function is called by the Number2String() function.)
"""
if (i < base... | 9301f2023623b92db233ac1955b75154a2de9f33 | 637,306 |
def gather_fas(job, seq_id_map, output_id_map, contig_fa_map):
""" take the split_fas output which has everything sorted by event, and move into the ref-contig-based table
from split_gfa. return the updated table, which can then be exported into the chromosome projects """
if not contig_fa_map:
re... | efb2a55eb1f2fd97f09d912ec1fbe384beb6a1d2 | 637,307 |
import re
def _is_auspex(path):
"""
Test if a given file path is an Auspex data file
"""
path = path.rstrip('/')
filename = path.split('/')[-1]
if re.findall(r".+.auspex", filename):
return True
else:
return False | a644f14d9c8e7647546efa7f0f63694edd65e951 | 637,308 |
def riccati_inverse_normal(y, x, b1, b2, bp=None):
"""
Inverse transforming the solution to the normal
Riccati ODE to get the solution to the Riccati ODE.
"""
# bp is the expression which is independent of the solution
# and hence, it need not be computed again
if bp is None:
bp = -b... | 0876babe4dffea545aeb2598508cbe19e50e04de | 637,309 |
def print_gcmc(gcmc):
"""Return string version of chemical potential records for DL CONTROL"""
return "{} {}".format(gcmc["id"], gcmc["molpot"]) | 0a172a5ffd82adef84af96a1fb67eb326e91d218 | 637,310 |
def _nestget(data, *path, default=""):
"""Obtém valores de list ou dicionários."""
for key_or_index in path:
try:
data = data[key_or_index]
except (KeyError, IndexError):
return default
return data | bfa85de67fa1518442c8514035390e896bd6491c | 637,311 |
def clean_unit_errors(merged_df):
"""
This function will look in a DataFrame for rows where the height_cat and weight_cat are set to
"Unit-Error-High" or "Unit-Error-Low". It will then multiply / divide the height and weight
values to convert them. It will also create two new columns: postprocess_heigh... | 88a99871cd2987d473d672c700e8972660c17f5b | 637,314 |
import queue
import threading
import six
import sys
def async_call(target, timeout=None):
"""Accepts a method and optional timeout.
Returns a new method that will call the original with any args, waiting for upto timeout seconds.
This new method blocks on the original and returns the result or None
if... | da8ff39a448b923bd02518f19bd5420931814760 | 637,315 |
def multfloat(a:float,b:float) -> float:
"""
Returns the product of two numbers i.e
a * b without using the '*' multiplication operator
>>> multfloat(5,3)
15
"""
#Change the code below
return a*b | eb9b0c2f4b24b90ba113d28571aab93e43bb2757 | 637,317 |
import os
def exists(filename):
"""
checks weather a directory or file of filename exists
:param filename: full path to filename to check the existence of
:return: boolean
"""
return os.path.exists(filename) | b2bbbde6b66a77ade4983764e87ba601e15e6cbc | 637,319 |
from datetime import datetime
def elapsed_days(item):
"""Return elapsed days since password was set."""
today = datetime.now()
try:
changed = None
if 'changed' in item:
changed = datetime.fromisoformat(item['changed'])
elif 'created' in item:
changed = datet... | 3831a2c4ee1d95269404e71c167d98fa461128a0 | 637,320 |
import stat
import os
import tempfile
import shutil
def check_keyfile(keyfile):
"""
keyfile must have the right access premissions in order to be useable. If the specified
file doesn't, create a temporary copy and set the right permissions for that.
Returns either the ``keyfile`` (if the permissions ... | fc027b4afda946f4d957b843f37a383968141c6e | 637,322 |
import re
def get_accepted_content_types(request):
"""Return accepted content types for the request's response.
Many thanks to https://stackoverflow.com/questions/
7459881/determine-the-requested-content-type
"""
def qualify(raw_content_type):
parts = raw_content_type.split... | 801682eac3ac417c612784635df254ace244cd66 | 637,323 |
def instanceof(obj, classinfo):
"""Wrap isinstance to only return True/False"""
try:
return isinstance(obj, classinfo)
except TypeError: # pragma: no cover
# No coverage since we never call this without a class,
# type, or tuple of classes, types, or such typles.
return Fals... | a9bb9fe54fe16d58ef8b944708fb837125f31147 | 637,325 |
def compound_where(keys, fields):
"""Create a filter on compound keys."""
args = {}
ors = []
for i, key in enumerate(keys):
ands = []
for field, value in zip(fields, key):
bind_name = '{}_{}'.format(field.replace('.', '_'), i)
ands.append('{} = :{}'.format(field, ... | 6a82d8077fa1457f6a0146d56379dc6ef497ca7d | 637,326 |
def get_playseq(data, length):
"""return data read from file as a list of pattern numbers
also return highest pattern number
"""
result = []
highpatt = 0
for bytechar in data[:length]:
test = int(bytechar)
result.append(test)
if test > highpatt:
highpatt = te... | 6528eaa4bb0f31f1a495c6ff3a4e571b38ae26a4 | 637,327 |
def get_index_of_value_interval_vector(vector, value):
"""
Function returns the index of the smallest closest value to a given number inside a vector
"""
if value < vector[0]:
return 0
for i in range(len(vector) + 1):
if value < vector[i + 1] and value > vector[i]:
return i + 1
return len(vector) - 1 | 3c837c35dee58ef8cb5408b694245c544b5df604 | 637,328 |
import random
def get_random_int(start=1, end=1000000):
"""Get an random integer between start and end inclusive."""
x = random.random()
i = int(x*(end + 1 - start) + start)
return i | 13bf15ac00a2c717540644daa6b36b23cb367dc0 | 637,329 |
import torch
def _pad_norm(x, implicit=False):
"""Add a channel that ensures that prob sum to one if the input has
an implicit background class. Else, ensures that prob sum to one."""
if implicit:
x = torch.cat((1 - x.sum(dim=1, keepdim=True), x), dim=1)
return x | 4439886e811d2a1e6d5241edc6cc39f0f645019b | 637,330 |
def saveInstancesMatsToFile(filename, matrices):
"""
save a list of instance matrices to a file
status = saveInstancesMatsToFile(filename, matrices)
status will be 1 if it worked
"""
f = open(filename, 'w')
if not f:
return 0
for mat in matrices:
for v in mat.flatten()... | 74da1160e6e5d12434e32fc9e46f01035169444f | 637,331 |
import torch
def all_edges(n):
"""Return a tensor of all (n choose 2) edges
Constructs all possible edges among n items. For example, if ``n`` is 4,
the return value will be equal to
.. code:: python3
torch.Tensor([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]])
"""
return torch.tr... | b873868959273f87efb0ea31cc65a3f01afcaca7 | 637,332 |
def externalarray(file_manager):
"""
An array of external array references.
"""
return file_manager.external_array_references | cee20da69b485ef2260e7222135cd58466d8ad49 | 637,333 |
import numpy
def averaging (stat):
"""Converts a statistic for a single arrival to one that
averages over a list of arrivals."""
return lambda arrvl: numpy.mean ([ stat(a) for a in arrvl ]) | 992ee8aecd1df28a6169dcf07718a04b09abc830 | 637,334 |
def matrix_add(list1, list2):
"""
Accepts two lists-of-lists of numbers and returns one
list-of-lists with each of the corresponding numbers in the
two given lists-of-lists added together.
Example:
>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
... | f95de8387502ff2f244ba0c3e2b6d7fe0763e2bb | 637,336 |
def pad(s):
"""
This function is to pad a plaintext.
parameters:
s: str
string to be Padded
"""
pad_byte=16-(len(s)%16) #Number of bytes to be Padded.
return s+pad_byte*(chr(pad_byte)) #String of padded palintext. | 42640193817cbc60be8a1edf583d998ce205eddf | 637,337 |
def eratosthenes(n):
"""
this fxn is the Sieve of Eratosthenes.
this algorithm generates a list of positive integers up to a given input n,
then removes all multiples of 2, then 3,then 4, and so on until only the numbers
that are divisible by 1 and itself are left in the list. and therefore the lis... | a84ddbd257794ca49e65c1d04f9c62a37c47b191 | 637,338 |
import os
import subprocess
def find_unpack_script():
"""Get the unpack script either from folder passed from arg or download from unity-jar-resolver.
Returns:
path of the unpack script. None if not found.
"""
built_folder_ext = "_unity"
built_folder_postion = os.path.join("external", "src", "googl... | 1b2a957ddba7df0bd729fa27f4ac7f11c991eed9 | 637,339 |
import torch
def seg_voting(nms_segs, all_segs, all_scores, iou_threshold, score_offset=1.5):
"""
blur localization results by incorporating side segs.
this is known as bounding box voting in object detection literature.
slightly boost the performance around iou_threshold
"""
# *_... | f761c97bc05a450fefa6c6492c8a47f248b8daff | 637,340 |
def exit():
""""Exits" a program."""
# Right now, we don't know what the maximum PC will be. We create a thunk,
# which we evaluate to the maximum PC in the second pass.
return "{{ _exit_thunk() }}" | bd0d129d8173242df1497e653f1da8c7d71c515f | 637,341 |
def _compare(local, remote):
"""Compare versions."""
if local == remote:
return True
else:
return False | 4ad19adc79401deb9a93d3ff32dc58f32a58c4c5 | 637,342 |
import random
def fuzz(buf, add_buf, max_size):
"""
Called per fuzzing iteration.
@type buf: bytearray
@param buf: The buffer that should be mutated.
@type add_buf: bytearray
@param add_buf: A second buffer that can be used as mutation source.
@type max_size: int
@param max_size: Ma... | 6cb6757a658cc43d881ab4f11d88e616a31a2402 | 637,343 |
def readme():
"""
Read ReST readme file, use as long description.
"""
with open('README.rst') as file:
data = file.read()
data = data.replace("`LICENSE <LICENSE>`__", "LICENSE")
return data | 47cc49de286353d94cd1b2d9455f08a451825dd7 | 637,344 |
import struct
def readStruct(fmt, file, offset=None):
"""Read struct from file."""
if offset is not None: file.seek(offset)
sLen = struct.calcsize(fmt)
r = struct.unpack(fmt, file.read(sLen))
if len(r) == 1: return r[0] # grumble
return r | f3423d255668341ed6ae9b5a770cdc94a0d1b523 | 637,345 |
from datetime import datetime
def is_time_in_range(start: datetime, end: datetime, now: datetime):
"""Return true if now is in the range [start, end]"""
if start <= end:
return start <= now <= end
return start <= now or now <= end | 6f5cf0a25723ff65d259746d610f09d810e28330 | 637,346 |
def get_interface_connected_adjacent_router_interfaces(
device, link_name, num=1
):
""" Get list of connected interfaces from adjacents routers
Args:
device ('obj'): Device object
link_name ('str'): Interface alias in topology
num ('int'): Number of interfaces to ret... | 534baf2410df4e87a98581429b45347c31f58f7f | 637,347 |
def ainv(x):
"""Additive inverse"""
return -x | 4a21c25695539070253277fdc6961e81a9ffb81e | 637,348 |
def dup_ff_primitive(f, K):
"""Returns content and a primitive polynomial over a field. """
return K.one, f | f82d3183fe67a8123851c04905c629edaab61a75 | 637,349 |
import inspect
def getAllClasses(modules):
"""List all classes in a modules list"""
result = {}
for module in modules:
for name, value in inspect.getmembers(module):
if inspect.isclass(value):
result[name] = value
return result | e28ef9ac479120b5bc8c5f8aea3ab6f3938e8aa2 | 637,350 |
def scale_pixels(X_np_a, max_pixel_intensity):
"""Scale pixel values to be in [0, 1] to help gradient-descent optimization.
Args:
X_np_a (:obj:`numpy.ndarray`): Matrix of pixel intensities
max_pixel_intensity (int): normalization constant set by user
Returns:
matrix of scaled inten... | a0ad7ea7db749236f353bba091c2d2b3fc444d38 | 637,351 |
def get_num_classes(self):
""" Retrieves the number of classes in dataset """
return len(self.id_to_class_info) | 4b51c76d865a97e30d7531c8a05469e5fc8d66d7 | 637,352 |
def subfinder_bool(mylist, pattern):
"""if a subpattern is in a list return
a bool"""
matches = []
for i in range(len(mylist)):
if mylist[i] == pattern[0] and mylist[i:i+len(pattern)] == pattern:
matches.append(pattern)
return True
return False | a228cf85ae6f8b44c82dbaf099da4a2c5a622daf | 637,353 |
import functools
def suppress_errors_raw(func):
"""
Automatically silence errors that occur within a function
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
pass
return wrapper | 001903423682560dc9b7e6b00d2f6e98f82c6240 | 637,354 |
import random
def getAction(action_list,action_values,minimax_val):
"""
Returns a random action of the actions with minmax_val
"""
req_actions = list()
min_val_indexs = [i for i in range(len(action_values)) if action_values[i]==minimax_val]
for i in range(len(min_val_indexs)):
req_act... | 25f3b5c2954709c82f5ea0833400ca4b7ef0c898 | 637,355 |
def dump_dict(dump):
"""Returns dict of common profiles (radial quantities)
"""
return {'y': dump.y,
'tn': dump.tn,
'xkn': dump.xkn,
'abar': dump.abar,
'zbar': dump.zbar,
} | 38877c9daa27115ac67ec9f5176f9bcccd5b8ebd | 637,356 |
import math
def damping(temp, relhum, freq, pres=101325):
"""
Calculates the damping factor for sound in dB/m
depending on temperature, humidity and sound frequency.
Source: http://www.sengpielaudio.com/LuftdaempfungFormel.htm
temp: Temperature in degrees celsius
relhum: Relative humidity as ... | 6780e2123a5845f238516273b713699cc75b4fe6 | 637,357 |
def _paths_to_tree(paths):
"""Build a tree from the given paths.
The structure of the tree is described in the docstring for _prune_paths.
"""
tree = {}
for path in paths:
t = tree
for c in path:
if c not in t:
t[c] = {}
t = t[c]
return t... | 35b5a1a7b2b54f85252d1a45a4c59f8b8b9e0b3e | 637,358 |
from typing import Tuple
def _calc_externally(p1: float, p2: float, ratio: Tuple[float, float]) -> float:
"""Calculate the point that divides externally.
Args:
p1 (float): point 1
p2 (float): point 2
ratio (float): rate of division
Returns:
float: divided point
"""
... | 3bb16242e8ed575dbadfa41058de04d16fafdab9 | 637,359 |
import click
import os
import json
def _create_command_class(config_option_key, config_path_option_key):
"""Creates click.Command subclass that overrides values from config file at the provided path
:param config_option_key: Option key for config json
:param config_path_option_key: Option key for config j... | b0b8cd8e144c4325d9081d3fc08757e471cd7c1a | 637,360 |
from typing import Sequence
from typing import Tuple
from typing import Mapping
import re
import collections
def _parse_qualifiers(
type_name: str,
qualifiers: Sequence[str]) -> Tuple[str, Mapping[str, bool]]:
"""Separates qualifiers from the rest of the type name."""
parts = re.split(r'\s+', type_name)
... | ebbef2ca8c623a5aa1b1483e95022681b02e52a2 | 637,361 |
def json_set_hook(dct):
"""
Return an encoded set to it's python representation.
"""
if not isinstance(dct, dict):
return dct
if '__set__' not in dct:
return dct
return set((tuple(item) if isinstance(item, list) else item) for item in dct['__set__']) | a1f9b157044d85597c167629dd7baaed28a6c8f8 | 637,362 |
def is_main(args):
"""
returns True if process is being run on the main GPU
"""
return args.local_rank in [0, -1] | 95a94a1216b1332d9bd7f5fae153dadf9b5c3d4e | 637,363 |
import re
def cnvtNum(s):
"""Sometimes scientific notation values in spex output are expressed
without an 'e', e.g. 5.62495-100, so we need to convert by hand.
"""
try:
v = float(s)
except ValueError:
m = re.match('([0-9.]+)([+-][0-9]{3})', s)
if not m:
raise V... | 40b604a6593bb13bbd8ed08e61640e81f1cd1801 | 637,365 |
def slp_into_tuple_with_nulls(space, seq_w):
"""
create a tuple with the object and store
a tuple with the positions of NULLs as first element.
"""
tup = [None] * (len(seq_w) + 1)
w = space.wrap
num = 1
nulls = [None for i in seq_w if i is None]
null_num = 0
for w_obj in seq_w:
... | b202d3f843206729f4f82a38b666852008bff696 | 637,366 |
def is_chinese(word):
"""
判断是否为中文,如果是中文,返回true
:param word: str
:return: bool
"""
for ch in word:
if '\u4e00' <= ch <= '\u9fff':
return True
return False | de2c082a9b42ac7154bcb6bb33ab79ab21e3293c | 637,367 |
def accuracy_score(y_true, y_predictions):
""" Calculates the accuracy score for the model"""
correct = 0
for yt, yp in zip(y_true, y_predictions):
if yt == yp:
correct += 1
return correct / len(y_predictions) | 94063777427a65b02451660d31f9206252206146 | 637,368 |
from typing import Union
from typing import List
import warnings
def set_seasonal_period(self, given_period: Union[int, float, List[int], List[float]]):
"""Checks we're given proper seasonal period(s) and ensures we can assume self.seasonal_period will be a list"""
if given_period is None:
return None... | e44b4382d588be12d7ba3479204c20ae3edbfd5f | 637,370 |
import os
def find_xlsx_files(filepath):
""""
creates list of all .xlsx files in data path
:param filepath: path to data directory
:type filepath: string
:return files: list of filenames that are *.xlsx files
"""
files = [file for file in os.listdir(filepath) if
(not file.star... | 6e067059fb70229080b7367615175294ebad841a | 637,371 |
def get_client_commands():
"""Generates client-side commands."""
return [
{'name': 'close',
'description': 'Close the messenger',
'detailed': '<b>Usage:</b> /close<br><br>'
'Ask you to close messenger.'},
{'name': 'logout',
... | 0c1e914c4f6f0d7fb4c8c094396136553187aad5 | 637,372 |
import re
def isHexEncodedString(subject):
"""
Checks if the provided string is hex encoded
>>> isHexEncodedString('DEADBEEF')
True
>>> isHexEncodedString('test')
False
"""
return re.match(r"\A[0-9a-fA-Fx]+\Z", subject) is not None | 359143b15c88d94569e9a690f62d5f055c50cf11 | 637,373 |
import os
import codecs
def open_local(paths, mode="r", encoding="utf8"):
"""打开本地文件 ."""
path = os.path.join(*paths)
return codecs.open(path, mode, encoding) | 97b1e2acc8f0b613f8dcbc055ca00d6002c0e34f | 637,375 |
def num_cat_feature_columns(df):
"""
Takes a pandas Dataframe (part of the black_friday_data_hack project) as input and
separates numerical features from categorical features
Arguments: data - DataFrame
Returns: tuple of numerical features and categorical features
... | 35467a6b4704b8495d8e13d96b26fc2cb75bcd0c | 637,376 |
def get_default_settings():
"""
Return the default settings for generating LaTeX circuits.
settings is a dictionary with the following keys:
gate_shadow: Whether or not to apply shadowing to the gates.
lines: Settings for the lines.
gates: Settings for the gates.
control: Settings f... | 0d51b7f248fddb4f2c1c415c379ab41779ee4288 | 637,377 |
def crystal(ele):
"""
Tell me the name of element.
I will tell you its crystal structure and recorded lattice parameter.
"""
if ele in ('Cu', 'cu'):
lat_a = 3.597 # unit is A
lat_b = lat_a
lat_c = lat_a
cryst_structure = 'FCC' # the name of crystal structure
if... | 5799901edd8271cd8d79e6343cde2e91c6ea1b36 | 637,378 |
def transform(legacy_data):
"""Transforms legacy data into shiny new data."""
scores = dict()
for key, value in legacy_data.items():
for char in value:
scores[char.lower()] = key
return scores | 74ade262d1e33fbba26c7915916bb1dbcb21374c | 637,379 |
def preprocessing(dataset, low, high):
"""
* IQR(Interquartile range) function to find if the data is classified as outlier or not
* returns a boolean array (if the corresponding data(row) is outlier it will be true otherwise false)
----------
dataset: input data to process
low:
high:
... | 53b60b326a0dfb203b25c6473d8298fa4f37cd90 | 637,380 |
def trans_data_to_axis(ax):
"""Compute the transform from data to axis coordinate system in axis `ax`"""
axis_to_data = ax.transAxes + ax.transData.inverted()
data_to_axis = axis_to_data.inverted()
return data_to_axis | 2416a5472d51abe3a4389627820b392d737ad58d | 637,381 |
import time
def get_timestamp(seconds):
"""Returns the formatted timestamp
;param seconds: the length of time in seconds
;return: the formatted timestamp
"""
return time.strftime("%H:%M:%S", time.gmtime(seconds)) | dd913fecca0f832c87e995c31ff0181829fd4672 | 637,382 |
import requests
import shutil
def download_image_url(url, output_filename):
"""
https://stackoverflow.com/questions/13137817/how-to-download-image-using-requests
"""
res = requests.get(url, stream=True)
if res.status_code == 200 and res.headers['content-type'] in ('image/jpeg',):
with open... | 451d04bcefb3f481befa4823be068ef936e1b8e9 | 637,383 |
import argparse
def build_argument_parser():
"""Build and return the argument parser."""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("filenames", nargs="*", help="Filenames to check.")
parser.add_argumen... | fde4b09fd95197c02648bbbd87498eba8935d252 | 637,384 |
def get_docs(d):
"""
Accepts a dictionary of the form {user: [cleaned word list]} and then
returns the a list of lists, where each outer list is the word list for a
particular user. This forms our document corpus on which we make LDA
predictions.
"""
docs = []
for user in d:
tex... | 0e76ebc8b1a0f986cc00f4f0efaa7b7794676364 | 637,385 |
def get_Pin_ast(DLP, Pout):
""" Calculate Pin_ast for given DLP (or DLP_ast) and Pout
"""
return DLP + Pout | 61cd1c1841a391c48a9fbb8d784ecddf10545429 | 637,386 |
def create_post_url(graph_url, app_id, app_secret):
"""to make the URL"""
post_args = "/?key=value&access_token=" + app_id + "|" + app_secret
post_url = graph_url + post_args
return post_url | a1e79c85847181432b2bcb558b09df495f8b0d59 | 637,387 |
import torch
def padding_map(X, padding_value):
"""
:param X: tensor(batch, max_seq_len)
:param padding_value: token of pad
:return: list of len batch with values of appropriate lengths
"""
return torch.sum((X != padding_value), dim=1) | 6a0953887e138f45fc0910fab94c626ffc707a38 | 637,388 |
def filter_sb_transposon(fusions):
"""Filters fusions with genes related to transposon sequences."""
mask = fusions['fusion_name'].str.contains('En2|Foxf2')
return fusions.loc[~mask] | 7a1d1cf9904b52172e1b8a0a47ba286cd2000084 | 637,389 |
def getValidPublicIpRange():
"""Get list of all valid public IP range
return: ([[long, long], (...)]) List of IP range
"""
# IP range taken from https://en.wikipedia.org/wiki/Reserved_IP_addresses
return [[16777216, 167772159], # 1.0.0.0 to 9.255.255.255
[184549376, 1681915903], # 11.0.0.0 to 10... | 648ab217947c8e9c30e911c452e07cd2652b096b | 637,390 |
def _get_plural_forms(js_translations):
"""Extracts the parameters for what constitutes a plural.
Args:
js_translations: GNUTranslations object to be converted.
Returns:
A tuple of:
A formula for what constitutes a plural
How many plural forms there are
"""
... | 75a229b01e531d3bb0d9d95c0ce9b3868c37d299 | 637,391 |
def get_pubmed_ids(dataframe):
"""Create reference content: Function to seperate pubmed ids to form eutils query string"""
pubmed = dataframe[(dataframe["reference_source"] == "PubMed")
| (dataframe["reference_source"] == "NCCN")
| (dataframe["reference_source"] == ... | cce39ebf3b1e5a28ad86a229c7275bd15191eb23 | 637,392 |
def isWeekend(dt):
"""Finds if a date lies on a weekend or not. Returns a boolean"""
if 0 < dt.weekday() < 6:
return False
else:
return True | 61c1f8df1f8791147c794b60c0f6452b4b540510 | 637,393 |
def get_file_content(filename):
"""Returns the contents of the specified file.
:param filename: The full path/name of the file
:return: The contents of the file
"""
file_contents = ''
with open(filename) as f:
file_contents = f.read()
return file_contents | 6fd24994de7b8cd086a41cb3e9ddb61226c50156 | 637,394 |
def get_incoming_grammatical_relation(sdp, event_token, event_index):
"""First check whether this is a collapesed conj or prep
then search for it in the the rest of the parse.
"""
prep_or_conj=[e for e in sdp if e[0].endswith("_"+event_token)]
if len(prep_or_conj)>0:
return prep_or_conj[0][0... | 297dae60b0f0d79051b03da0983e4aa9f0442597 | 637,395 |
import shutil
def _adjustParams(func, left, bottom, width, height, center, **kwargs):
"""
Returns what the width and height should be set to depending on the current terminal's size, if no width or height
is already set.
:param func: The func parameter. If this is a string, it should be returned as a... | 6a1a235bba669057dce760841bcd94074de0ea23 | 637,396 |
def meanNormalization(data):
"""
Mean Normalize (Standardize data)
"""
std = data.std()
data = data.astype(float)
data -= data.mean()
data /= std
print('-'*70)
print("Mean normalization")
print("mean value =\t\t",data.mean())
print("std value =\t\t",data.std())
... | a454107116ebcfa99705ecbc412a1e7e7f659036 | 637,398 |
def factorial(n):
"""
Return the factorial of a number n.
"""
f = 1.0
for i in range(0, n):
f *= (n - i)
return f | 3019ebb65b71f98720993f421ca2ce8cb175d2f0 | 637,399 |
import os
import hashlib
def get_hash(name):
"""
This function receives the name of the file and returns the hash code
Hash is composed by taking the first and the last 64kb of the video file,
putting all together and generating a md5 of the resulting data (128kb).
Parameters
----------
... | 6f7d2810008baab28d660f4188e9d032d704abee | 637,400 |
def _http_forbidden(start_response):
"""Responds with HTTP 403."""
start_response('403 Forbidden', [('Content-Length', '0')])
return [] | 1bbff6e657c19520afd9176e0e787e31d532c2cc | 637,401 |
def get_movienames2samples_from_header(header):
"""Given an input BAM header dict, return a dict {moviename: sample}.
...doctest:
>>> header = {'RG':[{'ID': 'myid', 'PU': 'mymovie', 'SM': 'mysample'}, {'ID': 'myid2', 'PU':'mymovie2', 'SM': 'mysample2'}]}
>>> d = get_movienames2samples_from_hea... | 1017242b600d01e20a1ded417e01f7e5f74d3708 | 637,402 |
def in2cm_table(start, end, step):
"""convert inch to cm"""
"""and print results"""
#
inches = list(range(start, end + step, step))
inches = [float(inch) for inch in inches]
cms = [inch * 2.54 for inch in inches]
return (inches, cms) | 473a6ff883c8881ee19b84d49e094dac15dd8738 | 637,403 |
def id_mapping(IDs1, IDs2, uniq_ref_only=True, IDs2_sorted=False):
"""
Mapping IDs2 to IDs1. IDs1 (ref id) can have repeat values, but IDs2 need
to only contain unique ids.
Therefore, IDs2[rv_idx] will be the same as IDs1.
Parameters
----------
IDs1 : array_like or list
ids for... | 70f4ca9da834362afb9d4631652421750f299a63 | 637,404 |
def github_site_admin_action(rec):
"""
author: @mimeframe
description: A Github site admin tool/action was used.
Example: 'staff.fake_login'
"A site admin signed into GitHub Enterprise as another user.""
reference: https://help.github.com/enterprise/2.11/ad... | 1766d85d1b7e96dfc080e3c209c48619b683fc98 | 637,405 |
def get_testcase_subdirectory_regex():
"""
Used to get the regex that will match the split test case CWE ID
Starting in 2012 the CWE ID will be of the form: CWEXYZ_s01, CWEXYZ_s02, etc.
"""
return "CWE.*_s\d{2,}$" | 52b7d70ced7bf1405274b26a01f9ae94bcc85243 | 637,406 |
def de_vec(a, rows, cols):
"""Column-major de-vectorization. First dimension is batch dim.
"""
batch = a.size(0)
# dim = math.floor(math.sqrt(a.size(1)))
a_mat = a.reshape(batch, cols, rows).permute(0, 2, 1)
return a_mat | 4a63a655b158de2e714e402b61f402d9876f2e85 | 637,407 |
def set_param(fit_param,param_name,def_val):
"""Helper function for IB.py to handle setting of fit parameters."""
param = fit_param.get(param_name,def_val) # extract param, def = def_val
if param is None: param = def_val # if extracted param is None, use def_val
return param | a69f5be6d464bdbd0274aee98ef330ee9cea71f7 | 637,408 |
import argparse
def parse_cmdline(args):
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description=(
'download_xnat.py downloads xnat dicoms and saves them in BIDs compatible directory format'))
#Required arguments
requiredargs = parser.add_argument_group('... | cc9d969dd21fdf219d04a520f4cebaa238d30140 | 637,409 |
def scale(x, param_scale):
""" Scale each column of matrix by mins and maxes defined in vectors"""
v_min, v_max = param_scale[0], param_scale[1]
v_range = v_max-v_min
v_scaled = (v_range * x) + v_min
return v_scaled | 9da772bfdc35184a7778280de9da74e3210712f4 | 637,410 |
import time
def date_time_string():
"""Return the current date and time formatted for a message header."""
WEEKS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
MONTHS = [
None,
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]
now = t... | 6fe446513c11aec660ecefec21e739c1525dc5b1 | 637,411 |
import hashlib
def get_file_md5(fpath, blocksize=2**20):
"""Get a file's MD5 checksum.
Code from stackoverflow.com/a/1131255
Parameters
----------
fpath : string
Path to file
blocksize : int
Read file in chunks of this many bytes
Returns
-------
md5sum : string
... | 1df1e6c31ab30f025b27dc7d8a4b89146858bdf6 | 637,412 |
def xsd_datetime_str_from_dt(dt):
"""Format datetime to a xs:dateTime string.
Args:
dt : datetime
- tz-aware: Used in the formatted string.
- tz-naive: Assumed to be in UTC.
Returns:
str
The returned format can be used as the date in xs:dateTime XML elements. It
... | c722a88a1eee276342066af2098d404f8302863a | 637,413 |
from typing import Mapping
def parse_kv_list(params):
"""Create a dict from a "key=value" list.
Parameters
----------
params : sequence of str or mapping
For a sequence, each item should have the form "<key>=<value". If
`params` is a mapping, it will be returned as is.
Returns
... | 083f0941f23a61d9a99ad5bf08749a50a0038248 | 637,414 |
def process_result(result: dict):
"""Processes single surveyjs result"""
target = {}
for variable in result:
if isinstance(result[variable], dict):
for key in result[variable]:
target[str(variable) + '_' + str(key)] = result[variable][key]
else:
target... | 75b5e25fccc13d0b7f19cf8d71ca59b9476ce3a3 | 637,415 |
def change_label(tweets):
"""
DESCRIPTION:
transorms labels {1,-1} to {__label__1, __label__-1} for fasttext representation
INPUT:
tweets: Dataframe of train tweets
OUTPUT:
transformed representation, compatible with fasttext input
"""
return tweets.apply(l... | e9ab9f7b58336d80e284e138c1bb180c7d0e2fbf | 637,416 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.