content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import asyncio
async def preprocessor(input_data: str):
"""Simple feature processing that converts str to int"""
await asyncio.sleep(0.1) # Manual delay for blocking computation
return int(input_data) | f32deb8fa261f7ab72a024e056a41025f1cdf9b2 | 673,158 |
def _power_of_two(value):
"""Returns whether the given value is a power of two."""
return (value & (value - 1)) == 0 | b7493be7fc11cf92ad73fcdffda462aaa60ce623 | 673,159 |
def snake_to_camel(s: str) -> str:
"""Convert string from snake case to camel case."""
fragments = s.split('_')
return fragments[0] + ''.join(x.title() for x in fragments[1:]) | 5593e29ed345861dd0bada4a163c5006042a9fdb | 673,162 |
def _get_norm_procedure(norm, parameter):
"""
Returns methods description of the provided `norm`
Parameters
----------
norm : str
Normalization procedure
Returns
-------
procedure : str
Reporting procedures
"""
if parameter not in ('sample_norm', 'gene_norm'):
... | ef1f16cffedafb90675239823aec52791c5d2fae | 673,165 |
from typing import Dict
from typing import Union
from typing import List
import json
import base64
def extract_syft_metadata(data: str) -> Dict[str, Union[str, List[str], bytes]]:
"""
Parse metadata from the syft output string
:param data: syft SBOM json string
:type data: str
:return: dict with ... | f375a7bcd1ad3e6df9e83befb0c0d7abd7db0f98 | 673,167 |
def getMObjectByMDagPath(dagPath):
"""
Retrieves an MObject from the given MDagPath.
:type dagPath: om.MDagPath
:rtype: om.MObject
"""
return dagPath.node() | 019b6c47f6b65582cb46a846987b53b27ee0e325 | 673,170 |
from typing import List
from typing import Tuple
def split_series(
series: List,
*,
reserved_ratio: float = 0.2,
test_ratio: float = 0.5,
) -> Tuple[List, List, List]:
"""
Split a series into 3 parts - training, validation and test.
Parameters
----------
series
a time seri... | 1e8e249f6c156f48071a1ca5892e47ea19dd00e1 | 673,171 |
import datetime
def group_datetime(d, interval):
"""Group datetime in bins."""
seconds = d.second + d.hour * 3600 + d.minute * 60 + d.microsecond / 1000
k = d - datetime.timedelta(seconds=seconds % interval)
return datetime.datetime(k.year, k.month, k.day, k.hour, k.minute, k.second) | bba4a6a8eb789af7f8825cb4c4e8fc8073892dd2 | 673,178 |
import re
def regex_match(pattern):
"""A curried regex match. Gets a pattern and returns a function that expects a text to match the pattern with.
>>> regex_match(r"phone:(\d*)")("phone:1234567").group(1) # noqa: W605
'1234567'
"""
def regex_match_inner(text):
return re.match(pattern, ... | ae466d108291fecc1cca985c0caa9d98c75e3d0a | 673,180 |
def public(fun, scope=None, cookie=False):
"""
Functions that allow any client access, including those that haven't logged
in should be wrapped in this decorator.
:param fun: A REST endpoint.
:type fun: callable
:param scope: The scope or list of scopes required for this token.
:type scope:... | dad6ba65416ae1cfca26284439c0da7d17dba7e4 | 673,181 |
def flip_second_half_direction(team):
"""
Flip coordinates in second half so that each team always shoots in the same direction through the match.
"""
second_half_idx = team.Period.idxmax(2)
columns = [c for c in team.columns if c[-1].lower() in ["x", "y"]]
team.loc[second_half_idx:, columns] *=... | 65f32282e3f04c3c2a703a852f0f8ce23b6ddabf | 673,184 |
import math
def fuel_counter(masses):
"""Function that computes the fuel needed for the input masses.
Expected input is required to either be a list/tuple or scalar"""
if isinstance(masses, (tuple, list)):
return sum(fuel_counter(mass) for mass in masses)
return max(int(math.floor(masses / 3) ... | f4cfa540502bbd4a3eb0c06415dbd9e0e00979cf | 673,185 |
def shutdown_cost_rule(mod, prj, tmp):
"""
If no shutdown_cost_rule is specified in an operational type module, the
default shutdown fuel cost is 0.
"""
return 0 | 5f7c87ed85f77b16e596eaf9c2e360a0891696ec | 673,186 |
def list_medias(api, lang, **params):
# type (ApiClient, str, dict) -> (Iterable[dict])
"""List all the medias.
Args:
api (object): The ApiClient instance used for request.
lang (str): the lang. Defaults to english (en).
``**params``: optional dictionary of search p... | ce2fad1fa02bf69dc4279f9aa7178d2560220209 | 673,188 |
def pseudo_residual_regression(target, output):
"""Compute the pseudo residual for regression with least square error."""
if target.size() != output.size():
msg = "The shape of target {} should be the same as output {}."
raise ValueError(msg.format(target.size(), output.size()))
return targ... | 0a346bd827be414cbd52a1905ebaa1b093738065 | 673,190 |
def plural(text, num):
"""Pluralizer: adds "s" at the end of a string if a given number is > 1
"""
return "%s%s" % (text, "s"[num == 1:]) | b958a7b57f95323fbf40fef28dea4e267581330e | 673,195 |
def get_time_signature(h5,songidx=0):
"""
Get signature from a HDF5 song file, by default the first song in it
"""
return h5.root.analysis.songs.cols.time_signature[songidx] | 322c18f45daa7a59d47c1edfac10334fd5071c6a | 673,196 |
def hamming_distance(a, b):
"""
Counts number of nonequal matched elements in two iterables
"""
return sum([int(i != j) for i, j in zip(a, b)]) | 425644ad818f8ee3862bab7b8d15b0e5f8a65e12 | 673,201 |
import torch
def EER(positive_scores, negative_scores):
"""Computes the EER (and its threshold).
Arguments
---------
positive_scores : torch.tensor
The scores from entries of the same class.
negative_scores : torch.tensor
The scores from entries of different classes.
Example
... | 414f162cc43e7b74056e24b46a3b0be71ec10f42 | 673,202 |
def get_tensor_shape(x):
"""
Get the shape of tensor
Parameters
----------
x : tensor
type float16, float32, float64, int32, complex64, complex128.
Returns
-------
list.
Examples
---------
>>> import tensorlayerx as tlx
>>> x_in = tlx.layers.Input((32, 3, ... | 0b84762060c8ddd0c4d571eedfe7c67c7e1f3d00 | 673,205 |
import typing
def validate_list(expected, lst: list) -> typing.Union[str, bool]:
"""
Validate a list against our expected schema.
Returns False if the list is valid.
Returns error in string format if invalid.
"""
if not isinstance(lst, list):
return "Expected argument of type `%s`, g... | 1318eaa1b8b4b1730b356475d5b2a3bdc037405f | 673,211 |
from typing import Any
def get_nested(the_dict: dict, nested_key: str, default: Any = None) -> Any:
"""
Returns the value of a nested key in an dictorinary
Args:
the_dict (dict): The dictionary to get the nested value from
nested_key (str): The nested key
default: The value to be ... | a7ad16c4cdf48dd2b48fa82081a2f1a8b57a78a5 | 673,213 |
import re
def percent_decode(data):
""" Percent decode a string of data.
"""
if data is None:
return None
percent_code = re.compile("(%[0-9A-Fa-f]{2})")
try:
bits = percent_code.split(data)
except TypeError:
bits = percent_code.split(str(data))
out = bytearray()
... | b47f6a469056540a2df0d07009b3328d74e024a6 | 673,214 |
def always_do(action):
"""Returns a policy that always takes the given action."""
def policy(state, rng):
return action
return policy | d8c2f33f0dbe8a112e6472b8e14466b2bdb824a4 | 673,217 |
from typing import Sequence
def read_containers(text: str) -> Sequence[int]:
"""
Read the puzzle input into a list of integers representing the container sizes.
"""
return [int(line) for line in text.split("\n")] | 4c0b4dcd80a7934da4560d21d14a5962446d5db8 | 673,219 |
import random
import string
def get_job_id(length=8):
"""Create random job id."""
return "".join(random.choice(string.hexdigits) for x in range(length)) | e968b8e1a466b35545a23e01fe6905f9003eab8c | 673,220 |
import math
def circle_area(diameter):
"""Returns the area of a circle with a diameter of diameter."""
return 1/4*math.pi*(diameter**2) | 67d8225e6e8d1cf9e7c56e265ee067db71c03dfe | 673,221 |
import warnings
def create_gobnilp_settings(score_type, palim=None, alpha=None):
"""
Creates a string of Gobnilp settings given the allowed arities and parent size.
Parameters
----------
score_type : int
The scoring function used to learn the network
0 for BDeu or 2 for BIC
pa... | c78cdb0c4d5351adeca894c8869a4429f3c34578 | 673,222 |
def binary_search(array, item):
"""function to search for the value in a list
Args:
array(list): a sorted list of values
item: the value to be searched for in the array
Returns:
the position of the item from the list or a not found
"""
low = 0
high = len(array) - 1
"""whenever a search is ... | 99b7dc0038ada278090514935924901923824a66 | 673,226 |
def _axes_to_sum(child, parent):
"""Find the indexes of axes that should be summed in `child` to get `parent`"""
return tuple(child.index(i) for i in child if i not in parent) | f7606521efa00be87f1dda2e3940be178c92a530 | 673,228 |
def minimax(val, low, high):
""" Return value forced within range """
try:
val = int(val)
except:
val = 0
if val < low:
return low
if val > high:
return high
return val | 9fdbc8ba8306fc53c4d938b70316b6ea569ebcc3 | 673,229 |
from typing import Tuple
import configparser
def read_login() -> Tuple[str, str]:
"""
read login from file
:return: mail & password
"""
config = configparser.ConfigParser()
config.read("login.ini")
mail = config.get("LOGIN", "email")
password = config.get("LOGIN", "password")
r... | ca4c3ef1cba83be231b7e1c7d84f838a3bcb8f1a | 673,230 |
def rom_to_hex(rom):
"""Convert rom bytearray to hex string."""
return ''.join('{:02x}'.format(x) for x in rom) | e158aba27f2ae3654118ab948aafd0f873ae9e3e | 673,231 |
def remove_nipsa_action(index, annotation):
"""Return an Elasticsearch action to remove NIPSA from the annotation."""
source = annotation["_source"].copy()
source.pop("nipsa", None)
return {
"_op_type": "index",
"_index": index,
"_type": "annotation",
"_id": annotation["_... | 2a997bb9b79f81b203dcfbb198e83e5a8f8d37f5 | 673,232 |
def read_queries(file, interactive=False):
""" Return list of reference and generated queries """
query_list = []
with open(file, 'r') as src:
for line in src.readlines():
if interactive is True:
reference, gen = line.strip('\n').split(",")
else:
... | 4efe991fa364ede10da23a141ed988df6134e7c9 | 673,233 |
def _insert_char_at_pos(text, pos, ch):
"""
Inserts a character at the given position in string.
"""
return text[:pos] + ch + text[pos:] | 0a552d89aca58e1651d513b4543fb4393439dd85 | 673,234 |
def mk_lst(values, unlst=False):
"""
while iterating through several type of lists and items it is convenient to
assume that we recieve a list, use this function to accomplish this. It
also convenient to be able to return the original type after were done
with it.
"""
# Not a list, were not ... | 670064588bed9f7dd22d3605412a657ddd5204fc | 673,237 |
def image_shape(images):
"""Check if all image in `images` have same shape and return that shape."""
shape = None
for image in images:
if not shape:
shape = image.shape
else:
if shape != image.shape:
raise ValueError
return shape | a5724f023f7c0b5602915bd2cfa1c766e068580e | 673,239 |
def trim_description(desc: str, n_words: int) -> str:
"""Return the first `n_words` words of description `desc`/"""
return " ".join(str(desc).split(" ")[0:n_words]) | f0b1a38374455e8e02f8271161a822d8e2e964b6 | 673,241 |
def ahs_url_helper(build_url, config, args):
"""Based on the configured year, get the version arg and replace it into the URL."""
version = config["years"][args["year"]]
url = build_url
url = url.replace("__ver__", version)
return [url] | 0113cfb558e1e23d9f1f25c35e8553796afedd5f | 673,243 |
import uuid
import json
def create_event(_action, _data):
"""
Create an event.
:param _action: The event action.
:param _data: A dict with the event data.
:return: A dict with the event information.
"""
return {
'event_id': str(uuid.uuid4()),
'event_action': _action,
... | a941043851672a4741696047795f08b2050d007e | 673,245 |
def level_up_reward(level, new_level):
""" Coins rewarded when upgrading to new_level. """
coins = 0
while level < new_level:
coins += 5 + level // 15
level += 1
return coins | a655e7e297b1b84d9d20a2873274d7c05ad65544 | 673,249 |
def substitute_str_idx(s: str, r: str, i: int) -> str:
"""Substitute char at position
Arguments:
s: The str in which to substitute
r: The char to substitute
i: index of the substitution
Returns:
The string `s` with the i'th char substitute with `r`
"""
z = ''.join([(lambda: r,... | 9cdef667249c3447338085ff47de01a58a192be2 | 673,251 |
def rotate_address(level, address, rotate_num):
"""Rotates the address with respect to rotational symmetries of SG
Args:
level: A nonnegative integer representing the level of SG we're
working with.
address: np.array of size (level+1) representing the address
vector of... | 98048b7d1a6de2a35da55e181f8d7ac4a1bc00f9 | 673,253 |
def get_key(file_name):
"""
Get id from file name
"""
return file_name.split('-')[0] | 500b76f9d0656191759c9fc0be75b0e62c1cba62 | 673,254 |
from tabulate import tabulate
from typing import List
def convert_cross_package_dependencies_to_table(
cross_package_dependencies: List[str],
markdown: bool = True,
) -> str:
"""
Converts cross-package dependencies to a markdown table
:param cross_package_dependencies: list of cross-package depend... | b7753975c3896d7842a8f13f8e2c45a5b044cc6f | 673,255 |
def calc_league_points(pos_map, dsq_list):
"""
A function to work out the league points for each zone, given the rankings within that game.
@param pos_map: a dict of position to array of zone numbers.
@param dsq_list: a list of zones that shouldn't be awarded league points.
@returns: a dict of zone number to leagu... | 72df0c18d919fbdec2241e45337dfdab943fba8a | 673,256 |
def getEnd(timefile, end_ind):
"""
Parameter
----------
timefile : array-like 1d
the timefile.
end_ind : integer
the end index.
Returns
-------
the end of the condition.
"""
return timefile['ConditionTime'][end_ind] | 74b31b3028eece0a1398161548cfdb429b7af6a8 | 673,258 |
from typing import List
def split_module_names(mod_name: str) -> List[str]:
"""Return the module and all parent module names.
So, if `mod_name` is 'a.b.c', this function will return
['a.b.c', 'a.b', and 'a'].
"""
out = [mod_name]
while '.' in mod_name:
mod_name = mod_name.rsplit('.', ... | f1a8423f5446b7d05c52789194f431e0220f5fa0 | 673,262 |
def import_class(name):
"""Import class from string.
Args:
name (str): class path
Example:
>>> model_cls = import_class("tfchat.models.PreLNDecoder")
"""
components = name.split(".")
mod = __import__(".".join(components[:-1]), fromlist=[components[-1]])
return getattr(mod, co... | 051602a7662706403b8841853e20e468f2bc22a7 | 673,265 |
def is_fractional_es(input_str, short_scale=True):
"""
This function takes the given text and checks if it is a fraction.
Args:
text (str): the string to check if fractional
short_scale (bool): use short scale if True, long scale if False
Returns:
(bool) or (float): False if no... | 3ae68829cda38e64bca1f796dd729930b43fffe2 | 673,266 |
from typing import Iterable
from typing import Any
from typing import List
from typing import Set
from typing import Type
def _get_overloaded_args(relevant_args: Iterable[Any]) -> List[Any]:
"""Returns a list of arguments on which to call __torch_function__.
Checks arguments in relevant_args for __torch_func... | 3e39f179e057d813bbb36bb7d4e0ee05cf09ce79 | 673,268 |
def get_view_setting(view, sname, default=None):
"""Check if a setting is view-specific and only then return its value.
Otherwise return `default`.
"""
s = view.settings()
value = s.get(sname)
s.erase(sname)
value2 = s.get(sname)
if value2 == value:
return default
else:
... | 591647a85fd8e6e14df4f04eefbc5ee9bcb2bdf5 | 673,269 |
def strip_comments(lines):
"""
Returns the lines from a list of a lines with comments and trailing
whitespace removed.
>>> strip_comments(['abc', ' ', '# def', 'egh '])
['abc', '', '', 'egh']
It should not remove leading whitespace
>>> strip_comments([' bar # baz'])
[' bar']
It... | eaf3e19d53fc2f57376db4f3fcd91a0e9d6840e7 | 673,271 |
def find_between(s, first, last):
"""
Find sting between two sub-strings
Args:
s: Main string
first: first sub-string
last: second sub-string
Example find_between('[Hello]', '[', ']') -> returns 'Hello'
Returns:
String between the first and second sub-strings, if any... | d2df4c89d63f07678cba8283849917ff767b0903 | 673,284 |
def makeAdder(amount):
"""Make a function that adds the given amount to a number."""
def addAmount(x):
return x + amount
return addAmount | 0c4dc0427f3b30ec4e91dd72f62fe62b494b6074 | 673,285 |
import types
import enum
def skip_non_methods(app, what, name, obj, skip, options):
"""
Skip all class members, that are not methods, enum values or inner
classes, since other attributes are already documented in the class
docstring.
"""
if skip:
return True
if what == "class":
... | 51bbe79bc473e10b6b86114cea42649e4887fa8e | 673,286 |
from typing import Dict
def _answer_types_row(row: Dict[str, str]):
"""
Transform the keys of each answer-type CSV row. If the CSV headers
change, this will make a single place to fix it.
"""
return {
'k': row['Key'],
'c': row['Choices'],
} | 1ff0eddd95a3550209579a96759a0cf2f72d45a3 | 673,288 |
def twos_complement_to_int(val, length=4):
"""
Two's complement representation to integer.
We assume that the number is always negative.
1. Invert all the bits through the number
2. Add one
"""
invertor = int('1' * length, 2)
return -((int(val, 2) ^ invertor) + 1) | 91e4d93bf334b3cc33e94cec407d09f8d74afb6b | 673,290 |
import re
import time
def wait_for_logs(container, predicate, timeout=None, interval=1):
"""
Wait for the container to emit logs satisfying the predicate.
Parameters
----------
container : DockerContainer
Container whose logs to wait for.
predicate : callable or str
Predicate ... | f067485b6681e4b00e2b70a93a39e38b1119df92 | 673,298 |
import shutil
def prepare_empty_dirs(dirs: list):
"""
建立空目录。若已经存在,则删除后创建。
parents=True
Args:
dirs: Path list
Returns:
dirs 中各个目录的句柄
"""
result = []
for d in dirs:
if d.exists():
shutil.rmtree(d.as_posix())
d.mkdir(parents=True, exist_ok=Fal... | a672542576ea7eeff8b99aa43d223cfe48069ecc | 673,300 |
def update_header(login_response, call_header):
"""Function to process and update the header after login"""
token = str(login_response).split()[2] + " " + str(login_response).split()[3]
call_header['Authorization'] = token
return call_header | 5af2fef622bcf76339ac6b968af61ecb0000093c | 673,304 |
import torch
def log2(input, *args, **kwargs):
"""
Returns a new tensor with the logarithm to the base 2 of the elements of ``input``.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.log2(ttorch.tensor([-4.0, -1.0, 0, 2.0, 4.8, 8.0]))
tensor([... | 32064dc7409d35b794df5a7a23894a574c4902bf | 673,310 |
def binary_search(array, x):
"""
Binary search
:param array: array: Must be sorted
:param x: value to search
:return: position where it is found, -1 if not found
"""
lower = 0
upper = len(array)
while lower < upper: # use < instead of <=
mid = lower + (upper - lower) // 2 ... | 087e2f5178bebf8f8e14aa7a92df905bd9da08ba | 673,312 |
def insert_position(player, ship, starting):
"""Insert a valid position (e.g. B2)."""
while True:
if starting:
position = input(player.name + ", where do you want to place your " + ship[0] + "(" + str(ship[1]) + ")? ").upper()
else:
position = input(player.name + ", whe... | d5fd397295661816f3ffb512cab9a45f701a56c1 | 673,313 |
def select_longest_utr3_exonic_content(transcripts):
"""Select transcript(s) with longest UTR3 exonic content"""
ret = [transcripts[0]]
longest = transcripts[0].utr3_exonic_content_length
for i in range(1, len(transcripts)):
t = transcripts[i]
exonic_content_length = t.utr3_exonic_conte... | 46b9fd36b766871169cee7783927934ee356ca6f | 673,314 |
import torch
def _moments(a, b, n):
"""
Computes nth moment of Kumaraswamy using using torch.lgamma
"""
arg1 = 1 + n / a
log_value = torch.lgamma(arg1) + torch.lgamma(b) - torch.lgamma(arg1 + b)
return b * torch.exp(log_value) | 00e38aedd21e7e2ed89bde68b5f6464d4be5a707 | 673,315 |
def single_byte_xor(byte_array, key_byte):
"""XOR every byte in 'byte_array' with the 'key_byte'"""
result = bytearray()
for i in range(0, len(byte_array)):
result.append(byte_array[i] ^ key_byte)
return result | 8f7857f8572a493129fa87ec525c687137deec91 | 673,318 |
def get_region_for_chip(x, y, level=3):
"""Get the region word for the given chip co-ordinates.
Parameters
----------
x : int
x co-ordinate
y : int
y co-ordinate
level : int
Level of region to build. 0 is the most coarse and 3 is the finest.
When 3 is used the sp... | 3b018413e57fc7baa3d36e816b47b545c9d8c1e5 | 673,321 |
def get_calendar_event_id(user, block_key, date_type, hostname):
"""
Creates a unique event id based on a user and a course block key
Parameters:
user (User): The user requesting a calendar event
block_key (str): The block key containing the date for the calendar event
date_type (st... | 0286a74d04a377d8033a901fe394ef2eb8389c1f | 673,325 |
def dnn_activation(data, model, layer_loc, channels=None):
"""
Extract DNN activation from the specified layer
Parameters:
----------
data[tensor]: input stimuli of the model with shape as (n_stim, n_chn, height, width)
model[model]: DNN model
layer_loc[sequence]: a sequence of keys to find... | 516a643b049df7f0b9d4a6be74af6998001eb303 | 673,326 |
from typing import Any
def expected(request) -> Any:
"""Expected test case result."""
return request.param | e7d889f0111fc711b92a8fbdd3d0d4985a166729 | 673,327 |
def clean_path(path):
"""
Add ws:///@user/ prefix if necessary
"""
if path[0:3] != "ws:":
while path and path[0] == "/":
path = path[1:]
path = "ws:///@user/" + path
return path | df4b2f73560121bcc7ba9c14eb7c6035afd3b27d | 673,336 |
def strip_comments(s):
"""Strips the comments from a multi-line string.
>>> strip_comments('hello ;comment\\nworld')
'hello \\nworld'
"""
COMMENT_CHAR = ';'
lines = []
for line in s.split('\n'):
if COMMENT_CHAR in line:
lines.append(line[:line.index(COMMENT_CHAR)])
... | 06674a5e84c9b8e397009d4fac93c76a1b4e07d7 | 673,337 |
def translate_p_vals(pval, as_emoji=True):
""" Translates ambiguous p-values into more meaningful emoji.
Parameters
----------
pval : float
as_emoji : bool (default = True)
Represent the p-vals as emoji. Otherwise, words will be used.
Returns
-------
interpreted : string
"... | 993df8319c2bc6bb201864909289f7efca0aa681 | 673,339 |
def str2LaTeX(python_string):
"""
Function that solves the underscore problem in a python string to
:math:`\LaTeX` string.
Parameters
----------
python_string : `str`
String that needs to be changed.
Returns
-------
LaTeX_string : `str`
String with the new underscor... | 79fca8841215880cd1ff47862672f8d685485ff1 | 673,343 |
import telnetlib
import socket
import logging
import errno
def connect_telnet(router, port):
"""
Establish a telnet connection to a router on a given port
"""
#
# Establish a telnet connection to the router
try:
# Init telnet
telnet_conn = telnetlib.Telnet(router, port, 3)
... | 758b7c32944580415a277ac05a97a74d78a69d12 | 673,350 |
def ip_range(network):
"""Return tuple of low, high IP address for given network"""
num_addresses = network.num_addresses
if num_addresses == 1:
host = network[0]
return host, host
elif num_addresses == 2:
return network[0], network[-1]
else:
return network[1], networ... | b0c4f17e6a8646a92e7141828efc7e364b5a547d | 673,351 |
def none_split(val):
"""Handles calling split on a None value by returning the empty list."""
return val.split(', ') if val else () | 13be5a7ad226c07b70dc566027c17cc19c120510 | 673,356 |
def distinct_terms(n):
"""Finds number of distinct terms a^b for 2<=a<=n, 2<=b<=n"""
return len(set([a**b for a in range(2, n+1) for b in range(2, n+1)])) | 8200593f3966cf04127984311110404402b7847b | 673,362 |
def t01_SimpleGetPut(C, pks, crypto, server):
"""Uploads a single file and checks the downloaded version is correct."""
alice = C("alice")
alice.upload("a", "b")
return float(alice.download("a") == "b") | 6f58d83a48856e339a4698f1717a8b464127e02a | 673,364 |
def get_as_list(base: dict, target):
"""Helper function that returns the target as a list.
:param base: dictionary to query.
:param target: target key.
:return: base[target] as a list (if it isn't already).
"""
if target not in base:
return list()
if not isinstance(base[target], l... | 1b286f90e04fe025ffc63dca41b4c38c920d1fb4 | 673,367 |
def intget(integer, default=None):
"""Returns `integer` as an int or `default` if it can't."""
try:
return int(integer)
except (TypeError, ValueError):
return default | d40bb6d2c1689f4a76b63ac25e86687149a2e120 | 673,372 |
def hexagonal(n):
"""Returns the n-th hexagonal number"""
return n*(2*n-1) | baed71c64f6a0e56f6ad4c4079ea4d217177566d | 673,374 |
def isSubListInListWithIndex(sublist, alist):
"""
Predicates that checks if a list is included in another one
Args:
sublist (list): a (sub)-list of elements.
alist (list): a list in which to look if the sublist is included in.
Result:
(True, Index) if the sublist is included in the l... | 4870f77deaa1837192bd1e217b9dd7ef58935c51 | 673,375 |
def gcd(x: int, y: int) -> int:
"""
Euclidean GCD algorithm (Greatest Common Divisor)
>>> gcd(0, 0)
0
>>> gcd(23, 42)
1
>>> gcd(15, 33)
3
>>> gcd(12345, 67890)
15
"""
return x if y == 0 else gcd(y, x % y) | 8e8f51f703085aabf2bd22bccc6b00f0ded4e9ca | 673,381 |
from glob import glob
def list_files_local(path):
""" Get file list form local folder. """
return glob(path) | e965d76baadba61ffe8c5314396ef9191b7b886d | 673,384 |
def combine(background_img, figure_img):
"""
:param background_img: SimpleImage, the background image
:param figure_img: SimpleImage, the green screen figure image
:return: SimpleImage, the green screen pixels are replaced with pixels of background image
"""
# (x, y) represent every pixel in the... | 07ae5d988fa3c7e5132ad9a50173a682be6cc840 | 673,385 |
import socket
import struct
def ip2long(ip):
"""
Convert IPv4 address in string format into an integer
:param str ip: ipv4 address
:return: ipv4 address
:rtype: integer
"""
packed_ip = socket.inet_aton(ip)
return struct.unpack("!L", packed_ip)[0] | f80a0b9a72ae74543941b082d600201aa793c6ea | 673,387 |
def invert(record):
""" Invert (ID, tokens) to a list of (token, ID)
Args:
record: a pair, (ID, token vector)
Returns:
pairs: a list of pairs of token to ID
"""
return [(k,record[0]) for k,v in record[1].iteritems()] | d4deb41f1572824d2a5c6dfcde12d68df8944f70 | 673,402 |
def inv_map(dictionary: dict):
"""
creates a inverse mapped dictionary of the provided dict
:param dictionary: dictionary to be reverse mapped
:return: inverse mapped dict
"""
return {v: k for k, v in dictionary.items()} | 2182f0537c8a317ec6332a4be03efee5da6b5837 | 673,404 |
import re
def IsValidFolderForType(path, component_type):
"""Checks a folder is named correctly and in a valid tree for component type.
Args:
path: a relative path from ontology root with no leading or trailing
slashes. Path should be the top level for the component.
component_type: the base_lib.Co... | 32b1fdbcec72d9289bb05cad9e93a2090aaaeff2 | 673,410 |
import requests
def get_latest_version_number() -> str:
"""
Gets the latest pip version number from the pypi server.
Returns: (str) the version of the latest pip module
"""
req = requests.get("https://pypi.org/pypi/monolithcaching/json")
return req.json()["info"]["version"] | 12c291049ec873c4d68cc36b9356d481d0ceb090 | 673,412 |
def convert_021_to_022(cfg):
"""Convert rev 0.21 to 0.22
The rev 0.22 only affected the fuzzy logic methods. The membership shape
is now explicit so that the user has the freedom to choose alternatives.
"""
assert ("revision" in cfg) and (cfg["revision"] == "0.21")
cfg["revision"] = 0.22
f... | cc3bf75f041008f26441aa554b311cd756c17962 | 673,413 |
import fnmatch
def filter_tests(tests, filters):
"""Returns a filtered list of tests to run.
The test-filtering semantics are documented in
https://bit.ly/chromium-test-runner-api and
https://bit.ly/chromium-test-list-format, but are as follows:
Each filter is a list of glob expressions, with ea... | 065c2fd7e0d9a8b65ad8da620980ea730080da64 | 673,414 |
def get_all_descendants(root, children_map):
"""
Returns all descendants in the tree of a given root node, recursively
visiting them based on the map from parents to children.
"""
return {root}.union(
*[get_all_descendants(child, children_map)
for child in children_map.get(root, ... | 8a6485c25f05a572e97ec88b35223c0171a90128 | 673,415 |
import time
def curr_time() -> int:
"""Return the current time in ms."""
return int(time.perf_counter() * 1000) | 242df05bb6134261b1c98f945effb247c64ecd93 | 673,419 |
def team_game_result(team, game):
"""Return the final result of the game as it relates to the team"""
if game.winner == team:
return "Win"
elif game.winner and game.winner != team:
return "Lose"
elif game.home_team_score > 0:
return "Tie"
else:
return "Scoreless Tie" | fb5e71326be4c3b4227a3df83d7745478b6ae954 | 673,420 |
def get_assay_collections(assays, irods_backend):
"""Return a list of all assay collection names."""
return [irods_backend.get_path(a) for a in assays] | 72cbd753676515dbcb9894a90c1d1c84a92d83bf | 673,421 |
def fact(n):
"""
Factorial function
:arg n: Number
:returns: factorial of n
"""
if n == 0:
return 1
return n * fact(n - 1) | 64fbfc1870fa4714f1e6f5e219f0e751d339328f | 673,425 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.