content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def hours_to_days(hours):
"""
Convert the given amount of hours to a 2-tuple `(days, hours)`.
"""
days = int(hours // 8)
hours_left = hours % 8
return days, hours_left | 849961d6fc1ce68c72d300885cddb05aebba0941 | 677,560 |
def get_primes(start, stop):
"""Return a list of prime numbers in ``range(start, stop)``."""
if start >= stop:
return []
primes = [2]
for n in range(3, stop + 1, 2):
for p in primes:
if n % p == 0:
break
else:
primes.append(n)
while primes and primes[0] < start:
del primes[0]
return primes | 21991dd24a2f92b3c91bd2d69ec8c462bde58537 | 677,561 |
from pathlib import Path
def find_dictionary_file():
"""Return the filepath of the .labelauditignore.json dictionary file."""
file_name = ".labelauditignore.json"
parent_directories = [Path().resolve()] + list(Path().resolve().parents)
for directory in parent_directories:
file_path = directory... | 3118fca999da4c75096d99b378469e94853f8184 | 677,562 |
def circumcentre(A, B, C):
"""Compute the centre of the circumscribed circle."""
D = 2 * (A[0]*(B[1]-C[1]) + B[0]*(C[1]-A[1]) + C[0]*(A[1]-B[1]))
if D == 0:
return None
K_x_A = (A[0]*A[0] + A[1]*A[1]) * (B[1]-C[1])
K_x_B = (B[0]*B[0] + B[1]*B[1]) * (C[1]-A[1])
K_x_C = (C[0]*C[0] + C[1]*C... | ed3abf9ffd6161d5b1c8490ac4da1468d1d877e8 | 677,563 |
def format_number(number):
"""Format numbers for display.
if < 1, return 2 decimal places
if <10, return 1 decimal places
otherwise, return comma formatted number with no decimal places
Parameters
----------
number : float
Returns
-------
string
"""
if number == 0:
... | 254251f9d0b847c6bb020d19953a2c7deb801b7c | 677,564 |
def filter_channels_by_server(channels, server):
"""Remove channels that are on the designated server"""
chans = []
for channel in channels:
sv, chan = channel.split(".", 1)
if sv == server:
chans.append(chan)
return chans | 358bd83bd2cc6b6fabaced3cac99b0c56741ad06 | 677,565 |
def isFloat(string):
""" is the given string a float? """
try: float(string)
except ValueError: return 0
else: return 1 | 4605d2975523dab25ec598ee7ed0324c0c200b05 | 677,567 |
import json
def load_from_json_file(filename):
""" writes an object form JSON file """
with open(filename, encoding="utf-8") as f:
new_obj = json.loads(f.read())
return new_obj | 7c7581bcf228c50287d0fbdbe5267db1bfce7c0c | 677,568 |
import io
import tarfile
import gzip
import shutil
def _make_control_tgz(package, mode):
"""Make the control.tar.gz file.
:param package:
The :py:class:`~apkkit.base.package.Package` instance for the package.
:param str mode:
The mode to use for control.tar ('x' or 'w').
:returns:
... | d58eb930764c5872973a30c27588247e81d7cbd2 | 677,569 |
import json
import os
def list_file_data():
"""
Function: list_file_data\n
Parameters: None\n
Return: list of data in analysis.log file\n
"""
epsilon = 0.0
learning_rate = 0.0
decay_factor = 0.0
with open('input_files/scenario_input.json', 'r') as file_pointer:
file_data = ... | 70e0823ccd1bb18501f8afd2528e7bc8897dfa8d | 677,570 |
def transform(m, b, n):
"""
Given vector 'b', Calculate vector 'a' such that:
2*a-n*one == M * (2*b-n*one), where 'one' = (1, 1)
--> a = M*b + (I-M)*one*n/2
M is the transformation matrix,
the coordinates of 'a' and 'b' range from 0 to n-1.
"""
bb = []
for j in range(... | 53909072ee9471fb26b89687d7d026638d57463b | 677,571 |
from typing import Optional
from typing import IO
def openfile(spec: Optional[str]) -> Optional[IO[str]]:
"""Open file helper.
Args:
spec: file/mode spec; for example:
* ``file`` uses mode ``w``
* ``file+`` uses mode ``a``
* ``file+r`` uses mode ``r``
Return... | 435547e3fa359a787f1f14b378a6eed9a0c3ee53 | 677,572 |
def find_source(UpperSeq, LowerSeq, Src, Trg):
"""
Assign SourceLoc to the first coded or compound (NE in the UpperSeq; if
neither found then first (NE with --- code Note that we are going through
the sentence in normal order, so we go through UpperSeq in reverse order.
Also note that this matches e... | ee59c9fbf0733cca0cbd5f07085770b2a72696fb | 677,573 |
from pathlib import Path
def _get_file_dict(fp,fname):
""" Find an image matching fname in the collection
This function searches files in a FilePattern object to find the image dictionary
that matches the file name, fname.
Inputs:
fp - A FilePattern object
fname - The name of the... | ba4e744a644c6f6f75fde47aa6b30790dbb70c38 | 677,574 |
def apply_fct_to_sm(opt_model, fct, start=None, stop=None, step=None):
"""Iterate in reverse over seq_model.ifcs. Override if needed."""
sm = opt_model.seq_model
start = len(sm.ifcs)-1 if start is None else start
stop = 0 if stop is None else stop
step = -1 if step is None else step
num_changes ... | 060bb620d169389709c5a6aeb201b26489cac797 | 677,575 |
import bz2
import logging
def bzip_blocks_decompress_all(data):
"""Decompress all of the bzip2-ed blocks.
Returns the decompressed data as a `bytearray`.
"""
frames = bytearray()
offset = 0
while offset < len(data):
block_cmp_bytes = abs(int.from_bytes(data[offset:offset + 4], 'big', ... | 2e1d5bb8f6692a0a16eaa277d0567cfe6efc58c4 | 677,576 |
def index_fasta( f ):
"""
Makes a simple index for a FastA file
:param f: an opened fasta file
:return: a dict with the chromosomes as keys and the tell positions as values
"""
lpos = f.tell()
rval = {}
# for each line in the fasta
l = f.readline()
while l != "" :
# re... | 67dc0b00bfb6cf4bd057250e34d9626eb18813f7 | 677,578 |
def concatenate_rounds(rounds_1, rounds_2):
"""
:param rounds_1: list - first rounds played.
:param rounds_2: list - second set of rounds played.
:return: list - all rounds played.
"""
return rounds_1 + rounds_2 | 7ef6e284fab1a2ff3a51a8a34373268ad9c1823d | 677,579 |
from typing import Tuple
def _get_output_pad(plain: bool) -> Tuple[int, int, int, int]:
"""Return the padding for outputs.
Args:
plain (bool): Only show plain style. No decorations such as
boxes or execution counts.
Returns:
Tuple[int, int, int, int]: The padding for outputs.... | 5fdc2b645238028cfe17f8773c1f1a343da692ec | 677,581 |
def height(root):
"""Function to return the height of a binary tree
Args:
root (Node): The root node of the binary tree
Returns:
(int): The height of the binary tree
"""
left = 0
right = 0
if root.left:
left = 1 + height(root.left)
if root.right:
right =... | 5b351705fe9f25f2eda7716d4e80b6630508a318 | 677,583 |
def _to_iloc(data):
"""Get indexible attribute of array, so we can perform axis wise operations."""
return getattr(data, 'iloc', data) | 137dc760dc1e33e319017a0b8356a5e12add6b61 | 677,584 |
def psu2ppt(psu):
"""Converts salinity from PSU units to PPT
http://stommel.tamu.edu/~baum/paleo/ocean/node31.html
#PracticalSalinityScale
"""
a = [0.008, -0.1692, 25.3851, 14.0941, -7.0261, 2.7081]
return (a[1] + a[2] * psu ** 0.5 + a[3] * psu + a[4] * psu ** 1.5 + a[5] *
psu ** 2 ... | d73195c5632f794e0e75aadaa85886291246e429 | 677,585 |
import numpy
def ex6_atleast_2d_fill(height=1000, width=1000):
"""Fill using atleast_2d and transpose"""
sine = numpy.sin(numpy.arange(width))
cosine = numpy.cos(numpy.arange(height))
return numpy.atleast_2d(sine) * numpy.atleast_2d(cosine).T | 882d01d456e44f4e462ec771b39f248f7732d181 | 677,586 |
def _nextSibling(self):
"""
Return the next sibling
NOTE: This is fairly inefficient. The reason that it has
to be done this way is because Text nodes are a subclass of
`unicode` which is an immutable object. This means that
we can't have two references to the same Text object (i.e.
`... | a00ea99a48ab0ca18b5ed043733ee6eecffffcba | 677,587 |
import re
def parse_show_ip_bgp_summary(raw_result):
"""
Parse the 'show ip bgp summary' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show ip bgp summary command in a \
dictionary of the form:
::
{
... | 0b4f7e2f18a3430647ddf99cfad0c6f64d369b3f | 677,588 |
def no_preview(message_text: str, link: str) -> bool:
"""
Checks if the found url is inside the no-preview <brackets>.
"""
return f"<{link}>" in message_text | 2c6d3c1477dd58c08262bde0d78d888fe6dde3df | 677,589 |
def cfilter(choices, vlist):
"""
Returns whitelisted countries.
"""
v = lambda choices, whitelist: tuple((k) \
for k2 in whitelist for k in iter(choices) if k[0] == k2)
return v(choices, vlist) | 43c890dd7d5f179ed70ab03867af281f98c9bc7c | 677,590 |
def build_part_check(part, build_parts):
"""
check if only specific parts were specified to be build when parsing
if the list build_parts is empty, then all parts will be parsed
"""
if not build_parts:
return True
return bool(part in build_parts) | 9b9923b45e794bff3df03a63cbbed3280a25d211 | 677,591 |
def build_userid_display(userid, user_item):
"""Build and return the string to display for selecting a user.
Displays info from users table so user can pick the ids.
"""
return u' id=%-3s %-20s %-16s %-16s %s, %s' % (userid,
user_item['CompanyNam... | a4090f4e8881861355516eb1e6aae2f6d32a21bd | 677,592 |
import argparse
import sys
def get_args():
"""Parse user giver arguments"""
parser = argparse.ArgumentParser(
description="DrugZ for chemogenetic interaction screens",
epilog="dependencies: pylab, pandas",
)
parser._optionals.title = "Options"
parser.add_argument(
"-i",
... | 1d889c5ca82e74942fd6602486583b40268f2a17 | 677,593 |
import os
def sub_dire(base, dire, fname=None):
""" Build path to a base/dire. Create if does not exist."""
if base is None:
raise ValueError(f"base={base} is not valid")
else:
path = os.path.join(base, dire)
if not os.path.exists(path):
os.makedirs(path)
if fn... | 4d9a0c43d0ee4b6514681e8973c190cb113eef5a | 677,594 |
import base64
def generate_aws_checksum(image_checksum: str) -> str:
"""
Takes an MD5 checksum provided by SciHub and generates a base64-encoded 128-bit
version, which S3 will use to validate our file upload
See https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Clie... | 00a7eed956e581fd27db7d6bd65f7e56c4e79211 | 677,595 |
def get_model_chain_ids(structure):
"""
Extracts model and chain ids from structure object.
Parameters
----------
structure: Bio.PDB.Structure.Structure
Returns
-------
struct_id: tuple
tuple of (modelid, chainid)
"""
modelnum = []
chainid = []
for model in str... | 2e4c84f6387397d35db71df5365deaeb21bb39c3 | 677,596 |
def stats_path(values):
"""
Return the stats path for the given Values object.
"""
# The filter() call here will remove any None values, so when we join()
# these to get our stat path, only valid components will be joined.
return '.'.join(filter(None, [
# plugin name
values.plugi... | 41fe636a7f0e2152f3fccb75731eed66b7223a07 | 677,597 |
def kth_to_last(k, node):
"""."""
curr_node = node
kth_to_last_nodes = []
for _ in range(k):
if not curr_node.next:
raise ValueError('k larger than list')
curr_node = curr_node.next
while curr_node:
kth_to_last_nodes.append(curr_node.val)
curr_node = curr... | 99c56bc4087a8dd5158bd4c73b6f0a0db621b4bb | 677,598 |
def dedupe_n_flatten_list_of_lists(mega_list):
"""Flatten a list of lists and remove duplicates."""
return list(set([item for sublist in mega_list for item in sublist])) | 552bc12b971741a0616da553ae548e8165ad6e5f | 677,600 |
def fatorial(num, mostra=True):
"""
-> Função para calculo do fatorial de um número
:param num: número a ser fatorado
:param mostra: se irá mostrar o calculo ou somente o resultado final.
:return:
"""
i = 1
l_fatorial = ''
for x in range(num, 1, -1):
i *= x
if mostra:... | c16d2c37148a41447ede1561d062f24dc22c6431 | 677,601 |
def get_rabbitmq_handler(handler, decode_body=True):
"""
:param handler: The handler method to handle the message defined by the user. It is derived from the `CONSUMERS`
variable defined above
:param decode_body: Most queues return the body in byte format. By default the message is decoded and then... | 1997d0961be4ca4a14a21bed3527a5138a47c131 | 677,602 |
def is_monic(f):
"""Check if the homomorphism is monic."""
return len(set(f.keys())) ==\
len(set(f.values())) | 43c42e052e0ac6910e962cf2f22c9aec52b4e7b2 | 677,603 |
def load_std_type(net, name, element):
"""
Loads standard type data from the data base. Issues a warning if
stdtype is unknown.
INPUT:
**net** - The pandapipes network
**name** - name of the standard type as string
**element** - "pipe"
OUTPUT:
**typedata** - dicti... | 4ab28db65e25bed3fb2f2231f8061b8e82261f67 | 677,604 |
def selection_sort(lst):
"""Implement selection sorting algorithm."""
if len(lst) < 2:
return lst
def smallest_index(lst):
smallest = lst[0]
sm_index = 0
for i in range(len(lst)):
if lst[i] < smallest:
smallest = lst[i]
sm_index = ... | 16be2b90bb297caea10f1093005d7056f641c2d2 | 677,606 |
import torch
def rgb_denormalize(x, stats):
"""
x : N x C x *
x \in [-1, 1]
"""
mean = torch.tensor(stats["mean"])
std = torch.tensor(stats["std"])
for i in range(3):
x[:, i, :, :] = x[:, i, :, :] * std[i] + mean[i]
return x | c6f65fbd4b155d90881c87e155eea1ef5dd3d827 | 677,608 |
def _strip_image(image):
"""Remove white and black edges"""
for x in range(image.width):
for y in range(image.height):
r, g, b, a = image.getpixel((x, y))
if r == 255 and g == 255 and b == 255:
image.putpixel((x, y), (0, 0, 0, 0))
image = image.crop(image.g... | 882374f949be23963ab8dc7a1ef74b906da7f007 | 677,609 |
import string
def base_encode(number, alphabet=string.ascii_lowercase, fill=None):
"""Encode a number in an arbitrary base, by default, base 26. """
b = ''
while number:
number, i = divmod(number, len(alphabet))
b = alphabet[i] + b
v = b or alphabet[0]
if fill:
return ... | 6194e6730f2022f8f9e2feffea8d51997ac2e93f | 677,610 |
def aXbXa(v1, v2):
"""
Performs v1 X v2 X v1 where X is the cross product. The
input vectors are (x, y) and the cross products are
performed in 3D with z=0. The output is the (x, y)
component of the 3D cross product.
"""
x0 = v1[0]
x1 = v1[1]
x1y0 = x1 * v2[0]
x0y1 = x0 * v2[1]
... | fb59030dc3cd0a8073dc17f34b4185ec4ca2e437 | 677,611 |
import os
import sys
def _get_env():
"""Extracts the environment PYTHONPATH and appends the current sys.path to
those."""
env = dict(os.environ)
env["PYTHONPATH"] = os.pathsep.join(sys.path)
return env | ea4121fbeba1c24c08e6d7c47b2eec8cf3986759 | 677,612 |
def epoch_init(M, i, j, w):
"""
Initialize epoch index from daily period, day of week and week of cycle.
:param M: Model
:param i: period of day
:param j: day of week
:param w: week of cycle
:return: period of cycle in 1..n_prds_per_cycle
"""
return (w - 1) * M.n_days_per_week() * M... | 4d97b93c18131f06635f636c94ecc79a12e43f1e | 677,613 |
import argparse
def parseargs():
"""
Parse the command line arguments
:return: An args map with the parsed arguments
"""
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="Produce a validation report for GASKAP HI observations. Either a cu... | 93e30a7b283739083e88a3f91e3cc174b5fbc7d7 | 677,614 |
def prior_transform_null(parameter):
"""Transforms our unit cube samples `u` to a flat prior between in each variable."""
#min and max for beta and epsilon
##although beta and epsilon does not have an upper bound, specify an large upper bound to prevent runaway samplers
aprime = parameter
amin ... | a78774fd000a88453a0e0b126125914f708dff43 | 677,615 |
def reverse_words3(s):
"""
Reverse words in a string without using split or reversing methods.
"""
words = []
length = len(s)
# Parse all words. Skip spaces.
i = 0
while i < length:
if s[i] != " ":
word_start = i
i += 1
while i < length and s... | 2122ed086e6869c4b3b1a158f9870b4fe7e54f5f | 677,616 |
def expose( func ):
"""
Decorator: mark a function as 'exposed' and thus web accessible
"""
func.exposed = True
return func | 076f168d0a78092c427e544374b221c885f99959 | 677,617 |
import os
def get_names_labels(filename, labels, sep, new_base):
"""
Gets the names and the labels from the given original filename and labels
:param filename: Original filename in the the old csv file
:param labels: Labels located in the old csv file
:param sep: operating system path separator
... | 8cae639b73c4e98423cee23cc836e81aa6ce160f | 677,618 |
def colored(color, text):
"""
Returns a string of text suitable for colored output on a terminal.
"""
# These magic numbers are standard ANSI terminal escape codes for
# formatting text.
colors = {
"red": "\033[0;31m",
"green": "\033[0;32m",
"blue": "\033[0;1;34m",... | 42d808283367a913bfe572c04b96b9e3b53a9646 | 677,619 |
def sort_bed_by_bamfile(bamfile, regions):
"""Orders a set of BED regions, such that processing matches
(as far as possible) the layout of the BAM file. This may be
used to ensure that extraction of regions occurs (close to)
linearly."""
if not regions:
return
references = bamfile.refer... | 3deb046485a9bb445820bff638f9a5337dc4a112 | 677,620 |
def to_xbrl_expressions(pattern, encode, parameters):
"""Placeholder for XBRL"""
return ["", ""] | 99475a69879465499c728b3b0cdd79ca59470542 | 677,621 |
def GetEndOfBlock(code, end_op):
"""Get the last line of block."""
"""It returns -1 if it can't find."""
for i in code:
if end_op in i:
return code.index(i)
else:
return -1 | 4edfa1ece719fb0d7b90913bed88b03b6ffb7ad0 | 677,622 |
def conn(rethink_tables, rethink_empty_db):
""" Provides a handle to a RethinkDB server with a unique
database for the current test module, and tables created as
specified in rethink_tables
"""
return rethink_empty_db | 978f27c06d3d866b060620d47cbd711ef9c02b53 | 677,623 |
def xo_game():
"""
Input a board position from 1-9 to mark position of XO.
Returns the XO board with summary of move(s)
"""
X_moves = []
O_moves = []
moves = []
moveCount = 0
board = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
# Game turns prompt and conditional rules ba... | 3bf24b6f488e5c3f774379626d3efa30444c6af8 | 677,624 |
def response(context):
"""Shortcut to the response in context"""
return context.response | 63fd6b29602183f2d4f88a4f6f5eb30bc37e8a10 | 677,625 |
def remove_title(input):
"""remove title inside training data. (title doesn't have period at the end)"""
if input.strip() and input.strip()[-1] not in ["。", "?", "!"]:
return ""
return input | da90ebe302af202d58728a7408ce3c6af391cda1 | 677,626 |
import requests
import time
def get_with_retry(*args, **kwargs):
"""
fetch url with retry times
args & kwargs for request.urlopen
"""
retry_time = 3
relay_step = 5
for i in range(retry_time):
try:
response = requests.get(*args, **kwargs)
return response
... | ab6e09e51d658c1630e58d987504498337575fd7 | 677,627 |
import argparse
def neg_int(value: str) -> int:
""" Negative int value not including 0 """
error_msg = f"{value} is an invalid negative int value"
try:
int_value = int(value)
except ValueError:
raise argparse.ArgumentTypeError(error_msg)
else:
if int_value >= 0:
... | 59535331281305ed1d78b8250967c0af566f8b60 | 677,628 |
def align_subwords_to_tokens(subwords, tokens):
""" Mapping subwords to tokens should be a many-to-one mapping, since many subwords form a single token
'tokens' should be Serif tokens
Will return a dict from subword_id to token_index
:type subwords: list[nlplingo.tasks.sequence.run.SubWord]
:type t... | f22a1a41888025828898fe27c755c28e7aea57a0 | 677,629 |
def addyear(df2):
"""[Include year column in daily temperature data]
Args:
df2 ([type]): [DataFrame including info from raw data]
Returns:
[type]: [DataFrame with year for each data point added]
"""
df2_temp = df2
df2_temp['year'] = df2.index.year
df2 = df2_temp
retur... | ad71a4ad63fdb2b390d389e8b50c5d615d1fa69e | 677,630 |
def ANNOTATIONS(annotations):
"""Serialize the content of an object annotation set.
Parameters
----------
annotations: vizier.core.annotation.base.ObjectAnnotationSet
Set of object annotations
Returns
-------
dict()
"""
values = annotations.values()
return [{'key': key,... | 420cd30f8e67ecf48b74a2dc34433dd557201852 | 677,631 |
def street_address(anon, obj, field, val):
"""
Generates a random street address - the first line of a full address
"""
return anon.faker.street_address(field=field) | 78c801c813e2245c64b3902e03c09baac3429255 | 677,632 |
def ABCD_eq(b,c,d):
"""
Basic estimator formula for count in 'A' (signal domain)
DEFINITION: A = B x C / D
^
|C | A
|-----
|D | B
0------>
"""
return b * c / d | 1d74b935ac7e406eb52b23e07af2eb5623f84790 | 677,633 |
def decode_text_from_webwx(text):
"""
解码从 Web 微信获得到的中文乱码
:param text: 从 Web 微信获得到的中文乱码
"""
if isinstance(text, str):
try:
text = text.encode('raw_unicode_escape').decode()
except UnicodeDecodeError:
pass
return text | 3e433086fafbaa712e194d2a294dbf3e218549db | 677,634 |
def nested(path, query, *args, **kwargs):
"""
Creates a nested query for use with nested documents
Keyword arguments such as score_mode and others can be added.
"""
nested = {
"path": path,
"query": query
}
nested.update(kwargs)
return {
"nested": nested
} | a0dcdc8df4d765c494b05d9b112cf3f58779145f | 677,635 |
def __get_service_names(scenario_config):
"""
Gets the list of services from the scenario config.
If no services are given, an empty list is returned.
:param scenario_config: The scenario config.
:return: A list of services. [] if no service names are found.
"""
if 'services' in scenario_con... | ff266e479153478cf548ada8e2a862bf74e2cbc1 | 677,636 |
import subprocess
import queue
import threading
def command_output(command_args, **kwargs):
""" Executes a command and returns the string tuple (stdout, stderr)
keyword argument timeout can be specified to time out command (defaults to 15 sec)
"""
timeout = kwargs.pop("timeout", 15)
def command_ou... | 4113da165cebd870a8e15b7f2a1898195384b86d | 677,637 |
def float_range(start, stop=None, step=None):
"""Return a list containing an arithmetic progression of floats.
Return a list of floats between 0.0 (or start) and stop with an
increment of step.
This is in functionality to python's range() built-in function
but can accept float increments.
A... | 0d6299284ebd29f57e7b400305cc06874fd93119 | 677,638 |
import string
def only_alpha(text):
"""Convert unicode string to ascii string without punctuations."""
rstring = ""
for word in text:
for letter in word:
if (letter in string.ascii_lowercase) or \
(letter in string.ascii_uppercase) or \
(letter == ' ') or (lette... | 713c41825e7ddea6d13375165ff53e87a75ea0e4 | 677,639 |
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
wlist = s.split()
new_s = []
for w in wlist:
new_s.append(w[::-1])
return " ".join(new_s) | 60c7aceb61b6cd1ef0f451cc53b56aeb709c642a | 677,640 |
def solvable(board, n):
"""
:param board: board representation to check for solvability
:param n: size of the board (n x n)
:return: True if board is solvable puzzle else False
"""
arr = []
for i in range(n):
for j in range(n):
if board.arr[i][j] == 0:
con... | 13bd58428f86d81b7776dc7a07345a41178e80e1 | 677,641 |
def attendance_numbers(brother, events, accepted_excuses):
""" Returns the a of the row of the attendance csv containing information about the brother and his
attendance at events
:param Brother brother:
the brother whose information you need the count for
:param list[Event] events:
th... | dfdd5e233a1d1ec996061c11b8d999a5118a5316 | 677,642 |
from typing import Optional
def _find_month_number(name: str) -> Optional[int]:
"""Find a month number from its name.
Name can be the full name (January) or its three letter abbreviation (jan).
The casing does not matter.
"""
names = ['january', 'february', 'march', 'april',
'may', '... | df3e932badb9140e6c6a22c3be897ca9da978b7e | 677,643 |
def is_valid_email(email_address):
"""
Given a possible email address, determine if it is valid.
:param email_address: a string with a proposed email address
:return: true if email_address is valid, false if not
"""
valid = False
if '@' in email_address and '.' in email_address: # check... | 05aa770f5285a8ae0509b99a7c561fc42f53af64 | 677,644 |
def mult_empty_list():
"""
>>> mult_empty_list()
[]
"""
return 5 * [] * 100 | 08370fa2d37949cc82a24517d4c7289492cbe606 | 677,645 |
def compute_rebalancing_amount(target_nominal, price, contract, portfolio):
"""
Computes number of units to rebalance
"""
n_new = int(target_nominal / float(price * contract.multiplier))
position = portfolio.get_position(contract.symbol)
if position is not None:
n_old = position.net_posi... | 7b41486736b25eec19234c0d6769f435c9840551 | 677,646 |
def move_down(rows, t):
""" A method that takes number of rows in the matrix
and coordinates of bomb's position and returns
coordinates of neighbour located bellow the bomb.
It returns None if there isn't such a neighbour """
x, y = t
if x == rows:
return None
else:
return (... | 486f19fd235cd506cca7dbdca64e32a25b7939c7 | 677,647 |
def train_model(mdl, X_train, Y_train, X_val, Y_val, epochs, batch_size):
"""
trains model with fit-command. Use for early testing of model
Parameters:
mdl ... created keras model
X_train ... training features
Y_train ... training labels
X_val ... validation features
Y_val ... validatio... | 4181915a209fcf5feb7324530205b8750ea821a8 | 677,648 |
def _makeLongDec(myDecDeg):
"""Make a long dec sting i.e. in style of long XCS names
"""
# Positive
if myDecDeg>0:
if myDecDeg<10:
sDeg="0"+str(myDecDeg)[0]
else:
sDeg=str(myDecDeg)[:2]
mins=float(str(myDecDeg)[str(myDecDeg).index("."):])*60
... | c9dc50ec3d6783fb228d7501433f427f4309319b | 677,649 |
import base64
import json
def generate_encryption_metadata_for_dbobject(
encrypted_key, master_key, plaintext_key, initialisation_vector
):
"""Encrypts the supplied bytes with the supplied key.
Returns the initialisation vector and the encrypted data as a tuple.
Keyword arguments:
encrypted_key -... | e5c6bf68dc64c00710380f3f80bd5e96e0bcf330 | 677,650 |
def get_domain(domain_table):
"""
A helper function to get the domain for the corresponding cdm domain table
:param domain_table: the cdm domain table
:return: the domains
"""
domain = domain_table.split('_')[0].capitalize()
return domain | 97e447af7fdf842086d54d93931c6ed45ddf4b0e | 677,651 |
import binascii
def base58_to_byte(v, length):
""" decode v into a string of len bytes
"""
__b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
__b58base = len(__b58chars)
long_value = 0
for (i, c) in enumerate(v[::-1]):
long_value += __b58chars.find(c) * (__b58base**i)
result ... | 75cce4b3d8a71bd0543f9824ba4d3e439bf9110a | 677,652 |
def normalize_value(value, level=0):
"""Normalize a value to one compatible with Pavilion variables. This
means it must be a dict of strings, a list of strings, a list of dicts of
strings, or just a string. Returns None on failure.
:param value: The value to normalize.
:param level: Controls what st... | 3afdf02cc44b8b9250922b34ff2d37581b956ff5 | 677,653 |
import argparse
def string_of(max_len):
"""Returns an argparse validator of string of bounded length.
>>> validator = string_of(5)
>>> validator("hello")
'hello'
>>> validator("toolong")
Traceback (most recent call last):
...
ArgumentTypeError: "toolong" has more than 5 characters... | 85c5ffbca62a863e7d554bc2db4ded7c9ca2c8c6 | 677,654 |
import os
def get_files_list(chat_dir):
"""Short summary.
Args:
chat_dir (str): Path to user's folder.
Returns:
list: List of pairs (number, filename)
"""
print(chat_dir)
chat_dir_list = os.listdir(chat_dir)
chat_dir_list = sorted(list(filter(lambda x: not x.startswith('... | 33053aa8e98c75ab4c8ca974b9513b8429a778e2 | 677,655 |
import re
def getMatch(term, alist):
"""
This program internally used in ncbi_getTaxonomy and ncbi_Sp2Taxa
term: search_string
"""
pattern = re.compile(term)
matching_list = [i.split('__')[1] for i in alist if pattern.match(i)]
if len(matching_list) == 0:
return ''
else:
... | 82d7e52e1549832badd60e2c8267649fc1dd58ac | 677,656 |
def _particular_antigen_comp(donor: int, recipient: int) -> tuple:
"""Returns a particalar antigen compatibility, where each tuple member
marks a compatibility for a particular antigen (A, B, Rh-D).
If tuple member is non-negative there is a compatibility.
For red blood cell compatibility is required t... | 90d3b07823998126c64e03350bbf6453ef0e6e70 | 677,658 |
def fmt_price(amt):
""" Format price as string with 2 decimals """
return '{:,.2f}'.format(amt) | 03c36c1d297f26d173bb5d325e9be45c406ac8c7 | 677,659 |
def adjust_data(code_list, noun=12, verb=2):
"""Set the computer to a desired state by adjusting the noun and verb
parameters.
Parameters
----------
code_list : list
opcode as provided by advent of code
noun : int, optional
the first parameter (in position 1), by default 12
... | 56af12bd7c6c3a9e8b0da6c04db8f74604be9c72 | 677,660 |
def wrap_calculate_using_fixed(var):
"""
Arguments wrapper for calculate_using_fixed.
Calculate a fixed step-size value.
"""
kappa = var['kappa']
def calculate_using_fixed(var):
"""
Calculate a fixed step-size value.
Parameters
----------
var : dict
... | 2366808329b1128d627917232cd58fbce9cdef64 | 677,661 |
def computeblocksize(expectedrows, compoundsize, lowercompoundsize):
"""Calculate the optimum number of superblocks made from compounds blocks.
This is useful for computing the sizes of both blocks and
superblocks (using the PyTables terminology for blocks in indexes).
"""
nlowerblocks = (expecte... | 8d6db73e30fe3659be5e5073fffc374ce8292631 | 677,662 |
import time
import calendar
def AmericanDateToEpoch(date_str):
"""Take a US format date and return epoch. Used for some broken WMI calls."""
try:
epoch = time.strptime(date_str, "%m/%d/%Y")
return int(calendar.timegm(epoch)) * 1000000
except ValueError:
return 0 | 7de1365e3116ed8aa2ade0001e22f81673f7c0a6 | 677,663 |
def is_mirrored(rot):
"""
Return True if an eaglexml rotation is mirrored.
"""
return rot and rot.startswith('M') | 9673e58397604f4faa148e65cf6507d17d131ed1 | 677,664 |
import json
def remove_latent(df, path_json='src/python_code/settings.json'):
"""
Remove latent data from df
:param df: dataframe
:param path_json: setting file
:return: new dataframe
"""
settings = json.load(open(path_json))["OOD"]["Gather_Data"]
names_ood = settings["Set_DataSets"][i... | 30a53c1765e578bbbfd94419dcd75a1177cf5423 | 677,665 |
def WritePacketRaw(header, data):
"""
Given two raw bytearrays, return a bytearray representing the entire packet
"""
return header + data | 476749834ac680505863c2876f991f6f0e46385b | 677,666 |
def assert_flow_control(value):
"""
An example on flow control with bare asserts
"""
assert value
return "got a value of expected type!" | 76ab1743bbe8a699a953ac7d2919f5735889c723 | 677,667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.