content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def quicksort_equal_elements(s):
"""Quicksort from finxter modified to add all elements equal to the pivot
directly after the pivot, so that quicksort performs faster for cases
where there are many identical elements in the array to be sorted (e.g.
there are only 2 values for all elements, or 1 unique v... | 56d8d64ae8a1af07cda84907dfec10be029de0b1 | 596,368 |
def _parse_see_args(topic, data):
"""Parse the OwnTracks location parameters, into the format see expects."""
parts = topic.split('/')
dev_id = '{}_{}'.format(parts[1], parts[2])
host_name = parts[1]
kwargs = {
'dev_id': dev_id,
'host_name': host_name,
'gps': (data['lat'], da... | 8286952baa5cec02235cc8f2bbe0f95eb5496adb | 596,379 |
import json
def get_complexes() -> dict:
"""Reads and returns the file located at ../complexes.json as a Python
dictionary. This file contains aliases from both complex names and
abbreviations into a common name so that the user can execute `!staff TJ`
or `!staff Thomas Jefferson`, for instance.
"... | f9d6e1cc171770c1c1e33689ff450fa9d2583d5b | 596,380 |
def _multiply(array, matrix):
"""
multiply each row of a matrix by each element of an array
e.g. [1, 2] * [[1, 2, 3], [4, 5, 6]] = [[1, 2, 3], [8, 10, 12]]
"""
return array.reshape((-1,) + (1,) * (matrix.ndim - 1)) * matrix | 56ea86a483a16a449e1e3b99ac3f946df5fdcd5b | 596,385 |
def seconds_taken(diff):
"""Convert a time diff to total number of seconds"""
return int(diff.total_seconds()) | a27ab86348c3ee2447120c7fd7d7c5d95d335861 | 596,388 |
async def wait_or_kill_process(process):
"""
Wait for process to finish. On exception (especially cancellation), kill the
process.
"""
try:
return await process.wait()
except:
try:
process.kill()
except ProcessLookupError:
pass
await proc... | 83761258d076e46535b3b54b7af8344584ae2aa9 | 596,390 |
def rpc_to_gdal_dict(rpc, precision=12):
"""Construct a GDAL RPC meta-data dictionary from a RPCModel
The format of the dictionary matches what GDAL returns and contains
the standard fields from the RPC00B standard
"""
md_dict = dict()
fmt = '%0.' + str(int(precision)) + 'f'
md_dict['LONG_O... | f386d12e824c2099b7fa1ad82398406e5a92b2ca | 596,392 |
def sorted_subclasses(cls):
"""Return subclasses of `cls`, sorted alphabetically by name.
``pytest-xdist`` requires tests to be collected in a deterministic order.
This function is to be used for tests parametrized on subclasses.
Parameters
----------
cls
Returns
-------
list of c... | d9311a1dfc7e33429844f63ce37aef040a7ce33d | 596,396 |
import math
def _is_close(a, b, alpha=0.01):
""" Check if two blobs are close to one another
:param a: first blob. This is larger than b.
:param b: second blob. This is smaller than a.
:param alpha: The amount of overlap allowed between blobs
:returns: if blobs are close
"""
if alpha < 0 ... | 44b960303d5612895728bb939a0be28dd063f5b1 | 596,397 |
import torch
def horizontal_flip_boxes(w, boxes, encoding='coords'):
"""
Horizontally flip bounding boxes with respect to an image.
Parameters
----------
w : int
Width of the image, to which given boxes belong.
boxes : Tensor
Bounding box tensors (N, 4) in the format x1, y1, x... | 91f533508749a9a8ce516647f4f27fabb8cc027f | 596,398 |
def create_gdp_csv(pair_df, time_df, initial):
"""
Fills gdp dataframe missing values with previous values. Originally gdp data changes once
a month, but dataframe must contain entries for every minute.
Args:
pair_df: Currency dataframe containing columns for time and gdp
time_df: Dataf... | 216dadff112045332cd511d5ef8ca2926509cdc1 | 596,399 |
def get_machine_id_change_spec(client_factory, machine_id_str):
"""Builds the machine id change config spec."""
virtual_machine_config_spec = client_factory.create(
'ns0:VirtualMachineConfigSpec')
opt = client_factory.create('ns0:OptionValue')
opt.key = "machine.id"
... | 608dd49fedd7735d1a11a7bbc63425eec64ff492 | 596,401 |
from typing import Optional
def make_plain(value: Optional[str]) -> Optional[str]:
"""Returns a plain version of the field (remove redundant braces)
returns None if the field is None or empty string"""
if value is not None:
plain = value.replace("{", "").replace("}", "").strip()
if plain !... | e4d4b785a63c26bedaeed399bc458591c5352706 | 596,402 |
def format_authentication_result(authentication_result):
"""
Format the authentication result.
Args:
authentication_result (dict): The authentication result.
Returns:
dict: The formatted authentication result.
"""
formatted_authentication_result = dict()
formatted_authentic... | e3d5227c2e2fa67b5d77d77664d7f229ba30e56f | 596,406 |
def to_ternary_int(val) -> int:
"""Convert a value to the ternary 1/0/-1 int used for True/None/False in
attributes such as SENT_START: True/1/1.0 is 1 (True), None/0/0.0 is 0
(None), any other values are -1 (False).
"""
if val is True:
return 1
elif val is None:
return 0
eli... | 26062ebdc19aa582a504e6515cd90fb43f2780fc | 596,409 |
import re
def _mk_version_tuple(version):
"""Create a version tuple as required by a version info file.
Note: non-numeric parts of the version are stripped entirely and
empty numbers are replaced by zero's (1..1 -> 1.0.1)
Args:
version: a version string, e.g. '1', '1.2', '1.2.3', '1.2.... | 8c8fc95376ced35e2fbcddb67de26b3e03cb7a47 | 596,410 |
def getRoadrunnerValue(roadrunner, names):
"""
Provides the roadrunner values for a name. If no name,
then all values are given.
Parameters
----------
roadrunner: ExtendedRoadrunner
name: str/list-str
Returns
-------
object/dict
"""
if isinstance(names, str):
re... | bc4e2a616d968cab7675611c98a0e1e7ca1cbb93 | 596,412 |
def strip_white_spaces(input_list):
"""Takes a list of string as input
Removes the leading and trailing white spaces from each string in the list
Returns an output list having the string elements with leading and trailing
white spaces removed
"""
output_list = []
for element in input_list:
... | 5474c2255c463dbfec3453053d3c86dd16657f44 | 596,413 |
def path_to_class(path):
"""Given a class path, returns the class"""
module_path, cls_name = path.split(':')
module = __import__(module_path, fromlist=[cls_name])
cls = getattr(module, cls_name)
return cls | 4c17a17dd3c9e1f763ce64314d136ac94b33bf51 | 596,423 |
def crop_kps(img,kps,size,h_cent):
"""
Converts keypoints calculated on full image to corresponding cropped locations.
Parameters
----------
img : numpy.ndarray
A sample frame at full size.
kps : numpy.ndarray
The keypoints for the full size image.
size : int
The siz... | 23cccb4f61c5dff704a995189ede60c95f7019d0 | 596,424 |
def color_producer(elevation):
""" This returns color depending on the elevation """
if elevation < 1500:
return 'green'
elif 1500 <= elevation < 3000:
return 'orange'
else:
return 'red' | 74e5f5ac8f90da8096062d420250bc306c58464f | 596,426 |
def ytb_rss(user):
"""Return the url for the rss format."""
return "http://gdata.youtube.com/feeds/base/users/{0}/uploads?alt=rss".format(user) | 612f0e30b6fb19e6614a126f602d1e2cab364ead | 596,428 |
import math
def weight(total_doc_count: int, doccount: int, wordfreq: int) -> float:
"""
Weighting function for Document Term Matrix.
tf-idf => https://en.wikipedia.org/wiki/Tf%E2%80%93idf
"""
return math.log(total_doc_count / doccount) * wordfreq | c6337e40163287aa4088a848d6f04ef2555bd11e | 596,429 |
import json
def retrieve(corpus_path, labels_path="", edges_path=""):
"""
Retrieve corpus and labels of a custom dataset
given their path
Parameters
----------
corpus_path : path of the corpus
labels_path : path of the labels document
Returns
-------
result : dictionary with ... | f27acec7d3f80359bf3ea63f7fcf7d8eca0bf152 | 596,430 |
def type_and_index_field(field):
"""coerce field to an int, and, as the UI is one-indexed, decrememnt
field values >= 0 by 1."""
field = int(field)
if field >= 0:
field -= 1
return field | 9361944984f6138cdb0f2f3558373c3d8adac109 | 596,431 |
import copy
def copy_grid (grid):
"""return a copy of the given grid"""
newGrid = copy.deepcopy(grid)
return newGrid | 2db6abaa79dfe80b3cd06f72d9dcc12e4139cebc | 596,432 |
from typing import Union
import logging
def _level_to_int(level: Union[str, int]) -> int:
"""Convert a log level in str or int into an int.
Args:
level: Can be a string or int
Returns:
level as int.
"""
if not isinstance(level, int):
level = logging.getLevelName(level.upp... | 296529cb2160d94310da8a83d993e1e85fd4c354 | 596,434 |
def ndim(X):
""" Computes the dimension of input list """
if isinstance(X[0], (list, dict)):
return 2
else:
return 1 | e72989ebf3f6e517a0c94fc2e8a552703f6ac911 | 596,436 |
def spliter(re_match_from_filter):
"""
Split given re.match object from candidate filter into (book, locator) tuple
"""
book = re_match_from_filter.group('book')
locator = re_match_from_filter.group('locator')
return (book, locator) | b391ee882fc169176f1999708f4c9c5487032a40 | 596,443 |
import re
def parse(specification):
"""Parse optional configuration values.
This function parses the given ``specification`` value into a name and
a dictionary of key/value configuration pairs if specified.
Args:
specification (str): The specification to parse.
Returns:
A tuple ... | 89f20468a55302562aceb9f4b771318b08f75ceb | 596,446 |
def period(dance):
"""Number of dance iterations until programs return to starting positions.
"""
seen_positions = {str(dance)}
cycles = 0
while True:
dance.perform()
cycles += 1
positions = str(dance)
if positions in seen_positions:
break
seen_... | cbd68f698e22922e466ad954608aed34bc8a80cd | 596,447 |
def _remove_empty_values(dictionary):
""" Remove None values from a dictionary. """
return {k: v for k, v in dictionary.items() if v is not None} | 0b2f4da478f640ca6c4e35e1fc20afab11032cca | 596,450 |
def from_multi_index_to_3d_numpy(X, instance_index=None, time_index=None):
"""Convert panel data stored as pandas multi-index DataFrame to
Numpy 3-dimensional NumPy array (n_instances, n_columns, n_timepoints).
Parameters
----------
X : pd.DataFrame
The multi-index pandas DataFrame
ins... | 673127dca8903c56c60abfb5962de1254c89c8ae | 596,454 |
def get_wildcards(df_sim, df_div_winners, n_wc):
"""Calculate wildcards per simulation
:param df_sim: simulated data
:param df_div_winners: data frame with div winners in each iteration
:param n_wc: number of wildcard positions open
:return: data frame with wildcard teams per iteration
"""
return (
d... | b5782a158f646be570f661a51fd37afd9114c9bc | 596,455 |
def pareto_rule(data, default='otros'):
"""Implementation of Pareto rule to categorical variable.
"80% of outputs are produced by 20% of inputs"
Parameters
---------
data: pandas.Series
categorical variable to map Pareto rule
default: str
value to group tail values of data.
... | 77b1e98de1323c8329ec7e95806ab0e7e1c73e10 | 596,460 |
def get_key(string: str, dictionary: dict[str, str], default: str = "") -> str:
"""Get key from a value in Dictionary. Return default if key doesn't exist"""
for key, value in dictionary.items():
if value == string:
default = key
return default
return default | dd55408c327d1b1c2ed8c2f7f70459c0eff4da82 | 596,463 |
def uri2label(uri, schema):
"""Given a URI, return the label"""
return [
record["rdfs:label"] for record in schema["@graph"] if record["@id"] == uri
][0] | fda33caa3143b315f9382d571eecc3807229ab68 | 596,470 |
import math
def combinations_calculator(n, r=1):
"""Calculates number of combinations."""
return int((math.factorial(n)) / (math.factorial(r) * math.factorial(n - r))) | 159d6284d0ba27d6408d781dd8db6e262e45ef10 | 596,473 |
import random
import string
def generate(length=16):
"""
Generate a strong Password
"""
return "".join(
random.SystemRandom().choice(string.ascii_letters + string.digits)
for _ in range(length)
) | 22bbc308d1f2b2875781c864247ed993757118ea | 596,475 |
def flatten_dict(dct, key_string=""):
"""
Expects a dictionary where all keys are strings. Returns a list of tuples containing the key vaue pair where the
keys are merged with a dot in between.
"""
result = []
for key in dct:
updated_key_string = key_string + key + "."
if isinsta... | 03537c9a771eaa2dbcbafc235da02602b895c690 | 596,476 |
def list_to_col(df, list_col: str):
"""Takes a dataframe like the following:
idx | list_col
----+----------
1 | [1, 2]
2 | [3, 4, 5]
and returns the following:
idx | list_col
----+----------
1 | 1
1 | 2
2 | 3
2 | 4
2 | 5
"""
return df.explode(l... | 00b7974f3202265e2b184acbc78028358a454729 | 596,478 |
def is_device_target(hostname, device_list):
"""
Check if CV Device is part of devices listed in module inputs.
Parameters
----------
hostname : string
CV Device hostname
device_list : dict
Device list provided as module input.
Returns
-------
boolean
True i... | 354c33c2a22b2ec67c44784d18f539f9ee9ea1c3 | 596,479 |
def matches_compact_repr(matches):
"""
Return a string representing a list of license matches in a compact way.
"""
return ', '.join(m.rule.identifier for m in matches) | 55352d8d5feeb25ce2a2477807adbbc8c3666b95 | 596,480 |
def calc_psf_scaling(pupil_grid, ndim, maxdim):
"""Calculate the input and output grid spacings.
Args:
pupil_grid: A RayGrid instance
ndim: The sampling across the wavefront
maxdim: The total width of the sampling grid
Returns:
delta_x: The linear grid spacing on the entran... | ac9d37eae9bc647786c190150e7e1b14a250eb41 | 596,481 |
import socket
def get_ip_address_type(addr: str) -> socket.AddressFamily:
"""Return socket.AF_INET6 or socket.AF_INET4 for the provided address."""
socket_type = None
# First try it as an ipv4 address.
try:
socket.inet_pton(socket.AF_INET, addr)
socket_type = socket.AF_INET
except... | 197c7fa532deb937135cfb46017d47c76c5fa01a | 596,482 |
def squeeze_singletons(item, to_squeeze):
""" Squeeze singletons in item.
This should be used with `normalize_index` like so:
```
index, to_squeeze = normalize_index(index, data.shape)
out = data[index]
out = squeeze_singletons(out, to_squeeze)
```
"""
if len(to_squeeze) == len(item... | de4c4a095277b49058327b0bcd33ca5c352aa7e8 | 596,483 |
def _write_export(export, file_obj=None):
"""
Write a string to a file.
If file_obj isn't specified, return the string
Parameters
---------
export: a string of the export data
file_obj: a file-like object or a filename
"""
if file_obj is None:
return export
elif hasattr... | 9799b0fee03970808cfc0672eedf7aad5f3998b1 | 596,487 |
import re
def snake_case(word):
"""Make an underscored, lowercase form from the expression in the string.
>>> snake_case("DeviceType")
'device_type'
:param str word: the word to be converted to snake case.
:return str: the word converted to snake case.
"""
word = re.sub(r'([A-Z])', r'_\1... | ed6c5a1511fd640bc6ff2393e03ae15cd67a0b4f | 596,490 |
def disjoint_bounds(bounds1, bounds2):
"""Compare two bounds and determine if they are disjoint.
Parameters
----------
bounds1: 4-tuple
rasterio bounds tuple (xmin, ymin, xmax, ymax)
bounds2: 4-tuple
rasterio bounds tuple
Returns
-------
boolean
``True`` if bounds a... | 0ebb120bfdf805c715c11e7bc1c4140c6ca7d47a | 596,493 |
def get_signed_connectome(matrix, method='negative'):
"""
Function used to extract positive or negative values from matrix
Parameters
----------
matrix : 2D array, n x n
Connectivity matrix in square form
method : {'negative', 'positive'} | 'negative' default
This is used to... | d7437c9a4a7abd12c7787bc9d3e3cffc67f39cb7 | 596,496 |
from typing import Optional
from typing import List
import re
def sub_general(text_in: str, patterns: Optional[List[List[str]]]) -> str:
""" substitutions general
Performs general substitutions from regex expression.
Parameters
----------
text_in: str
text to modify
patterns: list[li... | 34bdc720157d3eed9032d4db7b2a00e8e76d13a7 | 596,497 |
def verify_indices_all_unique(obj):
"""
Check that all axes of a pandas object are unique.
Parameters
----------
obj : pd.Series / pd.DataFrame / pd.Panel
The object to validate.
Returns
-------
obj : pd.Series / pd.DataFrame / pd.Panel
The validated object, unchanged.
... | 9f3d2eea0d59a81b8dfeb9b7e1968e559caeb8f3 | 596,498 |
def find_row(fname, string1, string2='', how='both', num_row=False):
"""Search strings inside plain text files and returns matching\
line or row number.
Parameters
----------
fname : str
Path to plain text file.
string1 : str
String to search.
string2 : str
Extra str... | 0ee59bb8ecfad1d2d56117897c0341bf6271e03c | 596,500 |
def is_it_float(query):
"""Check if query is a valid number
Arguments:
query {str} -- Input query string
Returns:
float -- Parsed float
None -- if query failed to be parsed
"""
try:
return float(query.replace(",", ""))
except ValueError:
return None | d437e4646a24ec5a83665981c84d99149d1e6b82 | 596,502 |
def _most_specific(a, b, default = None):
"""
If a and b are from the same hierarcy, return the more specific of
[type(a), type(b)], or the default type if they are from different
hierarchies. If default is None, return type(a), or type(b) if a
does not have a type_cls
"""
if (hasattr(a, 'type_cls') and h... | 446808ec27dd30ccc06f97d408c1e9f8eeaa0f76 | 596,504 |
def colorize(s, color):
""" Return an HTML colorized string for `s`
"""
color = color.lower()
return "<font color=%s>%s</font>" % (color, s) | 6148f41cfca00af1637db4e93c56787510e41ecb | 596,508 |
import base64
def decode_base64(b64: str):
"""Decodes a base64 value with or without padding."""
# Accept unpadded base64 by appending padding; b64decode won't accept it otherwise
if 2 <= len(b64) % 4 <= 3 and not b64.endswith('='):
b64 += '=' * (4 - len(b64) % 4)
return base64.b64decode(b64, ... | 2e05bd8724108e0f7e1def89d05538275896d2df | 596,509 |
import json
def to_json(o):
"""Convert given data to JSON."""
return json.dumps(o, sort_keys=True) | 81f0322053e2e05705ba58f3d97d4fbcf6c5a0d4 | 596,510 |
from datetime import datetime
def get_datetime() -> str:
"""
Get formatted UTC datetime string
:return: str
"""
dt = str(datetime.utcnow())[:19]
for c in [":", "-", " "]:
dt = dt.replace(c, "_")
return dt | 474a4923ca1a75a0d53c138392f5953206b31234 | 596,511 |
def __parseConnectionString(connectionString):
"""
Parses the queue connection string. Returns a dict of parameters found.
"""
return dict(item.split('=') for item in connectionString.split(';')) | 3b771e94439df25e20a64903c680a36d340d4f5d | 596,513 |
def words_and_tags_from_wsj_tree(tree_string):
"""Generates linearized trees and tokens from the wsj tree format.
It uses the linearized algorithm described in https://arxiv.org/abs/1412.7449.
Args:
tree_string: tree in wsj format
Returns:
tuple: (words, linearized tree)
"""
stack, tags, words = ... | e3871547254d33d5ab99cf1ec685b291db620a0f | 596,515 |
def should_continue() -> bool:
"""Prompt the user to determine if an action should continue."""
val = input('Submit CLs? [y/N] ')
if val.lower()[:1] == 'y':
return True
print('Aborting.')
return False | 5af06954c08c414a67c5810f349f9e78533c2282 | 596,516 |
import collections
def _load_filter(filter_str):
"""Load plugin filter from environment string."""
if not filter_str:
return {}
filt = collections.defaultdict(list)
for entry in filter_str.split(':'):
section, pattern = entry.split('=')
filt[section].extend(pattern.split(',')... | 08836e3e5f08cba179a7672c6007e20d95a0d05b | 596,519 |
def apply_function_on_axis_dataframe(df, func, axis=0):
"""Apply a function on a row/column basis of a DataFrame.
Args:
df (pd.DataFrame): Dataframe.
func (function): The function to apply.
axis (int): The axis of application (0=columns, 1=rows).
Returns:
pd.DataFra... | 631a9e3e62f8fc382f26450a9d9399842a544bda | 596,522 |
def join(sep, xs):
"""Returns a string made by inserting the separator between each element and
concatenating all the elements into a single string"""
return str(sep).join(xs) | 085e768026ec150e51ed9ec32d0ce7a04e1394f8 | 596,525 |
def bdev_compress_delete(client, name):
"""Delete compress virtual block device.
Args:
name: name of compress vbdev to delete
"""
params = {'name': name}
return client.call('bdev_compress_delete', params) | 0ccf183c0f6d97b8e6fdcfa37b7f3c3692967a8a | 596,526 |
def int_overflow(value: int) -> int:
"""
Simulates 32bit integer overflow.
"""
return ((value ^ 0x80000000) & 0xffffffff) - 0x80000000 | 19311b0684e28cb3dbd82d9dcaffe06340dc463c | 596,529 |
def check_param(var, datatype):
"""Checks if a variable is the correct data type.
If it's not correct, return the error message to raise.
Parameters
-----------
var
the variable to check.
datatype
the data type to compare against.
Returns
----------
str
t... | 51c8ed53e516b3f6b53c2f584ca94f82ed2dd60d | 596,530 |
def calc_quadrant_from_decimal_number(value: int) -> str:
"""Return a quadrant (4-ary) from a given decimal number.
Parameters
----------
value: int
a decimal number
Returns
----------
str : a quadrant
"""
base = 4
q = ""
tmp = int(value)
while tmp >= base:
... | 858bf354251e8ffa62c544965d6652da74b81e16 | 596,531 |
def find(collection, item, field='name'):
"""
Finds an element in a collection which has a field equal
to particular item value
Parameters
----------
collection : Set
Collection of objects
item
value of the item that we are looking for
field : string
Name of the ... | 441e38c56defe207090e9473b2fd94b46c032491 | 596,533 |
def list_slice(arr, sl):
"""
Helper method to slice all arrays contained in a list.
"""
if isinstance(arr, list) or isinstance(arr, tuple):
ret = []
for v in arr:
ret.append(v[sl])
return ret
else:
return arr[sl] | d9692305a2cb776813ebe14e3f59d0673d41fc6c | 596,535 |
def make_color_tuple(color):
"""
turn something like "#000000" into 0,0,0
or "#FFFFFF into "255,255,255"
"""
R = color[1:3]
G = color[3:5]
B = color[5:7]
R = int(R, 16)
G = int(G, 16)
B = int(B, 16)
return R, G, B | 6852f640caf5107a27d4f4d472a18e52a8a49281 | 596,539 |
from typing import Sequence
from typing import Dict
from typing import Any
from functools import reduce
import operator
def _get_in(nested_keys: Sequence[str], dct: Dict[str, Any]) -> Dict[str, Any]:
""" Returns dct[i0][i1]...[iX] where [i0, i1, ..., iX]==nested_keys."""
return reduce(operator.getitem, nested... | a7f27ad9bf5a152a5cee7af7667316a9ea03c19f | 596,541 |
def listify(text, separator=None):
"""Turn 'text' into a list using 'separator'"""
if isinstance(text, list):
return text
if isinstance(text, (set, tuple)):
return list(text)
if separator:
text = text.replace("\n", separator)
return [s.strip() for s in text.split(separator... | 99cc01a206c79bc0f16668f2c94107f6dea3a07e | 596,542 |
def validate_config(config, items, logger):
"""
Validates if all items are available in the configuration.
config is the general dictionary with all the configurations.
items is a dict with per domain which attributes we require.
logger is the logger from the caller to log the errors to.
Retur... | a33090056c62f318131ded4bcd63b68fe814ac7f | 596,544 |
def pad_bits(bits, pad):
"""pads seq with leading 0s up to length pad
ex) pad_bits([0,1], 4) -> [0,0,0,1] """
assert len(bits) <= pad
return [0] * (pad - len(bits)) + bits | 3452b2494b3bc5f19881c0d948692b1e9a92ad1b | 596,545 |
def repeating_key_xor(plaintext, key):
"""Implements the repeating-key XOR encryption."""
ciphertext = b''
i = 0
for byte in plaintext:
ciphertext += bytes([byte ^ key[i]])
# Cycle i to point to the next byte of the key
i = i + 1 if i < len(key) - 1 else 0
return ciphertex... | e2d9787a3ef44f32f1cf80ffedecf41410edc47a | 596,548 |
def get_contents_lektor_file(filepath):
"""Returns contents of contents Lektor file as string"""
with open(filepath, "r") as file:
contents = file.readlines()
return "".join(contents) | f265525cccbbc602bdef1a89ff0bca558edccb10 | 596,551 |
import requests
def query_overpass_api(query):
"""Query overpass api.
Args:
query (str): Query to be send to overpass api.
Returns:
dict: Response of the query.
"""
overpass_url = "http://overpass-api.de/api/interpreter"
response = requests.get(overpass_url,
... | c819e56b8c2eae9ffec6a0e570ac7aa9f03c9d8f | 596,559 |
def crop_address(place):
"""
Crops address and returns new variant
>>> crop_address("Jo's Cafe* San Marcos* Texas* USA")
' San Marcos* Texas* USA'
>>> crop_address("San Marcos* Texas* USA")
' Texas* USA'
>>> crop_address(" Texas* USA")
' USA'
"""
place = place.split("*")
pla... | 9f55534cab8768bd217d136b3792a5599cd33fd2 | 596,562 |
def parse_im_name(im_name, parse_type='id'):
"""Get the person id or cam from an image name."""
assert parse_type in ('id', 'cam')
if parse_type == 'id':
parsed = int(im_name[:8])
else:
parsed = int(im_name[9:13])
return parsed | 9b05fc76aa689bda9e0f482bfed6ce2c281d9bbc | 596,563 |
def p_row(request) -> float:
"""Algorithm p_row parameter."""
return request.param | f687c6e830c7db837b87898d2226518e51b68ad8 | 596,564 |
def mutiply_values(iterable, indexes):
"""Mutliplies the values of the iterable given by a list of indexes"""
indexes = set(indexes)
product = 1
for i, x in enumerate(iterable):
if i in indexes:
product *= x
indexes.remove(i)
if len(indexes) == 0:
b... | 71e5a3a98bc3a8fbea9d50650991509e62d481de | 596,565 |
def pow_op_to_callable(expr: str) -> str:
"""
Replace a string expression of the form 'a**b' or 'a^b'
to 'pow(a, b)'. Expressions of the form 'a**(b**c**...)'
will be replaced with 'pow(a, b**c**...)'.
A necessary precondition is that the expression either contains
'^' or '**'.
Parameter... | a75c82380305b66f9024597c05f9dca9017e854a | 596,567 |
from datetime import datetime
def _rebuild_log(log, results, timestamp=None):
"""
Given results of a search, build an updated version of the log.
This builds and returns a new log containing only entries present
in ``results``. Results not previously seen are timestamped with
the given time; othe... | 6b5c0298cd34f2f71205c26d62598fec09783c30 | 596,570 |
def addtosigma_dfa(Din, addition):
"""Given a DFA Din and a proposed addition to its Sigma,
if there is an overlap with the existing Sigma ,
complain and reject (possible user typo); else
add to Din's Sigma and return the new D. Useful when
we define a DFA via markdown and later want to ... | c774831f807a0dac346d498d8d0a51e88c5eb0af | 596,571 |
import random
def random_choice(img, transforms):
"""
Random selects one transform from a list of transforms and applies that on the image.
Args:
img: Image to be applied transformation.
transforms (list): List of transformations to be chosen from to apply.
Returns:
img, Tran... | 48dcaac924389bd16dd087e9a9e93be54e65351c | 596,576 |
def id_class_name(class_id, classes):
"""
Returns name of the class as per the given id
Args:
class_id(int): Number of the class.
classes(dict): dictinary of all the classes in given dataset.
returns:
Name of the Class.
"""
for key, value in classes.items():... | 1393a7d50df201b170975717e2de20214773384c | 596,578 |
def _find_branch(pt, targets, branches):
"""Determines which branch a pathway belongs to and returns that branch.
A ShortestPath belongs to a branch if the first surface exposed residue it reaches during the
pathway is the target of that particular branch.
Parameters
----------
pt: ShortestPat... | 6a79186fecd22c2253b67c82d83e06a0aaa6a0d2 | 596,581 |
def make_train_test_splits(windows, labels, test_split=0.2):
"""
Splits matching pairs of windows and labels into train and test splits.
"""
split_size = int(len(windows) * (1-test_split)) # this will default to 80% train/20% test
train_windows = windows[:split_size]
train_labels = labels[:split... | dba7784edb96b6461b3f2a4291c23169275cfd85 | 596,583 |
def negative(image, extra_inputs={}, parameters={}):
""" Applies a **Negative Filter** onto an image. \n
Arguments:
*image* (NumPy array) -- the image to be filtered
*extra_inputs* (dictionary) -- a dictionary holding any extra inputs
for the call (empty)
*parameters* (diction... | b07e7c6c1243b68db4972a0f80765c260bf8b8db | 596,585 |
def compute_prior_pseudocounts(vs, rv, pseudocount_base, pseudocount_match):
"""
Make pseudocounts dict.
Input: vs a list of votes (domain of prior)
rv a particular vote (e.g. the reported vote)
pseudocount_base a prior pseudocount (e.g. 0.5)
... | f190e8cdf9462f5d13d4846c6561810a35f0011c | 596,587 |
def fib(n):
"""Calculates the nth fibbonaci number. NOTE: Uses index counting"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2) | 1662f9b826dc8a74eab9776f9d3032d2ffb88a38 | 596,589 |
def filter_dict_by_keys(dict_, field_names):
""" Returns a copy of `dict_` with only the fields in `field_names`"""
return {key: value for (key, value) in dict_.items()
if key in field_names} | e85306de1c7947cc7fd9abb81a724953d79d861f | 596,590 |
def __list__(*args):
""" Function for list literals.
__list__(x, y, z, ...) == [ x, y, z, ... ]
"""
return list(args) | be7afa82b3231bf2b1542afa1cd83efea5c2b492 | 596,593 |
def mask_by_length(xs, lengths, fill=0):
"""Mask tensor according to length.
Args:
xs (Tensor): Batch of input tensor (B, `*`).
lengths (LongTensor or List): Batch of lengths (B,).
fill (int or float): Value to fill masked part.
Returns:
Tensor: Batch of masked input tensor... | 295ee7da65d012d02d987c2778ed6f843aeb4280 | 596,597 |
def hw_from_req(req):
""" Utility function to get the hardware resource from requests """
return req.app['com.opentrons.hardware'] | 644e2e64e1f2ab875fc0155b595d91b8050c4884 | 596,598 |
def lessthan(obj1, obj2):
"""
Is the span of obj1 < span obj2
"""
return obj1.span[1] < obj2.span[0] | 2dbf51442b5d2eca43b1fd82044082f17489297d | 596,601 |
import dis
def endswith_expr(func):
"""Does the function end with an expression (not assigment or return)"""
code = func.__code__
co_code = code.co_code
return (
len(co_code) > 6
and co_code[-6] == dis.opmap["POP_TOP"]
and co_code[-4] == dis.opmap["LOAD_CONST"]
and co_c... | db37ba077b5ec2a19084bc6d3a7e87ae9d8a75ca | 596,602 |
def last_first(author):
"""Parse an author name into last (name) and first."""
if ',' in author:
tokens = author.split(',')
last = tokens[0].strip()
first = ' '.join(tokens[1:]).strip().replace(' ', ', ')
else:
tokens = author.split(' ')
last = tokens[-1].strip()
... | 407eae286b8e92c5fbed26d74921aac162deec97 | 596,603 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.