content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
from typing import Optional
def distance(v1: List[int], v2: List[int]) -> Optional[int]:
"""
Determine the distance between two vectors, i.e. the number of positions in which their value differs.
:param v1: first vector
:param v2: second vector
:return: distance as describe... | 253a27d9df7edd5d281854fd9b24b0b498876cc5 | 624,611 |
def endswithoneof(inputstr, seq):
"""
Check if *inputstr* ends with one of the items in seq. If it does, return
the item that it ends with. If it doe not, return ``None``.
:param inputstr: input string
:param seq: sequences of items to check
:return: the item the the input string ends wit... | 7eef43bc6d33b973465ca2ceb07b8d08156a63a1 | 624,616 |
import yaml
def save_dict_as_yaml(input_dict, path):
"""
Save a dictionary to a YAML file.
Args:
input_dict: Dictionary which will be saved to file
path: Path to the YAML file which will be (over-) written.
"""
with open(path, 'w') as f:
return yaml.dump(input_dict, f) | 7bd52eb46d3367ac193554883ac131f60cd6ebf9 | 624,617 |
import yaml
import random
def get_random_subject(species='human'):
"""
Function to get a random data config file and subject for a given species.
Note: only human data are configured at the moment
Parameters
----------
species: str
'human', 'rodent', or 'nhp'
Returns
-------... | b5f03da80febc08339bda78e535d4a2a19bedbec | 624,618 |
def compute_fixed_point(g, x0, tol=1e-8, print_n=False):
""" Compute the fixed point of g(x). """
prev_x = x0
x = g(x0)
n = 1
while(abs(prev_x - x) > 0.5 * tol):
prev_x = x
x = g(x)
n += 1
if(print_n):
print("\tn = %d" % n)
return x | ab9c1ed68c15a692af49d34f446734a7be68c3a9 | 624,619 |
import math
def is_triangle_number(num):
"""Returns whether a number is a triangle number.
A triangle number n is one for which there exists an integer x with
n = (x^2 + x) / 2. Solving this quadratic equation gives
x = (-1 +- sqrt(1 + 8n)) / 2
which will be an integer if and only if 1 + 8n... | 3b0f10387ff3f67fd84e8d10a7fd74e12fbf2109 | 624,620 |
def _user_get_full_name(user):
"""
Override regular get_full_name which returns first_name + last_name
"""
return user.profile.full_name if user.has_profile() else " ".join([user.first_name, user.last_name]).strip() | a1bd053ccd1b45ce891119f5e6804bca30e7e599 | 624,622 |
def tle_scientific_2_float(number):
"""
This method transforms a scientific suffix from the TLE format into a
string format that can be parsed into a float by Python. The format is the
following:
15254-5 = 0.15254 >>> 15254E-5
-333-3 = -0.333 >>> 333E-3
@param number String where the decim... | 9b82eb2b3832577b03433832f8b97bb85a2ae5a4 | 624,624 |
from datetime import datetime
def print_time(x):
""" Print the current
Description
-----------
Appends the current time into a print statement
Parameters
----------
x : String
A message to be printed
"""
ts = datetime.now().strftime("%y-%m-%d %H:%M:%S")
print(f"[{ts}]... | 11ba832fad817a91c40cee567721c1fdde37041d | 624,626 |
def _imshow_formater(arr):
"""Creates a formating function to show the values of imshow in the status
bar.
:param arr: Array to be shown
:returns: function formater(x, y) that should be set to ax.format_coord
"""
def format_coord(x, y):
col, row = int(x + .5), int(y + .5)
if (c... | 8ef4657c441a5c1ae565a2ebf1312eecd689095b | 624,627 |
def _copy_dir_entry(workdir: str, user_id: int, user_group: int,
dirname: str) -> str:
"""Returns the Dockerfile entry necessary to copy a single extra subdirectory
from the current directory into a docker container during build.
"""
owner = "{}:{}".format(user_id, user_group)
return """#... | a9ae168d2bd350a8b8d6a9692e4baf661bec39ef | 624,630 |
def collatz_sequence_length(starting_value: int) -> int:
"""
Given solution relies on just calculating the length, which takes out the longer and more
expensive collatz calculation that requires storing the sequence. Passing the integer parameter
is cheaper than storing, appending, and passing a list da... | 6647038f06a794de9e8dbbeed7d9dca753f166f1 | 624,640 |
def has_admin_privileges(user):
"""Return whether the specified user has admin privileges."""
# Finding this is the point of the challenge...
return user["position"].lower() == "admin" | b81f0c4faf69ae60ba7f5d43084c09fdf6f7c90f | 624,643 |
import csv
def load_urls(src):
"""
Load given url file csv into memory.
It assumes that only two columns are present. One is key, other is value.
"""
with open(src) as f_h:
data = csv.reader(f_h, delimiter=",")
return dict((int(row[0]), row[1]) for row in data) | 552b17cab44a2a2d0793b56f4ba39261634b0d89 | 624,644 |
def _is_num(x):
"""Return: True if x is an int or float"""
return type(x) in [int,float] | 4d1e41ccd2017e71853db3fe1eb85a7384c4e9f0 | 624,646 |
def strftime(datetime, formatstr):
"""
Uses Python's strftime with some tweaks
"""
# https://github.com/django/django/blob/54ea290e5bbd19d87bd8dba807738eeeaf01a362/django/utils/dateformat.py#L289
def t(day):
"English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'r... | bc748022e5e85c52c70f781c2c5b3bdfdaa1ecc6 | 624,647 |
def get_heart_rate(message_fields):
""" get_heart_rate
return the heart rate as float from a message.as_dict()['fields'] object
Args:
message_fields: a message.as_dict()['fields'] object (with name 'record')
Returns:
heart rate in bpm or 50. if not found
"""
for message_field i... | e28f004e14fa0711c24f0ccdf79c83408e58cf04 | 624,649 |
def drake(Rs, fp, ne, fl, fi, fc, L):
"""
Ecuación de Drake.
Parámetros
----------
Rs : float
Tasa anual de formación de estrellas en la
galaxia.
fp : float
Fracción de estrellas que tienen planetas en su órbita.
ne : float
Número de esos planetas orbitando d... | 87f7514c72305082905984157db79267dc80912a | 624,656 |
def tile_to_quadkey(tile_x, tile_y, level):
"""This is a function that converts tile coordinates at a certain
level of detail of a Bing Map to a unique string identifier (QuadKey).
:param tile_x: The x axis coordinate of the tile at `level` level of detail
:param tile_y: The y axis coordinate of th... | 6416511a03e4bb65eef969fa223aacbb18b8ee32 | 624,657 |
import sqlite3
def create_abundance_dict(database, datasets):
"""Process the abundance table by dataset in order to create a dictionary
data structure organized like this:
transcript_ID -> dataset -> abundance in that dataset
"""
abundance = {}
conn = sqlite3.connect(database)
... | 973bf185d5d83be7c738ec0dd1c4c8d39202ff5c | 624,658 |
import pkg_resources
import pathlib
def _get_ee_sources_path() -> str:
"""Gets the ee-sources folder path.
Returns:
The ee-sources folder path.
"""
ee_extra_py_file = pkg_resources.resource_filename("ee_extra", "ee_extra.py")
pkgdir = pathlib.Path(ee_extra_py_file).parent
return pkgdi... | 150c703871825968eab3b4b737b0a132dba63a2d | 624,659 |
def merge_optional_trees(tree, big_tree):
"""Merge two MacroConditionTrees when one or both objects may be `None`."""
if tree is not None:
if big_tree is None:
return tree
else:
return big_tree.merge(tree)
else:
return big_tree | b8aaad8d595bf5dd9848bd7df37222044f34a604 | 624,662 |
def ibis_test_file(tmp_path):
"""Return a golden ibis model file to test with."""
ibis_file = tmp_path.joinpath("test.ibs")
with open(ibis_file, "w", encoding="UTF-8") as output:
output.write(
r"""[IBIS Ver] 5.1
[File Name] example_tx.ibs
[File Rev] v0.1
[Date] 2019-02-10
... | 15e8c0c257c968f91eff21fd515cbec7521c4a1d | 624,665 |
def _calc_trsp_at_density_levels(trsp_ds, rho_w, rho_s, ufld, vfld, lat=None):
"""Helper function to compute transport at binned density levels
given the maskW and maskS. Extracted here to do the same operations for
latitude or section masks
Parameters
----------
trsp_ds : xarray Dataset
... | a22ca4c899c821179d17be39cc3b5197a3722b70 | 624,670 |
def tower(n):
"""computes 2^(2^(2^...)) with n twos, using recursion"""
if(n==0):
return 1
return 2**tower(n-1) | 30554f29eee5498d06910d580afaaa606894a83a | 624,671 |
import re
def _single_quote_strings(sql: str) -> str:
"""Replace unquoted double-quotes with single-quotes."""
return re.sub(r"(?<![\\])\"", "'", sql) | 8cb5cda475b0e1cbb60dc85cbdb4354741fd5ae4 | 624,673 |
def random_state_tuple_axis_1(request):
"""
Specific to `test_sample*_axis_1` tests.
A pytest fixture of valid `random_state` parameter pairs for pandas
and cudf. Valid parameter combinations, and what to check for each pair
are listed below:
pandas: None, seed(int), np.random.RandomState
... | aa9a7d6d916dcac0ae89c91b3ac735b7175329fe | 624,675 |
def _mul(x, y):
"""
Multiply x and y.
:param x: First element
:param y: Second element
:return: The multiplication result of x and y.
"""
return x * y | 132ce1678014de9512b73ead87cb53cfa3baaf46 | 624,676 |
def is_overlap(object1, object2):
"""Detects overlap between two rectangles.
Taking two objects, detects whether they overlap.
Assumes the presence of the following attributes:
- x
- y
- width
- height
Tests whether the rectangles are above/below each other, or
left/right of ea... | 648ea314a76cdd00d757239afbe1200cfad880f4 | 624,678 |
def lst_depth(lst):
"""Check max depth of nested list."""
if isinstance(lst, list):
return 1 + max(lst_depth(item) for item in lst)
return 0 | d94ba4ae4076fe9ad9685f89f8cfcb4540ace2d0 | 624,679 |
def is_operator(node):
"""This function checks whether a validation node is an operator or not.
Args:
node(str): The node key you want to check.
Returns:
: bool.
"""
return node.startswith('$') | fe8136058b924f9831af1dba3d67c2bf5ed30687 | 624,682 |
import re
def remove_punctuation(body):
"""
- Removes punctuation, symbols, and numbers
- Changes to lower case
- Strips new lines and extra spaces
Args:
body: a body of text
Returns:
A string with clean-up procedures applied
"""
punctuation_removed = re.sub(r'[^\sa-zA-... | f2ce17029f998d4be2a897999ed7cc1f27f9f0d2 | 624,688 |
def convertToCPM(dose, period):
"""
Converts from milliSieverts/hr to CPM
Parameters:
dose (double): The dosage
period (double): The time period over which the dosage
is administered
Returns the measurement in CPM
"""
conversionFactor = 350000 / 1.0
return conversionFactor * dose / period | 1ec1f1b49c2596496b0b3dc6fe857fdea1e776c0 | 624,694 |
from typing import List
def _read_from_path(config:dict, path:List[str]):
"""Reads nested dictionary.
Eg `_read_config({'foo':{'bar':1}}, ['foo','bar']) = 1`
"""
if len(path) == 1:
return config[path[0]]
return _read_from_path(config[path[0]], path[1:]) | ec1b6917ca854cdb90c6b82a5833433428a83be5 | 624,696 |
def should_cache_download(url: str) -> bool: # pragma: no cover
"""
Determine whether this specific result should be cached.
Here, we don't want to cache any files containing "-latest-" in their filenames.
:param url: url string which is used to decide if result is cached
:return: When cache shou... | 8406668267b7e6b20b16a020646092547aee78cd | 624,699 |
def smallest_with(expr, symbol):
"""
Return the smallest sub-tree in an expression that contains a given symbol.
"""
assert symbol in expr.free_symbols
candidates = [arg for arg in expr.args if symbol in arg.free_symbols]
if len(candidates) > 1 or candidates[0] == symbol:
return expr
... | b20f6bd35359557e0ceea28c27bcf9f2a9b436ba | 624,701 |
def pipe_commands(commands):
"""Pipe commands together"""
return ' | '.join(commands) | b90bd203c3a6ff7fa57701425d0551ee98d5c0b6 | 624,704 |
def parseColorLine(ls, keys, flags=set()):
"""
>>> parseColorLine("CODE 0 VALUE #05131D FOO".split(), {"CODE", "VALUE", "EDGE", "BAR"})
({'CODE': '0', 'VALUE': '#05131D'}, set())
"""
d = {}
s = set()
for idx, val in enumerate(ls):
if val in keys and idx+1 < len(ls):
d[val... | 0cd1fddd490990fb57769f9dc1f4c37ba138eba0 | 624,707 |
import json
def get_json(x):
"""Convert Python dict to JSON.
Convert Python dictionary into a JSON string.
Args:
x: Python dictionary
Returns:
JSON string
"""
return json.dumps(x) | bb7c5625834ecc56daba6f71ac7204b5fb38408b | 624,708 |
def max_degree(graph):
""" Return the maximum degree in the graph """
return max(graph.degree, key=lambda kv: kv[1])[1] | f0ce7063df056bdd6046a496eee44ad7f219e32b | 624,715 |
def sequential(inputs,
layers,
):
"""Applies a sequence of layers to an input."""
output = inputs
for layer in layers.values():
output = layer(output)
return output | 7005dccf74bad55afa44747249d1802ee0bc03db | 624,716 |
def unscramble(word, unscramble_map: dict) -> str:
""" Takes a scrambled input word, and converts to unscrambled.
Args:
word (str): Scrambled input
unscramble_map (dict): Map of scrambled char->unscrambled char """
return "".join(sorted([unscramble_map[char] for char in word])) | aecb8bd551f4250ced3dd1634d4689bf3ecbfd16 | 624,717 |
def assert_params_all_zeros(module) -> bool:
"""Check if the parameters of the module is all zeros.
Args:
module (nn.Module): The module to be checked.
Returns:
bool: Whether the parameters of the module is all zeros.
"""
weight_data = module.weight.data
is_weight_zero = weight_d... | a00ccc7fa8718d97df71f3c21bed39c09bc4a9a2 | 624,718 |
def prepend_parts(parts_prefix, n):
""" Recursively preprend parts_prefix to the parts of the node
n. Parts is a list of markers that indicates where you are in the
regulation text. """
n.label = parts_prefix + n.label
for c in n.children:
prepend_parts(parts_prefix, c)
return n | 37a11e2ff2b0b3a633e372d0488412f568522163 | 624,732 |
import warnings
import copy
def clone_trainer(trainer, is_reinit_besides_param=False):
"""Clone a trainer with optional possibility of reinitializing everything besides
parameters (e.g. optimizers.)"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
trainer_new = copy.deep... | fc65f663665265fa31a5cd0bcca2e5b05464e079 | 624,734 |
def onlydigits(value):
"""
Filtre `value` pour ne garder que les chiffres.
On peut ainsi retirer toutes les sauts de lignes présents
dans le fichier `score.txt`.
Parameters
----------
value : str
La chaîne à filtrer
Returns
-------
str
La chaîne obtenue après f... | 46d0c8c271bbec3e49792dbab6183e982b107387 | 624,735 |
def get_same_padding(kernel_size):
"""Return SAME padding size for convolutions."""
if isinstance(kernel_size, tuple):
assert len(kernel_size) == 2, 'invalid kernel size: %s' % kernel_size
p1 = get_same_padding(kernel_size[0])
p2 = get_same_padding(kernel_size[1])
return p1, p2
... | e7e5cbc2f87543015731fe50560708f2fb68ff16 | 624,738 |
def _tofloat(obj):
"""Convert to float if object is a float string."""
if "inf" in obj.lower().strip():
return obj
try:
return int(obj)
except ValueError:
try:
return float(obj)
except ValueError:
return obj | 6d4bea95cf4e13d929ea8f5d50b87f28af896a92 | 624,739 |
def rtf_encode(text):
"""
Convert unicode text to rtf format with substitution of non-ascii
characters. (Based on Martijn Pieters' code.)
"""
return ''.join(['\\u%i?' % (ord(e) if e < u'\u8000' else ord(e) - 65536) if (e > '\x7f' or e < '\x20' or e in u'\\{}') else str(e) for e in text]) | 2fb4a0f9a0326320fee6ac965319c9e2f1897fd9 | 624,740 |
from pathlib import Path
def get_project_path(project_name: str) -> Path:
"""Get the assets project path for the given project name (with no ".flxproj").
If you want to open the project, please use open_project() or copy_project() instead,
as they will copy the project to a temporary directory and clean ... | 05a5c4cb18b4e7b239da258fd6ca87185a0dec1c | 624,741 |
def mirror_from(source, attributes, only_getters=True):
"""Decorator (factory) for classes that mirror some attributes from an
instance variable.
:param source: the name of the instance variable to mirror from
:param attributes: list of attribute names to mirror
:param only_getters: if true only ge... | f40fb88b6982e5520aa740d334bd8eb1897d4024 | 624,742 |
def get_netcdf_response(coverage_offering, dataset, crs):
"""Uses a standard xarray function to create a bytes-like data stream for http response"""
dataset.attrs['crs'] = crs
return dataset.to_netcdf() | 1289f522133f663f26ca13bad7d2820619c328a9 | 624,743 |
def echo(s):
"""Return the string passed in."""
return "We are echoing: %s" % s | 770497efe8d9b5662eae3811f59f155fc9202f43 | 624,746 |
import math
def round_up(x, near):
"""
Round x to nearest number e.g. round_up(76, 5) gives 80
Args:
x: Number to round-up
near: Number to which round-up to
Returns:
rounded up number
"""
return int(math.ceil(float(x) / float(near))) * near | f0726917905a363cbea3547a0cf03fcf8c1ee109 | 624,747 |
def get_penalty(start_time, submit_time):
"""
:param start_time: time in DateTimeField
:param submit_time: time in DateTimeField
:return: penalty in seconds
"""
return max(int((submit_time - start_time).total_seconds()), 0) | a97e3fc4ea2853ccd3c73f41d807023ae00e353c | 624,748 |
def cleanFilePaths(file, listOfResults, type=None):
"""
Constructs the data which consists of a dictionary within a dictionary.
The first level has keys that are the data file name, and the second
level contains two keys: saved and read. Within 'saved' and 'read'
are a list that contains the scripts... | a3f4306fdc2c7bf623075c31a0e6a591bc6facd1 | 624,751 |
def qe_at(df, energy):
""" Extracts QE at the specified energy.
"""
return df[df.E >= energy].sort_values(by='E', ascending=True).iloc[0].QE | 0473fea95bb6c4f09432556b19217b9bd58f31fe | 624,753 |
def dot(u1,u2):
""" Dot product of two vectors """
return u1[0]*u2[0] + u1[1]*u2[1] + u1[2]*u2[2] | 740f613598b2a725b26ad8f685f63b2cd5ce7ebd | 624,756 |
def exists_jpg_extension(files):
"""Checks whether any file in files is a jpg image
Args:
files: List of filenames
Returns:
True if any file is a jpg otherwise False
"""
has_jpg_extension = ['jpg' in fname for fname in files]
return any(has_jpg_extension) | 342846e89c52b3f791b5eadc4c99638f6d309596 | 624,759 |
import string
def num_to_str(num, b=36, numerals=string.digits + string.ascii_lowercase):
"""
Converts integer num into a string representation on base b
@param b {int} base to use
@param numerals {string} characters used for string representation
@returns {string} string representation of num in ... | 8d19813fdbc72bffbdc23659b9d8afa1b77cbc41 | 624,763 |
def UppercaseMutator(current, value):
"""Uppercase the value."""
return current.upper() | ee16c6a92cd7e3f4d55859d22ab7a23c0a39af9b | 624,764 |
def seconds_until_start(start_time, current_time):
"""Return the number of seconds until start time"""
difference = start_time - current_time
return difference.seconds | 9bb93199c854be392970b789b7906e90f93e0aa2 | 624,771 |
def n_subsystems(request):
"""Number of qubits or qumodes."""
return request.param | af17deedd29ab69e31ec36c0de17ecc79ab67598 | 624,773 |
import base64
def img_stream_to_b64str(stream, urlsafe=False):
"""
Convert a byte stream of image file to Base64 encoded string.
:param stream: The byte stream of the file.
:param urlsafe: Trigger using URL-Safe format.
:return: Encoded Base64 string.
"""
if urlsafe:
stream_base64 ... | cc132c0e24f7153beb45ddbc8d66b82dedcc18c0 | 624,775 |
def area(circle):
"""Get area of a circle"""
return circle.get('radius') ** 2 * 3.14159 | 5d64b5fcfe8d82bc994e2e12aeab90c276943fa5 | 624,780 |
def get_reference_source(lockin):
"""Get the reference source. Return either internal (1) or external (0).
args:
lockin (pyvisa.resources.gpib.GPIBInstrument): SRS830
returns:
(int): 1 for internal, 0 for external.
"""
return int(lockin.query("fmod?").split("\n")[0]) | 21c4dabba2312976be4cfbb1837af3ec83863bb0 | 624,782 |
from datetime import datetime
def get_tag(tag=None):
"""
Simple helper function to create a tag for saving a file if one does not already exist.
This is useful because in some places we don't know whether we will have a tag or not,
but still want to save files.
Parameters
----------
tag ... | 5cecc708086dbcb1a7361ecf55dd015f9edaeedf | 624,785 |
def array_to_dict(rows, key="openstack_id"):
""" Convert a list of dicts into a dict based on key"""
result = {}
for row in rows:
key_value = row.pop(key)
result[key_value] = row
return result | 73e7697df11ff3cbff458e4fe7f434e458c296c8 | 624,786 |
def is_(t, x):
""" Check whether the type of a given x is a given type t.
"""
return type(x) is t | 275809e23e38a4785c3f7f7509305b72864db108 | 624,789 |
import socket
def dnsname(ip):
"""Returns the DNS hostname of the provided IP address if it's in DNS (PTR record)"""
try:
return socket.gethostbyaddr(ip)[0]
except:
return 'null' | 43ccd2b89aeadcc65a2d689532252fb28603b6f6 | 624,793 |
def first_differences(signal):
"""The mean of the absolute values of the first differences of the raw signal"""
# build the first differences list
first_diff = []
for i in range(0,len(signal)-1):
first_diff.append(abs(signal[i+1]-signal[i]))
fd_sum = sum(first_diff)
delta = float(fd_sum)/(len(signal)-1)
retur... | b0f2d95f945dc80541521fcb2a59ca704af73221 | 624,802 |
def extract_components_from_flow(flow):
"""Given a versionedFlowSnapshot object, extract out the processors
and create a list of tuples where each tuple is
(component name, component version)"""
extract = lambda p: (p["bundle"]["artifact"], p["bundle"]["version"])
return [ extract(p) for p in flow["... | 90e8099b53416d12c0912407a76c0fc938d114e0 | 624,804 |
import re
def format(changelog):
"""Clean up changelog formatting"""
changelog = re.sub(r"\n\n+", r"\n\n", changelog)
return re.sub(r"\n\n+$", r"\n", changelog) | 6514e96a050e14d8d461bfd8e966c780a2b67c00 | 624,808 |
def my_extract(value, delim=',', index=0):
"""Split a given string and return value at given index position."""
return value.split(delim)[index] | 43c179f3468775fbcd2be942fa02f4fe0897eb5f | 624,811 |
def parse_percent(val):
"""Turns values like "97.92%" into 0.9792."""
return float(val.replace('%', '')) / 100 | 5ae9c2d90cac68aec47fc624253b9c9fa3bf1d7a | 624,813 |
def log_target_types(all_logs=False, **kwargs):
"""
Log targets for log tasks. A log target defines the log types
that will be affected by the operation. For example, when creating
a DeleteLogTask, you can specify which log types are deleted.
:param bool for_alert_event_log: alert events traces... | 2345e25f394ae8be8ac1c4c4fdbb9e4c83e54b22 | 624,814 |
def mblg_to_mw_johnston_96(mag):
"""
Convert magnitude value from Mblg to Mw using Johnston 1996 conversion
equation.
Implements equation as in line 1654 in hazgridXnga2.f
"""
return 1.14 + 0.24 * mag + 0.0933 * mag * mag | f23acde1063c9c0f4c13a5d3679bf7e894fd6a00 | 624,816 |
def interactions(G, nbunch=None, t=None):
"""Return the list of edges present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
G : Graph opject
DyNetx graph object
nbunch : ite... | d6607c52e014dc4591152aa81d620a494b4582c5 | 624,821 |
def weasyl_sysname(target):
"""Return the Weasyl sysname for use in a URL for a given username."""
return ''.join(i for i in target if i.isalnum()).lower() | 6be503fda69ecf4ca27ebb43bde680373e40b84b | 624,823 |
def set_of_words2vec(vocab_list, input_set):
"""
句子转换为向量,如果字典中有这个词则将该单词置1,否则置0
:param vocab_list: 所有单词集合列表
:param input_set: 输入数据集
:return: 匹配列表[0,1,0,1...],其中 1与0 表示词汇表中的单词是否出现在输入的数据集中
"""
# 创建一个和词汇表等长的向量,并将其元素都设置为0
result = [0] * len(vocab_list)
# 遍历文档中的所有单词,如果出现了词汇表中的单词,则将输出的文档向... | a8460bd3a3b7ca45aea0cea4c9722c4514f678ed | 624,825 |
def by_date_range(analysis, from_timestamp, to_timestamp):
"""
Filters list of analysis objects with attribute "createdDate".
Returns a new list of analyses objects that were created between from_timestamp and to_timestamp
:param analysis:
:param from_timestamp: unix timestamp (float)
:param to_... | 580d250a2e71ccbfac0be9b7f3deabcc44de6264 | 624,826 |
import torch
def log_bound_and_scale(scale, bounds):
"""
Scale, de-log, and bound
Args:
scale (torch.tensor): divide input by this value, then take exp
bounds (torch.tensor): tuple, clamp to (bounds[0], bounds[1])
"""
return lambda x: torch.clamp(torch.exp(x / scale), bounds[0]... | 55c6393924a0ec8abe8a953a9430618d5839b95c | 624,829 |
import struct
import binascii
def make_chunk(chunk_type, chunk_data):
"""Create a raw chunk by composing chunk type and data. It
calculates chunk length and CRC for you.
:arg str chunk_type: PNG chunk type.
:arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**.
:rtype: bytes
"""
out... | 19843007bdde2b74182c80a6b03404db131735f8 | 624,834 |
def is_iterable(value):
# noinspection PyUnresolvedReferences
"""
Returns ``True`` if *value* is an iterable container (e.g. ``list`` or ``tuple`` but not a **generator**).
Note that :func:`is_iterable` will return ``False`` for string-like objects as well, even though they are iterable.
The same a... | 8666b84d9d41db4bafcdb1f6e2984e702b2a4eba | 624,838 |
def encrypt(plaintext, key, cipher):
"""
Using Vignere cipher to encrypt plaintext.
:param plaintext: plaintext to encrypt with given key and given cipher
:param key: the key is appended until it has same length as plaintext;
each character of the key decides which cipher to use to
... | 9aa3d75077f6ae8c7b033e4e979109f76767b483 | 624,839 |
import inspect
def is_class(object):
"""Check if the given object is a class"""
return inspect.isclass(object) | a49a6d4ea7dd01070bb59d9f787e7eb2a9641a16 | 624,841 |
def init_guess_word(length):
"""
Returns the initial guess word state.
The guess word is initialised with underscores, one for each letter
of the target word.
Args:
length: the length of the target word
Returns:
The initialised guess word, a list of `length` underscores
... | 5e02354b31d93e934ca49fa488be7e8816635913 | 624,842 |
def gcp_histone_normalize(data_df, gcp_normalization_peptide_id):
"""Subtract values of gcp_normalization_peptide_id from all the other probes.
Remove the row of data corresponding to the normalization histone.
Assumes that all probes should be normalized to the same peptide id.
Args:
data_df ... | d7dc0b386f43851391f2834714ba778f748a6c16 | 624,843 |
def HHMM_to_dec_deg(HHMM):
"""Converts a string HHMM to decimal hours."""
return 15*(int(HHMM[0:2])+float(HHMM[2:4])/60.) | fb183f3f2935e9d104532285e560a6a4fe14233b | 624,844 |
def get_tagname(tags, tagid):
"""Get tag name from tag ID from extracted Ghost tags."""
for tag in tags:
if tag['id'] == tagid:
return tag['name'] | 97a434ebad9711b637b64f9e06c87f264e1f22f0 | 624,845 |
def aggregate_values_by_key(rdd):
"""Given an RDD in the form of:
``RDD[(0, 1), (0, 2), (1, 2)]``
Aggregate each key (first index in the tuple) into an RDD of
keys to lists of all values associated with the key.
Examples
--------
>>> x = sc.parallelize([("a", 1), ("b", 1), ("a", 2)])... | 9079b96f3e9e656b78c544f4c1a8ab1aa9d733ff | 624,847 |
def generate_num_processes_default(AUTOMS_NUM_PROCESSES):
""" Generates the default num processes parameter value to use using configured 'num processes' """
if AUTOMS_NUM_PROCESSES is None:
num_processes_default = 1
else:
num_processes_default = AUTOMS_NUM_PROCESSES
return num_proces... | b6c2109eaad9def8e4dcc3ea41726eed6d685cd3 | 624,848 |
import six
def as_bool(val):
"""Converts an arbitary value into a boolean."""
if isinstance(val, bool):
return val
if isinstance(val, six.string_types):
if val.lower() in ('f', 'false', '0', 'n', 'no'):
return False
if val.lower() in ('t', 'true', '1', 'y', 'yes'):
... | 953dd42888115a7fdccf07c286a7261bd6a6d5d9 | 624,850 |
def populated_table(empty_table, request):
"""
Populate a table within the test database before executing test.
The table will have the same name as the test_function itself. Setup and teardown
of the database is handled by the unique_database fixture.
Args:
empty_table: pytest fixture that creates an e... | 2e018ed0c04510ed574b9b01cf4e30e44d035a9e | 624,853 |
def find_image(text: str) -> int:
"""Function to find if pdf has image only page.
text: text version of pdf document
return: 1 if image was found, 0 otherwise
"""
list_of_pages = text.split('\x0c')[:-1]
page_number = 0
found_image = 0
while page_number < len(list_of_page... | 95022e1263c53290b64ce61d665a5c0e305dfcc7 | 624,860 |
def _totalValue(comb):
""" Total a particular combination of items
Args:
comb tuple of items in the form (item, weight, value)
Returns:
tuple (total value, total weight)
"""
totwt = totval = 0
for item, wt, val in comb:
totwt += wt
totval += val
return (totval, totwt) | 2e01a9ee807f6879f8df7a2fdd5a87d620a9e997 | 624,864 |
def default_income(time, dt, *args):
"""
Income method stub
:param time: current simulation time
:param dt: time step for which production limits are calculated
:param args: additional arguments
:return: 0
"""
return 0 | ff4a99f84364d8a3873ff38cbd08c3e9d0732db6 | 624,865 |
def avg(list):
"""Find average value in a list or list-like object"""
return sum(list) / len(list) | 6c2944b042fee4a080bff348bf056cce19d1ae77 | 624,872 |
def distance(x, y):
""" Calculate the euclidean distance between two point in three dimensional space. """
return ((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2) ** 0.5 | b4ebd3831889b08d16e342d185782bb361e9c8ed | 624,880 |
def d_y_diffr_dy(x, y):
"""
derivative of d(y/r)/dy
equivalent to second order derivatives dr_dyy
:param x:
:param y:
:return:
"""
return x**2 / (x**2 + y**2)**(3/2.) | 8165fc947632b2dcd2d635d946abb6bb15940b57 | 624,881 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.