content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def predict(svc, reduced_x_test):
"""
The method predicts outputs for test samples by using learning model.
Parameters:
-----------
svc: trained learning model
reduced_x_test: features of testing set lying on principal component axes """
predictions = svc.predict(reduced_x_test)
retur... | 7c84374f5c43bfa855a0ef557a2c62f7b4f11f9a | 602,080 |
def list_texts(texts):
"""
Compile (Oxford) comma-delimited list of texts.
:param texts: [list] non-empty sequence of texts
:return: compiled text
"""
all_texts_but_last = texts[:-1]
if all_texts_but_last:
last_delimiter = (',' if len(all_texts_but_last) > 1 else '') + ' and '
... | 19bb6f12ad3b2ee72837065739fe1514e137ad95 | 602,083 |
import json
def load_metrics(source_file):
"""Reads the json file of metric definitions and returns a map of metric names to
metric definitions"""
raw_metrics = json.loads(open(source_file).read())
metrics = { }
for m in raw_metrics:
if m['key'] in metrics:
assert False, "Metric key %s already ... | 02a3390d25f2f5b18a6a231d7cd94d83b9fa048e | 602,084 |
def get_target(directions:list[int]) -> tuple[int, int]:
"""Gets the coordinates of the target following directions.
x axis runs E, y runs NE"""
x = y = 0
for direction in directions:
if direction == 0:
x += 1
elif direction == 1:
y += 1
elif direction ==... | 0542756616f8c056a484e0e6f5101ec355081892 | 602,090 |
def get_max_size(image_list):
""" Calculate the maximum height and width of all images in image_list.
Parameters
----------
image_list : list
List of images
"""
width_max = 0;
height_max = 0;
for image in image_list:
image_size = image.size
width... | 660a346e6946a83310c94cc24d515a3532877c93 | 602,092 |
import random
import math
def convert_to_polar(N):
"""
Generate a random set of N (x,y) cartesian coordinates,
convert them to polar coordinates.
Hints
tuple (a,b) in python is a sequence of immutable data.
"""
cartesian_set = []
a = 0
while a < N :
cartesian_set.ap... | c06c10a29ddd0d445f17c8c249e6796e6debb681 | 602,094 |
def format_position(position):
"""formats an ir_pb2.Position to "line:column" form."""
return "{}:{}".format(position.line, position.column) | fd12a0c1e5219c1eba201450dd0189844f40dfc0 | 602,098 |
import re
def bin_search_tag(fbin, st_tag):
"""search a tag from a binary file
The st_tag is either a double word little endian integer or bytes/bytearray format
:param fbin: input filename
:param dw_tag: double word tag, example 0x02B3CE1D
:returns lst_addr: list of addresses of all occurances of the tag... | fddcb7322e05a7e8595fa3374daddfda7c90a701 | 602,099 |
def calc_fitness(t, max_t, x, dx, theta, dtheta):
"""Calculate genome fitness. This fitness function is designed to minimise
pole oscillations.
Args:
t (int): The number of time steps the agent balanced the pole for.
max_t (int): The maximum number of time steps (solution threshold).
... | 9c5395ddb75b52a157bf1a4b9e7df1360461c9a3 | 602,101 |
def webhook(*args, **kwargs):
"""
Decorator to mark plugin functions as entry points for web calls
* route - web route to register, uses Flask syntax
* method - GET/POST, defaults to POST
"""
def wrapper(func):
func.is_webhook = True
func.route = args[0]
func.form_param... | 8528199400760f4def7015e47092faec9d8141d6 | 602,104 |
def is_admin(user):
"""return true if the user belongs to the admin group, false otherwise"""
if user.groups.filter(name="admin").exists() or user.is_superuser:
return True
else:
return False | 8dd6dc8d587921c69707be43da9bfe0ec06afaf4 | 602,106 |
def search_ceiling_of_a_number(arr: list[int], val: int) -> int:
"""Binary search to find the ceiling of a given number.
The ceiling of a number is defined to be
the smallest element *greater than OR equal* to val.
Complexity:
Time: O(logn) & Ω(1)
Space: O(1)
Args:
arr: ar... | 35ee9bc7fd490de07155728d21f4cba42bea5178 | 602,107 |
def textparts(msg):
"""Return a set of all msg parts with content maintype 'text'."""
return set(filter(lambda part: part.get_content_maintype() == 'text',
msg.walk())) | 9d1afacafa7f3b4054f77aa23a2c122b8c32b612 | 602,112 |
def moffat_r(r, alpha, beta):
"""
Moffat profile
:param r: radial coordinate
:param alpha:
:param beta:
:return:
"""
return 2. * (beta -1) / alpha ** 2 * (1 + (r/alpha) ** 2) ** (-beta) | af67976f33cd626a4bc388322aa0d274d38ca05b | 602,114 |
def getitem(data, item):
"""Implementation of `getitem`."""
return data.__getitem__(item) | 73c8ae50345f1a6b2cc3b026cae3b7be324726b7 | 602,117 |
def order(a, b):
"""order(a, b)
Returns ordered tuple made of a and b"""
return (a, b) if a<b else (b, a) | 11d30d9a5931a456222b2a5fb02e7cea55288817 | 602,118 |
def split_kwargs(original, anothers):
"""split a dict to 2 dicts.
Args:
original: original data.
antohers: the elments will be put the other dict if its key in
this tuple.
Returns: (original, new)
"""
new = {}
for key in anothers:
try:
new[... | 51834a82ece3349bf4550effc6e033cbf2c70a37 | 602,121 |
def update_trx_osnr(equipment):
"""add sys_margins to all Transceivers OSNR values"""
for trx in equipment['Transceiver'].values():
for m in trx.mode:
m['OSNR'] = m['OSNR'] + equipment['SI']['default'].sys_margins
return equipment | 09610fc51298c98678e2a069bbd61d3f0eadca89 | 602,123 |
def _erbn_to_freq(e):
"""Convert ERB number to frequency"""
return (10 ** (e / 21.4) - 1) / 0.00437 | 68887dbfe1eef7fb9dc06539fed4da8f7f30c30b | 602,126 |
def group4_forward_branch(layer, in_tensor):
"""Defines group 1 connections.
Args:
layer (torch.nn.Module):
Network layer.
in_tensor (torch.Tensor):
Input tensor.
Returns:
torch.Tensor: Output of group 1 layer.
"""
a = layer["up1"](in_tensor)
re... | 3a8ce771ac18fe00b033233482b8084c0692de00 | 602,127 |
import torch
def _batch_concat_with_no_op(tensors):
"""If there is only one tensor to concatenate, this is a no-op."""
if len(tensors) == 1:
return tensors[0].detach()
else:
return torch.concat(tensors, dim=0).detach() | 2ac71626e1a1555a0812eff9ef4c311432c5dd29 | 602,128 |
import re
def is_valid_recurrence(text):
"""Check that ``text`` is a valid recurrence string.
A valid recurrence string is ``DAILY``, ``ONCE``, ``WEEKDAYS``,
``WEEKENDS`` or of the form ``ON_DDDDDD`` where ``D`` is a number from 0-7
representing a day of the week (Sunday is 0), e.g. ``ON_034`` meani... | 2a485336ee532b16a0dba058a1b33ba4c43e239e | 602,137 |
def sep(*args):
"""join strings or list of strings ignoring None values"""
return ' '.join(a for a in args if a) | 322d9a3875c249f1d4512b1254b22916db15619f | 602,141 |
def params(req, resp):
""" Params from the URL string """
return req.params | 2f8f072d3b6610ee0885d1ce53fe15360820c719 | 602,145 |
def top_block_titles(config, block_type):
"""Extract the set of titles associated with a block type.
Each top level TRExFitter block has a title and we can extract the
titles of a specific top level block type.
Parameters
----------
config : str
Path of the config file.
block_type ... | 48660604ebf099394651bfa52330b9132c902ed5 | 602,147 |
def split_blocks(b: bytes, k_len: int) -> tuple:
"""Given a buffer and the key len, split the buffer into blocks.
:param b: The input buffer.
:param k_len: The key length.
:returns: A list of byte buffers.
"""
assert len(b) >= k_len
return tuple(
bytes(
b[j] for j in r... | 429c85067b4c3b563a4e095fe2d7b533a58e226f | 602,148 |
from typing import Tuple
def parse_pr_url(url: str) -> Tuple[str, int]:
"""Parse the given pull request URL and return its information.
:param str url: the PR URL from Github, formatted as:
https://api.github.com/repos/<account>/<repo>/pulls/<pr_number>
:return: the PR information as (full_repo_n... | 9ac519e6ba1abcd9a3756e33a8a64669222b397c | 602,153 |
def add_one(t_number, last_time_timeout):
"""Function will add a number if provided condition is set to True."""
if last_time_timeout:
t_number += 1
return t_number
else:
return 0 | 16e2b053e3641036731ff302d0d46f3528bb397b | 602,161 |
def createDockerRunArguments(image,
containerArgs,
jobTitle,
jobType,
user,
resultHooks=None):
"""
Return arguments to pass to docker_run Celery task.
:param imag... | 8ab7de8c799140c64fd49d46664e7cbb4f207154 | 602,162 |
import random
def choose_promo(promo_list):
"""
This is the algorithm to pick which promo to show.
This takes into account how many remaining days this
promo has to be shown.
The algorithm is currently as such:
* Take the remaining number of views each promo has today
* Add them togethe... | 59d9180664a2be8101e20b7383d513940bde39f0 | 602,166 |
def total_clicks_reward(responses):
"""Calculates the total number of clicks from a list of responses.
Args:
responses: A list of IEvResponse objects
Returns:
reward: A float representing the total clicks from the responses
"""
reward = 0.0
for r in responses:
reward += r.clicked
return rewar... | 4ef10872cb73ebd1ed7ace392bfe283236c489d2 | 602,168 |
def factory_fixed_sequence(values):
""" Return a generator that runs through a list of values in order, looping after end """
def seq_generator():
my_list = list(values)
i = 0
while(True):
yield my_list[i]
if i == len(my_list):
i = 0
return se... | 004f5965bfd4a5f4cfb68b35e2d8108679ff1106 | 602,169 |
def rtuFrameSize(data, byte_count_pos):
""" Calculates the size of the frame based on the byte count.
:param data: The buffer containing the frame.
:param byte_count_pos: The index of the byte count in the buffer.
:returns: The size of the frame.
The structure of frames with a byte count field is ... | 12a7d85880a4d30e6ae2bb8978946f270985ac1f | 602,170 |
def rotate_points(points):
"""Rotate the points around the center of the field.
Args:
points: Numpy array holding one or several points.
Returns:
The rotated points.
"""
# This assumes the center of the field is the origin: (0, 0)
return -points | cfb2428fda7a26a19d2fb86c36381c6df973f623 | 602,171 |
import logging
def getlog(name : str):
"""Create logger object with predefined stream handler & formatting
Parameters
----------
name : str
module __name__
Returns
-------
logging.logger
Examples
--------
>>> from __init__ import getlog
>>> log = getlog(__nam... | 05e02488db030f2f60d106de8cd0e247072d435a | 602,174 |
def find_index(arr, pred):
""" Find index of the first item that satisfies a predicate """
for index, elem in enumerate(arr):
if pred(elem):
return index
return -1 | 4bd65d40061f5102348d3c38fff6bd7fe669de90 | 602,176 |
def is_bad_message_ref_err(error: Exception) -> bool:
"""Check if error is caused by unknown message refrerence."""
return "In message_reference: Unknown message" in str(error) | 28d3684f61c25210ff91ffe1df8011ffd19b38c0 | 602,178 |
def avg_wordlen(values,delimiter = " "):
"""
#### returns the average length of given values:
if not specified, space will be the basic delimiter
#### Example:
x = avg_wordlen("One two three four five six")
### print("avg is: ",x)
>>> avg is 3.6666666666666665
"""
enteredValue... | 641f841073788ce9df46790d431cbad4bdc93fb7 | 602,182 |
def ping(msg):
"""Simply returns the args passed to it as a string"""
return str(msg) | a6950f00020c03bdce4f46baf9d78a38a7fba243 | 602,183 |
import math
def euclidean_dist_2_pts(p1, p2):
"""
Return euclidean distance between 2 points
:param p1: tuple(X,Y) of the first point's coordinates
:param p2: tuple(X,Y) of the second point's coordinates
:return: distance in the same metrics as the points
"""
x1, y1 = p1
x2, y2 = p2
... | d90e4d4cf672539ae7d614c5b32e26774060ed40 | 602,184 |
def extractLeafNames(nt):
""" given a newickTree BinaryTree object, returns a list
of leaf names as given by their .ID values
"""
names = []
if nt.right is not None:
names += extractLeafName... | d4a771a3ff4a5a44008be0d56bea43b3db2cc482 | 602,186 |
def _strip_span(span, text):
"""
Return span after stripping out whitespace on either side of text.
"""
start = span[0] + len(text) - len(text.lstrip())
end = span[1] - (len(text) - len(text.rstrip()))
return start, end | 30fba1d3af45420aed896b4670f38b9f6e6d83dc | 602,191 |
def get_note_flags(note):
"""
get the note flags
Returns a fixed length string:
'X' - needs sync
'*' - favorite
"""
flags = ''
flags += 'X' if float(note['modified']) > float(note['syncdate']) else ' '
if 'favorite' in note:
flags += '*' if note['favorite'] else ' '
... | ca85f2d3869b686216b49860961b044bd96ef9f6 | 602,195 |
def _create_circle(self, x, y, r, **kwargs):
"""
Helper method to simplify drawing circles on canvas
:param int x: x coordinate
:param int y: y coordinate
:param int r: radius
"""
return self.create_oval(x - r, y - r, x + r, y + r, **kwargs) | 371b65e50ce0789de9203c4abef78914abde90bb | 602,196 |
import copy
def truncate_list_of_lists(sents_tokenized, num_max, truncate_bottom=True):
"""Return a truncated list, with summ of tokens not exceeding maximum.
Truncate by lists. If single left list is still too long, truncate it by tokens.
In our context each element of sents_tokenized is a sentence repre... | 17afbc42dff5fdb28e76fbc8502e7a84aac3b5d1 | 602,200 |
def temp_tree_structure1(tmp_path):
"""
Creates temporary directories and files:
maindir/
|-- subdir1/
| |-- subsubdir1/
| | |-- subsubdir1_file1.txt
| |-- subdir1_file1.txt
| |-- subdir1_file2.jpg
|-- subdir2/
| |-- subdir... | 7e855e85c150fd30625feded884822711b2f3def | 602,201 |
def next_k_array(a):
"""
Given an array `a` of k distinct nonnegative integers, sorted in
ascending order, return the next k-array in the lexicographic
ordering of the descending sequences of the elements [1]_. `a` is
modified in place.
Parameters
----------
a : ndarray(int, ndim=1)
... | cc284c6ba48f55f1acd60c1be67e2fd106c6840b | 602,202 |
def FXR_calc(item):
"""
Calculate FNR,FPR,FDR,FOR.
:param item: item In expression
:type item:float
:return: result as float
"""
try:
result = 1 - item
return result
except Exception:
return "None" | db9a98d10d067972fb102ba0f099b8e2853fd5d9 | 602,205 |
def f_linear(x, a, b):
"""
compute the linear function value with given parameters
Parameters
----------
x: int or vector
independent variable values
a: double
slope parameter
b: double
y-intercept parameter
... | 02002ba3937d0cb1032d77489050f68f6fce4f0a | 602,208 |
def is_endpoint(url_or_endpoint:str) -> bool:
"""判断是不是端点
Args:
url_or_endpoint (str): url 或 端点字符串
Returns:
bool: 不是http则返回False
"""
if url_or_endpoint.startswith(('http://', 'https://')):
return False
return True | a50cf2da2a6adb6465f84d1483c451858d3d94bf | 602,210 |
def make_badge_dict(badges, profiles):
"""Make a dict of files and their badges."""
badge_dict = dict()
for badge, profile in zip(badges, profiles):
for filename in profile["files"]:
if filename in badge_dict:
entry = badge_dict[filename]
entry.append(bad... | bbadb4402b59de901f0f91ac4349f936e96a279e | 602,211 |
def shape_is_image(shape):
"""Check if is a 4D tensor which we consider to be an image."""
return len(shape) == 4 | a3e5a9a19e9f84f3ed4f0f3c1f07abdbace3b8db | 602,212 |
def GetChartsFromBenchmarkResultJson(benchmark_result_json):
"""Returns the 'charts' element from a given Chart JSON.
Excludes entries that are not list_of_scalar_values and empty entries. Also
raises errors for an invalid JSON format or empty 'charts' element.
Raises:
ValueError: Provided chart JSON is e... | 74db912eac4ec9412a77abcbe5fda28a5be9fd65 | 602,216 |
def parse_dat_data(entry: str) -> list:
"""
Converts a character-width delimitted file into a list.
Each element in the list is separated per the character length specified in the
headers file.
"""
return [
entry[0:7],
entry[7:13],
entry[13:19],
entry[19:21],
... | 98849ca58f4af1706d5121643274ca207b6d4eed | 602,217 |
def mfile_to_lines(mfile):
"""
Read the lines from an mfile
Parameters
----------
mfile : string
Full path to an m file
"""
# We should only be able to read this file:
with open(mfile) as fid:
return fid.readlines() | 843188720fe1c55eb34b62a6ddfa349f600f496e | 602,219 |
import torch
from typing import List
from typing import Dict
def _get_prediction_from_scores(
scores: torch.Tensor, classes: List[str]
) -> List[List[Dict[str, float]]]:
"""
Given scores for a batch, get the prediction for each word in the form of a
List[List[Dict[str, float]]] for callers of the torc... | a6ff6a637f122ab934ad042cb7239e738665d249 | 602,220 |
def convert_dollars_string_to_float(dollars_string):
"""Converts a string of the form '$x,xxx,xxx.xx' to its equivalent decimal value.
:param dollars_string: A string in dollar and cents form to be converted.
:returns: A floating-point number rounded to 2 decimal places.
"""
return round(float(doll... | cf27877e8b64275f49fe0a37529be8736e4d6645 | 602,222 |
def validate_window_size(s):
"""Check if s is integer or string 'adaptive'."""
try:
return int(s)
except ValueError:
if s.lower() == "adaptive":
return s.lower()
else:
raise ValueError(f'String {s} must be integer or string "adaptive".') | 297c79ea92489bce45124d546a9b0a6bd8cb6333 | 602,230 |
def abbreviate_middle(s: str, max_length: int) -> str:
"""Shortens string `s` by replacing the middle part with an ellipsis
sign ` ... ` if the size of the string exceeds `max_length`."""
assert max_length > 6
length = len(s) # type: int
if length > max_length:
a = max_length // 2 - 2 # ty... | c9625d4cfac6fd9a73e861f2faf1caf2398c93b4 | 602,232 |
def notas(*n, sit=False):
"""
-> calcula o total, a maior, a menor, e a média de notas da turma
:param n: notas a serem avaliadas
:param sit: (opcional) adiciona a situação da turma
:return: dict com as informações da turma
"""
dados = {
'total': len(n),
'maior': max(n),
... | d9c8d573445826b79b2dfbbf421d39b27ad7c6ab | 602,233 |
def binary_word_search(string, data):
"""A simple binary search algorithm to check if string exists in data."""
string = str(string)
if len(data) == 0:
return False
mid = len(data)//2
if data[mid] == string:
return True
elif string < data[mid]:
data = data[:mid]
else:... | 82defbb7d200b932c7a9163fd290b9b924e68ae0 | 602,234 |
def reference_products_as_string(dataset):
"""Get all reference products as a string separated by ``'|'``.
Return ``'None found'`` if no reference products were found."""
exchanges = sorted([exc['name']
for exc in dataset['exchanges']
if exc['type'] == 'refer... | f3139e91280654f7c557835f315ed96349ee81b9 | 602,235 |
def get_images_type(image_file):
"""Returns 'images_multiview' or 'images_multiview_frontOnly."""
return image_file.split('/')[-5] | 18101c2a0470882ec1ada9bca26d5c82859edb1f | 602,236 |
def clean_namelist_key_value(line):
"""
Cleans up a namelist "key = value line"
Removes all spaces, and makes the key lower case.
"""
z = line.split('=')
# Make key lower case, strip
key = z[0].strip().lower().replace(' ', '')
value = ''.join(z[1:])
return f'{key}... | 61f72f65b6e8cddafb5a6b9d85a9e52c4676cb24 | 602,242 |
def getModFromCipher(key: int, cipher: int, rest: int):
"""
get the base from the sipher, the key and the rest values
:param key: a temporary integer key
:param cipher: the ciphered base retreived from the file
:param rest: the rest of the equation (see Utilities:generateCipher)
:return: a inte... | b61aaa49842272d814dd34fd78ca2817c989f402 | 602,247 |
def replicate_input(x):
"""
Clone the input tensor x.
"""
return x.detach().clone() | a42c8929c549aa45cebaa55285855a1a81bf428c | 602,251 |
import math
def get_center(coords):
""" Gets the center coordinate (lat, lng) of a list of coordinate tuples.
Args:
coords: list of coordinate tuples
Returns:
Coordinate tuple of center point
"""
n = len(coords)
if n == 1:
return coords[0]
x, y, z = 0, 0, 0
... | 863781a2b7936e01912e78b36234e441946db928 | 602,254 |
import re
def filter_not_insp_keys(cite_keys):
"""Select keys that do not match the pattern of INSPIRE bibtex keys.
The current pattern to /not/ match is: `".*?:\d\d\d\d[a-z]{2,3}"`
Parameters
----------
cite_keys: array of string
An array of bibtex keys
Returns
-------
not_in... | 5f97689b9c14a7e89d64cfa7483c6b19055e52b0 | 602,261 |
from typing import List
import itertools
def flatten(nested_list: List[List[List[float]]]) -> List[List[float]]:
"""Flatten nested list"""
return list(itertools.chain.from_iterable(nested_list)) | eafa97d83b1fb1bd6140402f3dd9bdd8528ba86b | 602,263 |
def get_user_from_context(context):
"""
Get the user instance from the template context, if possible.
If the context does not contain a `request` or `user` attribute,
`None` is returned.
"""
try:
return context['user']
except KeyError:
pass
try:
request = context... | 6288c6eb6a96382dd8495e1d2d63f35aa9acb873 | 602,264 |
def wariancja(oceny, srednia):
"""
Wariancja to suma kwadratów różnicy każdej oceny i średniej
podzielona przez ilość ocen:
sigma = (o1-s)+(o2-s)+...+(on-s) / n, gdzie:
o1, o2, ..., on - kolejne oceny,
s - średnia ocen,
n - liczba ocen.
"""
sigma = 0.0
for ocena in oceny:
... | 452ce649f2599a1e969b0020871d591fa82017f7 | 602,265 |
def filecontent(filename,default=''):
""" Return the file's content as a string, default in case
there's an error
"""
try:
f = open(filename,'rb')
except IOError:
return default
c = f.read()
f.close()
return c | cf89bfd4e6054a82b98841f9737ad4c3e65320ed | 602,267 |
def pkcs7_unpad(bytes_, len_):
"""Unpad a byte sequence with PKCS #7."""
remainder = bytes_[-1]
pad_len = remainder if remainder != 0 else len_
msg = bytes_[:-pad_len]
pad = bytes_[-pad_len:]
if remainder >= len_ or any(p != remainder for p in pad):
raise ValueError("Invalid padding")
... | 2c8e6ec7f85bcf5e3b597a4dab351be8ea6fa74b | 602,273 |
def power_eq(x, a, b):
"""Power equation"""
return a * x ** b | 367a9977ea0239a9cd1f128c6dd839ee8738bd56 | 602,274 |
def parse_key_value(key_value, delimiter="="):
"""Splits a string like "x=3" into a 2-tuple ("x", "3")
Args:
key_value (str): The string containing the key and value separated by the delimiter.
delimiter (str): Separator between the key and value. Default is "=".
Return:
2-tuple: (... | 74fc14b8bc15d3c487640c55e155e4a6bd5d3eae | 602,275 |
import re
def find_email(article_content):
"""Given an article content (raw text), extracts and returns the first e-mail address found.
None string if nothing is found."""
article_content = article_content.prettify()
match = re.search(r'[\w\.-]+@[\w\.-]+', article_content)
if match is not None:... | 7ee69488f45fd7d83dca908b938912ba1ec2aaee | 602,279 |
def map(function, list):
"""
Given a function and a list,
return the list of the results of applying function(item) on all items
"""
return [function(item) for item in list] | 9a44c02e38342c77ea56fe874accecc5f1613de7 | 602,280 |
import torch
def pdist(feature):
"""Compute pairwise distances of features.
Args:
feature (torch.Tensor): (batch_size, channels, num_features)
Returns:
distance (torch.Tensor): (batch_size, num_features, num_features)
Notes:
This method returns square distances, and is optim... | 88250b7c169cf6628afa936fafd6e44ce836c9b1 | 602,282 |
def split_string(string):
"""split and lower the string"""
return string.lower().split(' ') | 761e16301c4fbf26a1241826747c01f2a0b09ab7 | 602,283 |
import torch
from typing import Tuple
def sym_inv_sqrtm2(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Symmetric matrix inverse square root, with square root return also.
Parameters
----------
x : torch.Tensor
symmetric matrix
Returns
-------
Tuple[torch.Tensor, torch... | 0ce5abf7e85d968bfe4d5130800033bd6a625926 | 602,286 |
import io
def read_file(filename, encoding="utf-8-sig"):
"""Read text from a file."""
with io.open(filename, encoding=encoding) as f:
return f.read() | 5e65b2a0810619632e53e27691b245766f405328 | 602,287 |
def _mod_exp(a: int, x: int, n: int) -> int:
"""
Fast modular exponentiation of a to the power x mod n.
"""
if x == 0:
return 1
elif x == 1:
return a % n
elif x % 2 == 1:
return (a * _mod_exp(a, x - 1, n)) % n
else:
return (_mod_exp(a, x >> 1, n) ** 2) % n | 9bb7152c2ae89c284559416f49a92d75f5642723 | 602,292 |
def _check_issue_label(label):
"""
Ignore labels that start with "Status:" and "Resolution:". These labels are
mirrored from Jira issue and should not be mirrored back as labels
"""
ignore_prefix = ("status:", "resolution:")
if label.lower().startswith(ignore_prefix):
return None
... | db9c0a56f3f294837d7846fc490f0d14397cc1c0 | 602,302 |
def get_operator_priority(char: str) -> int:
"""
Used to get operator priority, or to check if char is correct operator
:param char: Operator
:return: Operator priority (positive), or -1 if char is not correct operator
"""
if char == '!' or char == '#':
# '#' - unary minus
return... | 77e04dd590a5079f8f7c4bbc66f4e96dfc38e844 | 602,312 |
import re
def escape_ansi(line: str) -> str:
"""Remove ANSI escape sequences from string.
Args:
line: String with ansi sequences
Returns: String with ansi sequences stripped
"""
ansi_escape = re.compile(r"(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]")
return ansi_escape.sub("", line) | 51b34df39b78844e577ed153006d238b6e007658 | 602,313 |
def to_api_path(db_path):
"""
Convert database path into API-style path.
"""
return db_path.strip('/') | e54d90805f1dac374d2334c31cb18d892e4e514d | 602,315 |
def no_trailing_comma(l):
"""
By-lines wikidata dumps have trailing commas (on all but the last line). Remove them.
"""
if l[-1] == ',':
return l[:-1]
else:
return l | a580af1bc7f1f2bf1d0d147b93febe94f39977f6 | 602,316 |
def IoU(target, prediction):
"""
Calculates the Intersection over Union of two bounding boxes.
Parameters:
target (list): A list with bounding box coordinates in the corner format.
predictions (list): A list with bounding box coordinates in the corner format.
Returns:
iou_value... | 9f00a4ef92a073a07ad236f43348b3527ab9a173 | 602,320 |
def scaling_func(mag, ref, slope, ref_mag):
"""
Genaral form for cluster member scaling relations in equations 3 and 4 of Bergamini et al. 2019
:param mag: cluster member magnitude
:param ref: reference value (reference velocity dispersion or reference core radius or reference truncation radius) corris... | eb3316174a4ee8cb3552fdace97298947f073f80 | 602,322 |
import json
def load_defs(fname="definitions.json"):
"""
Loads JSON from the definitions file and converts it to a preferred format.
(The definitions file should be drop-in compatible with the one from the
divvy-binary-codec JavaScript package.)
"""
with open(fname) as definitions_file:
... | 3487b0af63d82dd166e46b587f14c4cf2c628e17 | 602,323 |
def log_request(r):
""" Serialize a httpx.Request object into a dict for logging """
return {
"method" : r.method,
"url" : str(r.url),
"headers" : dict(r.headers),
"data" : r.read().decode()
} | 962294d5dd1743079c56daa48e727562f9327905 | 602,330 |
import json
def gen_user_pref_call(key, val):
"""
Generate a javascript user_pref call for the given key, value pair.
Returns a string.
"""
res = "user_pref(\""
# Generate a javascript constant for the given value, dependent on type
val = json.dumps(val)
res += str(key)
res... | 94ec95109abc3c5850c853c0d1ec6d6d65cb64c0 | 602,336 |
def auth_header(encoded_jwt):
"""
Return an authorization header containing the example JWT.
Args:
encoded_jwt (str): fixture
Return:
List[Tuple[str, str]]: the authorization header
"""
return [('Authorization', 'Bearer %s' % encoded_jwt)] | 51974c16b9ee89fe580d7aa5306eaadee3173e47 | 602,337 |
import json
def format_record(element, band_column=None, band_type='int'):
"""
Format the tuple received from the geobeam file source into a record
that can be inserted into BigQuery. If using a raster source, the
bands and band_column will be combined.
Args:
band_column (str, optional): ... | c6e822af45035e2ff59228aeee7e93a1bb028d62 | 602,339 |
def rsa_decrypt(c: int, d: int, n: int) -> int:
"""
Implements RSA Decryption via the mathematical formula.
The formula is m=(c**d) % N
Returns the plain "text" really integer representation of the value.
:param c: Ciphertext integer.
:param d: the private key exponent.
:param n: the modulus.
:return: the pla... | 4d44a926060e47a428ad275e88fd3a63a0cab909 | 602,343 |
def hint_order(tup):
"""What order should the enumerator see hints?
Takes an (e, ctx, pool) tuple as input and returns a sort key.
"""
# current policy: visit smaller expressions first
e, ctx, pool = tup
return e.size() | 01fcb1ce12b8708ec60356f21a336132acdcc476 | 602,344 |
def find_human_indices(lst, condition):
"""
Find indices of lst satisfying the specified condition.
The output list contains indices starting from 1 rather than 0.
Input: lst - list
Input: condition - lambda function
Output: list of indices - list
"""
return [index+1... | 48e089a0b74aacbdb1b29c77f25cdd9489acc566 | 602,347 |
def get_dims(board) -> tuple:
"""Returns the (y, x) dimensions of a matrix"""
return len(board), len(board[0]) | 270b2fee5c845f9a73602e70a7a226c0f6154b11 | 602,350 |
def cut_parser(lines):
"""cut format parser
Takes lines from a cut file as input.
returns dict of {codon:count}.
"""
result = {}
for line in lines:
if line.startswith('#'):
continue
if not line.strip():
continue
fields = line.split()
resul... | bfbd0365b47d103135e5064aae8f32564cd805a5 | 602,352 |
def float_convert(val: str) -> float:
""" Converts the given value to a float type. """
return float(val) | 4f9b48c3800679263fcb1a29dbc57c387eaf4be4 | 602,357 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.