content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def latest(scores):
"""
Return the latest scores from the list
"""
return scores[-1] | ec5bb0a18f6a86e154065d4b2e4ae089ec45ffe7 | 58,389 |
import yaml
def read_yaml(infile, log=None) -> dict:
"""
Read YAML file and return a python dictionary
Args:
infile: path to the json file; can be hdfs path
Returns:
python dictionary
"""
if infile.startswith("hdfs"):
raise NotImplementedError
else:
return... | 9c0c2ce90841119d158a72966061db3a7fa9a36a | 45,701 |
def species_level(prediction):
"""Is this prediction at species level.
Returns True for a binomial name (at least one space), False for genus
only or no prediction.
"""
assert ";" not in prediction, prediction
return prediction and " " in prediction | e005b7890188e5920c53629eb349e6872f87019b | 418,159 |
def get_messages(sqs_queue, pull_batch_size=10, wait_time_seconds=5):
"""Get n messages from the provided sqs queue."""
messages = sqs_queue.receive_messages(
MaxNumberOfMessages=pull_batch_size, WaitTimeSeconds=wait_time_seconds)
return messages | 0f8b2ea2518df5cce3cc21a20927e5cb7bb70711 | 204,237 |
import itertools
def _get_length_sequences_where(x):
"""
This method calculates the length of all sub-sequences where the array x is either True or 1.
Examples:
x = [0,1,0,0,1,1,1,0,0,1,0,1,1]
_get_length_sequences_where(x)
[1, 3, 1, 2]
x: An iterable containing only 1, True, 0 and False v... | 78ae3c4a0f592df34a55ec5c71bcfbdfaf3ece43 | 478,040 |
import zlib
def read_zlib_chunks(read_some, dec_size, buffer_size=4096):
"""Read zlib data from a buffer.
This function requires that the buffer have additional data following the
compressed data, which is guaranteed to be the case for git pack files.
:param read_some: Read function that returns at ... | 04846dda234037eee25c82abbbd09ab8e77d020f | 311,163 |
import math
def evaluate(expression: str):
"""
Evaluate a math expression.
Args:
expression: string representing the math expression to be eval()
Returns:
result of the math expression from eval()
Raises:
NameError: If expression passed is not from math library
Example... | f48d5db64577b5d06645a02f84bc8fda17919412 | 483,202 |
def Manhattan_dist(curr_point, goal):
""" Finds the Manhattan distance of a point from the goal point
"""
return abs(goal[0] - curr_point[0]) + abs(goal[1] - curr_point[1]) | 113cd294b7fd485b249711a9d630e630f4ee5d9e | 287,590 |
def _gf2bitlength_linear(a):
"""
Computes the length of a polynomial coefficient bit vector = degree + 1.
Parameters
----------
a : integer
Polynomial coefficient bit vector.
Returns
-------
n : integer
length of polynomial `a`.
"""
n = 0
while a ... | b3d6ac750a38741109574666a97fe03d56a4091c | 272,471 |
def height(tree):
"""The height of a tree."""
if tree.is_leaf():
return 0
else:
return 1 + max([height(b) for b in tree.branches]) | ba5ef589646022619b0f1d75d8fd701cecc6d4b9 | 146,616 |
def defaults(obj, *sources):
"""
Assigns properties of source object(s) to the destination object for all destination properties
that resolve to undefined.
Args:
obj (dict): Destination object whose properties will be modified.
sources (dict): Source objects to assign to `obj`.
Ret... | 2e1752f2f31c75b8e03ef5144feea7149c3cc574 | 557,174 |
def update_haplotype(variant, reference_haplotype, reference_offset):
"""Updates haplotypes for a variant.
A list of variant haplotypes are updated given a variant and a reference
haplotype (this consists of a sequence and an offset wrt to the reference).
All ALT alleles are updated as independent updated hapl... | 47e69de78d24a10a7f441102587f29862b0ca18b | 210,126 |
def remove_stop_words(content, stopwords):
"""Removes the stopwords in an article.
:param tokens: The tokens of an article.
:type tokens: []str
:param stopwords: the list of stopwords
:type stopwords: []str
:return: The tokens of an article that are not stopwords.
:rtype: []str
"""
... | 97e7ef8e92853f629d9c6e2e211d423564d865dd | 653,375 |
import re
def fix_grams(ret_str):
"""
Search for gram strings that have been split with whitespace and rejoin them.
For instance "3 SG" will become "3SG"
"""
for gram in ['3SG', '1PL', '2SG', '2PL']:
for i in range(1, len(gram) + 1):
first, last = gram[:i], gram[i:]
... | 6365e2fe4a20ce448ab1bc5272fd87903fca5782 | 156,857 |
import binascii
def encode_domain(domain):
"""Given a domain with possible Unicode chars, encode it to hex."""
try:
return binascii.hexlify(domain.encode('idna'))
except UnicodeError:
# Some strange invalid Unicode domains
return None | ae2d761adcf5956b9657ea8d60d3ea202f19f241 | 44,583 |
def interpolation(alpha, t1: tuple, t2: tuple):
"""Return alpha * t1 + (1 - alpha * t2)."""
return tuple(alpha * i + (1 - alpha) * j for i, j in zip(t1, t2)) | b0a635bd30e81f4327ef0e51d7f0cf08168c3c60 | 353,041 |
def get_energy(conformer):
"""
A function to find the potential energy of a conformer
Variables:
- conformer (Conformer): the conformer object of interest
Returns:
- energy (float): the corresponding energy of that conformer.
Will result in an error if there is no ASECalculator object... | 559d589c0fc64dd30e60a12a74d08e61b06d4890 | 372,855 |
def check_all_jobs_complete(jobs):
"""Given a list of jobs from the DB, check that all are done processing."""
for job in jobs:
if(job['status'] == 'processing'):
return False
return True | bc9e9adc35233e032ae25ca0826f6acd74ca2347 | 547,388 |
async def valid_content_type(content_type: str) -> bool:
"""Return True if supported content-type."""
if content_type.lower() in [
"text/turtle",
"text/html",
"application/pdf",
"image/png",
]:
return True
return False | 67e70a6d199d3f270f83c3e16b856f70040a0424 | 176,444 |
def cssname(value):
"""Replaces all spaces with a dash to be a valid id for a cssname"""
return value.replace(' ', '-') | d374d84482d062fde387a967f7d790985e87033c | 61,445 |
def _to_bytes(str_bytes):
"""Takes UTF-8 string or bytes and safely spits out bytes"""
try:
bytes = str_bytes.encode('utf8')
except AttributeError:
return str_bytes
return bytes | fd16c24e80bdde7d575e430f146c628c0000bf9a | 703,678 |
import torch
def ccwh_to_xyxy(t: torch.Tensor) -> torch.Tensor:
"""
converts bbox coordinates from `(x_center, y_center, width, height)` to `(xmin, ymin, xmax, ymax)`
"""
assert t.size(-1) == 4, "input tensor must be of size `(N, 4)` with format `(x_center, y_center, width, height)`"
cc = t[..., :... | 0e31ac7829ef8033de323a007b792ff9cb52932b | 591,764 |
def load_paths_dict(preprocess_config):
"""Creates a dictionary of paths without the path to the df.
This is so that the attributes for Preprocessor can be set recursively.
Args:
preprocess_config (dict): From loading 'create_dset.yml'
Returns:
paths_dict (dict): same as config['paths_... | a417b0dc9004712329843a4d8fd34195eda33bab | 396,946 |
def srev(S):
"""In : S (string)
Out: reverse of S (string)
Example:
srev('ab') -> 'ba'
"""
return S[::-1] | 54cef6c2fef90d4b307266664b5cdaf785de4314 | 137,387 |
def as_ascii(input_string):
"""Helper function to parse a byte string to an ascii string if necessary"""
try:
return input_string.decode('ascii')
except AttributeError:
return input_string | 0cedf0f5a20cc78d88b6462b9682bff8bedfee55 | 319,363 |
def get_typeid(typename, field):
"""determine type ID (single letter indicating type) based on type name and optional field tag parsed from the URI"""
if typename == 'Agent':
if field in ('100', '600', '700'):
return 'P' # Person
else:
return 'O' # Organization
if typ... | 518ac505a00b5f153ce4f06b0651033858e94043 | 177,130 |
def remove_draw_parameter_from_composite_strategy(node):
"""Given that the FunctionDef is decorated with @st.composite, remove the
first argument (`draw`) - it's always supplied by Hypothesis so we don't
need to emit the no-value-for-parameter lint.
"""
del node.args.args[0]
del node.args.annota... | 54fd2824abffa8cde0af85e4293d66b9e19115ea | 65,596 |
def safe_join(separator, values):
"""Safely join a list of values.
:param separator: The separator to use for the string.
:type separator: str
:param values: A list or iterable of values.
:rtype: str
"""
_values = [str(i) for i in values]
return separator.join(_values) | e6ef01fe4bcdd5fa8ed34a922b896dc10ec7eda0 | 631,350 |
def exp_smooth(new_n, new_s, new_m, old_n, old_s, old_m, a = 0.05):
"""
This function takes in new and old smoothed values for mean, sd and
sample size and returns an exponentially smoothed mean, sd and sample
size.
"""
smooth_n = a*new_n + (1-a)*old_n
smooth_s = a*new_s + (1-a)*old_s
sm... | 08c8c8c5aee12e530cd5152d8e5558fabcb68058 | 633,023 |
def Not(thing):
"""Not(thing) is a nicer way of saying thing.Not()"""
return thing.Not() | f67ad1ce2206637598132ffe2d9a86a666d625e2 | 277,386 |
def num_add_commas(num):
"""
Adds commas to a numeric string for readability.
Parameters
----------
num : int
An int to have commas added to.
Retruns
-------
str_with_commas : str
The original number with commas to make it more readable.
"""
num_... | c1da51505c9d442daa981c349f9bde426acef987 | 575,093 |
from typing import List
def get_items_from_string(string: str, separator: str = ',', remove_blanks: bool = True) -> List[str]:
"""
Returns a list of items, separated by a known symbol, from a given string.
"""
items = [item.strip() if remove_blanks else item for item in string.split(separator)]
if... | ec6cc6f57c91ce3f701f21301141a6122086c65e | 571,462 |
def IsInclude(line):
"""Returns True if the line is an #include/#import line."""
return line.startswith('#include ') or line.startswith('#import ') | b62b4fa1cd44f923188649cadaaae769ec11ea89 | 442,580 |
def get_id_pair_from_nodes(node1, node2):
"""
This method returns a sorted pair of ids corresponding to two different nodes
:param node1: The first Node object
:param node2: The second Node object
:return: A sorted pair (id1, id2) of the corresponding ids such that id1 < id2
"""
id1, id2 = ... | ee4cba463ec57bbad9c305d7e9c4c569d927abe2 | 376,160 |
def build_slice_name( experiment_name, variable_name, time_index, xy_slice_index ):
"""
Builds a unique name for a slice based on the experiment, variable, and location
within the dataset.
Takes 4 arguments:
experiment_name - String specifying the experiment that generated the slice.
varia... | 486d97602081b0aefbb8e14689fbd8f4a942802a | 597,368 |
import getpass
def prompt_for_password(prompt_text):
"""Interactively prompt the operator for a password."""
return getpass.getpass(prompt_text) | 663046763b2352c379ec3b66d928cd73c874af98 | 441,150 |
import logging
def split(pattern, lyrics):
"""Split Binasphere lines.
Args:
pattern: List of integers indicating join pattern.
lyrics: String to split.
>>> split([0, 1, 1], 'a b c d e f')
['a d', 'b c e f']
"""
lyrics = lyrics.split()
num_lines = max(pattern) + 1
res... | 3dc8a9163b49d2f41a2405d253227af036c13048 | 64,683 |
import requests
import json
def GitHub_post(data, url, *, auth, headers):
"""
POST the data ``data`` to GitHub.
Returns the json response from the server, or raises on error status.
"""
r = requests.post(url, auth=auth, headers=headers, data=json.dumps(data))
r.raise_for_status()
return ... | 5e86aa8c3780e39f894b63c603c75779fcd159c7 | 54,380 |
def add_column_values(table, column_title, column_values):
"""
Adds a column to a specific table
Note that you must include a column title and the values of the column
"""
if len(table) == 0:
raise TypeError("Empty table")
table[0].append(column_title)
for j in range(1, len(table)):
... | 56ea4353053a88ed15973aced9321ede0e9166f2 | 206,439 |
def resolution_from_chunk_key(chunk_key):
"""
breaks out the resolution from the chunk_key.
Args:
chunk_key (str): volumetric chunk key = hash&num_items&col_id&exp_id&ch_idres&x&y&z"
Returns (str): resolution
"""
parts = chunk_key.split('&')
return parts[5] | d9d3dd10b9063e27a185db2e05f3f7503019d466 | 255,897 |
def mulND(v1, v2):
"""Returns product of two nD vectors
(same as itemwise multiplication)"""
return [vv1 * vv2 for vv1, vv2 in zip(v1, v2)] | 5fecb0e5732161b515f5e719448f0dd0e35ee103 | 325,540 |
import re
def read_query(fname: str) -> str:
"""Read a query from file.
Read query and remove all white space between tags.
Args:
fname: Filename tor read.
Returns:
Read query.
"""
with open(fname, "r") as file:
s = file.read()
return re.sub(r"\s+(?=<)", "", ... | 39083b8e6e3d4772fc170eb50b54715142ae7896 | 257,282 |
def io(func):
"""
@io decorator for blocking io operations.
In pycsp.parallel it has no effect, other than compatibility
>>> @io
... def sleep(n):
... import time
... time.sleep(n)
>>> sleep(0.01)
"""
return func | 8dc21702ac884d953e79df7d951dfef76ef71b93 | 616,986 |
import re
def remove_observed(exp_name: str | None) -> str | None:
"""Scrub (Observed) and calendar year from event names. 'Christmas Day (Observed) 2021' becomes 'Christmas Day'."""
if exp_name is None:
return None
regexp = ( # Captures (Observed), YYYY, and any whitespace before, after, and in... | 061b77ca413774275b28fc130f5a66d8e3813790 | 303,865 |
import torch
def _compl_mul_conjugate(a: torch.Tensor, b: torch.Tensor):
"""
Given a and b two tensors of dimension 4
with the last dimension being the real and imaginary part,
returns a multiplied by the conjugate of b, the multiplication
being with respect to the second dimension.
"""
#... | 3beda88d9c032fa7434bc363ecd3381effaca3ac | 584,483 |
from typing import Dict
from typing import Any
def suffix_dict_keys(in_dict: Dict[str, Any], suffix: str) -> Dict[str, Any]:
"""Adds the given suffix to all dictionary keys."""
return {key + suffix: value for key, value in in_dict.items()} | e16ebf829c4f5cf8421014f44a806421a04d5a86 | 58,205 |
def modify_intended_for (image_paths, contents, remove=False):
"""
Modify the given contents dictionary, storing the given image paths under the
IntendedFor key. If IntendedFor key already exists, its value is replaced by the
given image paths. If remove flag is True, then the value is replaced by an empty list... | 9f72695ea377989afb507f031f42ca11781c07b7 | 179,759 |
def tabindex(field, index):
"""Set the tab index on the filtered field."""
field.field.widget.attrs["tabindex"] = index
return field | c42b64b3f94a2a8a35b8b0fa3f14fe6d44b2f755 | 818 |
def get_block(file, S, E):
"""
Extract from `file` the next block starting with DOUBLE delimiters 'SS'
and ending with matching 'EE'.
Returns 3 values:
- the text found before the block start
- the block with its delimiters
- a boolean EOF indicator
"""
ch = file.read... | 5f1cb8d8b60c9d71f2929996a4a23cfffc55101e | 357,660 |
def check_final_winner(result):
"""
check_final_winner(result) --> string
result : ex) ['player', 'player']
반환값 : 만약 result 안에 'player' 가 두 개 이상이면 : 'player'
'computer' 가 두 개 이상이면 : 'computer'
otherwise : none
"""
print(f"player: {result.count('player')}승, computer: {resu... | 5be931344cf36e71783a9c881405b04e6b1cda5e | 93,922 |
def transition(color1, color2, position):
"""Generates a transitive color between first and second ones, based on the transition argument, where the value 0.0 is equivalent to the first color, and 1.0 is the second color."""
r1, g1, b1 = color1 >> 16, color1 >> 8 & 0xff, color1 & 0xff
r2, g2, b2 = color2 >>... | 86bab892fe39c640214fb172c15c2a87a0679c98 | 197,503 |
def get_substance(synset):
""" Look up and return the substance meronyms of a given synset. """
substance = synset.substance_meronyms()
substance = sorted(lemma.name() for synset in substance for lemma in synset.lemmas())
return substance | 59ec5ccc40ad8b33b5dd2f949740794f0d8d1e0e | 259,831 |
def partial_format(part):
""" This is just a convenience function so rather than putting
schema.thing.format(blah) everywhere, we just schema.thing(blah)
"""
def form(*args, **kwargs):
return part.format(*args, **kwargs)
return form | ee7c4b20b1a8e45ec50b89aeba7f2f06366f9dff | 256,193 |
def make_edge(nodes, distance):
"""
:param nodes: A tuple of address strings
:param distance: 'Distance' between edges
:return: A mapping object will be used in D3.js
"""
name = "{}_{}".format(*nodes)
return dict(type="edge", distance=distance, id=name,
source=nodes[0], tar... | e569cb3a3faafb1f234bc230c19aab5a94f9c4f4 | 540,389 |
def get_options_config_if_fewer_than_five_hundred(column_values):
"""
If there are fewer than 500 unique values for a column, return an Options configuration dictionary
:param column_values:
:return:
"""
unique_dict = {}
for value in column_values:
unique_dict[value] = True
uniqu... | 7aaae7d633d374a941593decc0cc6d5f1e8a7ecb | 111,181 |
def _make_closing(base, **attrs):
"""
Add support for `with Base(attrs) as fout:` to the base class if it's missing.
The base class' `close()` method will be called on context exit, to always close the file properly.
This is needed for gzip.GzipFile, bz2.BZ2File etc in older Pythons (<=2.6), which othe... | fed163bf5f0352b0eadc44db09dc88d5bea1616d | 305,649 |
import functools
import operator
def get_in(keys, coll, default=None):
""" Reaches into nested associative data structures. Returns the value for path ``keys``.
If the path doesn't exist returns ``default``.
>>> transaction = {'name': 'Alice',
... 'purchase': {'items': ['Apple', 'Oran... | 3d82585e1873930b12fa74fecb547e4b7e28ca9b | 114,412 |
def parse_node_coverage(line):
# S s34 CGTGACT LN:i:7 SN:Z:1 SO:i:122101 SR:i:0 dc:f:0
# "nodeid","nodelen","chromo","pos","rrank",assemb
"""
Parse the gaf alignment
Input: line from gaf alignment
Output: tuple of nodeid, nodelen, start_chromo, start_pos, coverage
"""
l... | b8d2c5eaad33fdee0e9f004982ec9a27f2a40726 | 685,700 |
def TransformCollection(r, undefined=''): # pylint: disable=unused-argument
"""Returns the current resource collection.
Args:
r: A JSON-serializable object.
undefined: This value is returned if r or the collection is empty.
Returns:
The current resource collection, undefined if unknown.
"""
# T... | b303164bf633530c8843d8ffb87f60085bc64401 | 486,581 |
def is_user(request):
"""Check if the incoming request is from the appropriate_user."""
return request.authenticated_userid == request.matchdict['username'] | 2ed218c70d712d6b03d470e7ebe228e872d20a0b | 612,195 |
def factorial(number, show=False):
"""
Calcula o fatorial de um núumero
:param number: o número a ser calculado o fatorial
:param show: mostrar o cálculo
:return: fatorial
"""
fact = 1
for count in range(number, 0, -1):
fact *= count
if show:
print(count, end=... | a55a17cb084e6055f630e5df5f876abc7b2adebf | 347,619 |
def ask_for_continuation(iteration: int) -> bool:
"""
Ask the user if we can proceed to execute the sandbox.
:param iteration: the iteration number.
:return: True if the user decided to continue the execution, False otherwise.
"""
try:
answer = input(
"Would you like to proc... | 93f007c7ac40bf618eee04dea01e25c2a85cc005 | 647,540 |
def custom_path_handler(instance, filename: str) -> str:
"""
Handle path and name to save file in storage
"""
dir_ = instance.hash[:2]
name = instance.hash
if '.' in filename:
file_extension = f'.{filename.split(".")[-1]}'
return f'{dir_}/{name}{file_extension}'
else:
... | 2aa6626f7fb439e516901fde4edff24328abd6d9 | 485,418 |
def _normalize_whitespace(s):
"""Replaces consecutive whitespace characters with a single space.
Args:
s: The string to normalize, or None to return an empty string.
Returns:
A normalized version of the given string.
"""
return ' '.join((s or '').split()) | cad713d5956b76c410bbfc538ffaeecbdd1f7f0f | 182,376 |
from typing import Optional
def is_world_language(lang_code: Optional[str] = None) -> bool:
"""
Determines if code is a world language code
"""
if lang_code in ("eng", "und", "zxx", None):
return False
else:
return True | 116314970d485d40bb30b94b2a98cc9b60262a91 | 412,112 |
def get_dict_path(base, path):
"""
Get the value at the dict path ``path`` on the dict ``base``.
A dict path is a way to represent an item deep inside a dict structure.
For example, the dict path ``["a", "b"]`` represents the number 42 in the
dict ``{"a": {"b": 42}}``
"""
path = list(path)
... | 2aa4930077258a6bac45717b2e2138ae8897a9a6 | 667,216 |
def pres_units(units):
"""
Return a standardized name (hPa or Pa) for the input pressure units.
"""
hpa = ['mb', 'millibar', 'millibars', 'hpa', 'hectopascal', 'hectopascals']
pa = ['pascal', 'pascals', 'pa']
if units.lower() in hpa:
return 'hPa'
elif units.lower() in pa:
re... | 4e0f8b14b6744adaadea8c294b437a4722476638 | 372,563 |
import math
import struct
def OSCString(next):
"""Convert a string into a zero-padded OSC String.
The length of the resulting string is always a multiple of 4 bytes.
The string ends with 1 to 4 zero-bytes ('\x00')
"""
OSCstringLength = math.ceil((len(next)+1) / 4.0) * 4
return struct.pack(">%ds" % (OSCstring... | 8b8dceffd11059bbe54b28701f82e07917939326 | 510,855 |
from typing import List
def split_string(x: str, n: int) -> List[str]:
"""
Split string into chunks of length n
"""
# https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa
return [x[i:i+n] for i in range(0, len(x), n)] | f0ad8cb6208616d274ee8749fb5b4a51391b0c8d | 648,504 |
def parse_header_entry(entry: str) -> dict:
"""Parses a header entry
Args:
entry (str): The header entry
Returns:
dict: The parsed entry (dict with keys: module, value, dimension, unit)
"""
assert isinstance(entry, str), "entry must be a string"
_categories = ["module", "value... | 8c675ba46c5863720e7f0083304925811611bc0b | 494,016 |
import time
def wait_for_all_nodes_state(batch_client, pool, node_state):
"""Waits for all nodes in pool to reach any specified state in set
:param batch_client: The batch client to use.
:type batch_client: `batchserviceclient.BatchServiceClient`
:param pool: The pool containing the node.
:type p... | caaf59d191179bea60d6a62b0f22f42b19683bc6 | 97,046 |
def decode_database_key(s):
"""Extract Guage_id, Reading_type, Datestr form provided keystring.
"""
lst = s.split("-")
gid = lst[0]
rdng = lst[1]
dstr = lst[2]
return (gid, rdng, dstr) | 365b829b86f31507314d6aa3eb1b72eee6ce3d75 | 524,016 |
import pathlib
def create_missing_dir(path):
"""Creates specified directory if one doesn't exist
:param path: Directory path
:type path: str
:return: Path to directory
:rtype: str
"""
path = pathlib.Path(path)
if not path.is_dir():
path.mkdir()
return path | ff4df4ca4e5ddc6d03e0d2007eb3a8404044f900 | 111,013 |
def _center_strip_right(text: str, width: int) -> str:
"""Returns a string with sufficient leading whitespace such that `text`
would be centered within the specified `width` plus a trailing newline."""
space = (width - len(text)) // 2
return space * " " + text + "\n" | ee858fc5fa1d9c37d263f6cc5ca6b5b2981164ea | 618,622 |
def get_repository_version(pear_output):
"""Take pear remote-info output and get the latest version"""
lines = pear_output.split('\n')
for line in lines:
if 'Latest ' in line:
return line.rsplit(None, 1)[-1].strip()
return None | d5351a604ec97d460b1938896e3243c102e1387b | 358,640 |
from math import sqrt
def heron(a, b, c):
"""Obliczanie pola powierzchni trojkata za pomoca wzoru
Herona. Dlugosci bokow trojkata wynosza a, b, c."""
if a + b > c and \
a + c > b and \
b + c > a and \
a > 0 and b > 0 and c > 0:
p = (a + b + c) / 2.0
area ... | e2004b72f1332cafae494f3d6ebec5da30e95c7f | 78,581 |
import random
def sample_filter(val, count=None):
"""Return a random sample from a list"""
if count is None:
# Return a single value
try:
return random.sample(list(val), 1)[0]
except ValueError:
return None
else:
# Return a list
try:
... | 985f82ab613f0d66601d380c42bf672f788b805c | 292,691 |
def slurp(filename):
"""
Given a `filename` string, slurp the whole file into a string
"""
with open(filename, "r") as source:
return source.read() | ebef1ed47975ac441dc42c570ca81e623e9ca9a3 | 371,378 |
from typing import Callable
import logging
def test_combination_wrapper(
test_combination: Callable[..., bool]) -> Callable[..., int]:
"""Wraps a test function with post processing functionality.
In particular, the wrapper invokes test_combination, logs the test and its
status, and returns a boolean to ind... | 831250a9dcfe6b43fd18ddace45450ddaafaae89 | 386,824 |
def section(name, underline_char='='):
""" Generate reST section directive with the given underline.
:Examples:
>>> section('My section')
'''
My section
==========
<BLANKLINE>
'''
>>> section('Subsection', '~')
'''
Subsection
~~~~~~~~~~
<BLANKLINE>
'''
"""... | 8bfa1a9e7fbe893d1808ed8dd0e70aa8cf412f1a | 560,076 |
from typing import List
import math
def rotate_point(x: float, y: float, cx: float, cy: float,
angle: float) -> List[float]:
"""
Rotate a point around a center.
:param x: x value of the point you want to rotate
:param y: y value of the point you want to rotate
:param cx: x value ... | 5996429c4cdfc56793c1726fcf1be8e19f3e09a8 | 422,173 |
def class_filter(dataset, classes, is_superclass=False, proportion=1.0):
"""
Handles filtering of (super)classes for use with tf.Dataset.
Arguments:
dataset: An instance of the Dataset class.
classes: A list of classes (or superclasses).
is_superclass: A flag indicate whether or not the "classes" par... | 6aee69302c6f53f574fece881e6e254bae77bcde | 81,455 |
def calc_duration_time(num_groups, num_integrations, num_reset_frames, frame_time, frames_per_group=1):
"""Calculates duration time (or exposure duration as told by APT)
Parameters
----------
num_groups : int
Groups per integration
num_integrations : int
Integrations per exposure
... | c5a1581fd815f95409810cfe051c255dfcb0933b | 553,420 |
def format_out(string_name, forecast_hour, value):
"""
formats polygon output
:param string_name: name of output field
:param forecast_hour: forecast hour of output
:param value: value of output
:returns: dict forecast hour, field name, and value
"""
return [{
'Forecast Hour': ... | 2a14c950c6290564491164385094c2aae8a418d7 | 391,706 |
def loadheader(filename):
"""
Load NAME file and parse header lines into dict.
filename -- input NAME file
"""
header = {}
with open(filename, 'r') as f:
for line in range(1, 19):
h = f.readline()
if ":" in h:
(key, val) ... | cc505761e9896bfb84692ca21311fb123c8f34e0 | 602,417 |
def calculate_stretch_factor(array_length_samples, overlap_ms, sr):
"""Determine stretch factor to add `overlap_ms` to length of signal."""
length_ms = array_length_samples / sr * 1000
return (length_ms + overlap_ms) / length_ms | 66c3b5fadf7998b6ecbd58761242ec4c253fd2f5 | 675,982 |
def state_reward(state, action):
"""State transitions on action
:param state: previous state
:type state: tuple
:param action: action
:type action: tuple
:return: new state and reward
:rtype: tuple
"""
x, y = state
dx, dy = action
# A -> A'
if (x, y) == (0, 1):
r... | 2bec9f0fcf0c40c435bc7585ac7de3d99243d878 | 216,895 |
def inherit_function_doc(parent):
"""Inherit a parent instance function's documentation.
Parameters
----------
parent : callable
The parent class from which to inherit the documentation. If the
parent class does not have the function name in its MRO, this will
fail.
Example... | 0d22610e66118363fdeda6139eab0a8065e6c354 | 21,481 |
def get_version_tuple(version):
"""
Return a tuple of version numbers (e.g. (1, 2, 3)) from the version
string (e.g. '1.2.3').
"""
if version[0] == "v":
version = version[1:]
parts = version.split(".")
return tuple(int(p) for p in parts) | f7357b367aef64655a47e0701400517effd6da33 | 459,375 |
import csv
def read_vote_data(filename):
"""
Reads a CSV file of data on the votes that were taken.
"""
f = open(filename, encoding='utf-8')
csv_reader = csv.reader(f)
votes = []
for row in csv_reader:
vote = {}
vote['date'] = row[0]
vote['number'] = row[3]
... | 28c4e3d771298c45b169a9436205da69d62cb827 | 126,515 |
def check_card_played_active(laid_card):
"""
Function used to check if card is a special kind of card with additional rules.
:param laid_card: tuple with last played card
:return: bool value, True if card is special, False otherwise
"""
if laid_card in [('hearts', 'K'), ('pikes', 'K')]:
... | ebdbb24aee1663711de5392c4759a3f7ffd9598e | 221,083 |
def _Spaced(lines):
"""Adds a line of space between the passed in lines."""
spaced_lines = []
for line in lines:
if spaced_lines:
spaced_lines.append(' ')
spaced_lines.append(line)
return spaced_lines | 750929d11f7c106075dbe93695c7beecb94b1ba7 | 426,367 |
import functools
from warnings import warn
def deprecated(version, replacement):
"""Decorator to deprecate functions and methods
Also handles docstring of the deprecated function.
Parameters
----------
version : str
Version in which the feature will be removed.
replacement : callable... | a8438989e906fe7ca3b3c0f6cf471c6e8bf79736 | 248,482 |
def getter_accessor(row, field):
"""Accessor for iterables whose items have implemented __getitem__,
like Pandas/Spark dataframes. Returns ``row[field]``."""
return row[field] | de84b52266c5dba8fcfe21165998d33ec542d413 | 240,756 |
def median(iterable, sort=True):
""" Returns the value that separates the lower half from the higher half of values in the list.
"""
s = sorted(iterable) if sort is True else list(iterable)
n = len(s)
if n == 0:
raise ValueError("median() arg is an empty sequence")
if n % 2 == 0:
... | cd69048720098864acf0d84e7cd1ac45023afaff | 619,462 |
def read_data(filename):
"""
Reads raw space image format data file into a string
"""
data = ''
f = open(filename, 'r')
for line in f:
data += line.strip('\n')
f.close()
return data | a705a62c3ef92ca1189e065018a2b6ee47a3fad6 | 680,681 |
def A_int(freqs, delt):
"""Calculates the Intermediate Amplitude
Parameters
----------
freqs: array
The frequencies in Natural units (``Mf``, G=c=1) of the waveform
delt: array
Coefficient solutions to match the inspiral to the merger-ringdown portion of the waveform
"""
re... | 7faf0fbfc67825dc43a9bd221dde397fc8e3f75f | 255,213 |
from typing import Callable
def _scroll_screen(direction: int) -> Callable:
"""
Scroll to the next/prev group of the subset allocated to a specific screen.
This will rotate between e.g. 1->2->3->1 when the first screen is focussed.
"""
def _inner(qtile):
if len(qtile.screens) == 1:
... | e778b6ef8a07fe8609a5f3332fa7c44d1b34c17a | 6,280 |
def submit_gcp_connector_sync_action(api, configuration, api_version, api_exception, gcp_connector_id):
""" Submits a synchronize action of a GCP connector.
:param api The Deep Security API exports.
:param configuration The configuration object to pass to the API client.
:param api_versi... | ac69abf5e01c889e1a8e233a5a3be396ce7c8776 | 101,468 |
from typing import OrderedDict
def get_star_ids_from_upload_file(fullpath):
""" Get and return all star ids from a given WebObs upload text file.
:param fullpath: upload text file name [string].
:return: list of all star IDs, no duplicates, preserving order found in file [list of strings].
"""
tr... | 82f172a1455e02b728d7337894805e68798abf04 | 52,334 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.