content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def _FormatDataTransferIdentifiers(client, transfer_identifier):
"""Formats a transfer config or run identifier.
Transfer configuration/run commands should be able to support different
formats of how the user could input the project information. This function
will take the user input and create a u... | 951a3576a1a53f9dd141e718c31c8b0314a550d7 | 705,575 |
import numpy as np
def Modelo(Mags, Phi, Me, alpha):
""" Modelo para ajustar
Parameters
----------
Mags, ERR : list
Magnitudes observadas
Phi, Me, alpha : .float, .float, .float
Parámetros del modelo
Returns
--------
F : list
Valores de la función... | 0e547058032bc682c6d0c5bffa5f00aaa1318989 | 705,576 |
import pickle
def read_img_pkl(path):
"""Real image from a pkl file.
:param path: the file path
:type path: str
:return: the image
:rtype: tuple
"""
with open(path, "rb") as file:
return pickle.load(file) | 8c7045d460e0583b02b565b818888c6b7991bc6b | 705,577 |
def conv_compare(node1, node2):
"""Compares two conv_general_dialted nodes."""
assert node1["op"] == node2["op"] == "conv_general_dilated"
params1, params2 = node1["eqn"].params, node2["eqn"].params
for k in ("window_strides", "padding", "lhs_dilation", "rhs_dilation",
"lhs_shape", "rhs_shape"):
... | cd7bad7d298e5f3faa971a9c968b3cd3a6a27812 | 705,578 |
import requests
from bs4 import BeautifulSoup
def get_urls():
""" get all sci-hub-torrent url
"""
source_url = 'http://gen.lib.rus.ec/scimag/repository_torrent/'
urls_list = []
try:
req = requests.get(source_url)
soups = BeautifulSoup(req.text, 'lxml').find_all('a')
for sou... | e14f15ebc7e39393bd614183e1eccb8fc1933359 | 705,579 |
import torch
def logsumexp(x, dim):
""" sums up log-scale values """
offset, _ = torch.max(x, dim=dim)
offset_broadcasted = offset.unsqueeze(dim)
safe_log_sum_exp = torch.log(torch.exp(x-offset_broadcasted).sum(dim=dim))
return safe_log_sum_exp + offset | 53a12a2c91c6a0cae3fcae46a860801f05480abe | 705,580 |
import os
def ls(directory, create=False):
"""
List the contents of a directory, optionally creating it first.
If create is falsy and the directory does not exist, then an exception
is raised.
"""
if create and not os.path.exists(directory):
os.mkdir(directory)
onlyfiles = [f
... | 42672a4070a00ca35ede6be83d7349518bcdb255 | 705,581 |
async def get_prices(database, match_id):
"""Get market prices."""
query = """
select
timestamp::interval(0), extract(epoch from timestamp)::integer as timestamp_secs,
round((food + (food * .3)) * 100) as buy_food, round((wood + (wood * .3)) * 100) as buy_wood, round((stone + (st... | 3571006c37319135a3202622b73e7e2379ca93ee | 705,582 |
import os
def ete_database_data():
""" Return path to ete3 database json """
user = os.environ.get('HOME', '/')
fp = os.path.join(user, ".mtsv/ete_databases.json")
if not os.path.isfile(fp):
with open(fp, 'w') as outfile:
outfile.write("{}")
return fp | 19fbb418ae91dab9c3dfc94da4a27375f507780b | 705,583 |
import os
def link(srcPath, destPath):
"""create a hard link from srcPath to destPath"""
return os.link(srcPath, destPath) | cdcb988e953c3918e616b179f3dc5d547bb75ccf | 705,584 |
import inspect
import sys
def is_implemented_in_notebook(cls):
"""Check if the remote class is implemented in the environments like notebook(e.g., ipython, notebook).
Args:
cls: class
"""
assert inspect.isclass(cls)
if hasattr(cls, '__module__'):
cls_module = sys.modules.get(cls.... | f017fea802fc4c98af1282ee51a51304d8ac01d9 | 705,585 |
def _pool_tags(hash, name):
"""Return a dict with "hidden" tags to add to the given cluster."""
return dict(__mrjob_pool_hash=hash, __mrjob_pool_name=name) | de9a9e7faa4d4f9dd3bfe05cb26790ff8ae66397 | 705,586 |
def get_nb_build_nodes_and_entities(city, print_out=False):
"""
Returns number of building nodes and building entities in city
Parameters
----------
city : object
City object of pycity_calc
print_out : bool, optional
Print out results (default: False)
Returns
-------
... | ff3b36dcd2ca7cd0be316b573f20a6dd16bd1c1d | 705,587 |
def construct_aircraft_data(args):
"""
create the set of aircraft data
:param args: parser argument class
:return: aircraft_name(string), aircraft_data(list)
"""
aircraft_name = args.aircraft_name
aircraft_data = [args.passenger_number,
args.overall_length,
... | da77ae883d67879b9c51a511f46173eb5366aead | 705,588 |
def Oplus_simple(ne):
"""
"""
return ne | 7476203cb99ee93dddcf9fda249f5532e908e40f | 705,589 |
def lin_exploit(version):
"""
The title says it all :)
"""
kernel = version
startno = 119
exploits_2_0 = {
'Segment Limit Privilege Escalation': {'min': '2.0.37', 'max': '2.0.38', 'cve': ' CVE-1999-1166', 'src': 'https://www.exploit-db.com/exploits/19419/'}
}
exploits_2_2 = {
... | 499e21091fb508b26564d06ad119d8b8ea783443 | 705,590 |
def cartesian2complex(real, imag):
"""
Calculate the complex number from the cartesian form: z = z' + i * z".
Args:
real (float|np.ndarray): The real part z' of the complex number.
imag (float|np.ndarray): The imaginary part z" of the complex number.
Returns:
z (complex|np.ndar... | 1fd44bc0accff8c9f26edfa84f4fcfafb2323728 | 705,591 |
def upper_case(string):
"""
Returns its argument in upper case.
:param string: str
:return: str
"""
return string.upper() | bbf3fc8b856d466ec73229145443566d85a3457a | 705,592 |
import os
def createNewLetterSession(letter):
"""
# Take letter and create next session folder (session id is current max_id + 1)
# Return path to session directory
"""
# Search for last training folder
path = "gestures_database/"+letter+"/"
last = -1
for r,d,f in os.walk(path):
for folder in d:
last ... | fc6da33f4a815db30c09bf6477b9707323a6da05 | 705,594 |
def total_cost(content_cost, style_cost, alpha, beta):
"""Return a tensor representing the total cost."""
return alpha * content_cost + beta * style_cost | 98d42bd8d62dc8cd7110b2f5eb9a9a4e4eb6bc65 | 705,595 |
import codecs
def get_line(file_path, line_rule):
"""
搜索指定文件的指定行到指定行的内容
:param file_path: 指定文件
:param line_rule: 指定行规则
:return:
"""
s_line = int(line_rule.split(',')[0])
e_line = int(line_rule.split(',')[1][:-1])
result = []
# with open(file_path) as file:
file = codecs.o... | a6ccda48f8083e5ff6827306f4abd7f19e8d445c | 705,596 |
def _is_unique_rec_name(info_name):
"""
helper method to see if we should use the uniqueness recommendation on the
fact comparison
"""
UNIQUE_INFO_SUFFIXES = [".ipv4_addresses", ".ipv6_addresses", ".mac_address"]
UNIQUE_INFO_PREFIXES = ["fqdn"]
if info_name.startswith("network_interfaces.lo... | cba744e1e5b6a9612363d2ca12d4751e1894c8ad | 705,597 |
def _json_view_params(shape, affine, vmin, vmax, cut_slices, black_bg=False,
opacity=1, draw_cross=True, annotate=True, title=None,
colorbar=True, value=True):
""" Create a dictionary with all the brainsprite parameters.
Returns: params
"""
# Set color pa... | 50ea71a5a99facf4c472f0c18984d84e23b8e301 | 705,598 |
def add_metadata(infile, outfile, sample_metadata):
"""Add sample-level metadata to a biom file. Sample-level metadata
should be in a format akin to
http://qiime.org/tutorials/tutorial.html#mapping-file-tab-delimited-txt
:param infile: String; name of the biom file to which metadata
... | e779f876159741de60e99002a90906b151dc7530 | 705,599 |
def get_qc_data(sample_prj, p_con, s_con, fc_id=None):
"""Get qc data for a project, possibly subset by flowcell.
:param sample_prj: project identifier
:param p_con: object of type <ProjectSummaryConnection>
:param s_con: object of type <SampleRunMetricsConnection>
:returns: dictionary of qc resul... | f267148f48f86151852e12fa3be8d5f8aefc6b11 | 705,600 |
def sql_sanitize(sql_name):
"""
Return a SQL name (table or column) cleaned of problematic characters.
ex. punctuation )(][; whitespace
Don't use with values, which can be properly escaped with parameterization.
Ideally retaining only alphanumeric char.
Credits: Donald Miner, Source: StackOverfl... | 9ce9e0e8bed2348079fb23f2d27c53880fa1c795 | 705,601 |
def render_horizontal_fields(*fields_to_render, **kwargs):
"""Render given fields with optional labels"""
labels = kwargs.get('labels', True)
media = kwargs.get('media')
hidden_fields = []
visible_fields = []
for bound_field in fields_to_render:
if bound_field.field.widget.is_hidden:
... | 22ac9c05b602c0f65ab2fc348ab9399855780bc3 | 705,602 |
def midpoint(rooms):
"""
Helper function to help find the midpoint between the two rooms.
Args:
rooms: list of rooms
Returns:
int: Midpoint
"""
return rooms[0] + (rooms[0] + rooms[2]) // 2, rooms[1] + (rooms[1] + rooms[3]) // 2 | 60b3ba53fb15154ff97ab9c6fa3cf1b726bc2df1 | 705,603 |
import random
def generate_concept_chain(concept_desc, sequential):
"""
Given a list of availiable concepts, generate a dict with (start, id) pairs
giving the start of each concept.
Parameters
----------
sequential: bool
If true, concept transitions are
determined by ID witho... | fcfeb345d92d627684d04da4c1d445120554bf15 | 705,604 |
def doFilter(pTable, proxyService):
"""
filter candidates by column header candidates
- column headers are kept, if they support at least (minSupport * #rows) many cells
- only filter for columns that are part of the targets (if activated)
subsequently remove:
- CTA candidates with less support... | 8b28f945e94e37302b2086e23f695c40c08b8d7c | 705,605 |
def int_or_float(x):
"""Convert `x` to either `int` or `float`, preferring `int`.
Raises:
ValueError : If `x` is not convertible to either `int` or `float`
"""
try:
return int(x)
except ValueError:
return float(x) | d0a4def320f88655e494f89b7239e47e1ee70d0d | 705,606 |
def nohighlight(nick):
"""add a ZWNJ to nick to prevent highlight"""
return nick[0] + "\u200c" + nick[1:] | 1b8d0cafc5df4a442daafdece59af1675ab1de33 | 705,607 |
import inspect
def obj_src(py_obj, escape_docstring=True):
"""Get the source for the python object that gets passed in
Parameters
----------
py_obj : callable
Any python object
escape_doc_string : bool
If true, prepend the escape character to the docstring triple quotes
Retu... | 8ce0c7cc7672de5005b5a1c60e6b6cf5fa9ee050 | 705,608 |
import random
def mutate_word(word):
"""Introduce a random change into the word: delete, swap, repeat, and add
stray character. This may raise a ValueError. """
word = list(word)
choice = random.randrange(4)
if choice == 0: # Delete a character
word.pop(random.randrange(len(word)))
... | f3b45f36893a7541131710ada5f1343387f06797 | 705,610 |
def pcc_vector(v1, v2):
"""Pearson Correlation Coefficient for 2 vectors
"""
len1 = len(v1)
len2 = len(v2)
if len1 != len2:
return None
else:
length = len1
avg1 = 1.0 * sum(v1) / len(v1)
avg2 = 1.0 * sum(v2) / len(v2)
dxy = [(v1[i] - avg1) * (v2[i] - avg2) for i in ra... | 98e5f3cc304a5d844be479d65ab7eeb760a34ba3 | 705,611 |
def decode(argument: str) -> tuple[list[int], ...]:
"""Decode argument string from command line
:param argument: argument string
:return: pair of list of digits
"""
char_lists = map(list, argument.split('-'))
range_ = tuple(list(map(int, clist)) for clist in char_lists)
return range_ | d3805396cab52fc09896ca9553f1ac3450f27e99 | 705,612 |
import os
def join_legacy_read_path(sample_path: str, suffix: int) -> str:
"""
Create a path string for a sample read file using the old file name convention (eg. reads_1.fastq).
:param sample_path: the path to the sample directory
:param suffix: the read file suffix
:return: the read path
"... | b6e12de4edfec05fb8a5fa2363dce284dcfdd5f0 | 705,613 |
def wrapper_configuration_get(): # noqa: E501
"""gets configuration details on the current wrapper configuration
# noqa: E501
:rtype: object
"""
return 'do some magic!' | 85ac6abbf09f93a08295584d7051aad2e8cad8d6 | 705,614 |
def d_enter_waste_cooler(W_mass, rho_waste, w_drift):
"""
Calculates the tube's diameter of enter waste to waste cooler.
Parameters
----------
W_mass : float
The mass flow rate of waste, [kg/s]
rho_waste : float
The density of liquid at boilling temperature, [kg/m**3]
w_drift... | 651c1adc0b90a286c2c8685c389268bc8834ad73 | 705,615 |
import re
import os
import time
def approx_version_number():
"""
In the event that git is unavailable and the VERSION file is not present
this returns a "version number" in the following precedence:
- version number from path
downloads of viral-ngs from GitHub tagged re... | 16adf3e5c274cf86bc9a7b3b53889e5340021798 | 705,616 |
def _x_orientation_rep_dict(x_orientation):
""""Helper function to create replacement dict based on x_orientation"""
if x_orientation.lower() == 'east' or x_orientation.lower() == 'e':
return {'x': 'e', 'y': 'n'}
elif x_orientation.lower() == 'north' or x_orientation.lower() == 'n':
return {... | 83434a8aef7003146a19c470b831e8e9cfa85f19 | 705,617 |
def _get_option_of_highest_precedence(config, option_name):
"""looks in the config and returns the option of the highest precedence
This assumes that there are options and flags that are equivalent
Args:
config (_pytest.config.Config): The pytest config object
option_name (str): The name of... | 4f3bca4ff5b0a1eb04fbdc7a5d22bc09dbc95df6 | 705,618 |
import math
def isPrime(n):
"""
check is Prime,for positive integer.
使用试除法
"""
if n <= 1:
return False
if n == 2:
return True
i = 2
thres = math.ceil(math.sqrt(n))
while i <= thres:
if n % i == 0:
return False
i += 1
return True | 458775fbd324dc976c91a035898b3122e6bc1109 | 705,620 |
def action_prop(param, val=1):
"""A param that performs an action"""
def fdo(self):
self.setter(param, val)
return fdo | 6a4f6e7e178e62755113d6b93a59534675dfa2dd | 705,621 |
def find_or_create(find, create):
"""Given a find and a create function, create a resource if it doesn't exist"""
result = find()
return result if result else create() | ffe608bf2da1b83d662b93266f4309976424300f | 705,622 |
import math
def Gsigma(sigma):
"""Pickle a gaussian function G(x) for given sigma"""
def G(x):
return (math.e ** (-(x**2)/(2*sigma**2)))/(2 * math.pi* sigma**2)**0.5
return G | 77eac3ca8b6ced0063074527b83c50e8681f980d | 705,623 |
def transform(data, transformer):
"""This hook defines how DataRobot will use the trained object from fit() to transform new data.
DataRobot runs this hook when the task is used for scoring inside a blueprint.
As an output, this hook is expected to return the transformed data.
The input parameters are p... | b52577c0b2a3f3edb1297dcf9c567f9845f04bd5 | 705,624 |
def convert_decimal_to_binary(number):
"""
Parameters
----------
number: int
Returns
-------
out: str
>>> convert_decimal_to_binary(10)
'1010'
"""
return bin(number)[2:] | 01a9be2e70c87091adc1d85759075668da9270f2 | 705,626 |
def choisir_action():
"""Choisir action de cryptage ou de décryptage
Entree : -
Sortie: True pour cryptage, False pour décryptage"""
action_est_crypter = True
action = input("Quelle est l'action, crypter ou décrypter ? \n<Entrée> pour crypter, autre touche pour decrypter, ou <Crtl> + Z ou X pour arréter.\n")
... | c0bceb748afb1fc32b865136c4a477f06a6412b2 | 705,627 |
import ast
import random
def t_rename_local_variables(the_ast, all_sites=False):
"""
Local variables get replaced by holes.
"""
changed = False
candidates = []
for node in ast.walk(the_ast):
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
if node.id not i... | 8faeea81faac55d5d45b897776cd87cb508404a5 | 705,628 |
from typing import List
def get_scale(notes: List[str]) -> int:
"""Convert a list of notes to a scale constant.
# Args
- *notes*: list of notes in the scale. This should be a list of string
where each string is a note ABC notation. Sharps should be
represented with a pound sign preceding... | 91cbcc7bfa05df52adf741b85f78beeabf819966 | 705,629 |
import math
def slurm_format_bytes_ceil(n):
""" Format bytes as text.
SLURM expects KiB, MiB or Gib, but names it KB, MB, GB. SLURM does not handle Bytes, only starts at KB.
>>> slurm_format_bytes_ceil(1)
'1K'
>>> slurm_format_bytes_ceil(1234)
'2K'
>>> slurm_format_bytes_ceil(12345678)
... | ce48c778b9605105ed9b66a55d27796fb90499cc | 705,630 |
def make_word_dict():
"""read 'words.txt ' and create word list from it
"""
word_dict = dict()
fin = open('words.txt')
for line in fin:
word = line.strip()
word_dict[word] = ''
return word_dict | a4213cf5ff246200c7a55a6d1525d6fd6067e31f | 705,631 |
def toCamelCase(string: str):
"""
Converts a string to camel case
Parameters
----------
string: str
The string to convert
"""
string = str(string)
if string.isupper():
return string
split = string.split("_") # split by underscore
final_split = []
for... | 5197ad3353f2e88ccf1dfca62aeae59260e016e7 | 705,632 |
def rowwidth(view, row):
"""Returns the number of characters of ``row`` in ``view``.
"""
return view.rowcol(view.line(view.text_point(row, 0)).end())[1] | f8db1bf6e3d512d1a2bd5eeb059af93e8ac3bc5f | 705,633 |
def retournerTas(x,numéro):
"""
retournerTas(x,numéro) retourne la partie du tas x qui commence à
l'indice numéro
"""
tasDuBas = x[:numéro]
tasDuHaut = x[numéro:]
tasDuHaut.reverse()
result = tasDuBas + tasDuHaut
# print(result)
return result | 579798cf5fe8bec02109bfd46c5a945faee1a42c | 705,634 |
def sec2msec(sec):
"""Convert `sec` to milliseconds."""
return int(sec * 1000) | f1b3c0bf60ab56615ed93f295e7716e56c6a1117 | 705,635 |
def object_get_HostChilds(obj):
"""Return List of Objects that have set Host(s) to this object."""
# source:
# FreeCAD/src/Mod/Arch/ArchComponent.py
# https://github.com/FreeCAD/FreeCAD/blob/master/src/Mod/Arch/ArchComponent.py#L1109
# def getHosts(self,obj)
hosts = []
for link in obj.InLis... | dccba2ef151207ebaa42728ee1395e1b0ec48e7d | 705,636 |
import torch
def collate_fn(batch):
"""
Collate function for combining Hdf5Dataset returns
:param batch: list
List of items in a batch
:return: tuple
Tuple of items to return
"""
# batch is a list of items
numEntries = [];
allTensors = [];
allLabels = [];
for... | b49ec88b4de844787d24140f5ef99ad9a573c6e3 | 705,637 |
import torch
def sparsity_line(M,tol=1.0e-3,device='cpu'):
"""Get the line sparsity(%) of M
Attributes:
M: Tensor - the matrix.
tol: Scalar,optional - the threshold to select zeros.
device: device, cpu or gpu
Returns:
spacity: Scalar (%)- the spacity of the matr... | b8675a768c8686571d1f7709d89e3abeb5b56a80 | 705,639 |
import math
def tgamma ( x ) :
"""'tgamma' function taking into account the uncertainties
"""
fun = getattr ( x , '__tgamma__' , None )
if fun : return fun()
return math.gamma ( x ) | 35c73e2e0a9945cb38beffb6376dd7b7bc6443e9 | 705,640 |
import os
def get_template_filepath(filename, basepath="templates"):
"""
Get the full path to the config templates, using a relative path to where the shippy script is stored
:param filename: (str) Name of the template file to look for
:param basepath: (str) Base directory to search for templates. De... | f1972c3366590449d9d747b1d03153e6fb0f1f2b | 705,641 |
import random
def findKthSmallest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def partition(left, right, pivot_index):
pivot = nums[pivot_index]
# 1. move pivot to end
nums[pivot_index], nums[right] = nums[right], nums[pivot_index]
... | d82176bd9539cf36416c5dc3c7da53a99f2a8f62 | 705,642 |
def lang_not_found(s):
"""Is called when the language files aren't found"""
return s + "⚙" | 064d73e10d6e2aa9436557b38941ed2eb020d7bb | 705,643 |
def same_variable(a, b):
"""
Cette fonction dit si les deux objets sont en fait le même objet (True)
ou non (False) s'ils sont différents (même s'ils contiennent la même information).
@param a n'importe quel objet
@param b n'importe quel objet
@return ``True`` ... | 0c33a33e01e5457c7216982df580abc90db47d2f | 705,644 |
import math
def yolox_semi_warm_cos_lr(
lr,
min_lr_ratio,
warmup_lr_start,
total_iters,
normal_iters,
no_aug_iters,
warmup_total_iters,
semi_iters,
iters_per_epoch,
iters_per_epoch_semi,
iters,
):
"""Cosine learning rate with warm up."""
min_lr = lr * min_lr_ratio
... | ac6b1850031a5c36f8de2c7597c374bc401aaee3 | 705,645 |
def on_segment(p, r, q, epsilon):
"""
Given three colinear points p, q, r, and a threshold epsilone, determine if
determine if point q lies on line segment pr
"""
# Taken from http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment
cr... | b8517fc9d3c6d916cac698913c35ba4e5d873697 | 705,646 |
def ja_nein_vielleicht(*args):
"""
Ohne Argumente erstellt diese Funktion eine Ja-Nein-Vielleicht Auswahl. Mit
einem Argument gibt es den Wert der entsprechenden Auswahl zurück.
"""
values = {
True: "Vermutlich ja",
False: "Vermutlich nein",
None: "Kann ich noch nicht sagen"
... | a4e58ab3f2dc9662e1c054ddfd32ff1ae988b438 | 705,647 |
def get_group(yaml_dict):
"""
Return the attributes of the light group
:param yaml_dict:
:return:
"""
group_name = list(yaml_dict["groups"].keys())[0]
group_dict = yaml_dict["groups"][group_name]
# Check group_dict has an id attribute
if 'id' not in group_dict.keys():
prin... | db9e027594d3a9a9e0a1838da62316cfe6e0c380 | 705,648 |
def return_state_dict(network):
"""
save model to state_dict
"""
feat_model = {k: v.cpu() for k, v in network["feat_model"].state_dict().items()}
classifier = {k: v.cpu() for k, v in network["classifier"].state_dict().items()}
return {"feat_model": feat_model, "classifier": classifier} | c0bcd9bd84f7c722c7de5f52d12cf6762a86e1e0 | 705,649 |
def transform(func, geom):
"""Applies `func` to all coordinates of `geom` and returns a new
geometry of the same type from the transformed coordinates.
`func` maps x, y, and optionally z to output xp, yp, zp. The input
parameters may iterable types like lists or arrays or single values.
The output ... | 71bde1500ec8370a7718542ee26181d2aad6591f | 705,650 |
def dict_zip(*dicts):
"""
Take a series of dicts that share the same keys, and reduce the values
for each key as if folding an iterator.
"""
keyset = set(dicts[0])
for d in dicts:
if set(d) != keyset:
raise KeyError(f"Mismatched keysets in fold_dicts: {sorted(keyset)}, {sorte... | 47416641a6451828b78ae6dfd81a48676fcea71f | 705,651 |
import argparse
def process_command_line():
"""
Parse command line arguments
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
Return a Namespace representing the argument list.
"""
# Create the parser
parser = argparse.ArgumentParser(prog='obflow_6_output',
... | 5563be1fa3e122222fccd9ca1edfce25907dcc58 | 705,652 |
import os
def path_splitter(path):
"""
Split a path into its constituent parts.
Might be better written as a recursive function.
:param path: The path to split.
:return: A list of the path's constituent parts.
"""
res = []
while True:
p = os.path.split(path)
if p[0] == ... | cf9ec119eb302ff45b7835a00e235215110c8dc5 | 705,654 |
def check_flush(hand):
"""Check whether the hand has a flush; returns a boolean."""
if len(hand) == len(hand.by_suit(hand[0].suit)):
return True
return False | de11f50f11b477e61f284063c7f0da0dda2dd87e | 705,655 |
import torch
def binary_accuracy(preds, y):
"""
Returns accuracy per batch
:param preds: prediction logits
:param y: target labels
:return: accuracy = percentage of correct predictions
"""
# round predictions to the closest integer
rounded_predictions = torch.round(torch.sigmoid(preds... | 2a321bb9e60a937a879619c2fa3baf1cbe968a33 | 705,656 |
import csv
def load_taxondump(idpath):
"""Importing the Acidobacteria taxon IDs"""
taxons = {}
with open(idpath) as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
taxons[row[1]] = row[0]
return taxons | b20c973f97d609b646e5c15be7cc320019f21236 | 705,657 |
import re
def _to_numeric_range(cell):
"""
Translate an Excel cell (eg 'A1') into a (col, row) tuple indexed from zero.
e.g. 'A1' returns (0, 0)
"""
match = re.match("^\$?([A-Z]+)\$?(\d+)$", cell.upper())
if not match:
raise RuntimeError("'%s' is not a valid excel cell address" % cell)... | 468f452a7e4d4b045ecbb1a1fc261712fb25f3fc | 705,658 |
def iter_children(param,childlist=[]):
"""
| Iterator over all sub children of a given parameters.
| Returns all childrens names.
=============== ================================= ====================================
**Parameters** **Type** **Description*... | 2edbdccc5957cbe6131da70d6dfc24ea67a19e69 | 705,659 |
import re
def parse_regex(ctx, param, values):
"""Compile a regex if given.
:param click.Context ctx: click command context.
:param click.Parameter param: click command parameter (in this case,
``ignore_regex`` from ``-r|--ignore-regiex``).
:param list(str) values: list of regular expressions... | b920d5a406ac3b7a8f28bb9125313c90eec5e212 | 705,661 |
import os
def FileJustRoot(fileName):
""" Gets just the root of the file name """
try:
return os.path.splitext(fileName)[0]
except:
return "" | 18fed9fbbaa0d5f3f08c89ff36a1f752605c52d2 | 705,662 |
def get_query_string(**kwargs):
"""
Concatenates the non-None keyword arguments to create a query string for ElasticSearch.
:return: concatenated query string or None if not arguments were given
"""
q = ['%s:%s' % (key, value) for key, value in kwargs.items() if value not in (None, '')]
return ... | cc73c157a8975e5df9c98efcd5b10396e5175486 | 705,663 |
def add_quotes(path):
"""Return quotes if needed for spaces on path."""
quotes = '"' if ' ' in path and '"' not in path else ''
return '{quotes}{path}{quotes}'.format(quotes=quotes, path=path) | 6e65da4512183ef62a0ac22b4c3c74f9e5273fbd | 705,664 |
def find_possible_words(word: str, dictionary: list) -> list:
"""Return all possible words from word."""
possible_words = []
first_character = word[0]
last_character = word[len(word) - 1]
for dictionary_entry in dictionary:
if (dictionary_entry.startswith(first_character) and
... | a3e63e6b6b9d8de3ca718cfc8e031bbc34630d50 | 705,665 |
def bostock_cat_colors(color_sets = ["set3"]):
"""
Get almost as many categorical colors as you please.
Get more than one of the color brewer sets with ['set1' , 'set2']
Parameters
----------
sets : list
list of color sets to return valid options are
(set1, set2, set3, paste... | d01a2c833c3ee4ab1a196184ec4aecdb6cfc97a0 | 705,666 |
def _quote_embedded_quotes(text):
"""
Replace any embedded quotes with two quotes.
:param text: the text to quote
:return: the quoted text
"""
result = text
if '\'' in text:
result = result.replace('\'', '\'\'')
if '"' in text:
result = result.replace('"', '""')
ret... | 71231e590e025c2ceb7b2dd4fde4465a9ff61a4c | 705,668 |
def exp2(x):
"""Calculate 2**x"""
return 2 ** x | d76d1e344e79ebb05d38a2e7e6ef36b6f367e85b | 705,669 |
def archived_minute(dataSet, year, month, day, hour, minute):
"""
Input: a dataset and specific minute
Output: a list of ride details at that minute or -1 if no ride during that minute
"""
year = str(year)
month = str(month)
day = str(day)
#Converts hour and minute into 2 digit integers (that are strings)
ho... | e550cb8ae5fbcfcc2a0b718dc2e4f3372f100015 | 705,670 |
def inputRead(c, inps):
"""
Reads the tokens in the input channels (Queues) given by the list inps
using the token rates defined by the list c.
It outputs a list where each element is a list of the read tokens.
Parameters
----------
c : [int]
List of token consumption rates.
inp... | ea70548f7da4fae66fe5196734bbf39deb255537 | 705,671 |
def myfn(n):
"""打印hello world
每隔一秒打印一个hello world,共n次
"""
if n == 1:
print("hello world!")
return
else:
print("hello world!")
return myfn(n - 1) | 4405e8b4c591c435d43156283c0d8e2aa9860055 | 705,672 |
import requests
def check_internet_connection():
"""Checks if there is a working internet connection."""
url = 'http://www.google.com/'
timeout = 5
try:
_ = requests.get(url, timeout=timeout)
return True
except requests.ConnectionError as e:
return False
return False | 5f587e6077377196d2c89b39f5be5d6a2747e093 | 705,673 |
def wall_filter(points, img):
"""
Filters away points that are inside walls. Works by checking where the refractive index is not 1.
"""
deletion_mask = img[points[:, 0], points[:, 1]] != 1
filtered_points = points[~deletion_mask]
return filtered_points | 05a34602e8a555eb1f1739f5de910a71514a92ae | 705,674 |
def roq_transform(pressure, loading):
"""Rouquerol transform function."""
return loading * (1 - pressure) | b69d83579cdb904cc7e3625a371e1f6c0573e44b | 705,675 |
def get_image_urls(ids):
"""function to map ids to image URLS"""
return [f"http://127.0.0.1:8000/{id}" for id in ids] | a70cd4eea39ea277c82ccffac2e9b7d68dd7c801 | 705,676 |
import torch
def caption_image_batch(encoder, decoder, images, word_map, device, max_length):
"""
Reads an image and captions it with beam search.
:param encoder: encoder model
:param decoder: decoder model
:param image: image
:param word_map: word map
:param beam_size: number of sequences... | 192def399d6b05947df7bac06e90836771a22dda | 705,677 |
def descope_queue_name(scoped_name):
"""Descope Queue name with '.'.
Returns the queue name from the scoped name
which is of the form project-id.queue-name
"""
return scoped_name.split('.')[1] | 24de78d12399e0894f495cd5c472b10c2315e4af | 705,679 |
import os
def system_info(x):
""" Get system info. """
return list(os.uname()) | 4231e967190daee2ae7c6d9823878bcb0a957bc1 | 705,680 |
import torch
def rebalance_binary_class(label, mask=None, base_w=1.0):
"""Binary-class rebalancing."""
weight_factor = label.float().sum() / torch.prod(torch.tensor(label.size()).float())
weight_factor = torch.clamp(weight_factor, min=1e-2)
alpha = 1.0
weight = alpha * label*(1-weight_factor)/weig... | 5adf3a21e4cc4b9e7bf129ecf31cfe37ab7a305a | 705,681 |
def from_base(num_base: int, dec: int) -> float:
"""Returns value in e.g. ETH (taking e.g. wei as input)."""
return float(num_base / (10 ** dec)) | 447a07b3e282e5104f8dcd50639c658f3013ec7a | 705,682 |
def make_auth_header(auth_token):
"""Make the authorization headers to communicate with endpoints which implement Auth0 authentication API.
Args:
auth_token (dict): a dict obtained from the Auth0 domain oauth endpoint, containing the signed JWT
(JSON Web Token), its expiry, the scopes grant... | e7c9b93cfbda876668068fb871d3abaf06157204 | 705,683 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.