content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def raise_to_power(a: int, b: int):
"""
Raise a to the power of b.
"""
if b == 0:
return 1
b -= 1
return a*raise_to_power(a, b) | ff817002655ed70c260c4f340b8623fc9e9d83fe | 571,038 |
def readcsv(infile, separator=',', ignoreheader=False):
"""Read a csv file into a list of lists"""
with open(infile, 'r') as f:
list_of_rows = [[x.strip() for x in r.split(separator)]
for r in f.readlines()]
return list_of_rows if not ignoreheader else list_of_rows[1:] | 4d590e9f5881db0d2278336bbb95dfd106416690 | 571,039 |
import math
def pad_message(message, blocklength):
"""Pad a message so its length is a multiple of blocklength."""
message_padded_length = (
int(math.ceil(len(message) / blocklength)) * blocklength)
padded_message = message.ljust(message_padded_length)
return padded_message | c6338fe19da31e08873f952a811b23897aebf9a9 | 571,040 |
import torch
def create_eye_batch(batch_size, eye_size):
"""Creates a batch of identity matrices of shape Bx3x3
"""
return torch.eye(eye_size).view(
1, eye_size, eye_size).expand(batch_size, -1, -1) | ae1171af3f13e4be03ddada62481f0dcd9c6b202 | 571,041 |
def split_string(mystring, sep, keep_sep=True):
"""Splits a string, with an option for keeping the separator in
>>> split_string('this-is-a-test', '-')
['this-', 'is-', 'a-', 'test']
>>> split_string('this-is-a-test', '-', keep_sep=False)
['this', 'is', 'a', 'test']
Parameters
----------
... | c798c5819700981b53733892c6100415dde54b7a | 571,045 |
def get_lan_cursor_parameters(noc_name):
"""Returns list with position 0 as a SQL query to find all athletes from a specified NOC and position 1 as the search string description of the specified NOC's abbreviation."""
search_string = noc_name
query = '''SELECT DISTINCT
athletes.full_name
FROM
... | d00075dff1ab285a480f7967d42c2359f0b24ef8 | 571,052 |
def _convert_data_string_to_int(s : str):
"""
Transform the data string extracted from the webpage and return the corresponding int
Parameters:
s(str) : String of the data extracted from the webpage
Return :
n(int) : Reformatted integer value extracted from the string s
"""
... | d298cd103fc0dd4ee90b612383606104af3c08b8 | 571,055 |
def convert_timedelta(duration):
"""
Summary:
Convert duration into component time units
Args:
:duration (datetime.timedelta): time duration to convert
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers)
"""
days, seconds = duration.days, duration.seconds
... | 4a0a0b89608e895963df2ec5e890db7a1ae313c9 | 571,056 |
def get_transmitted_communication(myt):
"""
Return the values transmitted during the communication.
:param myt: agent
:return communication: the communication to be transmitted
"""
communication = myt.prox_comm_tx
return communication | eb63a2a25ab8bfaf41c2e97c57ca5f778d2bd3e5 | 571,058 |
def stellar_logzsol(logzsol=0.0, **extras):
"""Simple function that takes an argument list and returns the value of the
`logzsol` argument (i.e. the stellar metallicity)
Parameters
----------
logzsol : float
FSPS stellar metaliicity parameter.
Returns
-------
logzsol: float
... | dbb780a3039f2cfcd395ef9556e06936fe211ecb | 571,068 |
def freq_by_location(d):
"""
Takes in a dictionary of novel objects mapped to relative frequencies.
Returns a dictionary with frequencies binned by publication location into lists
list names key:
- *location_UK* - published in the United Kingdom
- *location_US* - published in the US
- *loc... | e29cae94c39985e31bdd3b87863254a6d4fbbe60 | 571,069 |
def a_single_column_apply_fn(batch, columns):
"""Simple function that applies to a single column."""
assert len(columns) == 1 and type(batch[columns[0]][0]) == int
return [e * 7 + 3.14 for e in batch[columns[0]]] | 6e2bda7f53d3a8a57e89b701f2dda52ff553cf1e | 571,071 |
def get_simple_rl_task_names(task_names: list) -> list:
"""Simplifies the task name.
For each task name in the provided list, this function splits the names using an underscore as
delimiter, then returns the last element in the split list as the simplified name.
Args:
task_names (list): The li... | 83c6b658d8ff5e19c330910c1184befcd1b57ff1 | 571,075 |
def is_exe(filename):
""" Check that a file is a Windows executable """
return filename.endswith((".exe", ".dll")) | eabf002ebfa0ccf1fe2d5de3c332e8533ce8f443 | 571,079 |
def weight_mean(arr, wei, NaN=False):
"""Perform the weight mean.
Parameters:
1. arr: the array of numbers
2. wei: the array of weights.
Each number in arr is weighted by its corresponding weight in wei and added. Then divided by the total weight (sum of weight)
If NaN=True, NaNs ... | e78e9d8f9ec532f1a0c597ead6fa6b4565a78e5c | 571,080 |
def user_key_as_str(refresh_token):
"""Convert user_key settings (set/not set) into string."""
return refresh_token if refresh_token else "not set" | a3a72b03b5bbfa1b3b736f7e6f931c497f3d3e83 | 571,091 |
def disable_motors(robot, joint_ids=None):
"""Return a function that disables the motors."""
def reset():
robot.disable_motor(joint_ids=joint_ids)
return reset | ae2e380f7b86d5ed918ce3ac7ac7a3ebace06327 | 571,094 |
def get_sum(list):
"""Calc the sum of values from a list of numbers
Args:
list: The list from where the calc will be done
Returns:
Return the sum of values from a list of numbers
"""
sum = 0
for value in list:
sum += value
return sum | 1d5e588993da40ff9f04e3f1cb5a5214c1b686bd | 571,095 |
from typing import OrderedDict
def pool_node_agent_skus_list_table_format(result):
"""Format pool node-agent-skus list as a table."""
table_output = []
for item in result:
table_row = OrderedDict()
table_row['Agent Id'] = item['id']
table_row['Publisher'] = item['publisher']
... | c0190851e274b76b989042047a3504854ec72b52 | 571,096 |
import yaml
def load_contents() -> dict:
"""
Loads contents.yml
"""
with open('articles/contents.yml', 'r') as file:
contents = yaml.safe_load(file)
return contents | f4301b5d2d24759a290aea1efdcd27b7bcddffe8 | 571,098 |
def change(current, previous):
"""Calculate the percent change between `current` and `previous`.
"""
if current == previous:
return 0
try:
v = ((current - previous) / previous) * 100.0
if v > 0:
return "+{:.2f}".format(v)
return "{:.2f}".format(v)
except Z... | b42fa21a451a7d9a49238b6452fa3561d8c4cb69 | 571,099 |
def _standardise_proc_param_keys(key):
"""Convert to lowercase, replace any spaces with underscore."""
return key.lower().replace(" ", "_") | 592f29c756fff2a103cb83d41e11c844a1898de3 | 571,100 |
def get_lc_name(stackname, ip_address):
"""
Convenience method to generate the launch configuration
name as a function of the stackname and the ip address
:param stackname:
:param ip_address:
:return: str
"""
name = stackname + '_ASG_LC_' + str(ip_address).replace(".", "-")
retur... | a2fbd5a5c5ec08c123b2b0b8f03d2f10ef7a91fe | 571,102 |
def binary_search(L, v):
""" (list, object) -> int
Precondition: L is sorted from smallest to largest, all the items in L can
be compared to v.
Return the index of the first occurrence of v in L, return -1 if v is not
in L.
:param L: list we want to scan
:param v: element we want to s... | 26509a263f726b75a53ba5e21d94be9e122cb424 | 571,103 |
def increment_index_versions(client, old_indices: list):
"""
Increment versions numbers for new indices, these kind don't matter because they should always be aliased to
the original format of {app_label}_{cls.__name__.lower()}_{year}.
:param old_indices: indices to be updated
:return: indices name... | b8044ff839508c1d7c54098791c9c67e7d6c934f | 571,110 |
import torch
def distance_to_reference_trajectory(pred_centroid: torch.Tensor, ref_traj: torch.Tensor) -> torch.Tensor:
""" Computes the distance from the predicted centroid to the closest waypoint in the reference trajectory.
:param pred_centroid: predicted centroid tensor, size: [batch_size, 2]
:type p... | d123e601a96c8db7d6a947e23a4ab308352cf778 | 571,119 |
def result2string(nodes):
"""Convert result list to string."""
return "\n".join([str(i) for i in nodes]) | 5185d64cb8bf149e7d9454ee59d41cce2f387409 | 571,124 |
from pathlib import Path
import gzip
import pickle
def store_pickle(obj, filepath):
"""
Store a compressed "pickle" of the object in the "pickle_data" directory
and return the full path to it.
:param obj: Any Python object that can be pickled
:param filepath: str or Path object
:return: Path... | 0b22ab8c2327f39bbd6e6ff2e36928ae5cfef95d | 571,128 |
def setup_dict(data, required=None, defaults=None):
"""Setup and validate dict scenario_base. on mandatory keys and default data.
This function reduces code that constructs dict objects
with specific schema (e.g. for API data).
:param data: dict, input data
:param required: list, mandatory keys to... | 2af75e90c7237103cf535571560fd6253772e65b | 571,129 |
def get_meta_data(file_name):
"""Helper function to retrieve a given file name's year, month, and zone.
Takes a string file_name formatted as ``'AIS_yyyy_mm_Zone##.csv'`` and returns the numerical
values of ``yyyy, mm, ##`` corresponding to year, month, and zone number as a tuple.
Args:
file_n... | f3c77ce6109282aa997ea39dc70b5181bd9abc8f | 571,132 |
def make_efile_url(efile_page_url: str) -> str:
"""
Helper function to get file download link
on a Portland EFile hosting web page
Parameters
----------
efile_page_url: str
URL to Portland efile hosting web page
e.g. https://efiles.portlandoregon.gov/record/14803529
Returns... | 2a074777cd66c83eeaa598fa441ff44be3301929 | 571,134 |
def _generate_select_expression_without_casting(source_column, name):
"""
Returns a column without casting. This is especially useful if you need to
keep a complex data type, like an array, list or a struct.
>>> from spooq.transformer import Mapper
>>>
>>> input_df.head(3)
[Row(friends=[Row... | c9144770739a0d28637614037572ac51c22c0e0c | 571,140 |
def code(text):
"""Formats text as code in Markdown format.
Args:
text(string): Text to format
Return:
string: Formatted text.
"""
return '`{0:s}`'.format(text.strip()) | b96c7cc0dc349aedae9196305acaebb4df07c5ee | 571,143 |
def is_ascii(string):
"""
Check for unicode encoded characters by trying to encode the string as ascii only
"""
try:
string.encode('ascii')
except (UnicodeEncodeError, UnicodeDecodeError):
return False
else:
return True | b4f44e176b1ce1aef3fd5e98923eb46cf3864862 | 571,146 |
def back_order_rate(total_back_orders, total_orders):
"""Return the back order rate for a period. Back orders are those that could not be shipped due to lack of stock.
Args:
total_back_orders (int): Total number of back orders.
total_orders (int): Total number of orders.
Returns:
B... | 0f0e71fe23bf151e8181686695711d8f52be27d7 | 571,147 |
def compute_test_pairs(job, input_files, format_function):
"""Takes the outputs of match_files and parse_input_files and constructs a new dictionary with results
to compare. For all the files in the job that are 'present' and included in input_files, a dictionary entry
keyed by the file name is created, con... | a3fabdaefc24b55636f8f823194b960d44a9167b | 571,148 |
def palindrome1(x):
"""
Determine if the argument is a palindrome, using a recursive solution.
:param x: An iterable.
:return: True if the argument is a palindrome, False otherwise.
"""
# Arguments of length 0 or 1 are always palindromes.
if len(x) < 2:
return True
# If the fir... | 9c3575edac07a6fbe97c0ad646be559898d6ab54 | 571,151 |
def cast_numpy_array_to_dtype(array, dtype):
"""Cast numpy array to given dtype."""
if array.dtype == dtype:
return array
return array.astype(dtype=dtype, copy=False) | 3bcb7e57dcb2615afb5c564c5b1bf9ffeb6d066a | 571,155 |
def countCheckedItems(widget_list, what_to_count):
"""
Calculation of the amount of records marked in the list.
:param widget_list: the current list for which the number of marked records is counted.
:param what_to_count: A parameter that tells the function what to count, for example: number of checked... | 8621448c9150a2b2ab2a131f7a708810ee3c03e8 | 571,157 |
def encode_html_for_file(html):
"""Hack in a meta tag at the top of an HTML snippet to make the resulting
file display correctly in a web browser."""
return ('<meta charset="utf-8">\n' + html).encode('utf-8') | dc3bbff05f2e1a1179406b843408fad2211df2e0 | 571,159 |
from typing import List
from typing import Dict
from typing import Any
from typing import Set
def parse_kinds(taints: List[Dict[str, Any]]) -> Set[str]:
"""
Parse the list of sources/sinks/tito from a Pysa JSON output
dump, e.g.
[ { "decl": null, "kinds": [ { "kind": "Test" } ]
into a set cons... | 5d266de8daf025c718b3857de865f7574f9de965 | 571,160 |
from typing import Iterable
def ip_groups_to_cidrs(ip_range_groups: Iterable):
"""Collapse ip groups list to CIDRs
Args:
ip_range_groups (Iterable): an Iterable of lists containing connected IPs
Returns:
Set. a set of CIDRs.
"""
ip_ranges = set()
for cidr in ip_range_groups:
... | 0f59ad79ced17f7d85849e8e4b01f89d70c7692a | 571,166 |
from typing import Counter
def num_profs_with_token(profTokenDict):
""" Returns a Counter with the number of professors a given token appears
in.
"""
counter = Counter()
for profCounts in profTokenDict.values():
tokensInProf = set()
for revCtr in profCounts:
tokensInProf = to... | fd6557ebb7a604b34a34dadbf025fa1e60e858b2 | 571,169 |
def get_im_physical_coords(array, grid, image_data, direction):
"""
Converts one dimension of "pixel" image (row or column) coordinates to
"physical" image (range or azimuth in meters) coordinates, for use in the
various two-variable sicd polynomials.
Parameters
----------
array : numpy.arr... | 18db75e08404004f0515233b4e759d4d69b92598 | 571,170 |
def batch_size(batch):
""" Calculates the size of a batch.
Args:
batch: A list of dictionaries representing mutations.
Returns:
An integer specifying the size in bytes of the batch.
"""
size = 0
for mutation in batch:
size += len(mutation['key'])
if 'values' in mutation:
for value in ... | d141914a01959da54d9e431f8ff8ba4a7fcaabf8 | 571,175 |
def get_resource_type_name(resource_values):
"""Gets resource type name from resource values."""
resource_type = resource_values['Type']
return resource_type.split('::')[-1] | 62944170fe9885ac632e2048f89b9336efdcd979 | 571,180 |
def get_port_width(tree):
"""Get the width of the RTL port, if the entry node specifies it"""
metal_entry = tree.chosen("metal,entry")
port_width = None
if metal_entry:
entry_node = tree.get_by_reference(metal_entry[0])
# If the entry node is a testram, the parent node
# is the ... | 1a2d1932c0c531b9947b957f92b59de8366917b8 | 571,183 |
def yes_no_checker(string):
"""Gets user input, if yes returns True,
else if no, returns false"""
yes_list = ['yes', 'y', '1']
no_list = ['no', 'n', '0']
while True:
try:
answer = input(string)
if answer.lower() not in yes_list and answer.lower() \
... | c6e0c221d354cfe6a93f8b9bd09a776b1aeb9b4b | 571,188 |
import math
def haversine_distance(lat1, lon1, lat2, lon2):
"""
Calculate the distance between two coords
using the haversine formula
http://en.wikipedia.org/wiki/Haversine_formula
"""
EARTH_RADIUS = 6371
lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])
dlat = lat2-... | 77698ae90a3a221f0e050f108789cf14e30e63ba | 571,192 |
import math
def H2N(H, e):
"""
Function: H2N
Purpose: Maps the hyperbolic anomaly angle H into the corresponding
mean hyperbolic anomaly angle N.
Inputs:
H = hyperbolic anomaly (rad)
e = eccentricity (e > 1)
Outputs:
N = mean hyperbolic anomaly (rad)
"""
if ... | beb663a71f91700340591a051cdf784bcab27e6d | 571,193 |
def sanitize_url_dict(url, url_attr="src"):
"""Sanitize url dict as used in django-bootstrap4 settings."""
if isinstance(url, str):
return {url_attr: url}
return url.copy() | cf8fdc675de432e79013f4743b9821f690c71cda | 571,194 |
def read_file(filepath):
"""Read a file and return a string.
Examples
---------
>>> data = tl.files.read_file('data.txt')
"""
with open(filepath, 'r') as afile:
return afile.read() | 674efc2517765937ae4d46f4b111419665b38ed2 | 571,197 |
def coq_def(name, params, body):
"""Coq definition
Arguments:
- `name`: name of the defined function
- `params`: strings representing the parameters
- `body`: the body of the definition
"""
return "Definition {0!s} {1!s} := {2!s}.\n".format(name, params, body) | 69fd43316dc8a09774ea84b0c0bc2227a4866e85 | 571,201 |
def is_snake_eyes(die1, die2):
"""Return true if face values of die total 2."""
SNAKE_EYES = 2
return True if (die1 + die2 == SNAKE_EYES) else False | d307da359e12f69d2ad12e1686e5d8800329b1cc | 571,202 |
def stripFields(obj, fields=[]):
"""
Removes fields that are specified in array
"""
return {k: v for k, v in obj.items() if k not in fields} | f69026652f079e95b9ec0c039d722b4a3e9adc08 | 571,204 |
def plur_sing(count, word, suffix=None):
""" Conditionally add an 's' for example, if count isn't 1. """
if suffix is None:
suffix = "s"
return f"{count} {word}{suffix * (count != 1)}" | 519651c1b020619cc3c0ace4d76e47fb57eae17b | 571,206 |
def _filter_designation_line(line):
"""
Filters given line, splits by delimiter and removes empty values.
:param line: line to filter.
:return: filtered list of values.
"""
filtered = filter(None, [x.strip() for x in line.split(' ')])
return filtered | fd986da59c2ed63079e10d5dc58cafd57e09d300 | 571,207 |
def srm_to_l(srm):
"""
Convert the SRM value to Lovibond
https://en.wikipedia.org/wiki/Standard_Reference_Method
"""
return (srm + 0.76) / 1.3546 | 472c99ab45edf7a3872c43b038f50d4f75c6a7b4 | 571,213 |
import pickle
def load_divergence_dict(file_name="divergence_dict"):
"""
Load the divergence dict from pickle.
"""
with open(file_name, "rb") as file:
divergence_dict = pickle.load(file)
return divergence_dict | 2faeebca2b046895c9b44731c0b8e59223944e98 | 571,214 |
def transpose(a):
"""
Returns the matrix transpose of 'a'.
:param a: The original matrix.
:return: the transposed matrix.
"""
result = [[0] * len(a) for x in range(len(a[0]))]
for a_row in range(len(a)):
for a_col in range(len(a[a_row])):
result[a_col][a_row] = a[a_r... | bdc4846c0b03d5a8dd4e67fc44e1b0b40cc13144 | 571,215 |
def _get_lon_lat(ds):
"""Return lon and lat extracted from ds."""
try:
lon = ds.cf['longitude']
lat = ds.cf['latitude']
except (KeyError, AttributeError):
# KeyError if cfxr doesn't detect the coords
# AttributeError if ds is a dict
lon = ds['lon']
lat = ds['l... | 20fc4f23cc38498800c35e1fa22516ff79a8be98 | 571,216 |
import multiprocessing
def splitList(inputList, bins = None, preserveOrder = False):
"""Split a list into sublists and return the list of sublists.
Args:
inputList: The list to be split
bins: The number of bins. Overrides cpu_count()
preserveOrder: if true, append to each sublist in list o... | 5f18c52ac50fac65787e1b9ffd9c2b7fa4a5ddbb | 571,217 |
def create_args_string(num) -> str:
"""
构造占位符
Args:
num(int):
Returns:
str: like '$1,$2...'
"""
l = []
for n in range(num):
l.append('$' + str(n + 1))
return ', '.join(l) | c09c88bbb422c774fccb0e6e2016e115541dd892 | 571,220 |
def _transform_branch_geometry_to_coords(branch_geo):
"""
Create coords entries from geodataframe geometries
:param branch_geo: The dataframe containing the branch geometries (as shapely LineStrings)
:type branch_geo: geopandas.GeoDataFrame
:return: branch_geo - The given geodataframe with coords
... | 341396e37dfde1b2bd0ee344738bbbf6257f0771 | 571,221 |
def uses_all(word, required):
"""Predicate which asks whether word uses *all* letter in required string.
word: string to be searched
required: string, word must use all letters in this string to be true
"""
# Sort of the converse of uses_only; this time if any letter in required
# is not found i... | 73d711804b7b7493fc344c6647b97717737d61b7 | 571,222 |
def srgb_to_linear(color: float):
""" Convert a sRGB gamma encoded color value to linear color value """
if color <= 0.04045:
return color / 12.92
else:
return pow(((color+0.055) / 1.055), 2.4) | 7b2dcad78d1c3e6efa68a6f79365ccabae073a4f | 571,227 |
def NDBI(ds):
"""
Computes the Normalized Difference Built-up Index for an `xarray.Dataset`.
The formula is (SWIR1 - NIR) / (SWIR1 + NIR).
Values should be in the range [-1,1] for valid LANDSAT data (swir1 and nir are positive).
This is a spectral index for which high values often indicate urban ar... | e74d1214f7c15daaabaf3a2ae5e38792fad57c01 | 571,229 |
def reverse(df, reset_index=False):
"""Reverse the dataframe.
"""
df_reversed = df.iloc[::-1]
if reset_index:
df_reversed = df_reversed.reset_index(drop=True)
return df_reversed | 6f507c75915d4abcd31581605ca6814f9cbe2331 | 571,231 |
def is_int_like(val):
"""Check if a value looks like an int."""
try:
return str(int(val)) == str(val)
except Exception:
return False | d06f096b3324fdf2189c5ec3b8027e4ec422520d | 571,232 |
def ident(num):
"""Create num×num identity matrix."""
matrix = []
for i in range(num):
row = [1.0 if i == j else 0.0 for j in range(num)]
matrix.append(row)
return matrix | d2ae084dd34c9d974dc7077085a36ebebe077fb3 | 571,233 |
def sum_all_multiples(cutoff):
"""Return the answer to the answer above.
Parameters:
cutoff -- int: the value under which we are summing values of 3 and 5
Return: int - sum of all multiples of 3 and 5 below cutoff.
Only natural numbers are included in the sum.
"""
sum = 0
... | 606f394ff913baa32e1e8b6411d9d79f227a7124 | 571,234 |
def config_multiple_workers_1(bitshares, account):
""" Prepares config with multiple workers on same account
"""
config = {
'node': '{}'.format(bitshares.rpc.url),
'workers': {
'ro-worker-1': {
'account': '{}'.format(account),
'amount': 1.0,
... | 5b4c80aa6291fe876dbea22a38abe1bafc83de3d | 571,237 |
def _inference_best_shape(n_images):
"""Inferences the best matplotlib row/column layout.
This method searches for the two closest factors of the number
`n_images`, and returns this tuple as the best shape, since this
is the closest to a square grid as possible.
"""
a, b, i = 1, n_images, 0
... | c09cb3956f1a644d80fc34491eee34c76b74c482 | 571,238 |
def remove_time_coordinate(cube):
"""Remove time coordinate for invariant parameters."""
cube = cube[0]
cube.remove_coord('time')
return cube | cd08ebde2582f11c37cb818ac9e9a85e2aff1162 | 571,240 |
def create_fips_ref(fips_df):
"""
Sets all the state names in the fips_df to lowercase for easier
comparisons and makes a dict reference with the FIPS code as
the key to shorten code instead of having to match/query the
DataFrame repeatedly.
"""
fips_state_ref = dict(zip(f... | cdbde94d410d82cf2ba5e329a39d1a15ebecb48d | 571,244 |
def check_native_segwit(script):
"""
Checks whether a given output script is a native SegWit type.
:param script: The script to be checked.
:type script: str
:return: tuple, (True, segwit type) if the script is a native SegWit, (False, None) otherwise
:rtype: tuple, first element boolean
""... | 20932afe883c4eee2e4cfe494ffacaf70a501f12 | 571,246 |
def format_mapping_file(headers, mapping_data, comments=None):
""" returns a large formatted string representing the entire mapping file
each input is a list, and all data should be strings, not e.g. ints
* headers defines column labels, and SampleID should not include a '#'
* mapping_data is a list of... | 71c7514c4c8e84e9386f38abbb0015e278259dca | 571,248 |
from typing import Counter
def identify_cipher(ciphertext: str, threshold: float) -> bool:
"""Identify letter transposition or substitution cipher.
Compare most frequent letters in **ciphertext** with the most frequent
letters in the English alphabet. If above **threshold**, it is a letter
transposit... | 72c6ac24a6b79c895d63b83fb9a0dd05067daa86 | 571,254 |
def exponentation_by_squaring(base, power):
"""
Calculates base ^ power using recursion, efficient algorithm to inbuilt pow() function
:param base: Base of expression
:param power: Power of expression
:return: returns base ^ power
"""
if power < 0: # Negative powers
return exponent... | 78b0e7121a9f1c0c17956d0efb13fde250e94032 | 571,261 |
import io
from typing import Iterator
from typing import Dict
import json
def read_csv(file: io.StringIO) -> Iterator[Dict]:
"""read in a CSV encoded text-stream and convert to native Python
>>> txt = '''"Name", "Sex", "Age", "Height (in)", "Consent Given"
... "Alex", "M", 41, null, true
... "Bert", ... | 466cb3fbb1de7374d9a9a238bd58be04f4317286 | 571,262 |
import typing
def format_issue_or_pr(data: typing.Dict[str, typing.Any], include_title: bool = True) -> str:
"""
Format a GitHub issue or pull request JSON into a markdown message.
If include_title is true, the title of the issue will also be included.
"""
result = f"[**#{data['number']}**]({data... | e5793b7f8546cd86c17f98bebf69ed088239ef0b | 571,266 |
import re
def is_list_type(gene_params):
"""
Determines if a gene is of a list type or not; e.g. returns ``False`` if type is ``"float"`` but ``True`` if type is ``"[float]"``
:param gene_params: a dictionary of parameters for a single gene; see :ref:`genome-params`
:type gene_params: dict
:retu... | 71300897c64a600f0e592e854e72bc14bf7849ea | 571,269 |
def get_related_name(model, field):
""" Extract the related name for a field.
`model` is the model on which the related field exists. `field` is
the field from the original model.
"""
opts = model._meta.concrete_model._meta
all_related_objects = [r for r in opts.related_objects]
for relatio... | 52a9a5b0651514010c1c32d3911df3663482a42b | 571,270 |
def already_all_imported(group, imported_filepaths):
"""Test is all the filepaths in groups are already imported in
imported_filepaths"""
nimported = sum(fp in imported_filepaths for fp in group)
return nimported == len(group) | c6bbd66795ba527dec81a45b959a4278543f92e1 | 571,272 |
def trace(vector):
"""np.trace() only work for square matrices. To get the trace of
stress/strain vectors, this function must be applied.
Parameters
----------
vector: numpy.ndarray
the stress/strain vector.
Returns
-------
trace:
the sum of diagonal components of the... | 6c44f2097d1ed11d54026a7dd5ec5e53bef66a7d | 571,273 |
def make_schedule(n,pattern):
"""
Make up an auditing schedule (a list of sample size s values to use)
start with 0
do pattern, then pattern repeated by multipied by last/first, etc.
end with n
note that last/first does not need to be an integer.
make_schedule(1000,[1,2]) # --> 0,1,2... | 47bacd1b0f6bfb2973bc373abbcdd7da288191bd | 571,276 |
def find_closure(rel, attrs):
"""
Finds the closure of attrs under the relations in rel.
Arguments:
rel (list[(list[str], str)]) : relationships to find closure under
attrs (list[str]) : attributes to find the closure of
Returns:
closure (set[str]) : attrs' closure, aka the att... | 25286cfe85df09f835643d7c6b990981980a88e9 | 571,277 |
def clamp(value, min_value, max_value):
"""Return value constrained to be within defined limits
Parameters
----------
value : int or float
Original value
min_value : int or float
Allowed minimum value
max_value : int or float
Allowed maximum value
Returns
... | 6795dff79c070337c18876579b09e751a25077a1 | 571,278 |
def extract_issue_title(message):
"""Extract issue title from the message."""
return message.subject | 0dfab4962c95fd9372dd735d658ad66dde32f1ad | 571,282 |
import torch
def perspective_projection(points, rotation, translation, focal_length,
camera_center):
"""This function computes the perspective projection of a set of 3D points.
Notes:
batch size: B
point number: N
Args:
points (Tensor([B, N, 3])): A set... | 8ac6f4ae61b6bbfb19f350fb4250128fe284419a | 571,284 |
def upsert_user_in_db(user_object, users_collection):
"""Updates or inserts the user object into users_collection.
Args:
user_object (dict): must contain a user_id and name and must not
contain other attributes.
users_collection (pymongo.collection): the MongoDB collection to use.
... | d5a656852ef11111557b48c64eaf19fa8668cc7c | 571,288 |
def read_required_guides(fn, expected_guide_length, num_alignments):
"""Read list of required guides.
There must be 3 columns in the file:
1 - an identifier for an alignment that the guide should be
covering (0-based, with maximum value < num_alignments)
2 - the guide sequence
... | f3f6d8c45b0e71d148c21198a52a53941e50d793 | 571,295 |
def left_column(matrix):
"""
Return the first (leftmost) column of a matrix.
Returns a tuple (immutable).
"""
result = []
for row in matrix:
result.append(row[0])
#
return tuple(result) | 547a091aaf8c7fd1847c8c42b6e0f7bc65b471a3 | 571,298 |
def __splitTime(sec):
"""Splits a timestamp into hour, minute, and second components.
:type sec: int
:param sec: timestamp as an epoch
:rtype: tuple
:return: (hour, min, sec)
"""
minute, sec = divmod(sec, 60)
hour, minute = divmod(minute, 60)
return hour, minute, sec | cc2c80f1c5e9df8c0f4b374bfe31cc2132767cc0 | 571,299 |
def inline_code(code: str) -> str:
"""
Covert code to inline code
Args:
code (str) : code to be converted to inline code
Returns:
str: inline code
"""
return f"`{code}`" | 83c654e466754ed07ffe8bfd1b2b986609c48ad1 | 571,302 |
def percent_slower(new, old):
"""
`new` is X percent slower than `old`
Args:
new (float): measure of time
old (float): measure of time (with same units as new)
Returns:
precent_slower: how much slower `new` is as a percentage of `old`
Example:
>>> new = 8.59755
... | 65a303fe2dda896e8b0e1c5af8c5fd8bf41237aa | 571,309 |
def decode_headers(headers):
"""Decode HTTP headers.
Args:
headers: String containing encoded HTTP headers.
Returns:
Dictionary of HTTP headers.
"""
def strip(l):
a, b = l
return (a.strip(), b.strip())
return dict([strip(h.split(':', 1)) for h in headers.split('... | a7da5016dd17e42bb9aa5f589629e64005019401 | 571,313 |
def organization(request):
"""Context processor for organization"""
if hasattr(request, 'organization'):
return {'organization': request.organization}
return {'organization': None} | e09cd24b6cb48e73d66f45be8449c6889ae1aa7d | 571,315 |
import re
def parseGenericUri(uri):
"""
Parse Generic URI into its components (as generic as possible)\n
Port is the only part type casted (parse delimited fields accordingly)
components dict format:
.. code-block:: python
res = {
'proto': <str|None>,
'userpw': <... | 1ce371b5c636bf126b43b66334bd93b9e39b3922 | 571,316 |
def isFloat(input: str):
"""
检测输入是否为float
:param input:字符串
:return:True 是; False 否
"""
try:
float(input)
except:
return False
else:
return True | 2c9dfa29caadbf4f759bc7b700a7f5ae2491f0e4 | 571,317 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.