content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
from typing import Tuple
import ipaddress
def validate_ipv4_net(network: str) -> Tuple[bool, str]:
"""
Checks if string is a valid IPv4 network
:param network: string representation of IPv4 network
:return: tuple of (bool, str). (True, msg) if valid; (False, msg) if invalid
"""
try:
i... | 53908b5907eb52b2249edf1a03aa26bba6ebba56 | 542,082 |
import struct
def serialize_port(port):
"""Serializes a port number according to the DNSCrypt specification"""
return struct.pack('!H', port) | 51463af3eea8161d96110a71e59af7c4ebbe18de | 321,535 |
def check_int(school, international):
"""
Checks if a school is an international school based on a school list and other criteria
Parameters
----------
school: current school being checked
international: AP/IB school list
Returns
-------
Y or N
"""
# list of criteria that ... | 5dd3d6152ad8ac55c70bb508e9b15f1c9a7f5e1b | 193,614 |
def dehom(x):
""" Convert homogeneous points to affine coordinates """
return x[0:-1, :] / x[-1, :] | 14e3c6b484513f8633457e7b7a64318040ec24c7 | 417,522 |
def composite(image1, image2, mask):
"""
Create composite image by blending images using a transparency mask.
:param image1: The first image.
:param image2: The second image. Must have the same mode and
size as the first image.
:param mask: A mask image. This image can have mode
"1"... | cce01353bde95b88b81110befcea98f0915abc7c | 119,177 |
def sql_timestamp_pretty_print(ts, lang: str = 'en', humanize: bool = True, with_exact_time: bool = False):
"""
Pretty printing for sql timestamp in dependence of the language.
:param ts: timestamp (arrow) as string
:param lang: language
:param humanize: Boolean
:param with_exact_time: Boolean
... | 79efcf545dceb3e6df58fde9f23b8fb023aa974c | 292,346 |
def geoIsOnSegment(loc, line):
"""
Determine if loc is on line segment
Parameters
----------
loc: list
First location, in [lat, lon] format
line: list of lists
Line segment, in [[lat,lon], [lat,lon]] format
Return
------
boolean
True if loc is on line segment, including two edge vertices
"""
[y1, x... | 435b5fd64ae0057fd60eeec84138c20903881748 | 477,809 |
def calculate_bmi(weight, height):
""" Given weight (pounds), height (inches)
Return BMI
"""
return (weight / (height * height)) * 703. | f9574c127f91a6209c19e4329aa2a1eb371933bb | 199,304 |
def page_not_found(error):
""" Handles 404 errors by simply just returning the code and no page rendering"""
return "", 404 | 8776b26997aca654a1281274d0ed8f35e1a0d8b6 | 496,818 |
def create_error_payload(exception, message, endpoint_id):
"""
Creates an error payload to be send as a response in case of failure
"""
print(f'{exception}: {message}')
error_payload = {
'status': 'MESSAGE_NOT_SENT',
'endpointId': endpoint_id if endpoint_id else 'NO_ENDPOINT_ID',
'message': f'{ex... | 90f266d22429d385e828dcdd92fca3d7b2e6df48 | 4,728 |
def is_pythonfile(file):
"""Returns True if file extension is py and if not then false."""
if file.endswith('py'):
return True
else:
return False | 4f7e1609e3d17d7ca58cdf31bebc27761d1d3fb1 | 437,291 |
def convert_comma_separated_integer_to_float(comma_separated_number_string):
"""Converts a string of the form 'x,xxx,xxx' to its equivalent float value.
:param comma_separated_number_string: A string in comma-separated float form to be converted.
:returns: A float representing the comma-separated number.
... | daddeaa78a3efb8ffd2d5eac122757f041da5f97 | 694,860 |
def pointToGridIndex(x, y, z, sx=1.0, sy=1.0, sz=1.0, ox=0.0, oy=0.0, oz=0.0):
"""
Convert real point coordinates to index grid:
:param x, y, z: (float) coordinates of a point
:param nx, ny, nz: (int) number of grid cells in each direction
:param sx, sy, sz: (float) cell size in each directio... | 8df63aa196ed3bec7bcc0ae6478b51308a2a0ab9 | 619,278 |
import click
def click_option_expand(f):
"""Add expand option to command."""
return click.option(
'--expand',
is_flag=True,
help="Display associated assets details"
)(f) | 9f2a6edd30649817df28eff57e804f4c851070da | 266,130 |
def read_str(data, start, length):
"""Extract a string from a position in a sequence."""
return data[start:start+length].decode('utf-8') | a2d5426937a9a2e61fe5a993951f7275ca50a460 | 186,236 |
def calc_mean_score(movies):
"""Helper method to calculate mean of list of Movie namedtuples,
round the mean to 1 decimal place"""
scores = [movie.score for movie in movies]
return round(sum(scores) / len(scores), 1) | f2923c8dd583b1e4aa54dfd4191c5a7aa5484b88 | 612,681 |
def compose_preprocess_fn(*functions):
"""Compose two or more preprocessing functions.
Args:
*functions: Sequence of preprocess functions to compose.
Returns:
The composed function.
"""
def _composed_fn(x):
for fn in functions:
if fn is not None: # Note: If one function is None, equiv. t... | 5fde96f972d0d730981e88e44ff4c220c242bcfd | 304,366 |
def normalize(sentence_sets, word2id, max_sent_len):
"""Normalize the sentences by the following procedure
- word to index
- add unk
- pad/ cut the sentence length
- record the sentence length
Args:
sentence_sets: the set of sentence paraphrase, a list of sentence list
word2id: word index, a dict... | a931e07cf9a4a0d04fa68e7ad28b57c7cdcf37d6 | 502,844 |
def get_mdict_item_or_list(mdict, key):
"""
Return the value for the given key of the multidict.
A werkzeug.datastructures.multidict can have a single
value or a list of items. If there is only one item,
return only this item, else the whole list as a tuple
:param mdict: Mu... | d330d3555a989f4b7f0b3e9b17cf5190f9244b70 | 519,390 |
def parse(afile, sep=' '):
"""Parse contact file.
@param afile contact file
@param sep separator of contact file (default=' ')
Ensures: Output is sorted by confidence score.
@return [(score, residue a, residue b)]
"""
contacts = []
for aline in afile:
if aline.strip... | 1dcf1bea41d4b79c297f29485e8f053c55052d3e | 269,924 |
def split(array, n):
"""
Splits an array into two pieces.
Args:
array: The array to be split.
n: An integer or float.
If n is an integer, one of the arrays will contain n elements, the other will contain every other element.
If n is a float, it needs to be between 0 and... | 095dab4f6f88bf3bb132771bf3d20abd9d239c49 | 512,324 |
def _get_session_id_from_cookie(request, cookie_name, cookie_signer):
"""
Attempts to retrieve and return a session ID from a session cookie in the
current request. Returns None if the cookie isn't found or the value cannot
be deserialized for any reason.
"""
cookieval = request.cookies.get(cook... | e88e186a7e0e38984706454b4cf9936ef1b639da | 113,376 |
def mask_data(ds, mask_mapping):
"""
Mask data values according to the mask_mapping parameter
"""
for var, missing_value in mask_mapping.items():
ds[var] = ds[var].where(ds[var] != missing_value)
return ds | f1e745aa33ee58b16cdc27b0c7a0f74bf99dc941 | 520,397 |
def twos_complement(value: int) -> int:
"""
This method returns the 16-bit two's complement of a positive number
(used for sending negative values to the controller). It raises an error
if the argument is too large or is negative.
"""
assert value.bit_length() <= 16, "Value too large!"
asser... | 58a48d6fa436c79158ba1e8de4a036acc712832e | 218,066 |
def is_content_authored_by(content, user):
"""
Return True if the author is this content is the passed user, else False
"""
try:
return int(content.get('user_id')) == user.id
except (ValueError, TypeError):
return False | 9a6846b04bce0066973aac3e3a5dfda2db2b1663 | 53,742 |
def _has_alternative_alignments(aligned_segment):
"""Return true if read has alternative alignments"""
tags = aligned_segment.get_tags()
return "XA" in [x[0] for x in tags] | 74a383afa42988adeca15c63f78ed10eb2deb8ed | 523,072 |
def single_pcrosstalk(total_pcrosstalk: float) -> float:
"""
Inverse formula to ``total_pcrosstalk''
Parameters
----------
total_pcrosstalk : float
The probability of total crosstalk events.
Returns
-------
p_crosstalk : float
The probability of a single crosstalk event... | 401934183dd50dfad5f15ca91a183054e756e4e7 | 570,721 |
def format_bird_bgp_community(target):
"""Convert from standard community format to BIRD format.
Args:
target {str} -- Query Target
Returns:
{str} -- Formatted target
"""
parts = target.split(":")
return f'({",".join(parts)})' | fc9339e3e0ffde33b6d7330d0f74c3cdee465aab | 523,493 |
def format_coefficient(model):
"""
Formats the coefficient of a model for display.
:param model: A linear model
:type model: sklearn.linear_model.LinearRegression
:return: The formatted coefficient
:rtype: str
"""
return "{:,}".format(round(model.coef_.tolist()[0][0], 2)) | e006ed5bde24f76fc2a980c679455f8fae65d83f | 280,554 |
def get_chess_square_reverse(size, x, y):
"""
Returns the coordinates of the start of the square block on the board given the block's
coordinates
"""
return (x * size // 8, y * size // 8) | 083b9bee26b70f4704ed0182fb1e4a2baeb01c4b | 419,068 |
from typing import Tuple
def xgcd(a: int, b: int) -> Tuple[int, int, int]:
"""Extended Euclidean algorithm.
Finds :code:`gcd(a,b)` along with coefficients :code:`x`, :code:`y` such that
:code:`ax + by = gcd(a,b)`.
Args:
a: first number
b: second number
Returns:
gcd(a,b),... | 6d8764e21511b473b968b24d6783ac97ead0a180 | 669,732 |
def _isnumeric(var) :
"""
Test if var is numeric, only integers are allowed
"""
return type(var) is int | 51c29247a5d4531f565534afe7750a13138c110e | 692,960 |
def tlv_string_xml_mapped() -> str:
"""Return the mapped XML data for the test tree as string."""
return """<Tlv>
<ConstructedTagE1>
<PrimitiveTag9F1E>16021437</PrimitiveTag9F1E>
<ConstructedTagEF>
<PrimitiveTagDF0D>M000-MPI</PrimitiveTagDF0D>
<PrimitiveTagDF7F>1-22</PrimitiveTagDF7F>
... | d30e1af8adaea971fd64bc9152d72b8626d55927 | 471,332 |
def extract_machine_code(assembly_lines):
"""
Extract machine code from assembly line dictionaries.
Args:
assembly_lines (list(dict)): List of assembly line info
dictionaries to extract machine code from. See
:func:`~.get_assembly_line_template` for details on what
... | 757dd311e13a5c73fb3715b7195349555c02aab4 | 589,582 |
def send_request(client, post_data, **kwargs):
"""uses a dict to create a request on dataforSeo api
parameters:
client : Restclient object created with create_request
post_data: dict created with create_request
Optional parameters:
server: server to use for request
returns json style list"... | 973fef88a77a592c8129ad5e409430173da08d69 | 648,639 |
def get_keys(d, value):
"""Renvoie la liste des clés de d ayant la valeur value."""
t = []
for k in d:
if d[k] == value:
t.append(k)
return t | fe68795007e1fa749da4acbd2935cdaee162ff38 | 434,409 |
def move_axis(data, label, new_position):
"""Moves a named axis to a new position in an xarray DataArray object.
Args:
data (DataArray): Object with named axes
label (str): Name of the axis to move
new_position (int): Numerical new position of the axis.
Negat... | da58b00560032ded1847066222f50da50ff7c171 | 559,658 |
import torch
def subsequent_mask(seq_len):
"""
## Subsequent mask to mask out data from future (subsequent) time steps
"""
mask = torch.tril(torch.ones(seq_len, seq_len)).to(torch.bool).unsqueeze(-1)
return mask | 43cace3a2d4cc32a43136cf36766f280707ee677 | 160,642 |
def time_until_next_event(prng, net_rate):
"""Compute the time at which the next event is due to occur.
All events are modeled as Poisson processes with exponentially
distributed waiting times. Units of time are chosen such that the
average time it takes for a given cell to divide is 1.
"""
re... | d429006563ab0ead27ec019f002665d77ec7dd9e | 391,101 |
def _update_dtypes(candidate_model):
"""Update dtypes of specific columns from float to int.
Updates dtypes of *candidate_model* so that columns representing integer
are set to integers.
Args:
candidate_model (pd.DataFrame): Data frame representing a causal
forest model, which might ha... | b0186ed415ad5dd7907ad10c1a000b2784d69285 | 157,258 |
import re
def filter_by_category(result, name_filter=None):
""" Filter by category name the result returned from ZIA.
:param result: Dict of categories from ZIA response.
:param name_filter: A regex string used to filter result.
:return: Filtered result.
"""
categories = result.get("categorie... | da5e1c716a86907bb953abf8821962e76094de9d | 77,509 |
def ipkg_meta_from_pkg(pkg):
"""Return meta dict for Installed pkg from a PackageDescription
instance."""
meta = {}
for m in ["name", "version", "summary", "url", "author",
"author_email", "license", "download_url", "description",
"platforms", "classifiers", "install_requires... | 7c73546854fe022005bb7cd65711d850fc744645 | 692,799 |
import copy
import random
def pick_random_idx(idices, num, seed=0):
"""
Pop the "num" number of random samples from the sequence "indices"
Args:
idices (Sequence):
num (Int): The number to pop up the samples from the "idices"
seed(Int): Random seed
Returns:
remai... | 45840fa4a2cb4991022caea67e3ba8a5ce713ce9 | 429,463 |
def _to_latex(string):
"""Latex-decorate a string."""
return ('$' + string + '$') | fc03b93086393c772aa932a37560f472d0624c6f | 126,334 |
def itoa(num, base=10):
""" Convert a decimal number to its equivalent in another base.
This is essentially the inverse of int(num, base).
"""
negative = num < 0
if negative:
num = -num
digits = []
while num > 0:
num, last_digit = divmod(num, base)
digits.append('0123456789... | 297bc917d689c7ca7065d9e53d62efeb84208cf8 | 568,533 |
def round(x: int, divisor: int) -> int:
"""Round x to the multiplicity of divisor not greater than x"""
return int(x / divisor) * divisor | e598827058d5c7c37e32f8d213690875403fbe8d | 52,251 |
def unwrap_twist(twist):
"""
Unwraps geometry_msgs/Twist into two tuples of linear and angular velocities
"""
l_x = twist.linear.x
l_y = twist.linear.y
l_z = twist.linear.z
a_x = twist.angular.x
a_y = twist.angular.y
a_z = twist.angular.z
return (l_x, l_y, l_z), (a_x, a_y, a_z) | 66c4eceeea7791790252ea01c7e8aabe28ea9be0 | 33,852 |
def antipode_v(ll):
"""Antipodes of points given by longitude and latitude."""
antipode = ll.copy()
antipode[0] -= 180
index = antipode[0] < -180
antipode[0, index] += 360
antipode[1] *= -1
return antipode | 0775c1b5d9ec77a0866708a072a08081077669d9 | 220,384 |
def where_above(list, limit):
"""
where_above behaves like table.where(column, are.above(limit)).
The analogy is completed if you think of a column of a table as a list and return the filtered column instead of the entire table.
>>> where_above([1, 2, 3], 2)
[3]
>>> where_above(range(13), 10)
... | fe02f5d88aff90cac4041fdf71b7fbfc2ed4a978 | 403,761 |
def funding_rate(self, symbol: str, **kwargs):
"""funding Rate history
GET /fapi/v1/fundingRate
https://binance-docs.github.io/apidocs/futures/en/#get-funding-rate-history
Args:
symbol (str, optional): the trading symbol
Keyword Args:
limit (int, optional): limit the results. Def... | f76b3d8d93d34164e0397c86bb18a1eb674612eb | 103,195 |
def has_attribute(object, name):
"""Check if the given object has an attribute (variable or method) with the given name"""
return hasattr(object, name) | 44f0cd1cc54fe61b755d94629e623afe234fe99d | 682,145 |
import re
def format_gid(gid):
"""Internal function to strip transcript dot-notation from IDs."""
return re.sub(r"\.\d*", "", gid) | f994298f8f9ef659f459cea678787d0cd661b6da | 529,380 |
def construct_dom_id_filter(dom_resource_subclass, dom_id_value):
"""
Returns a new dict w/ one entry: { <dom-id-key>: <dom-id-value>}
The dom-id-key is name of the ID field/attribute for the given type of
DOM resource (a subclass of pvc_nova.objects.dom.Resource). The
dom-id-key is obtained from ... | dfcb55672f301fbb19f082f89d590f7333be37b4 | 150,609 |
def _simple_string_value(tree, kind, name):
""" base function for extracting a simple parameter value.
:param tree: the parameters tree.
:param kind: the xml-tag name of the parameter.
:param name: the name of the parameter.
:returns value: the content of the parameter 'Value' as string."""
quer... | 473919cc08fb0b1fd0b73dcdcdc730affd29daff | 103,987 |
def find_optional_start(line):
"""Find the starting position of the optional fields on the given line."""
pos = 0
for i in range(0, 11):
pos = line.find("\t", pos)
if -1 == pos:
return -1
pos += 1
return pos | c10886a1768566c5ed8011a48fc8783dff12de1a | 297,776 |
def chirp_mass(mass1, mass2):
"""
Takes two masses and calculates the corresponding chirpmass.
Args:
mass1: Mass 1
mass2: Mass 2
Returns:
chirpmass: The chirpmass that corresponds to mass1, mass2
"""
return (mass1 * mass2) ** (3 / 5) / (mass1 + mass2) ** (1 / 5) | 41ccb3e573f361538c7591942b445e629b4c6c84 | 184,679 |
def _find_line_containing(source, index):
"""Find (line number, line, offset) triple for an index into a string."""
lines = source.splitlines()
if not lines:
# Special case: empty program
return 1, '', 0
this_line_start = 0
for zero_index_line_number, line in enumerate(lines):
... | 8c90e0989b1e073a7c0df65b32778040890b21bb | 195,885 |
from pathlib import Path
def get_file_id(fname):
"""Returns the Gutenberg File ID"""
pth = Path(fname)
# as per file structure the filename has some variations but the parent folder is always the ID
return pth.parent.name | 4cfa633937ea7baa0fe0f9390fdab59630437525 | 342,417 |
def length(seq):
""" Returns the length of the sequence `seq`. """
return len(seq) | 20e9ed2148e14c90b47ba6559312250ba5e03a51 | 421,574 |
def override(left, right, key, default):
"""Returns right[key] if exists, else left[key]."""
return right.get(key, left.get(key, default)) | f6f5da1840aa4fa70fe0db400be9bebd2f21e383 | 674,561 |
def get_syst ( syst , *index ) :
"""Helper function to decode the systematic uncertainties
Systematic could be
- just a string
- an object with index: obj [ibin]
- a kind of function: func (ibin)
"""
if isinstance ( syst , str ) : return syst
elif syst and hasattr ( syst , '... | 37b2b39245587da16345752e02759d2c94c93415 | 702,800 |
def isSignatureValid(expected, received):
"""
Verifies that the received signature matches the expected value
"""
if expected:
if not received or expected != received:
return False
else:
if received:
return False
return True | f911521998e45dfc3804039e9105a921e33e9a67 | 204,446 |
def get_attributes(aspect, id):
"""Return the attributes pointing to a given ID in a given aspect."""
attributes = {}
for entry in aspect:
if entry['po'] == id:
attributes[entry['n']] = entry['v']
return attributes | 2f1d1c006e7df700da9fff8e5238c93b20eed8c5 | 395,068 |
def diff_month(date1, date2):
"""Counts the number of months between two dates
Args:
d1 - date to
d2 - date from
Returns:
number of months between two dates
"""
return (date1.year - date2.year) * 12 + date1.month - date2.month | 2e224f9432cb4a2da7ad0b492d8acb9b4948f1af | 551,825 |
def boxBasics(box):
"""basic statistics of box. Returns (mean,var)"""
mean=box.box_data.mean()
var=box.box_data.var()
return (mean,var) | 0e9493722637adef80e606225bd712546c998470 | 671,622 |
def _resort_categorical_level(col_mapping):
"""
Resort the levels in the categorical encoders if all levels can be converted
to numbers (integer or float).
Args:
col_mapping: the dictionary that maps level string to int
Returns:
New col_mapping if all levels can be converted to num... | 0740b4bb210637a144e00e29ff023af375801c56 | 285,832 |
def OR(bools):
"""Logical OR."""
if True in bools:
return True
return False | 200e78e6ef1ce91ad36301cea0b8f56dc7301219 | 647,078 |
def ether2wei(ether: float):
"""Converts units of wei to Ether (1e18 * wei)."""
return ether * 1e18 | b826daaa171d24b43b7f901b6498f24f5481ed1c | 41,448 |
def GetDimensions(nc):
"""Returns a dictionary describing the dimensions in a netCDF file."""
return({name: {
"size": dim.size, "UNLIMITED": True} if dim.isunlimited() else {
"size": dim.size, "UNLIMITED": False}
for name, dim in nc.dimensions.items()}) | a8da5e01745962949fc9b098c4949ae7d6f558dc | 303,522 |
def _calculate_num_runs_failures(list_of_results):
"""Caculate number of runs and failures for a particular test.
Args:
list_of_results: (List) of JobResult object.
Returns:
A tuple of total number of runs and failures.
"""
num_runs = len(list_of_results) # By default, there is 1 run per JobResu... | f67a6b1fa6a5aefc19bfe7e99ed77473801e6b83 | 48,193 |
def check_padding(pads, dim, padval):
"""Check each padding start/end value
and set the sufficient pad value.
If we have asymmetry padding, we will return
True to indicate the need for a separate padding function"""
asymmetry = False
for i in range(dim):
s = pads[i]
e = pads[i+di... | 3841eda76f09910dbc4199123a723bcd017ee21e | 198,046 |
def cap_feature_values(df, feature, cap_n=10):
"""Cap the values of a given feature, in order to reduce the
effect of outliers.
For example, set NUMBER_OF_HABITABLE_ROOMS values that are
greater/equal to 10 to "10+".
Paramters
----------
df : pandas.DataFrame
Given dataframe.
f... | 273e755ec1b677b662732c8ae598581c01a25a53 | 118,786 |
def parse_title(raw_title):
"""
Format the title associated with a link.
This format a title associated with a link. Some of them include some bad
html elements/characters.
:param raw_title: A raw title
:type raw_title: str
:return: A formated title
:rtype: ... | 5f459aa852861637997a03e4b9d5e6557d6d8d65 | 383,536 |
def flatten(in_list):
"""Flatten list.
>>> flatten([])
[]
>>> flatten([1, 2, 3])
[1, 2, 3]
>>> flatten(([[1], [2, 3]]))
[1, 2, 3]
>>> flatten([1, [[2], 3]])
[1, 2, 3]
"""
def flatten_generator(in_list_inner):
for item in in_list_inner:
try:
... | d862a2daa508ca56f210a41573fb5ba8ac3877b9 | 256,130 |
def sql_from_filename(filename):
"""
Given a filename return the SQL it contains.
This function exists to support unit testing.
:param filename: path to exiting file containing SQL
:return: str: sql commands to execute
"""
with open(filename, 'r') as infile:
return infile.read() + "... | da965543f6ed2fafdb3717237c80457bf690e3ff | 99,138 |
def replace_null(x, replace = None):
"""
Replace null values
Parameters
----------
x : Expr, Series
Column to operate on
Examples
--------
>>> df = tp.Tibble(x = [0, None], y = [None, None])
>>> df.mutate(x = tp.replace_null(col('x'), 1))
"""
if replace == None: ret... | 6aa7906524b40633bf05ca0178891da249310fff | 508,326 |
def compute_offsets(task, nc_per_task, is_cifar):
"""
Compute offsets for cifar to determine which
outputs to select for a given task.
"""
if is_cifar:
offset1 = task * nc_per_task
offset2 = (task + 1) * nc_per_task
else:
offset1 = 0
offset2 = nc_per_task
... | 300eab41a67f084b7c0ea172fc682e138192d87a | 514,900 |
def is_prime(number):
"""checks if a given number is prime"""
prime = True
for n in range(2, number):
if prime and number % n == 0:
prime = False
print("The number is not prime")
if prime:
print("The number is prime")
return prime | a6119b54e3ff16d7e94ad4ac06e224c623ee5dd1 | 648,361 |
def _ReadFileAndPrependLines(file_path):
"""Reads the contents of a file and prepends the line number to every line."""
with open(file_path) as f:
return "".join("{}${}".format(line_number, line)
for line_number, line in enumerate(f, 1)) | 59c7d03710b7c06ad43fc989166d7a021ee45827 | 234,668 |
def recurse_combine(combo_items: list, idx: int = 0) -> list:
"""Recursively expands 'combo_items' into a list of permutations.
For example recurse_combine([[A, B, C], [D, E], [F]]) returns
[[A, D, F], [A, E, F], [B, D, F], [B, E, F], [C, D, F], [C, E, F]]
"""
result = []
if i... | effab4c6f29e353d19f88b23f7d2a3bfa854d431 | 674,653 |
import base64
def decode_to_bytes(data: str) -> bytes:
"""
Decodes a base64-encoded string and returns a sequence of bytes.
:param data: The base64-encoded string to decode
:return: decoded bytes
"""
data_bytes = bytes(data, "utf-8")
data_decoded_bytes = base64.b64decode(data_bytes)
re... | f2d4453c0129924b81d5ea2e5c1578bea72944ee | 496,780 |
def rubygems_download_url(name, version, platform=None, repo='https://rubygems.org/downloads'):
"""
Return a .gem download URL given a name, version, and optional platform (e.g. java)
and a base repo URL.
For example: https://rubygems.org/downloads/mocha-1.7.0.gem
"""
if not name or not version... | b6cfe7050bf30695bbeab621b2a3cc7f9c662817 | 422,110 |
def normalizeScifloArgs(args):
"""Normalize sciflo args to either a list or dict."""
if isinstance(args, dict) or \
(isinstance(args, (list, tuple)) and (len(args) != 1)):
return args
elif isinstance(args, (list, tuple)):
if isinstance(args[0], (list, tuple, dict)):
... | 49d4528b6ac05f7864f7b1c38f4cfe079b451870 | 227,872 |
def hexdecode(value):
"""
Decodes string value from hex to plain format
>>> hexdecode('666f6f626172')
'foobar'
"""
value = value.lower()
return (value[2:] if value.startswith("0x") else value).decode("hex") | b91af6ef77fa1bc8270b62dc72ed7c7a07d96aa9 | 609,319 |
def get_ami_info(ec2, ami_id):
"""
Returns information about the specified AMI.
Parameters
----------
ec2 : botocore.client.EC2
AWS EC2 client.
ami_id : str
AMI ID.
Returns
-------
dict
"""
resp = ec2.describe_images(ImageIds=[ami_id])
return resp['Image... | cdb1d05afae5bf0c76df0aa7eca5208771fd2923 | 593,379 |
from typing import Dict
from typing import Optional
def weighted_average(
distribution: Dict[str, float],
weights: Dict[str, float],
rounding: Optional[int] = None,
) -> float:
"""
Calculate a weighted average from dictionaries with the same keys, representing the values and the weights.
Args... | b6c710fc8039b79637c8d45329eb90cc0d1bb264 | 678,674 |
import torch
def rel2abs_traj(rel_pose):
"""Convert a given relative pose sequences to absolute pose sequences.
Args:
rel_pose (torch.Tensor): Relative pose sequence in the form of homogenous transformation matrix. Shape: [N,4,4]
Returns:
torch.Tensor: Absolute pose sequence in the form ... | b2533d65262da65d80eb4869afde7b1256a8ec52 | 128,893 |
def find_exec_in_executions(searched_exec, executions):
"""
Search if exec is contained in the executions.
:param searched_exec: Execution to search for.
:param executions: List of executions.
:return: Index of the execution, -1 if not found..
"""
for i, existing_exec in enumerate(executions... | 6d2dd2931742a1395a81462643afdbef2b49087e | 601,069 |
def get_aso_idx_from_id(df, aso_id):
"""Converts an ASO UUID to the corresponding array index
in the orbital prediction numpy array
:param df: The orbital prediction DataFrame
:type df: pandas.DataFrame
:param aso_id: The UUID of the ASO found in the `aso_id`
column of the provi... | 0042c71eda7c98fd86894912606c6eb9cc2df383 | 334,426 |
def word_to_put_req(word_vectors_map, word):
"""
Translate a word to a PUT request to be sent to DynamoDB
"""
return {
'PutRequest': {
'Item': {
'word': {
'S': word
},
'vector': {
'L': [{'N': str(... | 1734463d60869c4c51ba40f61ad19e16ead75345 | 38,422 |
import re
def apply_cigar(cigar, seq, qual, pos=0, clip_from=0, clip_to=None):
""" Applies a cigar string to recreate a read, then clips the read.
Use CIGAR string (Compact Idiosyncratic Gapped Alignment Report) in SAM data
to apply soft clips, insertions, and deletions to the read sequence.
Any inse... | 4f69386c370bff76314d055da123c3185d2768de | 360,094 |
import re
def make_xlat(*args, **kwds):
"""
Auxuliary function to define a translator that applies multiple character
substitutions at once.
Taken from "Python Cookbook, 2nd Edition by David Ascher, Anna Ravenscroft,
Alex Martelli", Section 1.18
:param args: Dictionary
:param kwds:
:... | a8c4f9a0a293479000d7947932c7fe9b9616e05e | 502,154 |
def unique_elements_lists(list_in):
"""return the unique elements in a list"""
return list(dict.fromkeys(list_in)) | dc893f678f079322b198894621d1c9b401b8878f | 172,541 |
from pathlib import Path
def is_raster_format (image_path: str) -> bool:
"""
Is the file at the provided path a raster image?
Parameters:
image_path (str): Path to file.
Returns:
bool: Whether the file is a raster image.
"""
RASTER_FORMATS = [".jpg", ".jpeg", ".tif", ".tiff"]... | 9817c1d08f0b8cd4a01073d03f753577106b1c54 | 91,151 |
import types
def is_function(tup):
""" Takes (name, object) tuple, returns True if it is a function.
"""
name, item = tup
return isinstance(item, types.FunctionType)
# def _start(self, spin):
# for args, kwargs in self.subscribers:
# self.subscribers_init.append(rospy.Subscrib... | e49e0973828d0eea848d29b8a1b954119f1fe490 | 592,682 |
def grids(dims, blocks):
"""
Determine the grid size, given space dimensions sizes and blocks
Parameters
----------
dims : tuple of ints
`(x, y, z)` tuple
Returns
-------
tuple
`(x, y, z)` grid size tuple
"""
if not len(dims) == 3:
raise ValueError("dims... | c2bfb27c5df4849a267233ff18327e4cfe2a6e7e | 214,367 |
from typing import Any
from typing import Union
from typing import List
def isType(val: Any, typeArr: Union[List[Any], Any]) -> bool:
"""Helper that checks if the supplied value `val` is of a specific type or of a type present in `typeArr`"""
if isinstance(typeArr, List):
anyMatched = False
... | e4faecf10edffa81b6680d55fa91ea6714a8f1df | 512,715 |
def get_vehicle_mass(vehicle_info):
"""
Get the mass of a carla vehicle (defaults to 1500kg)
:param vehicle_info: the vehicle info
:type vehicle_info: carla_ros_bridge.CarlaEgoVehicleInfo
:return: mass of a carla vehicle [kg]
:rtype: float64
"""
mass = 1500.0
if vehicle_info.mass:
... | 216f109e9f963ba6de92cf168055b1a7e516d777 | 13,555 |
def split_repo_name(repository):
"""Take a string of the form user/repo, and return the tuple
(user, repo). If the string does not contain the username, then just
return None for the user."""
nameparts = repository.split('/', 1)
if len(nameparts) == 1:
return (None, nameparts[0])
else:
... | 3740b80c2658315a27498b05832b120a937e053b | 621,659 |
import re
from datetime import datetime
def matroska_date_to_datetime(date):
"""
Converts a date in Matroska's date format to a python datetime object.
Returns the given date string if it could not be converted.
"""
# From the specs:
# The fields with dates should have the following format: ... | 8805d6c0015b518433302bd88ac7d17eb52fd687 | 445,790 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.