content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def replace_negative(l, default_value=0):
"""
Replaces all negative values with default_value
:param l: Original list
:param default_value: The value to replace negatives values with. Default is 0.
:return: Number of values replaced
"""
n_replaced = 0
for i in range(len(l)):
if l[i] < 0:
l[i... | 431781a48a36a00329537b92b589cf223b945ca4 | 13,536 |
from typing import Union
import pathlib
import shutil
import subprocess
def git_commit(path: Union[str, pathlib.Path], error_message: str = 'parent directory is not a repository') -> str:
"""
Finds the current commit of a git repository.
Parameters
----------
path: str or pathlib
The path to the git repositor... | 94839ba6e4ff6c2a23078468b1a920090470a7e8 | 13,537 |
def swap_64b(val):
""" Byte swap val (unsigned int64)
:param val: 64b value
:return: swapped 64b """
tmp = ((val << 8) & 0xFF00FF00FF00FF00) | ((val >> 8) & 0x00FF00FF00FF00FF)
tmp = ((tmp << 16) & 0xFFFF0000FFFF0000) | ((tmp >> 16) & 0x0000FFFF0000FFFF)
tmp = (tmp << 32) | (tmp >> 32)
retur... | 5b7fa81d352e94db03f8089f50fedd0ab7a3903e | 13,538 |
def getClassAttendance(moduleCode):
"""
Will take in the module code and use the code to open the file of the specified module and read it to created
the list of names, presents, absents and excuses. To be return for future use
:param moduleCode:
:return: (list)
"""
classData = open(f"{modul... | a618b90bd6be84fbe23c28ab8d71a57c108b76dc | 13,540 |
def layer_function2(x):
""" lambda function """
return x[0] + x[1] | 62a0ab30432fecad48afa18ecaf7d946ffb0d83b | 13,541 |
import yaml
def get_config(config):
"""Loads a yaml configuration file."""
with open(config, 'r') as stream:
return yaml.load(stream, Loader=yaml.FullLoader) | 58937acf5984b08193c78877fbb94c07c6d779df | 13,542 |
def is_rgb(image):
"""
Return True if image is RGB (ie 3 channels) for pixels in WxH grid
"""
return len(image.shape) == 3 and image.shape[-1] == 3 | f0452fc5f9b6eb69917f8b5de76329eb2e4f03b2 | 13,543 |
def get_method_args_as_dict(locals, should_remove_none=False):
"""
Use inside a class method to get all method arguments as a dictionary.\n
Must pass locals() in at top of method\n
"""
locals.pop("self")
if should_remove_none:
for k, v in locals.items():
if v is None:
... | e9903eb6216b81cb95fbeecaada8f3e34db864ee | 13,545 |
def _attr_list_to_dict(attr_list):
"""
_attr_list_to_dict -- parse a string like: host:ami, ..., host:ami into a
dictionary of the form:
{
host: ami
host: ami
}
if the string is in the form "ami" then parse to format
{
default: ami
}
raises ValueError if lis... | 378b1a55d908750eea2b457e35abce0a17364a41 | 13,547 |
def get_job_locations_from_db(loc_list):
"""Get the number of jobs by country as a dictionary."""
countries = {}
for loc in loc_list:
country = loc.split()[-1].lower()
if country == 'usa' or country == 'states' or country == 'us':
countries.setdefault('usa', 0)
countr... | dd394bc6889be4e87f55bc523e4a9bc5d4ed617a | 13,548 |
def humansize(nbytes):
"""
Translates a size in bytes to a human readable size format
:param int nbytes: integer of size of torrent file
:return: size in bytes in a human readable format
:rtype: str
"""
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
i = 0
while nbytes >= 1024 and i < len(su... | 98390c0f5c471b501caf2fa2bba1e593c8a17eb6 | 13,549 |
def pad_sents(sents, padding_token_index):
"""
Pad the sents(in word index form) into same length so they can form a matrix
# 15447
>>> sents = [[1,2,3], [1,2], [1,2,3,4,5]]
>>> pad_sents(sents, padding_token_index = -1)
[[1, 2, 3, -1, -1], [1, 2, -1, -1, -1], [1, 2, 3, 4, 5]]
"""
... | 0063d8716f7081644e4353de662d58f0dc04e8fe | 13,550 |
import os
def file_extension_detect(filename):
"""Determine if file is notebook or RDF,
based on the file extension.
"""
_, extension = os.path.splitext(filename)
rdf_exts = ['.ttl', '.nt', '.jsonld', '.json']
nb_exts = ['.ipynb']
if extension in rdf_exts:
return 'RDF'
elif ext... | 430cf1b12ae4bde6cc336f58f0a1fdc727369209 | 13,551 |
def clamp(minimum, n, maximum):
"""Return the nearest value to n, that's within minimum to maximum (incl)
"""
return max(minimum, min(n, maximum)) | a3db191a733041196b8a3e0cfc83731e839a14aa | 13,552 |
import sys
def move(start, dir):
"""
"""
if dir == "U":
mv = (-1, 0)
elif dir == "D":
mv = (1, 0)
elif dir == "L":
mv = (0, -1)
elif dir == "R":
mv = (0, 1)
else:
print("Direction needs to be U D L or R. Exiting")
sys.exit(1)
end = (start[0] + mv[0], start[1] + mv[1])
if end[0] < 0 or end[0] > 4... | 7e40bc61eb3d765985207ad62d69683b0546321f | 13,553 |
import operator
def normalize_data(data):
"""Normalizes a sequence of input data according to the heuristic
laid out in the module documentation.
"""
data = data or []
if isinstance(data, dict):
data = [{"key": key, "value": value} for key, value in data.items()]
data.sort(key=oper... | d1cacf020cd8df2762f747a85a41a758e1e12ba8 | 13,554 |
def get_vehicle_mass(vehicle_info):
"""
Get the mass of a carla vehicle (defaults to 1500kg)
:param vehicle_info: the vehicle info
:type vehicle_info: carla_ros_bridge.CarlaEgoVehicleInfo
:return: mass of a carla vehicle [kg]
:rtype: float64
"""
mass = 1500.0
if vehicle_info.mass:
... | 216f109e9f963ba6de92cf168055b1a7e516d777 | 13,555 |
def add_modules_to_metadata(modules, metadata):
"""
modules is a list of lists of otus, metadata is a dictionary of dictionaries where outer dict keys
are features, inner dict keys are metadata names and values are metadata values
"""
for module_, otus in enumerate(modules):
for otu in otus:... | b1dcd3e179a01c11d5a847094ceef4240d2b899e | 13,556 |
def longest_word(list_name):
"""Stores the number of rows. """
long_word = [0] * len(list_name) #Stores number of items in each sublist
i = 0
for column in list_name: #counts words in each sublist
l_word = 0
for word in column:
l_word += 1
long_word[i] = l_word
... | 932f250b50fc3c8161545e7c4741b255483923e5 | 13,557 |
def uvm_object_value_str(v):
"""
Function- uvm_object_value_str
Args:
v (object): Object to convert to string.
Returns:
str: Inst ID for `UVMObject`, otherwise uses str()
"""
if v is None:
return "<null>"
res = ""
if hasattr(v, 'get_inst_id'):
res = "{}".... | e56bd12094923bf052b10dcb47c65a93a03142a2 | 13,558 |
import tqdm
import json
def download_all_dicts_to_file(filename, search, mode='w'):
""" Download data from elastic search server
:param filename: str, name of file to save data
:param search: elasticsearch search object to query
:param mode, char, file write mode (w, a)
:return filename, str:
... | 4abea20e5cd58fa05bd498e4f7462530a2b677fe | 13,561 |
import os
def runcmd(cmd):
"""run command"""
pipe = os.popen('"' + '" "'.join(cmd) + '"', 'r')
std_out = pipe.read()
pipe.close()
return std_out.rstrip('\n') | 45fd11b886bcc37fa927527c67eb4eaaeee5c60d | 13,563 |
def _example_word(lang):
"""
Returns an example word for a given language
:param lang: str Language abbreviation
:return: A word. Should be one early in the vocab for that language
"""
return {
"de": "mann",
"es": "hombre"
}.get(lang) | e9d60f31cb0c5f2b1dd397e19b60a52a43fc41d2 | 13,564 |
def get_object_name(object):
""" Retrieves the name of object.
Parameters:
object (obj): Object to get name.
Returns:
str: Object name.
"""
if object.name[-5:-3] == '}.':
return object.name[:-4]
return object.name | fc695c8bf19817c3217bf6000358695c88de07aa | 13,565 |
def create_nine_digit_product(num):
""" Create a nine digit string resulting from the concatenation of
the product from num and multipliers (1, 2, 3,).... Return 0 if string
cannot be length 9.
"""
result = ''
counter = 1
while len(result) < 9:
result += str(num * counter)
... | 9c6765349edfa7e03dc8d2ffe7bf6a45155f3ad0 | 13,566 |
def peak_indices_to_times(time, picked_peaks):
"""
Converts peak indices to times.
Parameters
----------
time: ndarray
array of time, should match the indices.
picked_peaks: dict
dictionary containing list of indices of peak start, center, and end.
Returns
-----------
... | 99aa76fbc399b2b99d4dc9c8d3e4b67e4ee2d3af | 13,567 |
def es_annotation_doc():
"""
Minimal JSON document for an annotation as returned from Elasticsearch.
This contains only fields which can be assumed to exist on all annotations.
"""
return {
"_id": "annotation_id",
"_source": {
"authority": "hypothes.is",
"tar... | 085f8077d5f5cbf278a3b1be1734de081a55b769 | 13,568 |
def incmean(prevmean, n, x):
"""Calculate incremental mean"""
newmean = prevmean + int(round((x - prevmean) / n))
return newmean | 4176a07d0ad8eb96d3dd5d8b2cb46b8aecd1da20 | 13,569 |
def evenFibSum(limit):
"""Sum even Fib numbers below 'limit'"""
sum = 0
a,b = 1,2
while b < limit:
if b % 2 == 0:
sum += b
a,b = b,a+b
return sum | cdf9cdb1cfb419713e794afff4d806945994692e | 13,570 |
def get_n_first(file_names, checksums, N_first):
"""
Given a list of file_names and a list of checksums, returns the 'N_first'
items from both lists as a zip object.
:param file_names: list of file names
:param checksums: list of sha256 checksums
:param N_first: int or None. If None, all items ... | 13a8157dcd55fa43b0cd71eb877abddc832ff143 | 13,571 |
def get_library(gi, lib_name, lib_desc="", lib_synopsis="", create=True):
"""
Get the id corresponding to given library, and create it if it doesn't exist yet
"""
print("Looking for lib '" + lib_name + "'")
libs = gi.libraries.get_libraries()
found_lib = None
for lib in libs:
if not... | b8f9c6fff4c0162185fc71c08de9ff7b03272d4b | 13,572 |
def state_to_index(valuation, base):
"""
Maps states to an decimal integers.
"""
factor = 1
integer = 0
for i in range(len(valuation)):
integer += factor * valuation[i]
factor *= base
return integer | c05deefd07d0faf2749489fbc6f37576e1433c8d | 13,573 |
def get_lock_path_from_repo(git_repo):
"""
>>> app_module = {'git_repo': 'git@github.com:claranet/ghost.git'}
>>> get_lock_path_from_repo(app_module['git_repo'])
'/ghost/.mirrors/.locks/git@github.com:claranet/ghost.git'
>>> app_module = {'git_repo': ' git@github.com:claranet/spaces.git '}
>>> g... | b722e69dcaa5fd6a6299ee42ddaa7f14097a25a4 | 13,574 |
def get_unique_tasks(*task_groups):
"""
Compare input JSON objects containing tasks and return a unique set
:param json_objects: lists of task objects
:type json_objects: list
:rtype: list
"""
# Combine all sub-json objects into a single group
unique_tasks = []
# Get a list of ta... | c9eb32ea0a953e797ea28021c3a434941f7b05ff | 13,575 |
def directorio_imagen(instance, filename):
"""Obtiene el directorio para guardar las imagenes de los platillos"""
# Obtenemos la extension del archivo para guardar la imagen solo con el id y nombre del platillo
extension = filename.rsplit('.', 1)[1]
return f"platillo/imagen/{instance.id}_{instance.nomb... | 90db760562327a16858e1bf6419fb1ed6e9eeefa | 13,576 |
def cicle_move(A):
"""
move first to last and move elements between first and last 1 element back
:param A: list to execute cicle move
:return:
"""
tmp = A[0]
for i in range(len(A) - 1):
A[i] = A[i + 1]
A[len(A) - 1] = tmp
return A | 4948b863829d77a879ad0ec9745bb3a35e580026 | 13,577 |
def Words_Before_and_after(words, item, nbr):
"""
:param words: list of words
:param item: word of interest
:param nbr: number of words wanted before and after the word of interest
:return: list of words before and after the word of interest
"""
liste = [[words[item], item]]
for n in ran... | 6dc874565a308cc642bf0510a3be56264c6d89e9 | 13,578 |
import yaml
def df_to_yaml(df):
""" conert DataFrame to yaml string """
d = df.to_dict(orient='records')
return yaml.dump(d) | 285b4cad92e73fbaec19e631664bb474ecaf309f | 13,579 |
def get_polar(d, Re=6371.):
""" Convert to polar coordinates """
th = d.grange / Re
r = d.height + Re
dop, sth, dth = d.dop, d.sth, d.dth
return th, r, dop, sth, dth | 1d4710152b5dbbbfd09cdc5cbf934f3adb94deeb | 13,580 |
def _is_new_prototype(caller):
"""Check if prototype is marked as new or was loaded from a saved one."""
return hasattr(caller.ndb._menutree, "olc_new") | 1282db1ce6ae2e5f0bb570b036d7166a53287229 | 13,581 |
def grid(gdf):
"""
sampling the GNSS data by grids
Parameters
----------
gdf: geodataframe
geodataframe of all gnss data(population)
Returns
-------
list:
list of each grid which contains all related gnss data
"""
#create new column to... | f613359a0061fd2975607044ffcaa8b25b53dcfc | 13,584 |
def get_tasks_for_weekly_report(model_obj, company, date_from, date_to):
"""Отдает отфильтрованный кверисет с уникальными датой и описанием"""
return model_obj.objects.select_related(
'tag', 'employees').filter(
date__gte=date_from).filter(
date__lte=date_to).filter(
... | 3b46205d3c1bb5b5d472b350371561167aa2fb5b | 13,585 |
def detectFallingSeq(points_list):
"""Find falling temperatures sequences in given list and stores beginnings and ends of them in list.
Always with format [seq1 start index, seq1 end index, seq2 start index, seq2 end index, ...]
:param points_list: list of pipe temperatures
:return: list of indexes
... | e940497b72745af1669062373a6aca025ac0626c | 13,586 |
def count_symbols(atoms, exclude=()):
"""Count symbols in atoms object, excluding a set of indices
Parameters:
atoms: Atoms object to be grouped
exclude: List of indices to be excluded from the counting
Returns:
Tuple of (symbols, symbolcount)
symbols: The unique symbols in... | 31f7c116f07788171828f0e116ef28a43eb0e313 | 13,587 |
import ntpath
def lookup_folder(event, filesystem):
"""Lookup the parent folder in the filesystem content."""
for dirent in filesystem[event.parent_inode]:
if dirent.type == 'd' and dirent.allocated:
return ntpath.join(dirent.path, event.name) | e18df4610bba9cf71e85fe0038a5daf798822bd3 | 13,588 |
def extract_user(ops, json_data):
""" Extract user from JSON data.
"""
if json_data is None:
return None
if 'required_posting_auths' not in ops or 'required_auths' not in ops:
return None
if ops['required_posting_auths'] is None or ops['required_auths'] is None:
return None
... | 0722afa2f174628670658fbbc0f1a0ab80cd36fe | 13,591 |
def ParseDeviceBlocked(blocked, enable_device):
"""Returns the correct enabled state enum based on args."""
if enable_device is None and blocked is None:
return None
elif enable_device is None or blocked is None:
# In this case there are no default arguments so we should use or.
return blocked is True... | 4554ca5e33194fea77516e910516f3937cd61f3a | 13,592 |
import re
def getNormform(synonym):
"""
"""
a = re.sub("[^a-z0-9]", "", synonym[0:255].lower())
return " ".join(a.split()) | 36d60ad20ff8adee5e4d6f009119026db8a1b874 | 13,593 |
def hidden_digits(time_string):
""" converts time with unknown digits to max time with respect to hours and minutes given starting digits
Args:
time_string (str): a string representing an unknown time
Returns:
max_time_string (str): a string with filled in missing digits for max time
"""... | 15fdefb340ab5fe66b562f0fa642210db138c590 | 13,596 |
def action(method):
""" Marks an agent instance method to be registered as an action
:param method:
:return:
"""
method._register_action = True
return method | 15f32f6acd7e31e50ef3b61d0de04e029e65249a | 13,597 |
import re
def filter_illegal_chars(dirty, repl=''):
"""Remove character which allow to inject code which would be run by
displaying on the page
"""
illegal_chars_re = re.compile('[<>="]')
return illegal_chars_re.sub(repl, dirty) | d389df644959850ccd4de6dd7ab22f0276b47435 | 13,598 |
def exp_np_array_list(lst, power):
"""
Raise elements of a list (of np.arrays - elementwise) to power
@param lst: list of np.arrays
@param power: scalar, to which power the elements should be raised
@rtype list of np.arrays
"""
result = []
for nparr in lst:
result.append(nparr **... | 8c8b80c217f4a381e8514c7fff06dc98114087d9 | 13,599 |
import os
import re
def get_ch_names(path, dir):
"""获取文件中文名称,如无则返回文件名"""
file_ch_names = []
reg = r"new Env\(\"[\S]+?\"\)"
ch_name = False
for file in dir:
try:
if os.path.isdir(f"{path}/{file}"):
file_ch_names.append(file)
elif file.endswith(".js") ... | bae20e2a03b188aeb1f6dae33f6c3a66d26ca48e | 13,600 |
def check_if_significant(data, thresh=1e-5):
"""
trim data based on threshold.
Args:
pandas DataFrame: data needs to be trimmed.
threshold (float): a constant. Default = 1e-5.
Returns:
pandas DataFrame: data after trimming.
pandas DataFrame: corrsponding index of data.... | 62494c97559632f2d8d3e542320cb72f3da90eab | 13,601 |
import datetime
import calendar
def getWeekday(year, month, day):
"""
input: integers year, month, day
output: name of the weekday on that date as a string
"""
date = datetime.date(year, month, day)
return calendar.day_name[date.weekday()] | ca5164b6d7243033f57c3a803301ff3c3ec13d29 | 13,603 |
def rivers_with_station(stations):
"""Creates a list of rivers with at least 1 station"""
rivers = []
for i in stations:
if i.name != None:
if i.river not in rivers:
rivers.append(i.river)
return rivers | f935e97dca96a94d7d3e839b9b5178b701799e08 | 13,605 |
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_create_webex_meeting]
# this may also be the conference id for the developer sandbox
webex_email=
webex_password=
webex_site=
webex_site... | 5e5a1ca7e3402ab177c5805404beb8baed318aaf | 13,607 |
from typing import List
import inspect
def get_function_parameters_list(func) -> List[str]:
"""
Get parameter list of function `func`.
Parameters
----------
func : Callable
A function to get parameter list.
Returns
-------
List[str]
Parameter list
Examples
--... | bff2ec37a5564b87e48abf964d0d42a55f809a16 | 13,608 |
def getSectionText(cd, sectionLabel=None ):
"""
"""
markups = cd.getSectionMarkups(sectionLabel, returnSentenceNumbers=False)
txt = " ".join([m.getText() for m in markups])
return txt | d4bcaa109f5774bd3f5a9abb5a11829061b0ca8f | 13,609 |
def dp_make_weight(egg_weights, target_weight, memo={}):
"""
Find number of eggs to bring back, using the smallest number of eggs. Assumes there is
an infinite supply of eggs of each weight, and there is always a egg of value 1.
Parameters:
egg_weights - tuple of integers, available egg weights sor... | 8546ab2dd0394d2864c23a47ea14614df83ec2f7 | 13,612 |
def get_impact_dates(previous_model, updated_model, impact_date=None,
start=None, end=None, periods=None):
"""
Compute start/end periods and an index, often for impacts of data updates
Parameters
----------
previous_model : MLEModel
Model used to compute default start/e... | b2e6966e0fe2213e504e913d8cd64dbe84fa815b | 13,613 |
def unwrap_value(metadata, attr, default=None):
"""Gets a value like dict.get() with unwrapping it."""
data = metadata.get(attr)
if data is None:
return default
return data[0] | fee5f12f0fba86e221fe722b5829a50706ccd5dc | 13,614 |
import os
def parse_row(row, csv_path):
"""
:param row:
:param csv_path:
:return:
Parse a row of the CSV master file.
"""
table = row["table"]
inputs_dir = os.path.join(csv_path, row["path"])
project_flag = True if int(row["project_input"]) else False
project_is_tx = True if i... | afdabc7dd28f15d7a50e4e81af3434dbed588c80 | 13,615 |
def getTimestamp(self):
"""Get timestamp (sec)"""
return self.seconds + self.picoseconds*1e-12 | 0c913fdcd9a3ce07e31a416208a8488bd41cea81 | 13,616 |
def point_in_polygon(points, x, y):
""" Ray casting algorithm.
Determines how many times a horizontal ray starting from the point
intersects with the sides of the polygon.
If it is an even number of times, the point is outside, if odd, inside.
The algorithm does not always report c... | 26ab72c6b545f94d41b0d1228dd312d590ad208b | 13,619 |
def task3(ob):
"""
Function that take an object as input and prints its docs (__doc__) every sentence in one line.
Input: name of object (e.g. int)
Output: string ready to write.
"""
return ob.__doc__ | 859996692629a61664acf39309741020192f3da5 | 13,620 |
def get_finger_joint_limit_state(x,m):
"""Gets the joint limit state of the finger from a hybrid state"""
return m[3:6] | 90fa8e3dce6c9f9dc08e3e7c2fd9e447690202c1 | 13,622 |
def test_id(id):
"""Convert a test id in JSON into an immutable object that
can be used as a dictionary key"""
if isinstance(id, list):
return tuple(id)
else:
return id | 11e18a57648cb09f680751d1596193020523e5e1 | 13,623 |
import re
def MakeHeaderToken(filename):
"""Generates a header guard token.
Args:
filename: the name of the header file
Returns:
the generated header guard token.
"""
return re.sub('[^A-Z0-9_]', '_', filename.upper()) + '__' | d29f756e30c3214aac174302175c52ca28cad6cb | 13,624 |
def check_byte(b):
"""
Clamp the supplied value to an integer between 0 and 255 inclusive
:param b:
A number
:return:
Integer representation of the number, limited to be between 0 and 255
"""
i = int(b)
if i < 0:
i = 0
elif i > 255:
i = 255
return i | 374e0ffbe1d0baa80c56cafd3650fba8441c5ea0 | 13,625 |
import numpy
def get_signal_to_fluctuation_noise_ratio(signal_array, tfn_array,
roi_size=10):
""" The SFNR image is is obtained by dividing, voxel by voxel,
the mean fMRI signal image by the temporal fluctuation image.
A 21 x 21 voxel ROI, placed in the center of... | 4240adee5062b7a1302f010c92b91ed272287df7 | 13,627 |
def insert(rcd, insert_at_junctions, genotype):
"""
Given the genotype (ie the junction that was chosen), returns the corresponding insert
"""
junctions = ["x", "y", "z"]
if genotype[1] != "-":
j = junctions.index(genotype[1])
return insert_at_junctions[j]
else:
return "-... | 1bf3d7e8bb84659c3992e55fc51490c19701cff0 | 13,628 |
def clone_model(model, **kwargs):
"""Clone an arbitrary sqlalchemy model object without its primary key values."""
table = model.__table__
non_pk_columns = [k for k in table.columns.keys() if k not in table.primary_key]
data = {c: getattr(model, c) for c in non_pk_columns}
data.update(kwargs)
... | 5aa3efe0d508390a7f4ec6f22c0d4ffbfe3f04b5 | 13,629 |
def _convert_labels_for_svm(y):
"""
Convert labels from {0, 1} to {-1, 1}
"""
return 2.*y - 1.0 | eca685bea6fd991245a299999fcbe31cd3b1a9ad | 13,632 |
import numpy
def rgb2hslv(r:numpy.ndarray, g:numpy.ndarray, b:numpy.ndarray):
"""
Convert RGB to HSLV values
Parameters
----------
r, g, b : ndarray
Arrays with red, green, blue channel values (any dims, must match!)
Returns
-------
(h, sl, l, sv, v) : tuple
Hue, ... | f25148f97139315cc7e6d49fa4eacdef286c05b2 | 13,633 |
import math
def chunks(l, n):
"""Divide l into n approximately-even chunks."""
chunksize = int(math.ceil(len(l) / n))
return [l[i:i + chunksize] for i in range(0, len(l), chunksize)] | c7b395dec7939b863097b3da9cdd49fbe2a47740 | 13,634 |
def calcPptm(freq, T):
""" payment time to maturity """
return freq * T | 82c9935494ba32e9f990bdcd87ff86dc34ce7232 | 13,636 |
import re
def isXML(file):
"""Return true if the file has the .xml extension."""
return re.search("\.xml$", file) != None | 7fcfbb105a59f7ed6b14aa8aa183aae3fdbe082d | 13,637 |
def abs(n):
"""
this is abs function
example:
>>> abs(1)
1
>>> abs(-1)
1
>>> abs(0)
0
"""
return n if n>=0 else (-n) | 0e2c42526deca4658e65cbe6c9954e88cb5d9ff6 | 13,638 |
def add1(arr1, arr2):
"""
This version is hard-coded to accept 2 arrays only.
"""
output = []
for inner_list1, inner_list2 in zip(arr1, arr2):
inner_output = []
for num1, num2 in zip(inner_list1, inner_list2):
inner_output.append(num1 + num2)
output.append(inner_o... | 7d90bb432f77c34e743282e391c4ffe38623d659 | 13,639 |
def aggPosition(x):
"""Aggregate position data inside a segment
Args:
x: Position values in a segment
Returns:
Aggregated position (single value)
"""
return x.mean() | e9305d26f05710cc467a7fa9fd7b87737b8aa915 | 13,641 |
import functools
def wraps(wrapped, wrapper):
"""Contionally copies all the attributes a Wapi function can define"""
assigned = ('__module__', '__name__', '__doc__')
conditionally_assigned = ('_required_parameters_',
'_optional_parameters_',
'_read_only_',
'_write_only_',
'... | 0ffeebc62b9c5569ff991fcd09cfbdb425d9f267 | 13,642 |
from typing import Tuple
def empty_handler() -> Tuple[()]:
""" A stub function that represents a handler that does nothing
"""
return () | 1450ea04fefc4ad432e5d66a765bda0f5239b002 | 13,643 |
import torch
from typing import Tuple
from typing import Union
import warnings
def data_parallel(raw_model: torch.nn.Module, *args, **kwargs) -> Tuple[Union[torch.nn.Module, torch.nn.parallel.DataParallel], bool]:
"""
Make a `torch.nn.Module` data parallel
- Parameters:
- raw_model: A target `tor... | 5b98f0e7c67ac067aba9a9c5202cceded91827ac | 13,644 |
def collide_circle(left, right):
"""detect collision between two sprites using circles
pygame.sprite.collide_circle(left, right): return bool
Tests for collision between two sprites by testing whether two circles
centered on the sprites overlap. If the sprites have a "radius" attribute,
then that ... | 3e55b7b854bcc3032e93cad79f00b28b3f14715d | 13,645 |
from typing import Optional
from typing import Dict
import os
import sys
def _prepare_build_environment(cross_lib: Optional[str]) -> Dict[str, str]:
"""Prepares environment variables to use when executing cargo build."""
# Make sure that if pythonXX-sys is used, it builds against the current
# executing ... | ef861b68dbdbef382afa03358f010ae281746943 | 13,648 |
def get_visibilty(item_container):
""" """
if item_container.visible_start == item_container.visible_end:
return ' <i>[' + u'%s' % item_container.visible_start.strftime('%d.%m.%Y') + ']</i>'
else:
return ' <i>[' + u'%s-%s' % \
( item_container.visible_start.strftime('%d.%m.%Y'),
... | ac3b433651acb5743ed6bcef88594575144312da | 13,649 |
def get_cube_time_info(cube):
"""Return year, month and day from the cube."""
coord_time = cube.coord('time')
time = coord_time.cell(0).point
time_step = time.strftime("%Y%m%d")
return time_step | 35ea97aaecd41a4494753c11abd2ba6c9737faad | 13,650 |
def get_elmo(model, words, batch_size=16):
"""
Get elmo embeddings
:param words: list
:param model: elmo model
:param batch_size: batch size (should be 16)
:return:
"""
vector_list = []
# Create batches
batch = []
for i in range(0, len(words)):
word = words[i]
... | c258bc53b381bee952cbdda883e882f98ce2597b | 13,651 |
def comparador_3numeros(a,b,c):
"""int,int,int-->int,int,int
OBJ:comparar los números introducidos"""
if a>b and b>c: sol=str(a > b > c)
elif a>b and c>b: sol=str(a > c > b)
elif a<b and a>c: sol=str(b > a > c)
elif c<b and a<c: sol=str(b > c > a)
elif c>a and a>b: sol=str(c > a > b)
els... | 6d0fee4cffb72b41641702821491d98cd69bccb0 | 13,652 |
def get_discussions(book_object):
"""
获得本书所有的讨论
:param book_object: Book模型实例
:return: 本书所有讨论的列表
"""
return book_object.discussions.order_by('-pub_date').all() | 842a158a18e1e7a31579f409997d56a452f1cf61 | 13,655 |
import os
import re
import time
def get_version(package):
"""
Return package version as listed in `__version__` in `__init__.py`.
"""
init_py = open(os.path.join(package, '__init__.py')).read()
mth = re.search("__version__\s?=\s?['\"]([^'\"]+)['\"]", init_py)
if mth:
return mth.group(1... | 776afb3f41e18f2034bbd914b44018795ca13db3 | 13,656 |
def _object_format(o):
""" Object arrays containing lists should be printed unambiguously """
if type(o) is list:
fmt = 'list({!r})'
else:
fmt = '{!r}'
return fmt.format(o) | c71c0713d5b44c4733bc934d6026431e919db252 | 13,658 |
import traceback
def handle_error(error):
"""Error handler when a routed function raises unhandled error"""
print(traceback.format_exc())
return 'Internal Server Error', 500 | d93d3c4bbabb578b28ade961bb46793187a5ee06 | 13,659 |
import os
def pretty_path(input_path):
""" return path string replacing '~' for home directory """
home_path = os.path.expanduser('~')
cwd_path = os.getcwd()
output_path = input_path.replace(home_path, '~').replace(cwd_path, './')
return output_path | b10bc85e4fba7ac7c73b53bc2bf5c8a61573e39f | 13,660 |
import colorsys
def scale_lightness(rgb, scale_l):
"""
Scales the lightness of a color. Takes in a color defined in RGB, converts to HLS, lightens
by a factor, and then converts back to RGB.
"""
# converts rgb to hls
h, l, s = colorsys.rgb_to_hls(*rgb)
# manipulates h, l, s values and retu... | 2fee635f26419cfe8abc21edb0092a8c916df6ef | 13,661 |
import torch
def dummy_compute() -> torch.Tensor:
"""
returns a predefined size random Tensor
"""
return torch.rand(100, 100) | 9b1c05359c9b57573bd2771124e878ccee7eae87 | 13,662 |
def raster2array(rasters,band_no=1):
"""
Arguments:
rast A gdal Raster object
band_no band numerical order
Example :
raster = gdal.Open(rasterfn)
raster2array(raster,1)
"""
bands = rasters.RasterCount
if band_no>0 and band_no <=bands:
band = rasters.Get... | 76bdcffbf22a0936fe24c29eba975f21edd7cd41 | 13,663 |
def early_stopping(cost, opt_cost, threshold, patience, count):
"""
Determines if you should stop gradient descent. Early stopping should
occur when the validation cost of the network has not decreased relative
to the optimal validation cost by more than the threshold over a specific
patience count
... | 5baea9f867e8ca8326270f250327494a5c47af46 | 13,664 |
def is_if_then(tokens):
""":note: we assume single-line if have been
transformed in preprocessing step."""
return tokens[0:1+1] == ["if","("] | aa1a946ed94299e689534ca98dcf1d0fa9bdca32 | 13,667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.