content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def isLeft(p1,p2,p3):
"""Given three points, we determine if p3 is on the left of the directed line given by points p1 and p2.
Output: Signed distance between p3 and the line.
When output>0, p3 is on the left of the line."""
return ((p2.x-p1.x)*(p3.y-p1.y)-(p2.y-p1.y)*(p3.x-p1.x))/mat... | 7e2b0bd299636c19b6086a4463e5154170802b3f | 46,961 |
def os_path_norm(diroot):
"""function os_path_norm
Args:
diroot:
Returns:
"""
diroot = diroot.replace("\\", "/")
return diroot + "/" if diroot[-1] != "/" else diroot | 7065de60afbbfb0fc47126b978b8704fa615cc96 | 46,962 |
def matched_requisition(ref, requisitions):
"""Get the requisition for current ref."""
for requisition in requisitions:
if requisition["reference"] == ref:
return requisition
return {} | 806f7578cb5405b3f52b57274ecd9e4c4b5d157f | 46,963 |
import tempfile
import os
def UmaskNamedTemporaryFile(*args, **kargs):
"""Create NamedTemporaryFile which follows standard *NIX umask conventions.
Thanks to Pierre at https://stackoverflow.com/a/44130605/507544
"""
fdesc = tempfile.NamedTemporaryFile(*args, **kargs)
umask = os.umask(0)
os.uma... | 6439e6169cda645cd87425ebbdcc65feb91144d1 | 46,964 |
import time
def get_day_num(dayname) -> int:
"""Converts dayname to 0 indexed number in week e.g Sunday -> 6"""
return time.strptime(dayname, "%A").tm_wday | 29e2b00066b6a0ca207ae3cced3f7efb7ce2c190 | 46,965 |
import json
import os
def create_json(filename, data):
""" method to store the results in a json file """
with open(filename, 'w') as doc:
json.dump(data, doc, indent=4)
return os.path.isfile(filename) | faf07404df6e7363f2859c58ed744f2c9322fa35 | 46,966 |
def add_start(start, notes):
"""Adds the \"start\" delay to all the events inside of
a song called from another song"""
for note in notes:
if type(note) == list:
note[1] += start
elif type(note) == dict and note["type"] == "song":
note["start"] += start
return notes | 96cf76653af469eca6948f006e8301c500b3a705 | 46,967 |
def clean(s):
"""Clean up a string"""
if s is None:
return None
s = s.replace("\n", " ")
s = s.replace(" ", " ")
s = s.strip()
return s | e706b68c7ed5b78ca54a3fd94af5de35ee142d43 | 46,968 |
from typing import Dict
import os
def get_syn2cls_mapping(root: str) -> Dict[str, int]:
"""Maps ImageNet classes (i.e., Wordnet synsets) to numeric labels."""
try:
with open(os.path.join(root, 'LOC_synset_mapping.txt'), 'r') as f:
cls2syn = dict(
enumerate(list(map(lambda x... | ad816ed60d753b15132ab1c6ee291afead678ce0 | 46,969 |
import os
def command_exists_on_localhost(command: str) -> bool:
"""Check if a command exists on localhost"""
cmd_ext = "hash " + command + ' 2>/dev/null && echo "True" || echo ""'
return True if os.popen(cmd_ext).read() else False | ac45c09d0a786d6907ef6b6db9f006ef08438884 | 46,970 |
import re
def get_reconstruction_info(line):
"""
Scraps data for a shock-capturing recomnstruction kind of data output
:param line: line of a file (str)
:return: tuple of scalar tuples --> regex obj (can be treated as bool), name, recon
"""
name = ''
recon = [0, 0, 0]
match_obj = re.m... | c43001cfd3a200f1ce47e9a3704f34ef4ae6a0e0 | 46,971 |
def leapdays(y1, y2):
"""
Return number of leap years in range [y1, y2]
Assume y1 <= y2 and no funny (non-leap century) years
"""
return (y2 + 3) / 4 - (y1 + 3) / 4 | c7e7c3b4650ef1236fc70ba94240f7119d9397c0 | 46,973 |
import os
def if_main_process():
"""Checks if the current process is the main process and authorized to run
I/O commands. In DDP mode, the main process is the one with RANK == 0.
In standard mode, the process will not have `RANK` Unix var and will be
authorized to run the I/O commands.
"""
if ... | a4da7ebabbf121a8a0685615261bf7f0e3c0f80e | 46,974 |
import tempfile
import shutil
import atexit
def temporary_folder():
"""Get path to new temporary folder that will be deleted on program exit.
Returns a temporary folder using mkdtemp. The folder is deleted on exit
using the atexit register.
Returns:
path (string): an absolute, unique and te... | 6bf7ccb6aa9c18017508eeb045fd25ebd7e624cb | 46,980 |
import os
def local_file_path(filename: str) -> str:
"""Returns the full path of a local file."""
return os.path.join(os.path.dirname(__file__), filename) | 4b83f4bf77bfe13d2f538c9938df4eb3fbfd42fa | 46,981 |
def truncate_column(data_column, truncation_point):
"""
Abstraction of numpy slicing operation for 1D array truncation.
:param data_column: 1D np.array
:param truncation_point: int of truncation index to test
:return: np.array
"""
assert (len(data_column.shape) == 1) # Assert data_column is... | bc444517953228d003fc18851f5c22b2b70f6e55 | 46,984 |
from typing import Any
def _place_holder(x: Any):
"""
Whatever in, whatever out
Args:
x ():
Returns:
"""
return x | e39dfa1b4428ef265e4d371a069ebcfa7ff18e81 | 46,987 |
from typing import Optional
import json
def get_receive_count_for_rust_sqs_executor_line(line: str) -> Optional[int]:
"""
Corresponds to logs output from
info!(message_batch_len = message_batch_len, "Received messages");
in sqs-executor/lib.rs
"""
try:
json_line = json.loads(line)
... | ba85083fe867774a852961e89969f844351c19cc | 46,988 |
import math
def asinh(x):
"""Get asinh(x)"""
return math.asinh(x) | e0086dd83ca8a4dd005deed4ef0e58d11c306d0a | 46,990 |
def multiply_with_density(cube, density=1000):
"""Convert precipitatin from m to kg/m2."""
cube.data = cube.core_data() * density
cube.units *= 'kg m**-3'
return cube | aa469c1165898f6543300d70a58b5635d758ec56 | 46,991 |
from typing import Tuple
def get_ronik_time(time_splits : Tuple[int], seconds : int) -> Tuple[int]:
"""
generates time in new system
starts at 0 for all counts
last append is for orbits
"""
time = []
for time_split in time_splits:
time.append(seconds % time_split)
seconds //= time_split
time.append(s... | 7d9d700f756d3cbb26fe49f3711be369d5e92765 | 46,993 |
import io
def export_python(palette):
"""
Return a string of a Python tuple of every named colors.
Arguments:
palette (dict): Dictionnary of named colors (as dumped in JSON from
``colors`` command)
Returns:
string: Python tuple.
"""
# Open Python tuple
python_... | b32b97412612d36096aab088d6e3671e5059a32b | 46,994 |
import json
def getStatus(response):
"""
Get the status of the request from the API response
:param response: Response object in JSON
:return: String - statuse
"""
resp_dict = json.loads(response.text)
try:
status = resp_dict["status"]
except KeyError:
print('Retrieva... | a72a056ef574fdf0fb8f5744073d351836c6db07 | 46,997 |
def smog(polysyllables_count):
"""Given the number of words with at least 3 syllables in a text, compute the SMOG
grade.
Note that this was originally intended for the english language, and for a section
of text containing at least 30 sentences.
Keyword arguments:
polysyllables_count -- number ... | fa2cfd828e43e589b6a859477ebb5b213bfea301 | 46,998 |
def _create_custom_gendered_seq_names():
"""The names have detail that is adequately represented by the image."""
BOY = 0x1f466
GIRL = 0x1f467
MAN = 0x1f468
WOMAN = 0x1f469
HEART = 0x2764 # Heavy Black Heart
KISS_MARK = 0x1f48b
return {
(MAN, HEART, KISS_MARK, MAN): 'Kiss',
(WOMAN, HEART, ... | a79ca3f79134c91ac7c27843f35698a621235d98 | 46,999 |
def exec_tested_method(tx_name, method, tested_method, inputs, server_db):
"""Execute tested_method within context and arguments."""
if tx_name == 'transaction' and method == 'construct':
return tested_method(server_db, inputs[0], **inputs[1])
elif (tx_name == 'util' and (method in ['api','date_pass... | af0d404f2aeef53444d988b7677222815529b79f | 47,002 |
import itertools
def flatten_metas(meta_iterables):
"""
Take a collection of metas, and compose/flatten/project into a single list.
For example:
A: pkg1, pkg2a
B: pkg2b, pkg3
Flattened([A, B]) => [pkg1, pkg2a, pkg3]
Flattened([B, A]) => [pkg1, pkg2b, pkg3]
The resul... | 4125a7bea44989140909e91392cd3adb740e26f1 | 47,004 |
def plural(singular, plural, seq):
"""Selects a singular or plural word based on the length of a sequence.
Parameters
----------
singlular : str
The string to use when ``len(seq) == 1``.
plural : str
The string to use when ``len(seq) != 1``.
seq : sequence
The sequence t... | 352d8fca4b2b7fb8139b11296defd65796e0e712 | 47,005 |
def get_nations():
"""Restituisce la lista dei generi esistenti"""
nations = [
{'name': 'Italy'},
{'name': 'USA'},
{'name': 'France'},
{'name': 'UK'},
{'name': 'Japan'},
{'name': 'Indonesia'},
{'name': 'Canada'},
{'name': 'Mexico'},
{'name... | ba1790e93e3e71fa48abc302c51d2f5cd230dc03 | 47,006 |
def static_feature_array(df_all, total_timesteps, seq_cols, grain1_name, grain2_name):
"""Generate an arary which encodes all the static features.
Args:
df_all (pd.DataFrame): Time series data of all the grains for multi-granular data
total_timesteps (int): Total number of training samples ... | 58f4664fa318f1026a1c3e48616431f51b224704 | 47,007 |
def _get_org():
"""Gets the org for this python session"""
return '00000000-0000-0000-0000-000000000000' | 51ed4c27ba5b62572cb4ff9b18d87d922edf956c | 47,008 |
import typing
def get_cluster_sources(clusters: typing.Set[str],
source_map: typing.Dict[str,
typing.List[str]], side: str):
"""Returns a list of cluster source directories for the given clusters.
Returns:
The set of source directo... | 5599a0e50b5a486b938ec9622fa3f089dc313d29 | 47,009 |
def parse_vimeo_tag(text):
"""Replaces [vimeo: id] tags"""
video_id = text.group("video")
return f'<div class="video-container"><iframe src="https://player.vimeo.com/video/{video_id}" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>' | c11dd5d8e92b1be694ab6222f0975d44895975d2 | 47,012 |
def make_descriptions(painting):
"""Given a painting object construct descriptions in en/nl/sv.
Returns None if there is a problem.
@param painting: information object for the painting
@type painting: dict
@return: descriptions formatted for Wikidata input
@rtype: dict
"""
db_creator_n... | b0648f82a30ac499475383556a7aa48955f459d7 | 47,013 |
def no_fuse(x):
"""No fuse"""
return x + 2 | a05a4d007398248bf0ffa5d294239cbf75d77893 | 47,014 |
import re
def check_for_title(line):
"""
Check the current line for whether it reveals the title of a new entry.
:param srtr line: the line to check
:return: tuple (the entry title, the entry type) or (None, None)
"""
re_title = re.compile(
'^(?P<title>.+) \\((?P<type>EPHEMERA OBJECT|... | 73d7b73d29e51b87a37810d434582c975c6d0c07 | 47,015 |
def rotate_right(arr):
"""
Rotate a copy of given 2D list
clockwise by 90 degrees
and return a new list.
:param arr: A 2D-list of arbitrary
dimensions.
:return: A list that is "arr" rotated
90 degree clockwise by its center.
"""
n = len(arr)
m = len(arr[0])
res = [[Non... | 2d393acbb8accaae90dd562b5360199698a032a9 | 47,017 |
def get_dl_dir(cd, t, chan):
"""Get the cached download destination directory for file
Get the path for the destination directory for channel for GOES 16 ABI L1B
is downloaded. It does not check if the destination directory exists.
Args:
cd (pathlib.Path): Root path for cache directory
... | 33a315189feffe33a3c4ecc9d1851164b5b70e1c | 47,019 |
import os
def get_item(name):
"""
Retrieve a test resource by filename.
:param name: String filename of the requested resource
:returns: Absolute path to the requested resource
"""
current_path = os.path.realpath(__file__)
current_path = os.path.dirname(current_path)
current_path = o... | 2bc72219491c34ec918a113df8c8f737f87a6f5c | 47,020 |
def can_receive_blood_from(blood_group):
"""Return allowed blood groups given a specific blood group."""
can_receive_from = {
'A+': ['A+', 'A-', 'O+', 'O-'],
'O+': ['O+', 'O-'],
'B+': ['B+', 'B-', 'O+', 'O-'],
'AB+': ['A+', 'O+', 'B+', 'AB+', 'A-', 'O-', 'B-', 'AB-'],
'A-': ['O-', ... | 34c956f829a14c9b1ebe6f664c44d554451b11e0 | 47,021 |
def replace_ref_nan(row):
"""Function to replace nan info values of some references coming from references without PubMed id
with their reference id."""
if isinstance(row["combined"], float):
return row["reference_id"]
else:
return row["combined"] | 76f5effe6613178055e38721f8a09d459ab0a019 | 47,023 |
def list4ToBitList32(lst):
"""Convert a 4-byte list into a 32-bit list"""
def intToBitList2(number,length):
"""Convert an integer into a bit list
with specified length"""
return [(number>>n) & 1
for n in reversed(range(length))]
lst2 = []
for e in lst:
... | ac95e68927b703292913229f7a1d0316941f570e | 47,024 |
def board():
"""
Sudoku board for testing
"""
board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0,... | 69992170a55286586e10b544dd2707fdf73869ca | 47,025 |
def IpBinaryToDecimal(bin_ip):
"""
:param bin_ip: IPv4 in binary notation, e.g. 00001010000000000000000000000001
:return: IPv4 in decimal notation, e.g. 167772161
"""
return int(bin_ip, 2) | 20366a1667fd1f9c1f17e7c13c2292bd4a7e74b0 | 47,027 |
import numpy
def sph2Ludwig3(azl, EsTh, EsPh):
"""Input: an array of theta components and an array of phi components.
Output: an array of Ludwig u components and array Ludwig v.
Ref Ludwig1973a."""
EsU = EsTh*numpy.sin(azl)+EsPh*numpy.cos(azl)
EsV = EsTh*numpy.cos(azl)-EsPh*numpy.sin(azl)
retu... | 8ec7b6253ea4ab9e5ad2dee8b0374c7feeeeff1f | 47,028 |
import logging
import inspect
import sys
def check_config_missing(config: dict) -> bool:
""" Check that the minimal config items exist """
log = logging.getLogger(inspect.stack()[0][3])
try:
if "GENERAL" not in config:
raise KeyError("missing general section from configuration")
... | f923a33f20c7cb55ae2f5d423fd18c6a601f9746 | 47,029 |
def _rescale_0_1(batch):
"""
Rescale all image from batch, per channel, between 0 and 1
"""
for image_id in range(batch.size(0)):
for channel_id in range(batch[image_id].size(0)):
pix_min = batch[image_id][channel_id].min()
pix_range = batch[image_id][channel_id].max() - ... | 65e70cb6b3779f9ec776568a65fee13f56f0ca21 | 47,031 |
import numpy
def linear_percent(cumulative_histogram, percent, minv, binsize):
"""
Image contrast enhancement.
Given a cumulative histogram, upper and lower DN values are
computed and returned.
:param cumulative_histogram:
A 1D numpy array. Must the cumulative sum of a histogram.
:p... | 94ab268a7c8259fa4a24e38d5b7c351f1d52a972 | 47,032 |
import re
def extract_id(i):
"""Extracts the identifier from the URL in redo's ID column"""
r = re.compile(r'<a href="([^"]*)">([^<]*)</a>')
m = r.match(i)
if m is None:
ident = i
url = None
else:
ident = m.group(2)
url = m.group(1)
return {"trial_id": ident, "t... | d2eb2d021deae453c3c64a16ab5150d19ea45d6d | 47,033 |
import re
def __safe_file_name(name: str) -> str:
"""
This helper is responsible for removing forbidden OS characters from a certain string.
:param name: String to be converted
:return: Safe string
"""
return re.sub(r'<|>|/|:|\"|\\|\||\?|\*', '', name) | 6b52ededba763fa48c3e8c1d3f64c1487269e457 | 47,034 |
import argparse
def get_options():
"""Returns user-specific options."""
parser = argparse.ArgumentParser(
description='Set options for all devices.')
parser.add_argument(
'--save_type', dest='save_type',
type=str, default='RGB', choices=['RGB', 'D', 'IR', 'RGBD', 'RGBDIR'],
... | 2f60513713526c37fa9fd825b2419e82986b6df7 | 47,035 |
from pathlib import Path
def get_modality_from_name(sensor_path: Path):
"""Gets the modality of a sensor from its name.
Args:
sensor_path (Path): the Path of the sensor. Ex: CAM_FRONT_RIGHT, LIDAR_TOP, etc.
Returns:
str: the sensor modality
"""
sensor_name_str = str(sensor_path)
... | 4d37ea2bf096032eb824f7c951099fc7caea09fd | 47,036 |
def constant(value=0):
"""A flat initial condition. Rather boring, you probably want a source or some interesting boundary conditions
for this to be fun!
Args:
value (float): The value the function takes everywhere. Defaults to 0."""
return lambda x: value | 9286cfe97bdf0a19831fab3fc7d69268e6660674 | 47,037 |
import numpy as np
import math
def tile_slicer(im, shape):
"""Takes image and divides it into multiple tiles with equal specified shape.
Shape should be a tuple with the desired tile size. Returns as a dicctionary with
tile locations as keys of data type tuple. Returns tiled image, preserved shapes for p... | a51b01fbd04d1f468829bae40a5b30f5f053254a | 47,038 |
import os
def get_last_modification(file):
"""get time of last modification of passed file
Args:
file (str): absolute path of file
"""
if file is not None:
if os.path.exists(file):
return os.stat(file).st_mtime
else:
return None
else:
return... | 818e1579e43053037494f684f2861c42e4d634b9 | 47,040 |
def _csstr_to_list(csstr: str) -> list[str]:
"""
Convert a comma-separated string to list.
"""
return [s.strip() for s in csstr.split(',')] | 88b2197a6c86839426daf35bbddb212519ef1659 | 47,041 |
def update_cur_center(cur_center, matches, center):
"""Update current center"""
matched = []
for match in matches:
matched.append(match[0])
cur_center[match[1]] = (center[match[0]] + cur_center[match[1]]) / 2
for i in range(len(center)):
if i not in matched:
cur_cente... | 391d435b0f62c537e5dd6a022b491577ba1c140c | 47,042 |
import time
def render_vextab(vextab: str, show_source: bool = False) -> str:
"""Create Javascript code for rendering VExflow music notation
:param vextab: The Vexflow source code to render into music notation
:param show_source: ``True`` to include the original Vexflow music notation
... | 3b52a6befef4c78d1a3d6abaf270699da3273d47 | 47,043 |
import requests
def get_header_contents() -> str:
"""
Get js_ReaScriptAPI header from GitHub as raw string.
Returns
-------
str
"""
root_raw = 'https://raw.githubusercontent.com/'
header = (
'juliansader/ReaExtensions/master/js_ReaScriptAPI/' +
'Source%20code/js_ReaScr... | b2272dfbc131a422ec2aeb6e57d17a0ad6b41ae2 | 47,044 |
def serially():
"""
Force a testcase method to run serially (vs :func:`concurrently`).
Remember methods that are ran serially are run first and by
default are those that
- take more than one target as arguments
- are evaluation methods
"""
def decorate_fn(fn):
setattr(fn, "exe... | e62895ee9774ec69af6f46c0fdf593a8b3e026be | 47,045 |
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
moves = set()
for row in range(len(board)):
for col in range(len(board[0])):
if board[row][col] == None:
moves.add((row,col))
return moves | 639a4c6fbf701b7d3afc09198911ab3a1a587460 | 47,046 |
def _check_composite(n, s, d, a):
""" check compositeness of n with witness a. (n,s,d) should satisfy d*2^s = n-1 and d is odd """
a %= n
if a == 0: return False
x = pow(a, d, n)
if x == 1 or x == n - 1: return False
for y in range(1, s):
x = x * x % n
if x == 1: return True
... | 8ba5b281e848c919f09621d82e9b57d4fb529ecb | 47,047 |
def calc_water_to_residues_map(water_hbonds, solvent_resn):
"""
Returns
-------
frame_idx: int
Specify frame index with respect to the smaller trajectory fragment
water_to_residues: dict mapping string to list of strings
Map each water molecule to the list of residues it forms
... | 8a73998e7295e4ee5bf812804edfa4b521e2aa31 | 47,048 |
import shutil
def executable_path(*tries):
"""Find path to executable, or throw."""
path = None
for ex in tries:
path = shutil.which(ex)
if path:
break
if not path:
raise Exception(f"Unable to find path to {tries[0]}")
return path | 825bb53c9b44678e43cdd2b9d68d905932027737 | 47,049 |
def mod11(list, max_weight=7):
"""Implements Modulus 11 check digit algorithm.
It's a variation of the HP's Modulus 11 algorithm.
Requires the sequence to be calculated in a list of
integers.
The HP's Modulus 11 algorithm can be accessed through
the following link:
http://docs.hp.c... | 475e7e9b1403d62ad5a6ca040552bec633321512 | 47,051 |
def self_in_function(self=1) -> None:
"""A function containing `self` argument should not be ignored
>>> self_in_function()
None
"""
return None | 8ba962d11eefddf3ce916a3611c95cfe5e6e4f97 | 47,052 |
import csv
def get_tracked_sheets(cogs_dir, include_no_id=True):
"""Get the current tracked sheets in this project from sheet.tsv as a dict of sheet title ->
path & ID. They may or may not have corresponding cached/local sheets."""
sheets = {}
with open(f"{cogs_dir}/sheet.tsv", "r") as f:
read... | f0ebf10623f29b719801ee3069df0ce6160112c5 | 47,053 |
def update_over_braking_factor(driver, obf):
"""
Updates the over braking factor of the driver
:param driver: driver
:param obf: new over braking factor
:type driver: DriverProfile
:return: updated driver profile
"""
return driver.update_over_breaking_factor(obf) | a973fa3c6483d2ebf99770aac83c3057b0d14537 | 47,055 |
def artifact_fetch_error(reason):
"""artifact_fetch_error message"""
return"Failed to retrieve artifact: {}".format(reason) | 357183a1b11b027c9c9bd71776cec3e3760e519d | 47,056 |
import ast
def getconstant(tree):
"""Given an AST node `tree` representing a constant, return the contained raw value.
This encapsulates the AST differences between Python 3.8+ and older versions.
There are no `setconstant` or `makeconstant` counterparts, because you can
just create an `ast.Constant... | 82bfd20aec39b7d59d9f36642a53c706695cdb03 | 47,059 |
def collate_codes_offsts(rec_df, age_start, age_stop, age_in_months=False):
"""Return a single patient's EmbeddingBag lookup codes and offsets for the given age span and age units"""
codes = []
offsts = [0]
age_span = age_stop - age_start
if rec_df.empty:
codes = ['xxnone'] * age_span
... | e808f91d372cf9d9e0ad85bdf03e5e369f699f64 | 47,062 |
def sdp_term_p(f):
"""Returns True if `f` has a single term or is zero. """
return len(f) <= 1 | 1fbefa0f751d0583f4c20b81289df2b4ca4dfca6 | 47,063 |
def coding_problem_46(str):
"""
Given a string, find the longest palindromic contiguous substring. If there are more than one with the maximum
length, return any one. Examples:
>>> coding_problem_46("aabcdcb")
'bcdcb'
>>> coding_problem_46("bananas")
'anana'
"""
for length in range(... | af4033333274b23961edc048fdba034b29b801a7 | 47,066 |
def tostring(s):
"""
Convert to a string with quotes.
"""
return "'" + str(s) + "'" | 90c1cd55ecbf0e5562810399ab737f7b53b13305 | 47,067 |
from typing import List
def sort_array(arr: List[int]) -> List[int]:
"""
Sort given array without using sort()
>>> sort_array([4,3,2,1])
[1, 2, 3, 4]
Here, I'm going to use an algorithm called Merge Sort.
"""
if len(arr) > 1:
mid = len(arr) // 2
left = arr[:mid]
ri... | d6003eacfc5de35a28d8d4e087f3bd284e5fb18c | 47,068 |
def wifi_code(ssid, hidden, authentication_type, password=None):
"""Generate a wifi code for the given parameters
:ssid str: SSID
:hidden bool: Specify if the network is hidden
:authentication_type str: Specify the authentication type. Supported types: WPA, WEP, nopass
:password Optional[str]: ... | a479a2ea8c9a3aed40556e0c94f6dd5c8d67eca7 | 47,070 |
def calculate_polygon_area(corners):
"""Calculate 2D polygon area with given corners. Corners are assumed to be ordered.
Args:
corners (Nx2 array): xy-coordinates of N corner points
Returns:
float: polygon area"""
# Use the shoelace algorithm to calculate polygon's area
psum = 0
nsum = 0
npoin... | 87ed4e4c0c8e6655e70b6addf0588c37454f4968 | 47,071 |
def strip_newlines(string_in):
"""Tiny helper to strip newlines from json strings in CRD."""
return string_in.replace("\\n", "") | 5df483e5e14de042ca0a88f7baea9b44770be13c | 47,072 |
def get_global_stats(df):
"""Compute the metadata statistics of a given DataFrame and put them in a 2D list."""
stats = []
stats.append(["Number of rows", df.shape[0] ])
stats.append(["Number of columns", df.shape[1] ])
stats.append(["Number of duplicates", len(df) - len(df.drop_duplicates())])... | bf08c620e5937d73f1f0ce3a9ce251253919a516 | 47,075 |
def factorial_zeroes(n):
"""Consider a factorial like 19!:
19! = 1*2* 3*4* 5*6*7*8*9* 10* 11* 12* 13*14*15* 16* 17*18*19
A trailing zero is created with multiples of 10
and multiples of 10 are created with pairs of 5-multiples and 2-multiples.
Therefore, to count the number of zeros, we only need t... | f60b8be459cba3af795d360a51754fbc43959a63 | 47,076 |
import os
def use_gold_linker():
"""@return True if the gold linker should be used; False otherwise."""
return os.path.isfile("/usr/bin/ld.gold") | ad288f41b410df355c76dff88ccacbd4936ed6d9 | 47,080 |
def count_up_directory(path):
"""Returns a count of ../, for determining what the best path is to import"""
return path.count('../') | 1ecabc0582201b1f6a974975989aae56cb8387c9 | 47,081 |
def compare(M, A):
"""
:param M: Matrix with Names and DNA sequences
:param A: Array with DNA values
:return: String representing a person's name
"""
for line in M[1:]:
match = True
for j in range(1, len(line)):
if A[j-1] == line[j]:
continue
... | 286d14a53bf2e1cb6dbaa7592418f5626521b6ac | 47,084 |
def rootsearch(f, a, b, dx):
""" x1,x2 = rootsearch(f,a,b,dx).
Searches the interval (a,b) in increments dx for
the bounds (x1,x2) of the smallest root of f(x).
Returns x1 = x2 = None if no roots were detected.
"""
x1 = a
f1 = f(a)
x2 = a + dx
f2 = f(x2)
#
while f1*f2 > 0.0:
... | f6bb3ed2183850b2add575953ad6acee298f1a1f | 47,086 |
def eq_55_activation_of_heat_detector_device(
u: float,
RTI: float,
Delta_T_g: float,
Delta_T_e: float,
C: float
) -> float:
"""Equation 55 in Section 8.9 PD 7974-1:2019 calculates the heat detectors temperature rise.
PARAMETERS:
:param u: m/s, velocity of gases in p... | 480e33a54b769dce6d2167291c6058a8750418d0 | 47,087 |
import typing
def _convertbits(
data: typing.Iterable[int], frombits: int, tobits: int, pad: bool = True
) -> typing.List[int]:
"""General power-of-2 base conversion."""
# accumulator, will be filled later
acc: int = 0
# number of bits pushed to acc that have not yet been accounted for in ret
... | b8b8ffcfd14e053f69f1d5b06adf1193e6c0d7a6 | 47,088 |
def accuracy(y_test, y_pred):
"""Calcula métrica de acurácia para classificação."""
n = len(y_test)
corrects = sum([bool(y1 == y2) for y1, y2 in zip(y_test, y_pred)])
return corrects/n | cd5fb11842a7239071545e789bc1879dab9abf68 | 47,090 |
def unique(hasDupes):
"""
Removes duplicate elements from a list
@param hasDupes : a list with duplicate items
@return: list with duplicates removed
"""
ul = list(set(hasDupes))
ul.sort()
return ul | 88d3dc491a3519a46b95138f514d57319ccc3f3b | 47,091 |
def get_kernel_name(optype):
"""
for many similar kernels, we use one kernel predictor since their latency difference is negligible,
return the kernel name via the optype
"""
if "conv" in optype and "dwconv" not in optype:
optype = "conv-bn-relu"
if "dwconv" in optype:
optype = ... | b85e2f1e88df125c51b002718d41df0c5421c88c | 47,095 |
def get_matrix_stride(mat):
"""Get the stride between lines of a C matrix"""
itemsize = mat.itemsize
stride = mat.strides[0] // itemsize
assert mat.strides == (stride * itemsize, itemsize)
return stride | eec8e2f79b6ff9df449079298829413cdc3d248f | 47,096 |
def _map_nested_lists(f, x, *arg, **kw):
"""Recursively map lists, with non-lists at the bottom.
Useful for applying `dd.bdd.copy_bdd` to several lists.
"""
if isinstance(x, list):
return [_map_nested_lists(f, y, *arg, **kw) for y in x]
else:
return f(x, *arg, **kw) | a67e904bc6566c6a9ebf3c13d80a7bea9f9b3af4 | 47,097 |
async def find_channel(guild):
"""
Finds a suitable guild channel for posting the
welcome message. You shouldn't need to call this
yourself. on_guild_join calls this automatically.
Thanks FrostLuma for code!
"""
for c in guild.text_channels:
if not c.permissions_for(guild.me).send_m... | b3347be30652c0712104e8d35181ebdbfd101258 | 47,098 |
def get_dtype(matrix_type: int, precision: str='default'):
"""Reset the type if 'default' not selected"""
if precision == 'single':
if matrix_type in [1, 2]:
dtype = 'float32'
else:
dtype = 'complex64'
elif precision == 'double':
if matrix_type in [1, 2]:
... | 8908fbe7d5846a088c93ce3f44ddf925ca9eb0fe | 47,101 |
from pathlib import Path
def pathwalk(dir: Path) -> list[Path]:
"""Obtain all file paths in a directory and all it's subdirectories.
Function is recursive.
Args:
`dir` (`Path`): The starting, top-level directory to walk.
Returns:
(list): Containing Path objects of all filepaths in `... | e0cefd65166fb28b9c7c39acaf03978e9608c809 | 47,102 |
import os
def get_dataset_name():
"""Reads the name of the dataset from the environment variable `AICROWD_DATASET_NAME`."""
return os.getenv("AICROWD_DATASET_NAME", "cars3d") | b878df3ac7c61f43c3f107f8420e40d9b3b729fa | 47,103 |
def kataSlugToKataClass(kataSlug):
"""Tranform a kata slug to a camel case kata class"""
pascalCase = ''.join(x for x in kataSlug.title() if not x == '-')
# Java don't accept digits as the first char of a class name
return f"Kata{pascalCase}" if pascalCase[0].isdigit() else pascalCase | 92698e9002f42dd6f9abea1f6970b530575e54ef | 47,104 |
def least_significant_set_bit(n):
"""
Returns least-significant bit in integer 'n' that is set.
"""
m = n & (n - 1)
return m ^ n | 7813a92e53be724c14cbd68dc0cffd49490dc05e | 47,105 |
import os
import pickle
def get_T_V_T_dataset(file_path):
"""
list[
[label (int), [(x0, y0), (x1, y1), ..., (xn-2, yn-2), (xn-1, yn-1)]]
]
the range of x or y is 0 ~ 1
"""
tr_file_date_str = '2020_04_12'
va_file_date_str = '2020_03_07'
te_file_date_str = '2020_03_07'
... | 58fd4839e0ba914e611dd4c79faccb1aa8a43fcf | 47,108 |
import re
def apply_postprocessing(x_pred, postprocessing):
"""
Transforms x_pred depending on postprocessing parameters.
Parameters
----------
x_pred: pandas.Dataframe
Dataframe that needs to be modified
postprocessing: dict
Modifications to apply in x_pred dataframe.
Re... | 7704580745b06882e943ebe14065893238f9b548 | 47,110 |
def _is_id(value):
"""
Check if the value is valid InfluxDB ID.
:param value: to check
:return: True if provided parameter is valid InfluxDB ID.
"""
if value and len(value) == 16:
try:
int(value, 16)
return True
except ValueError:
return False... | 0606cb9da07f8a6a48f60ef7358746c1426f7d90 | 47,111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.