content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def import_module(dotted_path):
"""Import a module path like 'a.b.c' => c module"""
mod = __import__(dotted_path, globals(), locals(), [])
for name in dotted_path.split('.')[1:]:
try:
mod = getattr(mod, name)
except AttributeError:
raise AttributeError("Module %r has ... | ae20284dbf86d86bea7d4fd9e89dd392a8f49ba4 | 654,407 |
def getOverlap(a, b):
"""Return the overlap of two ranges. If the values of a overlap with
the values of b are mutually exclusive then return 0"""
return max(0, 1 + min(a[1], b[1]) - max(a[0], b[0])) | dbd74e31b63a512649ff7082a4ffc6ec92994446 | 654,409 |
def html_path(request, goldendir):
"""NYU Academic Calendar HTML file path"""
path = 'New York University - University Registrar - Calendars - Academic Calendar.html' # noqa
return goldendir.join(path) | bb31deca3003b7afad4ab6eb951a8c7e927b51c0 | 654,410 |
def brightness_from_percentage(percent):
"""Convert percentage to absolute value 0..255."""
return (percent * 255.0) / 100.0 | fa3ca902e0edba34db2b864a94d895ee47841879 | 654,411 |
import torch
def _log_sum_exp(mat, axis=0):
"""
Computes the log-sum-exp of a matrix with a numerically stable scheme,
in the user-defined summation dimension: exp is never applied
to a number >= 0, and in each summation row, there is at least
one "exp(0)" to stabilize the sum.
For instance, ... | 6c5302c3542ac441698b9ace3a2e8ea42631cd51 | 654,412 |
import sys
def task_dist():
"""Generate dist"""
return {'actions': [[sys.executable, '-m', 'build']],
'task_dep': ['build']} | 2e1dd8b8fa7502b3edddee0c83c9f6a305dc2bb9 | 654,413 |
import json
def to_json_sorted(text):
"""
Converts text to sorted(alphabetically on the attribute names) json value
:param text:
text to be converted to json
:return:
sorted json value
"""
json_value = json.dumps(json.loads(text), sort_keys=True, indent=0)
retur... | a99f08e7536565630824aa38c4982868ebd76a5b | 654,414 |
def pauli_block(M, idim):
""" Get the I, x, y, z component of a matrix.
:param M: The input matrix, aranged in four blocks:
[[upup, updn], [dnup, dndn]]. let norb be number of orbitals in
each block. (so M has dim 2norb1*2norb2)
:param idim: 0, 1,2, 3 for I , x, y, z.
:returns: the idim(th) co... | 6cdd71600764eaa1ef5d3c42c121be204822f10d | 654,415 |
import os
def _get_env_variable_value(env_variable):
"""This function returns the value of a given environment variable name.
.. versionadded:: 2.2.0
:param env_variable: The name of the environment variable to return
:type env_variable: str
:returns: The value of the environment variable or ``N... | e49287717b7946007f30e6fd10bfb4536e39a86a | 654,416 |
def get_column_headers(results):
"""Return the columnHeaders object from a Google Analytics API request.
:param results: Google Analytics API results set
:return: Python dictionary containing columnHeaders data
"""
if results['columnHeaders']:
return results['columnHeaders'] | e86b6363e74ea50872c1fa85cb6841d8bc194026 | 654,417 |
def find_pax(pnr, paxnum):
"""
Pax number is paxnum - 1 because paxes stored in list.
"""
paxes = pnr["name"]
if len(paxes) < int(paxnum):
return None
return paxes[int(paxnum) - 1] | 646fec4fb2397911a2ef3b41e5863b10f21df291 | 654,418 |
def true_fracture_stress(fracture_force, initial_cross_section, reduction_area_fracture):
"""
Calculation of the true fracture stress (euqation FKM Non-linear (static assessment))
Parameters
----------
fracture_force : float
from experimental results
initial_cross_section : float
... | 4da4aa2f6fac253803e107c0d81b0348d1b3a5a2 | 654,419 |
import random
def get_interp_method(interp, sizes=()):
"""Get the interpolation method for resize functions.
The major purpose of this function is to wrap a random interp method selection
and a auto-estimation method. """
if interp == 9:
if sizes:
assert len(sizes) == 4
... | 3d793d92df682ed1cadc24cc99d359b8e534a1c2 | 654,420 |
def build_url(video_id: str) -> str:
"""Converts a YouTube video ID into a valid URL.
Args:
video_id: YouTube video ID.
Returns:
YouTube video URL.
"""
return f"https://youtube.com/watch?v={video_id}" | a5e69ba3092e9deb3be9faac2f7c40bc7979b949 | 654,421 |
def validacion_entero(entero):
"""
float --> bool
OBJ: Validar si el dato introducido por el usuario es un número entero
"""
try:
dato = int(entero)
validacion = True
except:
print ('El dato introducido no es entero.')
validacion = False
return validacion | 8e0bbd5a52735ab6da5a1a5f720182889c06bc7d | 654,422 |
import subprocess
def get_goversion():
"""
:returns The go-version, assuming that go is installed.
"""
return subprocess.check_output(["go", "version"]).decode().strip() | ced6cdb2a803d4f201985a24d97c1a4e19c16f88 | 654,423 |
def partition_seq(seq, size):
"""
Splits a sequence into an iterable of subsequences. All subsequences are of the given size,
except the last one, which may be smaller. If the input list is modified while the returned
list is processed, the behavior of the program is undefined.
:param seq: the list... | 599e48da0db19b7fe7a5730a0659ac7ca130abf2 | 654,424 |
def unpad_pkcs5(padded, block_size):
"""
Returns the unpadded version of a data padded using PKCS5.
:param padded: String padded with PKCS5.
:type padded: :class:`str`
:return: :class:`str` -- Original, unpadded string.
"""
assert padded and len(padded) % block_size == 0
pad_size = ord... | c45c4463f543960f4e3f605abc7eb624736560e7 | 654,425 |
def write_file(filename="", text=""):
"""
Writes a string to a text file (UTF8) and
returns the number of characters written.
"""
with open(filename, 'w') as f:
return f.write(text) | 502790654937b63290d4219e901a8f8febe48a9c | 654,426 |
import math
def minBoltMetric(D, p, sigmay_b, sigmay_m, T = 0):
"""
D : Nominal diameter (mm)
P : Pitch of the iso metric threads (mm)
sigmay b : Yield stress of the bolt material (N/mm2)
sigmay m : Yield stress of the nut material (N/mm2)
---
T : Tension load (N)
"""
#
# Bolt... | 19b4d15f4ac49ccf010cdd01b590e94782e867b9 | 654,427 |
def text2int(relationship, sequence):
"""
DESCRIPTION:
A function to translate a sequence of letters into a sequence of
numbers.
:param relationship: [dict] the relationship between letters and
numbers. The numbers are ints. (key, value) -> (letter, number)
:param sequence: [str] the seque... | b39044e12791eed7146bb8453cf1d46b2132ce48 | 654,428 |
import numpy
def calculateJitterFactor(data):
"""
calculate the jitter factor as defined by Horii (Hollien et al.:
Hollien H, Michel J, Doherty ET. A method for analyzing vocal jitter in
sustained phonation. Journal of Phonetics. 1973;1973(1):85-91.)
@param data a list or numpy array with periods [s] of consec... | d9ffbe0c720ce25a1a56323d05cd6ee69d09aae1 | 654,429 |
def ts(avroType):
"""Create a human-readable type string of a type.
:type avroType: codec.datatype.AvroType
:param avroType: type to print out
:rtype: string
:return: string representation of the type.
"""
return repr(avroType) | ef7b0adbe798644eb7259cb386bccdbacd037683 | 654,430 |
import ntpath
def path_leaf(path):
"""Return the base name of a path: '/<path>/base_name.txt'."""
head, tail = ntpath.split(path)
return tail or ntpath.basename(head) | c09f79f359e4008517c517431a42d052770b1d06 | 654,431 |
import os
def ShortenPath(path):
"""takes path, converts it to absolute, and trims off cwd if that is the first part
if path passed in is shorter, returns that instead"""
in_path = path
path = os.path.abspath(path)
cwd = os.getcwd()+os.sep
if( path[:len(cwd)] == cwd ):
path = path[l... | af2cb9b10e356557c54b41a6e180bbc1e800c372 | 654,433 |
def sum(a, b, c):
"""
"""
return a + b, a + c | 3a20f4f6447204a487dd1fa3afcf905724a54f07 | 654,434 |
import torch
def generate_attention_masks(batch, source_lengths):
"""Generate masks for padded batches to avoid self-attention over pad tokens
@param batch (Tensor): tensor of token indices of shape (batch_size, max_len)
where max_len is length of longest sequence in the batch
@... | 5e9549f2419c7839bba427da9d03129185a6fc75 | 654,435 |
def new_in_list(my_list, idx, element):
"""Replace an element in a copied list at a specific position."""
if idx < 0 or idx > (len(my_list) - 1):
return (my_list)
copy = [x for x in my_list]
copy[idx] = element
return (copy) | 48fa685d9c9fbad89b36074dc8af92163b957460 | 654,436 |
def login(email, password):
"""Mock jesse login."""
return True | b48af24ad6237c5c328625ff5d299f9126f03a02 | 654,437 |
def canonicalize_eol(text, eol):
"""Replace any end-of-line sequences in TEXT with the string EOL."""
text = text.replace('\r\n', '\n')
text = text.replace('\r', '\n')
if eol != '\n':
text = text.replace('\n', eol)
return text | 7ff5a8ed1ede1f854c3bb18aa6a9076ea16667c9 | 654,439 |
def idfn(df, id_global_assignment):
"""ID measures: Number of false negatives matches after global min-cost matching."""
del df # unused
rids, cids = id_global_assignment['rids'], id_global_assignment['cids']
return id_global_assignment['fnmatrix'][rids, cids].sum() | ac22759df312342ec363c3ebc7057807e83ed526 | 654,440 |
import torch
def soft_cross_entropy_tinybert(input, targets):
""" Soft Cross Entropy loss for hinton's dark knowledge
Args:
input (`Tensor`): shape of [None, N]
targets (`Tensor`): shape of [None, N]
Returns:
loss (`Tensor`): scalar tensor
"""
student_l... | 93aa378509a098c6020dcede78ebd228e54cf318 | 654,441 |
import importlib
def modules(request):
"""Give imported HADDOCK3 modules."""
module_name, category = request.param
mod = ".".join(['haddock', 'modules', category, module_name])
module = importlib.import_module(mod)
return module | bea5eee03df6aaed886e91cc9e748590418185c9 | 654,442 |
def sanitize_sacred_arguments(args):
"""
This function goes through and sanitizes the arguments to native types.
Lists and dictionaries passed through Sacred automatically become
ReadOnlyLists and ReadOnlyDicts. This function will go through and
recursively change them to native lists and dicts.
... | 07849b685bbbd84e9164352c1cf03f69f9ef731d | 654,443 |
import random
def gen_random_six_num():
"""生成6位随机数组合
Returns:
str: 6位随机数组合字符串
"""
s = ''
for i in range(6):
s += str(random.choice(range(10)))
return s | 175fcfcf2235ea8c199a128f1c03af87f7f9ba79 | 654,444 |
def transform_array(array, f):
"""Args; 2D array e.g. [[2,2],[2,2]],
f = function e.g lambda x: x*2
return [[4,4], [4,4]]"""
height = len(array)
width = len(array[0])
for col in range(width):
for row in range(height):
val = array[row][col]
array[row][col] = f(va... | 1d616d8a4a9ba74248d386bb1c741be78707cbbc | 654,445 |
def _retrieve_yearly_data(yearly_data):
"""Auxiliary function to collect yearly data.
Returns list of lists in the form [mergedstatname, stat], where
mergedstatname - dictionary key joined with associated period.
"""
out = []
for t in yearly_data:
for key in t:
if key not in... | 1dc15cbe273394d2e652b9fbc222241f70b7921c | 654,447 |
def get_psr_name(psr):
"""
Get the pulsar name from the Tempo(2)-style parameter files by trying the
keys "PSRJ", "PSRB", "PSR", and "NAME" in that order of precedence.
Parameters
----------
psr: PulsarParameter
A :class:`~cwinpy.parfile.PulsarParameters` object
Returns
-------... | b847df5c11e486a224e9309d9e87c71771adc8fa | 654,448 |
def next_file(filename,count=1,filter="*"):
"""The file next alphabetically in the same directory.
If the is none return the current filename.
count: 1 for next next file (default), -1 for the proevious file"""
from os.path import dirname,exists,isdir
from glob import glob
from numpy import args... | 5bb25f87e8097721c417320e1cafc9b5b3fc49b3 | 654,449 |
def IsResultFailure(result_data): # pragma: no cover
"""Returns true if result_data indicates a failure."""
while isinstance(result_data, list):
result_data = result_data[0]
if not result_data:
return False
# 0 means SUCCESS and 1 means WARNINGS.
return result_data not in (0, 1, '0', '1') | af495cc9fdd5e21a4b93ccd01ccd6c11d2259d7d | 654,450 |
def get_diff_options(req):
"""Retrieve user preferences for diffs.
:return: ``(style, options, data)`` triple.
``style``
can be ``'inline'`` or ``'sidebyside'``,
``options``
a sequence of "diff" flags,
``data``
the style and options information represented as
... | 3e55c669afd0960f1ee8effa9269bdbb687ed960 | 654,451 |
def read_smi_file(filename, unique=True, add_start_end_tokens=False):
"""
Reads SMILES from file. File must contain one SMILES string per line
with \n token in the end of the line.
Args:
filename (str): path to the file
unique (bool): return only unique SMILES
Returns:
smiles... | 62423c1e54d2ba311c6deff8290f0e2a232dcf7d | 654,452 |
def gen_include_parameters(includes, systenIncludes):
"""生成头文件目录参数
包含普通头文件目录和系统级头文件目录
"""
include_parameters = ''
include_parameters += ' '.join(map('-I{}'.format, includes))
# for e in includes:
# include_parameters += '-I' + e
# 在中间加入一个空格隔开
include_parameters += ' '
inc... | c86c9531eebc255a97865ccf7f319109064260af | 654,453 |
def xor_cipher(data, key):
"""
Шифрует строку с помощью заданного ключа.
:param data: строка, которую необходимо зашифровать.
:param key: ключ для шифровки/дешифровки.
:return: зашифрованная строка.
"""
encoded = []
for data_char, key_char in zip(data, key):
# ord() - возвращает ... | 25131023f52fc7130eb90b727ccfc2ff4a18a989 | 654,455 |
def predict(interpreter, audio):
"""Feed an audio signal with shape [1, len_signal] into the network and get the predictions"""
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Enable dynamic shape inputs
interpreter.resize_tensor_input(input_deta... | 3a180de0724861b1c4d29b97fc607c5b78d65c63 | 654,456 |
def convert_tuple_to_string(creds_tuple):
"""Represent a MAAS API credentials tuple as a colon-separated string."""
if len(creds_tuple) != 3:
raise ValueError(
"Credentials tuple does not consist of 3 elements as expected; "
"it contains %d."
% len(creds_tuple))
r... | 8e4bf77c8c8254439f624bc041bb7737286f8693 | 654,457 |
def _confirm_pub_variable_changes(pub_variable_changes):
"""
确认公共变量的修改
:param pub_variable_changes:
:return:
"""
confirmed_pv_changes = []
if not pub_variable_changes or not isinstance(pub_variable_changes, list):
return confirmed_pv_changes
for pv_dic in pub_variable_changes:
... | b32a4518e12e73f21f4e0b91f5bdea77c030bb3b | 654,458 |
from pathlib import Path
from typing import List
def rglob_multi(root: Path, patterns: List[str]) -> List[Path]:
"""
Advanced recursive glob of a path collapsing multiple include/exclude patterns.
"""
files = []
for pattern in patterns:
# patterns starting with ! are treated as exclusions
... | a06fd1e32be1c89578d9f82f6bbe661585ca252a | 654,459 |
def detectEavesdrop(key1, key2, errorRate):
"""Return True if Alice and Bob detect Eve's interference, False otherwise."""
if len(key1) == 0 or len(key2) == 0:
return True
if len(key1) != len(key2):
return True
tolerance = errorRate * 1.2
mismatch = sum([1 for k in range(len(key1)) ... | 3e00c9cac94bd44c04f20ca314fa6fec9b00d33f | 654,460 |
def get_interaction(element_1, element_2, matrix_dimension):
"""Gets singular interaction between 2 elements of an ising matrix and returns the hamiltonion
Args:
element_1 ([int, int]): x, y coordinate of element 1 on the ising matrix
element_2 ([int, int]): x, y coordinate of element 2 on the ... | 423e68922d677a7f8f6f78213050ce6f92176091 | 654,462 |
def type_check(arg_name, pos, reqd_type):
"""
allows type checking at runtime for args or kwargs
"""
def decorator(fn):
# brevity compromised in favour of readability
def logic(*args, **kwargs):
arg_count = len(args)
if arg_count:
if pos < arg_co... | 5c2ad93ff5bf40d2389142122704d43012e6febf | 654,463 |
def bps2human(n, _format='%(value).1f%(symbol)s'):
"""Converts n bits per scond to a human readable format.
>>> bps2human(72000000)
'72Mbps'
"""
symbols = ('bps', 'Kbps', 'Mbps', 'Gbps', 'Tbps', 'Pbps', 'Ebps', 'Zbps', 'Ybps')
prefix = {}
for i, s in enumerate(symbols[1:]):
prefix[s... | 753cc2dc4b529947eae7dae59a81459e677b2b86 | 654,464 |
def get_pos(i):
""" return key positions in N253 (1..10) from Meier's Table 2:
0 = blank, if you want to use the peak in the cube
11 = map center, the reference position of N253
"""
pos = [ [], # 0 = blank
['00h47m33.041s', '-25d17m26.61s' ], ... | 66902f2fc3b6bfde1fa79ec598aec17466f34541 | 654,465 |
def check_weekend(x: int) -> int:
"""
Checks if the extracted day from the date is a weekend or not.
"""
return 1 if x > 5 else 0 | ab0e39403ce0987ca33be85ac8af4e4763defbb5 | 654,466 |
import builtins
def get_type_from_name(name: str) -> type | None:
"""
Returns the type matching the specified name
or None if not found.
:param name: the name of the type to lookup
:return: the type matching the specified name
or None if annotations found
"""
try:
return g... | 16dca59edf2d0b7193972f93b8fa6b14c0192750 | 654,467 |
def convex_hull(points):
"""Calculating 2D convex hull using Graham algorithm (XY plane).
Based on
https://leetcode.com/problems/erect-the-fence/discuss/103300/Detailed-explanation-of-Graham-scan-in-14-lines-(Python)
"""
# Computes the cross product of vectors p1p2 and p2p3
# value of... | 3961df3acf02c9def203068046c7297eb6aed8fe | 654,468 |
import os
def regression_table(dict, order, path, name):
"""
Generate a latex table out of regression analysis of each particle size
"""
bins = ['0.5', '2.5']
first = (r'\begin{tabular}{ccccccc}' + '\n'
r'\multirow{2}{*}{Particle size} & ' +
r'\multicolumn{3}{c}{\SI{0.5}{... | a112d49eda2262f489c42dd0a4cbf33e9555d0a6 | 654,469 |
def query_table2(user_id, session_id):
"""
This function returns the SQL neccessary to get all artists, songs, and the user name of
the user with user id passed as an agrument and in session with id passed as an argumemt.
"""
return "select artist_name, song_name, user_name from WHERE_USERID_SESSION... | ed15dc190f4890da9a91f0b6471cb4a5d69e2251 | 654,470 |
def get_first(mapping, *keys):
"""
Return the first value of the `keys` that is found in the `mapping`.
"""
for key in keys:
value = mapping.get(key)
if value:
return value | b9a436ec411cad8fdf007f19b076a0f9c1bacda6 | 654,471 |
def Cbar_ReverseArray():
"""Colour bar reverse options"""
Cbar_Reverse_List = ['Forward', 'Reverse']
return Cbar_Reverse_List | c36880acadd4ce55b118d000c4ba3561b042f7cd | 654,472 |
def calc_exposure_time(num_integrations, ramp_time):
"""Calculates exposure time (or photon collection duration as told
by APT.)
Parameters
----------
num_integrations : int
Integrations per exposure.
ramp_time : float
Ramp time (in seconds).
Returns
-------
exposur... | 8e54ee76d21ea9196fc2049e6171ad82b7b807e3 | 654,473 |
def HardswishConfig(argument_parser):
"""
Set CLI arguments
:param argument_parser: argument parser
:type argument_parser: ```ArgumentParser```
:returns: argument_parser
:rtype: ```ArgumentParser```
"""
argument_parser.description = """Applies the hardswish function, element-wise, as d... | e7ee22fb5d26502aba1b211b4808a1903194f6b0 | 654,475 |
def load_label_file(label_file):
"""
"""
label_list = list()
with open(label_file, "r", encoding="utf-8") as lf:
for line in lf:
line = line.rstrip()
if not line:
continue
label_list.append(line)
return label_list | a7327868a6ac18268fc368ebfc14b24b639c103a | 654,476 |
from typing import Dict
def basic_pep_filter(p, **kwargs) -> Dict[str, str]:
"""
Basic PEP filter, that does not convert the Project object.
This filter can save the PEP representation to file, if kwargs include `path`.
:param peppy.Project p: a Project to run filter on
"""
return {"pep_conv... | 6e3f1dae2013505a4aa511979951488c0e49b7d8 | 654,477 |
import re
def _is_camel_case(string: str) -> bool:
"""
Helper method used to determine if a given string is camel case or not. See the below details on the
exact rules that are applied.
1. First series of characters should be lower case
2. Every character group afterwards should string with an up... | c4af6ea950712b9d14f49bd67cf4d3a866474404 | 654,478 |
def dumpStats(caller):
"""dumps the current stats dictionary
This functions returns a copy of the stats dictionary with all stats key/values
:param caller: the calling Component (this is usually *self*)
:type caller: Namespace
:returns: { 'key1':value1, 'key2':value2, ...}
:rtype: dict
:Ex... | 31f4422a2550abcbb9f13d79e8cbca05197d62a4 | 654,480 |
def str2intlist(s, repeats_if_single=None):
"""Parse a config's "1,2,3"-style string into a list of ints.
Args:
s: The string to be parsed, or possibly already an int.
repeats_if_single: If s is already an int or is a single element list,
repeat it this many times to create ... | b9a043807141810fc9b30d8f0c29279492c6ecbe | 654,481 |
def parseStyle(s):
"""Create a dictionary from the value of an inline style attribute"""
if s is None:
return {}
else:
return dict([[x.strip() for x in i.split(":")] for i in s.split(";") if len(i)]) | e3d196d22b546bffee3f6f014c61c9d9045e8da1 | 654,482 |
def get_top_n_kmers(kmer_count, num):
"""Get a list of top_n most frequent kmers."""
return [item[0] for item in sorted(kmer_count.items(), key=lambda x: x[1], reverse=True)[:num]] | c42c5722a5d0e578d451336896afaeb1f84a03d8 | 654,483 |
def _break(req, *opts):
"""
Break out of a pipeline.
:param req: The request
:param opts: Options (unused)
:return: None
This sets the 'done' request property to True which causes the pipeline to terminate at that point. The method name
is '_break' but the keyword is 'break' to avoid conflicting with python built... | 8c9cacd38d3268a7d11993ea3870bc61be52cd38 | 654,484 |
def w12(x):
"""12bit unsigned int"""
return 0b1111_1111_1111 & x | 9bbc10de0380afadb67ed57b5b6d7e7f75cff92c | 654,485 |
def leia_dinheiro(txt):
"""
==> Essa função irá validar número em formatos de dinheiro (BRL)
:param txt: valor que irá ser formatado.
:return: float de txt.
"""
valido = False
while not valido:
entrada = str(input(txt)).replace(',', '.').strip()
if entrada.isalpha() or entra... | 68a59337b0d11660480de6d1f5a272a97f1a4ec0 | 654,486 |
def get_all_urls(html):
"""
gets the url of all the comments in a drug page
@params:
html: BeautifulSoup object
drugname: String
@returns: list()
"""
urls = list()
for title in html.find_all("span", class_="post-title"):
urls.append(title.a['href'])
return urls | 7feb7f5c89ce0c54fcdd7d9dd2b1ea2026a0ec33 | 654,487 |
def bool_exp(x, y):
""" bool_exp """
return not x > y | e0221f8f7ddfec25565de32eb8fb767aa794b3a8 | 654,488 |
def translate_to_group_coordinates(group_crop_list):
"""Translates lists of group crops into groups internal coordinates."""
if len(group_crop_list) == 1:
return group_crop_list
else:
group_crop_list_transl = []
for grp_crops in group_crop_list:
left_anch = min([crp[0] fo... | e2526be7c01ef48db681e7cd0f8da8aa97f35ca6 | 654,489 |
def get_padded_second_seq_from_alignment(al):
"""For a single alignment, return the second padded string."""
alignment_str = str(al).split("\n")[2]
return alignment_str | 4c1abab04b9631411e383956a5215665921b5036 | 654,490 |
def get_topic_response(meetup_id: int = 132) -> dict:
"""
create a Topic response
Keyword arguments:
meetup_id -- meetup id
return -> topic dict
"""
response: dict = {"id": meetup_id, "lang": "en", "name": "demo", "urlkey": "demo"}
return response | 3de2a69f87f0c1fccd00f8d40543c9c941e6df7c | 654,491 |
import json
def read_json(json_file):
""" (file) -> dict
Read in json_file, which is in json format, and
output a dict with its contents
"""
with open(json_file) as data_file:
data = json.load(data_file)
return data | c49067c54a04d7760a468298052d62c8cd536bb5 | 654,492 |
def string_to_dict(s, splitters=("|", ":", ",")):
"""Convert a string to a dictionary of dictionaries, based on
splitting rules: splitters."""
dct = {}
for tdict in s.strip().split(splitters[0]):
key, value = tdict.split(splitters[1])
dct[key] = value.split(splitters[2])
return dct | f5b1d080ad570ca237cd4bbfd3ba861409c65653 | 654,493 |
import argparse
def get_args():
"""Set up argument parser."""
p = argparse.ArgumentParser(description='Convert cookies')
p.add_argument('input', type=str, help='input text or file name')
p.add_argument('-n', '--no-base64', action='store_const',
const=True, default=False,
... | 1c416f8fbfd29f5cb1dd3798d5be75f4ea3263af | 654,494 |
import torch
def total_variance(img):
"""
get the L1 loss of total variance loss
:param img: tensor of shape(B,C,H,W)
:return: a scalar, total variance loss
"""
return torch.sum(torch.abs(img[:,:,1:,:] - img[:,:,:-1,:])) + torch.sum(torch.abs(img[:,:,:,1:] - img[:,:,:,:-1])) | 83f12d4c162683b331b1cf9795626e722ffb3f76 | 654,496 |
import struct
def fp32_to_bytes(data, is_big_endian=False):
"""小端字节序"""
return bytes(struct.pack('>f' if is_big_endian else '<f', data)) | 223029b00ff8d9bf17ce0720f7e42460a24d005a | 654,497 |
import subprocess
def get_phone_uuid():
"""
Retrieve UUID of connected android phone via adb command
:return: String
"""
getprop_cmd = f'adb shell getprop ro.serialno'.split()
proc = subprocess.Popen(getprop_cmd, stdout=subprocess.PIPE)
uuid = proc.communicate()[0].decode("utf-8").strip()
... | f17d55c901ddbd6688dd876a26d2e359898482f4 | 654,498 |
def zoo_om_re_ratio(carbon, d_carbon, ratio, d_ratio):
"""carbon and d_carbon im moles
carbon, ratio - to be changed
d_carbon, d_ratio - what changes the ratio"""
return (carbon+d_carbon)/(carbon/ratio+d_carbon/d_ratio) | 15c9729765d52a9bed5bc52cc472c5cfbbab388c | 654,499 |
def power(base, exponent):
"""As far as I know, this does not exist"""
if base is None or exponent is None:
return None
return base ** exponent | ad133ca23c39ec757c7680150bedbda2a936b0fd | 654,500 |
def mask_bits(n: int, bits: int) -> int:
"""mask out (set to zero) the lower bits from n"""
assert n > 0
return (n >> bits) << bits | 6a54c7e460db520b5fb5f04edb814062bf3083f3 | 654,501 |
import numpy
def conditional_convert_op(
base_lulc, lulc_nodata, converted_lulc, buffer_10m_array,
flow_accum_50m_slope_mask_array,
rasterized_50m_buffer_raster_path,
stream_array, target_nodata):
"""Convert LULC to the converted one on the special cases.
convert lulc to conve... | 6d9a948642475c93c3dcddea61f189ab317c0632 | 654,502 |
import os
def get_dir(path):
"""Automatically extracts the path to the dynophore trajectory
Args:
path (str): File path to the dynophore trajectory
Returns:
str: /some/file/path
"""
dir_path = os.path.dirname(os.path.realpath(path))
return dir_path | f92e88c27d18b43709e0123b98d90b5bc8ef2cee | 654,504 |
def clear_data(data):
"""Clear empty list or dict attributes in data.
This is used to determine what input data provided to to_ufos was not
loaded into an UFO."""
if isinstance(data, dict):
for key, val in data.items():
if not clear_data(val):
del data[key]
... | a598fbba33a113444bea934494d2ebbac122cf97 | 654,506 |
def l2rowg(X, Y, N, D):
"""
Backpropagate through Normalization.
Parameters
----------
X = Raw (possibly centered) data.
Y = Row normalized data.
N = Norms of rows.
D = Deltas of previous layer. Used to compute gradient.
Returns
-------
L2 normalized gradient.
"""
... | 584c9408bfc4eb4da144062a36affaa864cf549f | 654,507 |
def is_valid_int(value: str):
""" Checks whether the input is an integeral value or not """
try:
int(value)
return True
except:
return False | 60408ababe0817f1477a6db9d2fbadf86c072e7d | 654,508 |
def create_rock_question(index):
"""create_rock_question"""
return "Rock Question %s" % index | c202763fc4bc40760d7463fce7408046cf3837e2 | 654,509 |
def seq2batch(x):
"""Converts 6D tensor of size [B, S, C, P, P, P] to 5D tensor of size [B * S, C, P, P, P]"""
return x.view(x.size(0) * x.size(1), *x.size()[2:]) | 799eada00f9c7899db35fee8f2d10a8a8e3a0db5 | 654,510 |
def get_sort_key(sorting) -> list:
"""Return the sort colum value for sorting operations."""
return sorting["hostname"] | 7d337fb1f31af6844811c5cfd92617d73ebe956a | 654,511 |
import json
def load_json(input_file):
"""load json from a filename.
Parameters
==========
input_file: the input file to load
"""
with open(input_file, "r") as filey:
content = json.loads(filey.read())
return content | be9b772b12c563b8c708861153b44e613bbf7517 | 654,512 |
import json
def open_json(_file):
"""Loads the json file as a dictionary and returns it."""
with open(_file) as f:
return json.load(f) | c7d2ca5170dd91dbb343b0e15469a78f03e35403 | 654,513 |
def patched_has_permission(request) -> bool:
"""
Patched version of admin site has_permission,
to allow for the accounts:admin_login permission
"""
if request.user.is_active:
if request.user.is_staff:
return True
if request.user.is_superuser:
return True
... | d8832d5ad4de6f9a6310bcf68b7ab992668af5d5 | 654,514 |
import argparse
def get_arguments():
"""Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments.
"""
parser = argparse.ArgumentParser(description="Deep-Image-Matting")
parser.add_argument("--cfg",
default="./config/adobe.yaml",
metavar="FILE",
... | 992867ac3c69189ed5a49aad9fbf9afc255e130f | 654,515 |
def get_preprocessor(df):
"""
return the preprocessing pipeline
"""
## preprocessing pipeline
df['invoice'] = df['invoice'].str.replace(r"[a-zA-Z]",'').astype('int')
# numeric_features = []
# numeric_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='mean')),
# ... | e0f97781daa100a306d0a9dbce3782394efaded1 | 654,516 |
def math_wrap(tex_str_list, export):
"""
Warp each string item in a list with latex math environment ``$...$``.
Parameters
----------
tex_str_list : list
A list of equations to be wrapped
export : str, ('rest', 'plain')
Export format. Only wrap equations if export format is ``re... | f632246a14317309054e85310e83ee077ffdbc9f | 654,517 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.