content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def uptime():
""" Returns computer uptime in seconds """
return float(open('/proc/uptime').read().split()[0]) | c7d461f4ddf4ef81773840093e71d68f364653e5 | 655,428 |
import imp
def create_module(problem_data):
"""Creates a new module for storing compiled code.
Parameters
----------
problem_data - dict
Problem data dictionary
Returns
-------
New module for holding compiled code
"""
problem_name = problem_data['problem_name']
module... | 961bdaea85382d2a0f9f2a3d8f49a69c26819c07 | 655,429 |
import torch
def transform_homogeneous(matrices, vertices):
"""Applies batched 4x4 homogenous matrix transformations to 3-D vertices.
The vertices are input and output as as row-major, but are interpreted as
column vectors multiplied on the right-hand side of the matrices. More
explicitly, this funct... | 47c3d9a51188a28c88b489b02d4173c4ebddb46a | 655,430 |
def no_cleanup(value, args):
"""Default cleanup function, returns the unchanged value."""
return value | 67662efb7e52709bfc15d131fc4f597e7490e9e0 | 655,431 |
def last_number_divisible_by_50(currentNum):
"""Calibre fails to create TOC entries beyond 50 chapters, so we
limit each epub to be at most 50 chapters"""
currentNum -= 1
while currentNum % 50 is not 0:
currentNum -= 1
return currentNum | 27d6502e1450145e202fe0129b3feb776e689a7e | 655,433 |
from pathlib import Path
import yaml
def loadConfigDict(configNames: tuple):
# pathLib syntax for windows, max, linux compatibility, see https://realpython.com/python-pathlib/ for an intro
"""
Generic function to load and open yaml config files
:param configNames: Tuple containing names of config fil... | 1bbee88e3ff5df7f26f1502eb34d72a33d01b348 | 655,434 |
from datetime import datetime
def get_time():
"""
:return current time:
"""
return datetime.now().strftime("%H:%M:%S").__str__() | 0198e78e99675aaebd1cfa4cffc63f08a453bcb5 | 655,435 |
import os
def find_file(base_directory: str, filename: str):
"""Return the full path of the given ``filename`` in the ``base_directories`` or any of its subdirectories (recursively; file must match exactly)."""
for root, dirs, files in os.walk(base_directory):
if filename in files:
return... | 975ad30c849543fb7c4ac8d2e5d92de55adabb44 | 655,436 |
def py2pyx(pylines):
"""Generate pyrex code lines from python code lines
- Adds import of cython and numpy
- searches every line for "#c". If found text before "#c" is replaced with text after "#c", e.g:
"def func(a): #cpdef func(int a):" -> "cpdef func(int a):
"#cdef int b" -> "cdef int b"
"""
... | 52b8261aa4a809069bb815bc7f789cc1a108fd8c | 655,437 |
import math
def basic_dist(set1, set2):
"""
"""
return math.sqrt( sum((e1 - e2)**2 \
for e1, e2 in zip(set1, set2))) | b13692f2b30c1935261faaf869babc2545b7d386 | 655,438 |
def is_comment(string):
"""
Find out if line is a comment or line of code
:param string: line to analyze
:return: True if line is a comment
"""
chars = list(string)
if len(chars) <= 0:
return True
if chars[0] == "#":
return True
else:
return False | 2a6c761130bf608d7363334d95257d8d73332680 | 655,440 |
import zipfile
def un_zip(zip_file, uzip_folder=None):
"""Uncompression .zip file
Args:
zip_files: str, zip_file should be file path;
uzip_folder: str, uncompression files name.
Return:
uzip_folder: str, uncompression files name.
"""
assert zip_file[-4:]==".zip", '`zip... | 770b981aa7cc4576eaeee5d5e15b5912ea3c057a | 655,441 |
def extract_brackets(line):
"""Splits a scroll 'call line' into identifier + suffix."""
ident, _, enil = line[1:].partition("(")
thing, _, _, = enil.rpartition(")")
return ident, thing | 47b35a331ecf01c2772d6289f1ac8171f655573c | 655,442 |
import requests
import logging
import os
def network_per_exists_check(api_url, device_addr, peripheral_dir):
"""
Checks if peripheral already exists
"""
identifier = device_addr
try:
r = requests.get(f'{api_url}/{identifier}')
if r.status_code == 404:
return False
... | 09f2d6fc60321243a12309b421e971e8336b97b9 | 655,443 |
def assert_real(real, dim=3):
"""
:param real: supposed shape [B, C, m, m, 6]
:return: B, C, m
"""
[B, C, m, _, d] = real.shape
assert real.shape[3] == m
assert d == dim
return B, C, m | bf11c15423849c5d856da3495e978b86d5d8ba50 | 655,445 |
def input_output01(input):
"""
Expects a list of lists as input,
outputs each sublist in a line comma delimited.
"""
return '\n'.join(','.join(map(str,sl)) for sl in input) | 9f433f33b741e8039239ad12b5bda5cfebdad1d9 | 655,446 |
def i_am_the_spooler() -> bool:
"""Returns flag indicating whether you are the Spooler."""
return False | d5038f3863be84afee6f96782bedc070c5590236 | 655,447 |
import os
def analytics(self, args):
"""
Print analytics of program
No args
:Example:
reversing\@icsref:$ analytics
"""
try:
prg = self.prg
except AttributeError:
print('Error: You need to first load or analyze a program')
return 0
path = os.pat... | b733bb7c455e7fc0e657133855bac8d1815c3a01 | 655,448 |
def search_without_dead_links(search_factory):
"""
Here we pass filter_dead = True.
"""
def _search_without_dead_links(**kwargs):
return search_factory(filter_dead=True, **kwargs)
return _search_without_dead_links | 8a6d21b37209ff78152b046e012c9e6fc839cee8 | 655,451 |
def V_phrase_num(tr):
"""returns the number attribute of a verb-like tree, based on its head verb,
or '' if this is undetermined."""
if (tr.label() == 'T' or tr.label() == 'I'):
return tr[0][1] # the s or p from Is,Ts or Ip,Tp
elif (tr.label() == 'VP'):
return V_phrase_num(tr[0])
... | 165e7cb975d293dbb09dd33b7c14fc14247ee4e0 | 655,452 |
def _str_to_bytes(value: str) -> bytes:
"""Convert ``str`` to bytes"""
return value.encode("utf-8") | 50f7065188c30aeec321eac9e14d880537b66119 | 655,453 |
import sys
def get_python_version():
"""
Get the python version string for the current version of python that is
running.
Returns:
version (str): The major.minor version string
"""
info = sys.version_info
return '{major}.{minor}'.format(
major=info.major,
minor=in... | a5b81a53f0c54268c4f47f59c17a02e43b4305b1 | 655,454 |
import torch
def ordinal_accuracy(logits, levels, device='cpu', tolerance=0, reduction='mean'):
"""Computes the accuracy with a tolerance for ordinal error.
Parameters
----------
logits : torch.tensor, shape(num_examples, num_classes-1)
Outputs of the CONDOR layer.
levels : torch.tensor,... | 0c02598013044b4beefc28ddd8908edc64fe5423 | 655,455 |
def render_all(jinja_env, stig_ids, all_rules):
"""Generate documentation RST for each STIG configuration."""
template = jinja_env.get_template('template_all.j2')
return template.render(
stig_ids=stig_ids,
all_rules=all_rules,
) | e5b30bd5a724089eef58ffdf7e131c9592e23b26 | 655,456 |
import numpy
def isprime1(n):
""" This is the description of the function 2 ~ Loves it +1
Parameters
----------
n : int
int to check if prime
Returns
-------
bool
true if n prime
"""
if n>=2:
for i in range(2, int(numpy.ceil(numpy.sqrt(n)))):... | ca33eae5c0b3bb4d69c6556ee51ac942d2084516 | 655,457 |
def curry_clockwise_compare(center):
"""
Returns the clockwise comparison function
for sorting elements in clockwise order
given a center point
It returns a function used for comparison in sort,
in this implementation, the comparison function is
curried with the center of the circle you are comparing
t... | 0e846fc7cf7829040adaced3e211354fc15d5c9c | 655,458 |
def dataset1Ddata(alldata):
""" Parse a dataset into the x and y scan values
Returns:
x (array)
y (array)
"""
y = alldata.default_parameter_array()
x = y.set_arrays[0]
return x, y | 536a41897e004c2f3ed9d5908e0f19a1e85aab47 | 655,459 |
def rho_top_liq(x_aver_top_mass, rho_lc_x_aver_top, rho_hc_x_aver_top):
"""
Calculates the destiny of liquid at top of column.
Parameters
----------
x_aver_top_mass : float
The average mass concentration at top of column, [kg/kg]
rho_lc_x_aver_top : float
The destiny of low-boill... | df34b2831f578b913187d92edc54751d8e49fcb8 | 655,460 |
import torch
def cross_matrix(k):
"""Application of hodge star on R3, mapping Λ^1 R3 -> Λ^2 R3"""
K = torch.zeros(*k.shape[:-1],3,3,device=k.device,dtype=k.dtype)
K[...,0,1] = -k[...,2]
K[...,0,2] = k[...,1]
K[...,1,0] = k[...,2]
K[...,1,2] = -k[...,0]
K[...,2,0] = -k[...,1]
K[...,2,1]... | 57503ce49da6711be1ca7ccb776024912def32d0 | 655,461 |
def euclidian_distance(ptA, ptB):
"""
Returns the shortest path distance between the two Points
"""
if (ptA.X != ptB.X or ptA.Y != ptB.Y):
return ( (ptA.X - ptB.X)**2 + (ptA.Y - ptB.Y)**2 ) ** (1/2)
return 0.0 | e698fd2964116fd7462a3efe276217712f53cf17 | 655,462 |
def make_binder_pair( h1, h2 ):
"""Returns a binder pair from the two hits
A pair has the form:
( binder1, binder2, orientation1, orientation2 )
Where the binders are pssm names typically and the orientation describes
the strand the pssm binds to (true for positive strand).
"""
b1... | f498d326329c880bdcf26d2786b63b28656d4ab4 | 655,463 |
def rotate_order2_tensor(rotation, tensor):
"""Transform a tensor with a similarity transformation."""
return rotation @ tensor @ rotation.T | f3427f130ae40ed4c495f1745959cbc843584a44 | 655,464 |
from typing import Union
from typing import List
def get_corresponding(
value_or_matrix: Union[int, List[List[int]]], row: int, col: int
) -> int:
"""If `value_or_matrix` is a matrix, extract the value in cell specified by
`row` and `col`. If `value_or_matrix` is a scalar, just return it.
"""
if i... | bf838089464f48d2cb12a63e78a9fa0695a6303c | 655,465 |
import torch
def convert_frequencies_to_mels(f: torch.Tensor) -> torch.Tensor:
"""
Convert f hertz to m mels
https://en.wikipedia.org/wiki/Mel_scale#Formula
"""
return 2595.0 * torch.log10(1.0 + f / 700.0) | 05529939f23a53c3ff65e137ce89757ef5203417 | 655,466 |
def get_key(key, config, msg=None, delete=False):
"""Returns a value given a dictionary key, throwing if not available."""
if isinstance(key, list):
if len(key) <= 1:
if msg is not None:
raise AssertionError(msg)
else:
raise AssertionError("must pr... | 5089fae5a1f95b240a8ed93c493baeabe59b176d | 655,467 |
import os
def file_exists(file):
"""Check if a file exists.
Parameters
----------
file : str
The file name to check.
Returns
-------
bool
True if the file exists, False if it does not.
"""
return os.path.isfile(file) | a49915110a51c3d2c55dfda0a367edf0f14bf875 | 655,468 |
def plot_bounds(observed_min, observed_max):
"""Compute the plot bounds for observed data
Args:
observed_min (number) -- Lowest number found in data
observed_max (number) -- Highest number found in data
Returns: (number, number) A minimum and maximum x value for the plot
"""
if obs... | e1ffa81c4b7439d4caa4e5b2cb97b4c680d3018c | 655,469 |
import torch
def convert_data(data):
"""
Args:
data: The research data
Returns:
features: The features
labels: The data labels
"""
features = torch.tensor(data.features)
labels = torch.tensor(data.labels)
return features, labels | 9a8760ae6525fbb9e71553863e77c4a21ddb6535 | 655,470 |
def has_won_recursive(board):
"""Validate NxN board recursively."""
def find(row, col, move, count, x_or_o):
def valid_sq():
if -1 < row < len(board) and \
-1 < col < len(board) and \
-1 < count <= len(board)and \
x_or_o == board[row][col]:
return True
return ... | 1334233b7ae212ee6175d4ce9faee7421393aa01 | 655,472 |
def get_data_cfgstr(ibs, daid_list):
""" part 2 data hash id """
daids_hashid = ibs.get_annot_hashid_visual_uuid(daid_list)
return daids_hashid | c9916004db15f8f0209aa61047761bd762be2ad8 | 655,473 |
from typing import Any
from typing import Tuple
import os
def config_dirs(tmpdir: Any) -> Tuple[str, str, str]:
"""Generate XDG dirs and vars."""
config_dir = str(tmpdir.mkdir("config"))
cache_dir = str(tmpdir.mkdir("cache"))
data_dir = str(tmpdir.mkdir("data"))
os.environ["XDG_CONFIG_HOME"] = co... | ca6e6de135032aee615972fc9c1e4e7ac1eeef81 | 655,474 |
def strip_line_nums(line):
"""
Strip line numbers from the start of a line.
"""
# Find the end of a number at the start of the line, if there is one.
pos = 0
line = line.strip()
for c in line:
if (not c.isdigit()):
# Don't delete numeric labels.
if (c == ':')... | 62c3460e49f1cf7bb7b0245369068e95521e53bf | 655,475 |
def total_count(expression):
"""
Compute total count library size.
:param expression: Expression count matrix with genes as rows and samples as columns
:return: integer total count library size per sample
"""
return expression.sum(axis=0) | 51374fca9d9d13066900402f5a8f34149569e2a3 | 655,477 |
def positive():
"""
Validate that the given number is positive. Note that zero is neither
positive or negative.
>>> f = positive()
>>> f(0)
False
>>> f(5)
True
>>> f(-5)
False
>>> f(45.5)
True
:rtype: A validator function.
"""
def validator(num):
ret... | ad8c74d8c9f76ba4ad595179cbefc84f0473fdf7 | 655,478 |
def send_text_message(func):
"""发送文本信息"""
def inner(update, context):
text = func(update, context)
context.bot.send_message(
chat_id=update.message.chat_id,
text=text)
return inner | bc321efd102f88b67fec085a3180dc07771d7c8a | 655,479 |
def get_error_from_utilization(utilization, setpoint, current_instances):
"""
Consider scaling up if utilization is above the setpoint
Consider scaling down if the utilization is below the setpoint AND scaling down wouldn't bring it above the setpoint
Otherwise don't scale
"""
max_threshold = se... | d431d188ce4e99e8aa111bf582d5f438fe0d0c4f | 655,480 |
def filename_dist(dist):
""" Return the filename of a distribution. """
if hasattr(dist, 'to_filename'):
return dist.to_filename()
else:
return dist | 3791f8b03b254108a2a97bc725fd2802187367bd | 655,482 |
def chain_len2(chainify, authority_a, valid_authority, certificate_2):
"""Client certificate chain with length of 2"""
return chainify(certificate_2, authority_a, valid_authority) | 4b9b2025b3ebfe7d933620890e8af00d22cc0b92 | 655,484 |
def calcul_max(l: list) -> int:
""" returns the sum of the 2 highest elements of l """
_l = list(l)
max1 = max(_l)
_l.remove(max1)
max2 = max(_l)
return max1 + max2 | f62b53959e118ac5466edbdb04100e42c4f40bff | 655,485 |
def _s2_st_to_uv(component: float) -> float:
"""
Convert S2 ST to UV.
This is done using the quadratic projection that is used by default for S2. The C++ and Java S2
libraries use a different definition of the ST cell-space, but the end result in IJ is the same.
The below uses the C++ ST definition... | a78fa1ac89f74b3aa9bfc0585d10f440e6392391 | 655,486 |
import sys
def SingleComplement(inputBase):
"""
Returns the complementary base of a single input base.
"""
if inputBase == 'A':
return 'T'
elif inputBase == 'T':
return 'A'
elif inputBase == 'G':
return 'C'
elif inputBase == 'C':
return 'G'
# Denotes a... | 99cc227059c8f43b280d4a7efaa7397e480edd45 | 655,487 |
def split_class_def(iter_):
"""Splits into class or def lines."""
iter_ = iter_.strip()
if iter_.startswith("def"):
iter_ = iter_[3:]
# elif iter_.startswith("class"):
# x = iter_[6:-2]
return iter_ | d2bcbdba74c05497d171439d47cbc7e692e07c8c | 655,488 |
def _combine_tags(tags):
"""
Since url addresses do not respect case, we
convert all tags to lowercase, and combine tags
with the same chars. For example, Kids: [1, 2]
and kids: [3, 4] becomes kids: [1, 2, 3, 4].
"""
clean_tags = {}
for tag, images in tags.items():
tag = tag.lowe... | 64ef90a2e4e32160a977ec110c30fe48a7b6004d | 655,489 |
def delegate(connection, identity_token, whitelist=None):
"""Returns authentication token and cookies from given X-MSTR-
IdentityToken.
Args:
connection: MicroStrategy REST API connection object
identity_token: Identity token
whitelist: list of errors for which we skip printing erro... | e0d3e8f7f08945e7da6f162564452f5c1d974027 | 655,490 |
def confirm_name(message, name, force=False):
"""Ask the user to confirm the name.
Parameters
----------
message: str
The message to be printed.
name: str
The string that the user must enter.
force: bool
Override confirmation and return True. Default: False.
Returns... | 1acc14ed5d5226eb638446299489aa1c3ed0b36e | 655,491 |
def entangle_system(s, id, id2):
"""Entangle specified qubits of a system."""
aux = s.apply_gate("H", targets=id)
res = aux.apply_gate("X", targets=id2, controls=id)
aux.free()
return res | adef629fd7498c3927cc08b60da1a4aad1f13e95 | 655,492 |
def parse_encode_biosample(data):
"""Parse a python dictionary containing
ENCODE's biosample metadata into a dictionary
with select biosample metadata
:param data: python dictionary containing ENCODE' biosample metadata
:type s: dict
:return: dictionary with parsed ENCODE's biosample meta... | 3438fd4f1d38ff8e654c6b69036682ee6dc6c053 | 655,493 |
import json
import hashlib
def hash_dict(nested_dict):
""" Returns hash of nested dict, given that all keys are strings
"""
dict_string = json.dumps(nested_dict, sort_keys=True)
md5_hash = hashlib.md5(dict_string.encode()).hexdigest()
return md5_hash | 5f518698154b351ca38b8027f047b4a1153f2c83 | 655,496 |
import numpy
def parse_header(hdr, zero_offset):
"""
Parse a WCS header to arguments of pix2ang and ang2pix.
Parameters
----------
hdr : dict
WCS header
zero_offset : boolean
If zero_offset is True, the routine assumes 0-indexed pixel coordinates
(useful in Pyt... | 8b9502fe648a49ae662f5e8ebac85eb778d67ead | 655,497 |
from typing import Union
def milimeter_mercury_to_bars(mm_hg: float, unit: str) -> Union[float, str]:
"""
This function converts mmHg to bar
Wikipedia reference: https://en.wikipedia.org/wiki/Bar_(unit)
Wikipedia reference: https://en.wikipedia.org/wiki/Millimetre_of_mercury
>>> milimeter_mercury... | 71fc982cbaf0f43d493c9a20dcedb609b9009ecd | 655,498 |
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_secureworks_ctp]
# Required - base URL for the Secureworks API.
# Do not place '/' at the end of the url strings.
base_url=https://api... | 56735fe3ee098ab876f5ddc163ea45f6499cd427 | 655,499 |
def print_exptree(root):
"""
Print out an expression tree object via recursion.
Args:
root: expression tree (object type)
"""
# Empty tree
if root is None:
return 0
# Leaf node
if root.left is None and root.right is None:
return print(f'-- leaf: {root.data}'... | f95dbf1523b2222f72af40268edd8366dc5a2d43 | 655,500 |
from typing import Callable
from typing import List
from typing import Match
import random
def get_shuffler() -> Callable:
"""
This function returns a 'ranker' function. It is meant to be used
by matchmaker, e.g. `get_next_match(..., get_ranker(...))`, and it
is only this complex so we can capture the... | 044e3e37b40f3283e3a2f146db0b1214fdb7dcbf | 655,501 |
import collections
def merge(*ds):
"""Merge dictionaries; last one wins."""
r = collections.OrderedDict()
for d in ds:
r.update(d)
return r | c99eeb565a4838db222a2975a838a097f89e45f5 | 655,502 |
def check_shapes(mat1, mat2):
"""Check if the two matrices has the same shape
if not return None"""
shape = []
while (isinstance(mat1, list) and isinstance(mat2, list)):
lenMat1 = len(mat1)
lenMat2 = len(mat2)
if lenMat1 != lenMat2:
return None
shape.append(le... | 2d889966f16daa37c3a9530d413e45acd5d61bed | 655,503 |
import click
def valid_band(ctx, param, value):
""" Check image band validity (band >= 1)"""
try:
band = int(value)
assert band >= 1
except:
raise click.BadParameter('Band must be integer above 1')
return band | 9a95277c8ef6122a8f25bd712f11a8155e7ae0fb | 655,504 |
import socket
def get_node_ip_address(address="8.8.8.8:53"):
"""Determine the IP address of the local node.
Args:
address (str): The IP address and port of any known live service on the
network you care about.
Returns:
The IP address of the current node.
"""
ip_address, port = address.split(... | 039fdb773f1b392669d45bd98a87005e4a463f39 | 655,505 |
import json
def gluonts_get_cardinality(dataset_path="", TD=None):
"""
Cardinality of gluonts dataset
:param dataset_path:
:param TD:
:return:
"""
if TD is None :
cc = json.load(open( dataset_path + "/metadata.json", mode="r" ) )['cardinality']
else :
cc = [feat_static_cat.cardinality for... | a6a6030c8f5bccc372c2c8e8347a052f54c817d5 | 655,506 |
from typing import Dict
import os
import hashlib
def hash_dict(exp_dict: Dict) -> str:
"""Hash an experiment dictionary into a unique id.
Can be used as a file-name. Adapted from Haven AI (https://github.com/haven-ai/haven-ai).
:param exp_dict: An experiment dictionary.
:returns: A unique id for the e... | e5b48ab1b9cd8292a2ae875f34d4cb56111bd45f | 655,508 |
from typing import Sequence
from typing import List
def indexify(sequence: Sequence, index_source: Sequence) -> List:
"""For the given `sequence`, get the index of each item in the `index_source`"""
return [index_source.index(item) for item in sequence] | f06e44ba43a12433390475166f4b30ca32bcf1f3 | 655,509 |
def _decayed_value_in_linear(x, max_value, padding_center, decay_rate):
"""
decay from max value to min value with static linear decay rate.
"""
x_value = max_value - abs(padding_center - x) * decay_rate
if x_value < 0:
x_value = 1
return x_value | faae3ebf1eb98758aa798f02c644c8d8370d9216 | 655,510 |
import requests
import json
def get_future_weather_info():
"""
Function to retrieve prediction data
for Dublin Weather in JSON format.
"""
response = requests.get('http://api.openweathermap.org/data/2.5/forecast?q=Dublin,ie&APPID=70ef396e3ce3949e0934b4428e41f453')
if response.status_code == 2... | c225210b89c5f66e8b90f2590240b15101fd10a9 | 655,511 |
import json
def read_json_file(path: str):
"""Read a json file into a dict."""
with open(path, 'r') as f:
data = json.load(f)
return data | ad266f43de9d7dcec214dd2e17326052f2b185fe | 655,512 |
import string
import random
def generate_session_id(size=32, chars=string.ascii_letters+string.digits):
"""
Generate session id - 32 length string
with ascii letters and digits
"""
return ''.join(random.choices(chars, k=size)) | 4e306e2214bf759054c46a9bd90c461bc3930062 | 655,514 |
def clean_data(df):
"""
This is the function that cleans the data of the joined df
Input
df - the df as we read it
Output
Returns a cleaned df
"""
#Split categories into separate columns
categories = df['categories'].str.split(pat=';',expand=True)
#Rename the ... | 5fc5099ee000b6bb99f3dfac72f45298477a7f45 | 655,515 |
def get_chars(path_to_vocab):
"""
Return the list of all characters found in the vocabulary.
"""
chars = set()
with open(path_to_vocab) as f:
for line in f:
chars.update(line.rstrip())
return chars | b8422548a42b63e2d27ad81d2904739d027e1d73 | 655,516 |
import re
def at_least_one_equal_pair(num: str) -> bool:
"""Check if at least one unique pair is present."""
return any(len(group[0]) == 2 for group in re.findall(r"((.)\2+)", num)) | f22adc65de657e4e7f0c2f5abcf2b81d382297bb | 655,517 |
def fill_nan(df,list):
"""
Fill nan values with either mean or mode
Parameters
----------
df : dataframe
dataframe used for checking and filling nan values
list: list
list of columns to be checked
Returns
-------
df : dataframe
modified dataframe with no nan... | 5f07eb835c4e20b08e98d319b4749694ad81474f | 655,518 |
def _from_snapshot_request(pre_image, image):
"""
when patch location, check if it's snapshot-sync case.
"""
if pre_image.status == 'queued' and len(image.locations) == 1:
loc_meta = image.locations[0]['metadata']
return loc_meta and loc_meta.get('image_from', None) in ['snapshot',
... | 78b0bf5df0d2a317436c9f14d1e3f69f6a33d575 | 655,519 |
def cidade_pais(cidade: str, pais: str) -> str:
"""
-> Devolve o nome da cidade e do seu país formatados
de forma elegante.
:param cidade: O nome da cidade.
:param pais: O nome do país.
:return: Retorna a string -> 'Cidade, País'
"""
return f'{cidade}, {pais}'.title() | bf6412dcff2d27be910ebeda9442384442bd50e3 | 655,520 |
import re
def is_uuid(value):
"""Verify if the value can be a uuid"""
UUID_REGEX = re.compile(r'^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$',
re.IGNORECASE)
m = UUID_REGEX.match(value)
return m is not None | c3ba2e46e49f442c31f596be6cecb5df27b8c888 | 655,521 |
import os
def tordir_file(fname):
"""Make fname relative to the current directory, which should be the
top-level tor directory. Also performs basic path simplifications."""
return os.path.normpath(os.path.relpath(fname)) | 4ed435cef69f0970a2f01666b8920574e6a70fbd | 655,522 |
def create_envs(service_component_name, *envs):
"""Merge all environment variables maps
Creates a complete environment variables map that is to be used for creating
the container.
Args:
-----
envs: Arbitrary list of dicts where each dict is of the structure:
{
<environment... | b53e81a2368da1bc8991a63b66173ccf1acb31f0 | 655,523 |
def create_structure(hash):
"""
Recursive method that creates a JSON-like structure from a hash.
Refer to Starflyers.py for the input
Parameters
hash. A hash expression
Returns
base_structure. The structure of the given hash. Dictionary.
"""
index = 0
character = hash[ind... | b37d43c1280813ccb6387c28386fc3bb20fc84eb | 655,524 |
def recurrence_abc(n, alpha, beta):
"""See A&S online - https://dlmf.nist.gov/18.9 .
Pn = (an-1 x + bn-1) Pn-1 - cn-1 * Pn-2
This function makes a, b, c for the given n,
i.e. to get a(n-1), do recurrence_abc(n-1)
"""
aplusb = alpha+beta
if n == 0 and (aplusb == 0 or aplusb == -1):
... | 4aa5e16321977b36e128742c0e53f1538a5adf62 | 655,525 |
import math
def hit_info(mirror_corner_pos, hit_pos):
"""Get hit infomation, which mirror to hit?"""
is_left = False
is_top = False
if (math.fabs(hit_pos[0] - mirror_corner_pos[0]) < 0.001):
# left hit
is_left = True
if (math.fabs(hit_pos[1] - mirror_corner_pos[1]) < 0.001):
... | a95014306406ed2411f70c2925857df7aba5ae75 | 655,526 |
import time
def formated_time():
"""Helper function to reformat time to the specific format from below."""
ct = time.localtime()
return "{0:04d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z".format(*ct) | f4b1054a18085717b95f4c9507b335f6848a30ac | 655,527 |
def to_int(object):
"""RETURN : None if unable to convert to int"""
return int(object) | 3e89c089756f4f0e7d840caee5990f05519f6d99 | 655,528 |
def get_underline(string):
"""
Return an underline string of the same length as `str`.
"""
return "="*len(string) + "\n" | f8cd102447c0788af5c1385d8e01018d6f3eb71a | 655,529 |
import argparse
def parse_args(args):
"""
Parses arguments.
:param args: Arguments.
:return: Parsed arguments.
"""
parser = argparse.ArgumentParser('Tello Flight Commander',
epilog='One-Off Coder https://www.oneoffcoder.com')
parser.add_argument('-f', '--file', help='command file... | c870af26ffe95ccafdc871d738859f4db16d4023 | 655,530 |
def width_multiplier_op(filters: int,
width_multiplier: float,
min_depth: int = 8) -> int:
"""Determine the number of channels given width multiplier"""
return max(int(filters * width_multiplier), min_depth) | 872fff290eba98c4272ec74416bbf6b52462bed2 | 655,531 |
def get_status(runs):
"""Get the most recent status of workflow for the current PR.
Parameters
----------
runs : list
List of comment objects sorted by the time of creation in decreasing order.
Returns
-------
status : string
The most recent status of workflow.
Can ... | 081d5fb6e8218edcbf25adb9f8b1eeb2d2add1a1 | 655,532 |
from typing import Tuple
from typing import Dict
def parse_options_header(value: str) -> Tuple[str, Dict[str, str]]:
"""Like werkzeug.http.parse_options_header(), but ignores the options."""
return value.partition(';')[0].strip(), {} | 1f50d4328061d763c712422a130dc0877a688388 | 655,533 |
def backdoor_examples(xs, backdoor, eps):
"""
Inject a backdoor into training examples with norm epsilon.
"""
return xs + backdoor * eps | 86cb1c986f7ae78b88789bd613b41567d766f10f | 655,534 |
def fix_standard_imports(red):
"""
Handles import modification in the form:
import flask.ext.foo" --> import flask_foo
"""
imports = red.find_all("ImportNode")
for x, node in enumerate(imports):
try:
if (node.value[0].value[0].value == 'flask' and
node.value[0]... | 49e46129a2301077c1903b48326578b3867f7625 | 655,536 |
def html(module, tag):
"""Mapping for html tags.
Maps tags to title case, so you can type html tags as ``<audio>``
or ``<AuDiO>`` or whichever way.
"""
title = tag.title()
if title in {
"A",
"Abbr",
"Acronym",
"Address",
"Area",
"Article",
... | 5bf880fecd3d4b452bc9f3628f86da456deb62de | 655,537 |
from pathlib import Path
import re
def normalise_nci_symlinks(input_path: Path) -> Path:
"""
If it's an NCI lustre path, always use the symlink (`/g/data`) rather than specific drives (eg. `/g/data2`).
>>> normalise_nci_symlinks(Path('/g/data2/v10/some/dataset.tar')).as_posix()
'/g/data/v10/some/data... | 9dde3bfc5750ac9bd50680a6ab50b3db9699dd09 | 655,538 |
def get_user_input(case: str) -> str:
"""Get user input on what to do if the the dataframes are of same
width, but the column names differ.
"""
if case == "columns":
INPUT_STRING = (
"\nThe dataframes have the same number of columns, but their "
"names differ. \nIf you wa... | 450f72b9c7567946a81d38707f7f744e8f7d86e2 | 655,539 |
def calc_mean(values):
"""Calculates the mean of a list of numbers."""
values_sum = 0
for value in values:
values_sum += value
return values_sum / len(values) | 4db43d762ecc99d75c42e87992935d7f9c9a9feb | 655,540 |
def destroy_item(game, *args):
"""Removes an Item from the game by setting its location is set to None."""
(item, action_description) = args[0]
if game.is_in_inventory(item):
game.inventory.pop(item.name)
print(action_description)
elif item.name in game.curr_locat... | 92ea88a6023d872d412fb834565436cabb9b3321 | 655,541 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.