content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def exclude_ancestor_filediffs(to_filter, all_filediffs=None):
"""Exclude all ancestor FileDiffs from the given list and return the rest.
A :pyclass:`~reviewboard.diffviewer.models.filediff.FileDiff` is considered
an ancestor of another if it occurs in a previous commit and modifies the
same file.
... | 3fa5e39f136c4b29f1d6fe1eecbba2d7bf12f497 | 644,762 |
import random
def random_within_range(num_bytes, max_bytes=None):
"""Return a random int within range.
- If only ``num_bytes`` is set, return ``num_bytes``
- If both ``num_bytes`` and ``max_bytes`` are set, return random int within between
``num_bytes`` and ``max_bytes`` (including).
"""
r... | 4d87a735e7461464a24395a591ec37a86da4b3f1 | 644,763 |
def cleanup(run_dir):
"""
Cleans up the run directory.
"""
# Remove param_plots folder if empty
histo_dir = run_dir.joinpath('histogram_plots')
if histo_dir.is_dir() and not any(histo_dir.iterdir()):
histo_dir.rmdir()
# If run_dir is empty because there aren't enough good pixels, re... | 6c180dc2a3125e2a8c5074e0a5aee42c3473f36d | 644,766 |
import glob
import shutil
def copy_egg_info(dest_dir):
"""Copies the .egg-info directory to the specified location.
Args:
dest_dir: str. The destination directory.
Returns:
0 on success, 1 on failure.
"""
# Remove any trailing slash on the destination directory.
dest_dir = dest_dir.rstrip('/')
... | 39edab7773f9d02beac07f58e9eb5191f7f65321 | 644,769 |
from typing import Dict
def get_project_config_from_user() -> Dict:
"""
Ask the user for the information for the project config.
Returns: A dictionary with the config for the project, including local_dir, target, remote_dir, and port.
"""
local_dir = input('Path to code_sync on this local machin... | df30648f2ad1f07f4ac29694e3f74c5f56180a7b | 644,772 |
def get_wcs_ctype(wcs):
"""
Get celestial coordinate type of WCS instance.
Parameters
----------
wcs : `~astropy.wcs.WCS`
WCS transformation instance.
Returns
-------
ctype : {'galatic', 'icrs'}
String specifying the coordinate type, that can be used with
`~astr... | 612c5dd5659437a91f35ed984778b74dd4910ab4 | 644,779 |
def multiple(first,second):
"""Return multiplication of the 2 arguments.
Examples
--------
>>> multiple(4,5)
20
>>> multiple(2,1)
2
"""
return first * second | 6e0c997387ff839e7662d3b9e6974a4615e5d90d | 644,782 |
import operator
def _ext_proc_tpls_to_procs(xps):
"""List processors by each priority.
:param xps: A list of (file_extension, processor_cls)
:return: List of [processor_cls]
"""
return sorted((operator.itemgetter(1)(xp) for xp in xps),
key=operator.methodcaller("priority")) | ecc93f6bb6de68f72982329607e00f1f3f8a5274 | 644,783 |
import logging
def WriteToPoolCount(pool_d, rcbc_list,
counts, nSamples, out_prefix, indexes):
"""
Inputs:
pool_d (dict)
rcbarcode (s) => [barcode (str), scaffold (str), strand (str), pos (i)]
rcbc_list (list<str>): We get a list of all the rcbarcodes as they a... | 00e5448bbb773d8a8dc4e0541dc85ae3a1d66e73 | 644,784 |
def get_manual_finding_report_detail(manual_finding_reports):
"""
Iterate over manual finding report detail from response.
:param manual_finding_reports: manual finding report detail from the response
:return: List of manual finding report elements.
"""
return [{
'ID': manual_finding_re... | 91623bf01f23df31256631b8a7d905afcffb1a4c | 644,788 |
def reverse_str(numeral_str):
"""Reverses the order of a string."""
return numeral_str[::-1] | 0336a1ab5b5252e5f54062bb263d2c7e9682f0a7 | 644,789 |
def read_cols_query(col_names, table_name, schema_name):
"""
Obtain the query to read the columns from a table
:param col_names: (list of strs) list of cols names to read
:param table_name: (str) table name to read from
:param schema_name: (str) schema name of the table
:return:
A stri... | 542bb33dbfc2c7a570fb4bdf652d89ab87c7e20f | 644,791 |
from bs4 import BeautifulSoup
def lyrics_from_letrasmus(html):
"""Extracts lyrics from the html of a webpage of 'letras.mus.br'."""
lyrics = ''
soup = BeautifulSoup(html, 'html.parser')
verses = soup.select('.cnt-letra article p')
for para in verses:
lyrics += para.get_text('\n') + '\n\n... | 24c074bb0e66e6e20c6177c70a037e67a0088736 | 644,795 |
def normalize_key(key: str):
""" Normalize CSV header values """
key = key.lower().replace('_', '').replace('-', '').replace(' ', '')
return {
'startdatetime': 'start_date_time',
'enddatetime': 'end_date_time',
'resultslocation': 'results_location'
}.get(key, key) | 8e28a82af6d0efee81174d1e2e344b885b156140 | 644,799 |
def reflect(cp, anchor):
"""
Reflect the point `cp` through the anchor.
"""
vec = (cp[0] - anchor[0], cp[1] - anchor[1])
neg = (-vec[0], -vec[1])
return (anchor[0] + neg[0], anchor[1] + neg[1]) | 86ea4cdbd4f23c1d9bdddd54892d11d708749d4b | 644,803 |
import zlib
def zlib_encode(input,errors='strict'):
""" Encodes the object input and returns a tuple (output
object, length consumed).
errors defines the error handling to apply. It defaults to
'strict' handling which is the only currently supported
error handling for this codec.... | c7ae64666b763e935cc515c44ed1550410846c30 | 644,805 |
def getitem(obj, item):
"""Grab the item from the object.
Example usage:
someObj|getitem:key
"""
return obj[item] | 7bac8e8bace8ea1ad79073da9907ac57ed0af039 | 644,807 |
def _get_list_traj(trajectory):
"""Return a list of (proxy) snapshots from either a list or Trajectory
Parameters
----------
trajectory : :class:`.Trajectory` or :class:`.list`
trajectory or list to convert into a list of snapshots
Returns
-------
:class:`.list`
list of (prox... | 751fb4a579b0bb54870286e9229703abfb0936de | 644,810 |
import re
def is_empty_line(line: str):
"""Check if line is empty. Returns True if line contains only whitespaces"""
return bool(re.match(r"\s*\n", line)) | 7c84e416ac29d42de5224004d8ab4c6f3f5c215a | 644,815 |
def is_json_string(text: str) -> bool:
"""
Given an input text, is_json_string returns `True` if it is a valid JSON string, or False otherwise.
The definition of a valid JSON string is set out in the JSON specification available at https://json.org/.
Specifically, the section on strings defines them as: "A string ... | a57408c05e8672f370ede3e7f85cab595e70f082 | 644,816 |
def matches(value, attr_list):
"""Return whether value matches the attribute described by attr_list
Attributes come from mutagen as lists of strings (except for the "path"
attribute). If the value is surrounded by double quotes, we look for exact
matches; otherwise, we join together the attribute list ... | 57f29ee419214c254ca17a769ac3364cd1c00fab | 644,818 |
import struct
def retrieve_message(conn, out_format):
"""Retrieve a message from the client.
Parameters
----------
conn : socket.socket
socket for server connection
out_format : str or None
format of the output structure
Returns
-------
Any
received message
... | 5fcb0c9e3051d680a531e9a43414a474e4c69c54 | 644,820 |
def bits_to_target(bits):
""" Decodes the full target from a compact representation.
See: https://bitcoin.org/en/developer-reference#target-nbits
Args:
bits (int): Compact target (32 bits)
Returns:
target (Bignum): Full 256-bit target
"""
shift = bits >> 24
target = (bits &... | 58e140be51908ae0cde003e1ca938ea9e75d1724 | 644,822 |
def XOR(a, b):
""" Returns a XOR b (the 'Exclusive or' gate)
Args:
a (bool): First input
b (bool): Second input
Returns:
bool: The output of the XOR gate
"""
return ( a - b ).abs() | 6f98c5ab8ff5709e3f923163c6bad3e4e96cebdf | 644,823 |
def filter_out_none(dictionary, keys=None):
""" Filter out items whose value is None.
If `keys` specified, only return non-None items with matched key.
"""
ret = {}
if keys is None:
keys = []
for key, value in dictionary.items():
if value is None or key not in keys:
... | c7c1e3894beb55c7e978dd6822e091924dd58a5c | 644,829 |
def read(filename, binary=True):
"""
Open and read a file
:param filename: filename to open and read
:param binary: True if the file should be read as binary
:return: bytes if binary is True, str otherwise
"""
with open(filename, 'rb' if binary else 'r') as f:
return f.read() | 8faf5df9bfa326945dce4eec25efb32a12b2cd18 | 644,830 |
from typing import List
def prime_factors(n: int) -> List[int]:
"""
Returns prime factors of n as a list.
>>> prime_factors(0)
[]
>>> prime_factors(100)
[2, 2, 5, 5]
>>> prime_factors(2560)
[2, 2, 2, 2, 2, 2, 2, 2, 2, 5]
>>> prime_factors(10**-2)
[]
>>> prime_factors(0.02)... | 81ff86ca963f090cbc3d7e470191dca918dc92f7 | 644,831 |
def color_float_to_hex(r, g, b):
"""Convert RGB to hex."""
def clamp(x):
x = round(x*255)
return max(0, min(x, 255))
return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b)) | e8e82ecd5f6f418cdc0cd72f0b799d1dd0ad6b1d | 644,834 |
def propeller_navbar(navbar):
"""
Render a navbar.
**Tag name**::
propeller_navbar
**Parameters**:
navbar
The previously defined navbar instance
**Usage**::
{% propeller_navbar navbar_instance %}
"""
return navbar.as_html() | 24a318e7b3803a64f1dab695fcc0346c03e694bb | 644,835 |
def is_placement_possible(y, x, n, board):
"""
Returns whether or not a number can be placed at a provided coordinate
This function uses the following format: board[y][x] == is_placement_possible(n)?
:param x: the provided x coordinate (the column number from left)
:param y: the provided y coordinate (the row num... | ae212ac9aae142a385035bfbc9cd49a9aacb2322 | 644,840 |
def moeda(preco=0, valor='R$'):
"""
-> Faz a conversão do número real para moeda R$.
:param preco: preço a ser convertido.
:param valor: definida como padrão para o Real Brasileiro.
:return: retorna o preço formatado no Real Brasileiro.
"""
return f'{valor}{preco:.2f}'.replace('.', ',') | fb1267fd834ac4626fe49ce0aefd36a6dce1f8c2 | 644,842 |
def totalCredits (theDictionary):
"""Calculates the total credits student is taking this semester.
:param dict[str, int] theDictionary: The student's class information
with the class as the key and the number or credits as the value
:return: The total credits
:rtype: int
"""
total = 0 ... | 996175a794947d21424d006e95378c537ee37abf | 644,844 |
def _cap_first(s: str) -> str:
"""Returns string with first character capitalized. Why this isn't in
the Python stdlib is beyond me. The capitalize() function annoyingly
lowercases the rest of the string."""
return s[:1].upper() + s[1:] if s else s | b9f45070cfc0822c6bd498e9a116161095fe66f5 | 644,846 |
def calc_radiated_power_nadir(radiance_integrated,
pixel_resolution_along,
pixel_resolution_cross):
"""
Calculate the power radiated from a ground pixel at Nadir.
Returns
-------
double : Watts per Sterradian.
"""
return radiance_... | af81e9eaef7091d3794870fd6bfb89a977f47b1e | 644,854 |
def init_Npad(ROI, compression = 8):
"""Calculate the Npad for padding
can be adjusted with compression parameter
By default, 8 times smaller than ROI
"""
if (ROI[2]-ROI[0])>(ROI[3]-ROI[1]):
Npad = (ROI[2]-ROI[0])//compression
else:
Npad = (ROI[3]-ROI[... | 43044e85ae47202dfeaec09aca750596a5785ab8 | 644,857 |
def auto_capitalize(text, state = None):
"""
Auto-capitalizes text. `state` argument means:
- None: Don't capitalize initial word.
- "sentence start": Capitalize initial word.
- "after newline": Don't capitalize initial word, but we're after a newline.
Used for double-newline detection.
... | 01c0edeea8da059876a4d05cd8b51432cb9c842b | 644,858 |
def get_bearer_token(request):
"""Extracts a Bearer authentication token from the request and returns it if present, None
otherwise."""
auth = request.headers.get("Authorization")
if auth is not None:
try:
method, content = auth.split(" ")
if method == "Bearer":
... | 9e0c1ec830e00b18eae13aea22aab6fe67f469b6 | 644,860 |
import csv
def specification_file_read(spec_file_name):
"""
Returns the input from a CSV file as a dictionary.
Args:
- spec_file_name (String): Path to the CSV file.
Returns:
- (Dictionary(String:String)): Returns a list of Dictionaries mapping
the tables row entrys to the co... | 16d739d2fe1316ebf7d3ad070be7cee8bf05df20 | 644,861 |
import base64
def BinaryEncode(value):
"""If None, returns empty string. Otherwise, encode to a string."""
if value is None:
return ""
return base64.b64encode(value) | 5fdd18e1657f5d3f4ff1673f69f7f830e52c9850 | 644,862 |
import functools
def mobile_template(template):
"""
Mark a function as mobile-ready and pass a mobile template if MOBILE.
@mobile_template('a/{mobile/}/b.html')
def view(request, template=None):
...
if request.MOBILE=True the template will be 'a/mobile/b.html'.
if request.MOBILE=Fals... | 910c09fd3f55d7969f44de97239133c54bd62849 | 644,866 |
def build_indices(stream):
""" Parses the stream of logs and indexes it.
Args:
stream, list of string, format <metric_name>|<value>|<coma_separated_tags>
Returns:
pair of hashes,
first hash has the format {tag -> set([line_indices])}
second hash has the format {line_i... | fa3ae6ee9de69bb02f16c4a3272822c781973a8d | 644,872 |
def get_crowd_selection(selection_count, selection_map):
"""
Figure out what the crowd actually selected
:param selection_count: number of responses per selection
:type selection_count: dict
:param selection_map: maps selections to output fields
:type selection_map: dict
:return: the respo... | dc21a6c991073485f8fba16c9f0fdf9bd634ae08 | 644,873 |
from typing import Iterable
def has_intersection(left: Iterable[str], right: Iterable[str]) -> float:
"""Returns 1.0 if there is any overlap between the iterables, else 0.0."""
if len(set(left).intersection(right)) > 0:
return 1.0
return 0.0 | c8f7fb4952490b1ac8ae5214f013effc58b1c29a | 644,876 |
def extract_HBS_learning_curves(runs):
"""
function to get the hyperband learning curves
This is an example function showing the interface to use the
HB_result.get_learning_curves method.
Parameters
----------
runs: list of HB_result.run objects
the performed runs for an unspecifi... | f3f595f6969efdc4773dd680ccadaf8f79f1b54c | 644,878 |
def pick_and_pop(keys, d: dict) -> dict:
"""
pick all (key, val) pair from dictionary 'd' for all keys in 'keys'
Then, return a new dict with those picked (key, val) pair
"""
values = list(map(lambda key: d.pop(key), keys))
return dict(zip(keys, values)) | 327f89f91f5a37fa0bdcede4cee15c0800db4e2d | 644,882 |
def find_double_day(older_birthday, younger_birthday):
"""Takes 2 datetime.date objects representing different days, returns the date when one is
twice as old as the other
Precondition: older_birthday < younger_birthday"""
assert older_birthday < younger_birthday
difference = younger_birthday - olde... | a0becdd53b4d63b1a57a79c88bc3e86332a73812 | 644,885 |
def fit_to_block_size(sequence, block_size, pad_token_id):
""" Adapt the source and target sequences' lengths to the block size.
If the sequence is shorter we append padding token to the right of the sequence.
Args:
sequence (list): sequence to be truncated to padded
block_size (int): lengt... | 6f684e118b7dc2668df347d6c4f88829e00c6700 | 644,893 |
import re
def get_integer(number: str) -> int:
"""
Fetches all numbers and returns an integer
Args:
number: A string of the identified number
Returns:
An integer value of number
"""
return int("".join(re.findall(r"\d+", number))) | 8ae62fe2edf0aaa5972c2a2c90a5747a8f255b21 | 644,896 |
def proposed_cut_off_value(cut_off_value, length):
"""Proposes a cutoff-value if cut_off_value < 0 (=default)
Reynolds and Gutman (1988) recommend using a cut-off level of 3-5 for 50-60 paricipants
--> 4/55: relation cut-off/ladders
Args:
cut_off_value ([int]): [cutoff-value ]
length (... | b8e9ca4e53405ef61eabed44e214b541d5bded65 | 644,897 |
def get_query_statistics(tweets, sentiment_aggregate_list):
"""
Generates basic statistics for a given query set of Tweets.
:param tweets: A query set of Tweets
:param sentiment_aggregate_list: A list with number of positive, negative and neutral Tweets in the query set
:return: Dictionary with tot... | 855c3cda23a0cd47e26f16586c377000dad86586 | 644,898 |
def lines_that_start_with(string, fp):
"""Helper function to lines in a FORC data file that start with a given string
Inputs:
string: string to compare lines to
fp: file identifier
Outputs:
line: string corresponding to data line that meets the above conditions
"""
return [line fo... | a061184aa67138582fabb809b71b561e688b6cf8 | 644,901 |
def ignore_ctrlc(method):
"""Decorator to make a ProjectKey command ignore Ctrl-C.
- For a commands that runs programs that want to handle
Ctrl-C themselves - ipython for instance."""
method.ignore_ctrlc = True
return method | 9b873ad5818cbc9054d4983ab1671bf7064745bb | 644,903 |
def naive_matrix_multiplication_lists(a, b):
"""
Uses nested loops to calculate AB
:param a: An MxN matrix of numbers.
:param b: An NxP matrix of numbers.
:return: An MxP matrix of numbers which is the product: AB.
"""
M = len(a)
N = len(a[0])
if len(b) != N:
raise ValueError... | 88c980f0ae1361d7f1c33cdb640a640cd79cef08 | 644,904 |
def overrides_method(method_name, obj, base):
"""
Return True if the named base class method is overridden by obj.
Parameters
----------
method_name : str
Name of the method to search for.
obj : object
An object that is assumed to inherit from base.
base : class
The ... | 4631de0cb262737b56b561a954bd31ad0870bd82 | 644,905 |
import requests
def create_account(base_url: str, email: str, password: str, username: str,
firstname: str, lastname: str, secure: bool):
"""
Create an account with the server
:param base_url: base URL of server
:param email: email
:param password: password
:param username: ... | d84876449842b1a3b7cb28bedeb723ae61cc1e00 | 644,907 |
def split(path: str):
"""Split path into (head, tail) tuple. Tail is the last path component. Head is all the rest."""
if path == "":
return "", ""
r = path.rsplit("/", 1)
if len(r) == 1:
return "", path
head = "/" if not r[0] else r[0]
return head, r[1] | 4dac0895c42a1b56930e798af717e3ccae03b316 | 644,914 |
import io
import hashlib
def get_file_hash(filepath, algorithm):
"""
Get hash of a file.
:param filepath: the path to the file
:type filepath: str
:param algorithm: the desired hashing algorithm
:type algorithm: str
:return: Hash of the file in hex form.
:rtype: str
"""
file =... | 74085bfef322542547692aa4cc069e45fab40f21 | 644,923 |
def GetAlleleString(allele):
"""Get string representation of allele
If it is a sequence, return upper case sequence
If _SV type, return string representation
Parameters
----------
allele : ALT allele from vcf.Record
Returns
-------
str_allele : str
String representa... | 53fb7b3e41c41f125fdcdaea216e49b37f005bf8 | 644,930 |
def enum_metaclass(enum_param, return_name=False, start=0):
"""
Returns a ``type`` subclass that may be used as a metaclass for
an enum.
Paremeters:
:enum_param: the name of class attribute that defines enum values.
The metaclass will add a class attribute for each value i... | 315713063e4e0df321999c4296775a4a92d63698 | 644,935 |
def readfile(file_dir):
""" readfile(file_dir:str)
Returns the content of a file in an array.
"""
f = open(file_dir)
content = [line.rstrip('\n') for line in f]
return content | 2b05d1edb4e3d6dc31f8a18c29f42c2f3a68dd37 | 644,937 |
def isAbundant(x):
"""Returns whether or not the given number x is abundant.
A number is considered to be abundant if the sum of its factors
(aside from the number) is greater than the number itself.
Example: 12 is abundant since 1+2+3+4+6 = 16 > 12.
However, a number like 15, where the sum of the... | 45a42385c80aee3be5c06156347e69ea2b43461e | 644,943 |
def strip_and_get(val, fallback=""):
"""
Return the enclosing text or provided fallback value
:param val: item to get text and strip whitespace
:param fallback: fallback when val is None
:return: stripped text value
"""
if val:
return val.text.strip(' \t\n\r')
else:
retur... | 2290859e342d1fd7ca0e897f1b92c35252028caf | 644,948 |
import binascii
def hexlify(x):
"""Return the hexadecimal representation of the binary data. Decode from ASCII to UTF-8."""
return binascii.hexlify(x).decode('ascii') | 096b177ba0dde2fe7d1b2e087648500e80a4c501 | 644,954 |
def solve_for_scale(a_scale, a_n_bits, b_scale, b_n_bits, y_n_bits):
""" Finds the scale factor for the following case:
y = a * b
We know the scale factor and the number of bits of a, as well as b. We also know the number of
bits for y. This function computes the resulting scale factor for y
... | f1f516b6b3be6edc5af4cede96d290636bee0fe6 | 644,959 |
def isbit(integer, nth_bit):
"""Tests if nth bit (0,1,2..) is on for the input number.
Args:
integer (int): A number.
nth_bit (int): Investigated bit.
Returns:
bool: True if set, otherwise False.
Raises:
ValueError: negative bit as input.
Examples:
>>> isb... | a94f6b81284ac484a8441f96ac8b374c2cb9b6ae | 644,964 |
import string
import re
def remove_punctuation(text):
"""
Remove punctiation from piece of text
"""
text = [t for t in text if t not in string.punctuation]
text = [t for t in text if t not in ['...']]
text = [re.sub(r'(?:\@|https?\://)\S+', '', (t)) for t in text]
# text = [re.sub(r'[^\w\s... | e9b36daa286273145d04d942ba940472efafb33f | 644,967 |
def clusters_from_blast_uc_file(uc_lines, otu_id_field=1):
""" Parses out hit/miss sequences from usearch blast uc file
All lines should be 'H'it or 'N'o hit. Returns a dict of OTU ids: sequence
labels of the hits, and a list of all sequence labels that miss.
uc_lines = open file object of uc file
... | a6bf15f496a84421dc51ee4a56efbcbaa3580f39 | 644,969 |
def get_tablename(model):
"""return the model's table name"""
return model._m.table_name | 3a04f6d03f4c43aa094ebbcd35bf2d6e430bf312 | 644,970 |
def print_attrs(attr, celebA_dataset):
"""
human-readable format for CelebA attributes vector
"""
legible = ''
for i, a in enumerate(list(attr)):
if a == 1:
legible += celebA_dataset.attr_names[i] + ", "
return legible | b973d4899d3a1361b63bc38a79b5ed3f12ef9741 | 644,974 |
def calc_t_int(n_group, t_frame, n_frame, n_skip):
"""Calculates the integration time.
Parameters
----------
n_group : int
Groups per integration.
t_frame : float
Frame time (in seconds).
n_frame : int
Frames per group -- always 1 except maybe brown dwarves.
n_sk... | 0d8a302e9c0caa54fd187f12de905efa8f63b221 | 644,975 |
def filter_blast_result(alignment, record):
"""
The binding pocket of the target structure should be covered by identical residues in the test sequence. We
don't know where the target-sequence binding pocket is located. To increase the chances that the test sequence
and target sequence have identical bi... | ae1c3280a832acc6ec2d77e9043bc3626e57d578 | 644,976 |
def calculate_integration_error(
max_forth_derivative: float, low: float, high: float, length: int) -> float:
"""Find integration error if Simpson method is used.
Args:
max_forth_derivative: precalculated value.
low: left range boundary.
high: right range boundary.
lengt... | 4f4103f136bda7c1b3ba6017dcc0023255fea440 | 644,980 |
def defined_submodule(arr):
"""
Check if model uses submodules
"""
return any([el.endswith('_module]') for el in arr]) | d195d98bffb7418fbb0e7a55525e3b6c4d488439 | 644,981 |
import math
def calc_triangle_area(a,b,c):
"""
使用海伦公式计算三角形面积
a、b、c为三角形边长
:return: 三角形面积
"""
p=(a+b+c)/2
return math.sqrt(p*(p-a)*(p-b)*(p-c)) | bc7499009f93125d58cda13a76f9b15b4a7f98e5 | 644,983 |
def im2mat(img):
"""Converts and image to matrix (one pixel per line)"""
return img.reshape((img.shape[0] * img.shape[1], img.shape[2])) | 9d4727d3284645707c3f2632c46fb24096b2cf17 | 644,986 |
import functools
import time
def simple_timer(func):
"""Simple decorator to give a rough estimate of calculation time. Thank you to RealPython for
the help -- https://realpython.com/primer-on-python-decorators/"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()... | 2fe48aa691d2e4cf8528c951fa6c74eda6d390ee | 644,987 |
import sqlite3
def build_type_dict_from_row(row: sqlite3.Row):
"""This function takes a row from a sqlite3 query, and returns a dict of damage modifers by type."""
type_dict = {'type': row[0], "effectiveness": {}}
for i in range(len(row.keys())):
if i == 0:
continue
else:
... | c664dc0a40a58c8777a98f0ff5d7ab2f14f99199 | 644,988 |
def _iso_datetime(value):
"""
If value appears to be something datetime-like, return it in ISO format.
Otherwise, return None.
"""
if hasattr(value, 'strftime'):
if hasattr(value, 'hour'):
return value.isoformat()
else:
return '%sT00:00:00' % value.isoformat(... | f30581205661d514e7c62a9e4f880531863ac01f | 644,991 |
import click
def prompt_password(ctx, param, use_password): # pylint: disable=W0613
"""Prompt for password."""
if use_password:
mysql_password = ctx.params.get("mysql_password")
if not mysql_password:
mysql_password = click.prompt("MySQL password", hide_input=True)
return... | afe4e2876e35cb36fdbff2538f9f409b282db662 | 644,995 |
def parse_and_validate_longitude(request):
"""Extract and Check the validity of longitude.
Args:
request: HTTP request.
Returns:
longitude(float) if valid.
Raises:
ValueError: if longitude is not float, or outside range [-180, 180].
"""
lon = float(request.rel_url.quer... | 3a9d191be67e3b091ddcb7354bb8fc0ff2985b43 | 644,998 |
def calculate_outlier_bounds(df, column_name):
"""
Calculates outlier bounds based on interquartile range of distribution of values in column 'column_name'
from data set in data frame 'df'.
:param df: data frame containing data to be analyzed
:param column_name: column name to analyze
:return: d... | c9fab21820569fa1759f0a12706448ad7711fd2b | 644,999 |
import types
def get_function(callable_):
"""If given a method, returns its function object; otherwise a no-op."""
if isinstance(callable_, types.MethodType):
return callable_.__func__
return callable_ | e662cdde35cf40f330f2e846255ba9c206ed0e38 | 645,002 |
import re
def normalize_underscore_case(name):
"""Normalize an underscore-separated descriptor to something more readable.
i.e. 'NAGIOS_SERVER' becomes 'Nagios Server', and 'host_components' becomes
'Host Components'
"""
normalized = name.lower()
normalized = re.sub(r'_(\w)',
... | b3aa00e94f1429b994f20f98f42419dfb62d313d | 645,003 |
import math
def int_log(x: float, base: float = math.e) -> int:
"""Finds the nearest integer to ``log(x, base)``.
Args:
x: The number whose logarithm will be found.
base: The numeric base of the logarithm.
Returns:
The result of rounding ``log(x, base)`` to the nearest integer.
... | f8095584333ea6bae78111570014d8a63a732fc6 | 645,007 |
from typing import Dict
from typing import Optional
def get_new_name(attrs: Dict[str, str],
mark_name: str = '',
name_map: Optional[Dict[str, str]] = None) -> str:
"""Get new name for a node.
Args:
attrs (Dict[str, str]): A dict contains attributes of an ONNX node.
... | a541b05a4cd0021815062698d48a2fb155d60f01 | 645,008 |
import getpass
def get_password(args):
"""Set the password or getpass it in a secure way"""
if not args.password:
password = getpass.getpass(prompt="Password for {} @ {}: ".format(args.username, args.server))
else:
password = args.password
return args, password | ef1c5a91fd273eb88633f64134664cdfd96262fa | 645,009 |
def join(*args):
"""Forms join instruction."""
inputs = [arg[0] for arg in args]
return {
'cmd': 'join',
'inputs': inputs,
'args': args,
} | cb20ae8629ef6d36678bc3b16849302456570a4d | 645,012 |
def in_right_closed_range(s, min_val, max_val):
"""
Check if a value lies in the right-closed interval (min_val, max_val].
:param s: Value to check.
:param min_val: Lower boundary of the interval.
:param max_val: Upper boundary of the interval.
:return: True/False whether or not the value lies ... | 45609cb244c1b73daa1a0da1102478ba948dbfd4 | 645,013 |
def find_cheapest_fuel_use(positions: list[int]) -> int:
"""
Returns the amount of fuel used for the cheapest
alignment position.
Args:
positions (list[int]): The list of starting positions.
Returns:
int: Fuel usage.
"""
positions = sorted(positions)
median = positions[... | f3a00e96ad4fc81a5527786fe6cc0afbb2474253 | 645,019 |
def display_body_parts(image, image_draw, coordinates, image_height=1024, image_width=1024, marker_radius=5):
"""
Draw markers on predicted body part locations.
Args:
image: PIL Image
The loaded image the coordinate predictions are inferred for
image_draw: PIL ImageDraw m... | b7da1c98a11bde3876749979f483bd09ee5d327b | 645,020 |
def end_text_with_single_terminating_newline_character(text: str) -> str:
"""Ensure the text ends with a single terminating newline character."""
return text.rstrip() + '\n' | f8e8e6b4dd3d985c913b43a54a4c69cd5065995b | 645,025 |
import math
def truncate(number, digits) -> float:
""" Truncates number to a specified number of digits
Args:
number (float): Number to truncate
digits (int): No. of digits to truncate to
Returns:
Truncated number (float)
"""
stepper = 10.0 ** digits
return math.trunc... | 8b19614173fccb2615a96d2f8951e0e9858c6921 | 645,030 |
def _asciizToStr(s):
"""Transform a null-terminated string of any length into a Python str.
Returns a normal Python str that has been terminated.
"""
i = s.find('\0')
if i > -1:
s = s[0:i]
return s | 5670ef331888be44af59745a96496c7a045f6e4f | 645,035 |
from typing import Any
import pickle
def load_file_from_disk(loc_folder: str, filename: str) -> Any:
"""Loads a file that was previously saved to the disk.
:param loc_folder: The location of the containing folder.
:param filename: The name of the file to be loaded.
:return: The contents of the loaded... | 8be6ab9cb9e24bc8ecc363750a04ef2f1fcb19c0 | 645,038 |
def scientific_notation(value: float | str, precision: int = 2) -> str:
"""Return number in string scientific notation z.wq x 10ⁿ.
Examples:
>>> scientific_notation(float(0.3))
'3.00 x 10⁻¹'
>>> scientific_notation(int(500))
'5.00 x 10²'
>>> scientific_notation(-1000)
... | 1120c1ff58a3018a2ae6addc5a3b83d24316511c | 645,041 |
def fpr(fp: int, tn: int) -> float:
"""False Positive Rate computed from false positives and true negatives."""
return fp / (fp + tn) if fp + tn else 0.0 | 455610e45cad46e56dae87a71f0ec842763cbc05 | 645,046 |
def make_row(table, row, model_name):
"""
Parameters:
-----------
table : `collections.defaultdict`
The dictionary to fill.
row : `pandas.DataFrame`
The dataframe to get the data from.
model_name : `str`
The model name.
Returns:
--------
table : `collecti... | e0537ee89dfc8162c6576a9236b5c31e2030a3a7 | 645,051 |
def ascii64_paths(tnum):
"""
Return components of the path to the data for trigger `tnum`, both at
the COSSC FTP site and locally: (group, fname, remote).
group name of the group directory containing the trigger directory
rfname name of the remote ASCII data file, "cat64ms.<tnum>"
r... | 133cd0e400c1cc215cb2c2f203cd4dc94f00018d | 645,052 |
from typing import List
import itertools
def generate_partitions(num_elements: int, num_parts: int) -> List[List[int]]:
"""Generates partitions of num_elements into num_parts nonnegative parts.
Args:
num_elements: The number of things to permute (a nonnegative integer).
num_parts: The number of groups to... | 98fe5f3ed600d3b6a44174808f384896086fadc1 | 645,053 |
def is_state_error(state_meta):
"""
Determines if the state resulted in an error.
"""
return not state_meta['result'] | e8054b69257f15064fcd392ba33ad0f0c76fed37 | 645,056 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.