content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import pathlib
def get_path_name(name: pathlib.Path | str | None) -> pathlib.Path | str:
"""Get the full name from a directory name or path and a file name or path.
Args:
name (pathlib.Path | str | None): Directory name or file name.
Returns:
str: Full file name.
"""
if name is N... | 0eb4abd9cf82f022d0a0c3d380fab3e750c183d3 | 25,184 |
def getFirstLineContaining(lines, keyLineStart):
"""
Given a split abfinfo text, return a stripped value for the given key.
"""
for line in lines:
if line.startswith(keyLineStart):
line = line.replace(keyLineStart, "")
line = line.strip()
return line
retur... | ea9128d51d0d32075c212f3f11306b8cbb9f0fb6 | 25,189 |
def tokenize(name):
"""Turn a string into a list of character tokens."""
#name = name.lower() #ignore cases
characters = [c for c in name] #make a list of characters
characters = ['<START>'] + characters + ['<STOP>'] #add beginning and end token
return characters | 9ed489baf16b6e91f67ed74c1f77c3c40205147e | 25,190 |
def hex(n):
"""render the given number using upper case hex, like: 0x123ABC"""
return "0x%X" % n | 2759c53b50214b138da8c986820b3acc61ed0ab2 | 25,191 |
def es_index_successful(response):
"""
Test if an Elasticsearch client ``index`` method response indicates a
successful index operation. The response parameter should be a dictionary
with following keys:
.. sourcecode:: python
{
'_shards': {
'total': 2,
... | e76e84d8461078da03f820089297ea9ca28f0911 | 25,195 |
def verify_header(filename):
"""
verify the signature file header (pastadb)
"""
with open(filename, "rb") as f:
if f.read(7) == "\x70\x61\x73\x74\x61\x64\x62":
return True
return False | 5958179b0656ac7b4e8681e20d2746176592da3a | 25,196 |
import requests
def _request_limit_reached(exception):
""" Checks if exception was raised because of too many executed requests. (This is a temporal solution and
will be changed in later package versions.)
:param exception: Exception raised during download
:type exception: Exception
:return: `Tru... | 67280ea48cce3238d0c574ec8ad1b13719df4990 | 25,197 |
import tempfile
def make_environment(case, method='HEAD', path=u'/', qs=None, host=None,
server_name='localhost', port=80, script_name='',
url_scheme='http', headers={},
content_type=None, content_length=None,
http_protocol='http/1.1'... | 4b2fdd959fa538478b9166f5ade0d157847eb7ca | 25,202 |
from typing import List
def parse_raw_value(raw_value: str, linesep: str) -> List[List[str]]:
"""Parse raw values from VEP"""
parsed = list()
for line in raw_value.strip().split(linesep):
# This is the regular case
if "\t" in line:
parsed.append(line.split("\t", 1))
# S... | 4ce5fff141628c553f59e87e9beb4174bd400a19 | 25,208 |
def format_datetime(dt):
"""
Returns ISO 8601 string representation
"""
return dt.isoformat() | fbbdec6086618f94826a69230b88bfa9e79ca472 | 25,213 |
def get_labelled_groups(labelled_measures_table, labelname):
"""
Provides a simple way of splitting a labelled measures table into multiple tables each corresponding to a given label.
Args:
labelled_measures_table (Dataframe): A measures table with a column corresponding to a label.
labelname (String): The n... | 40bacfaf0044185034fde3a0eb31f7e1ab7a94ad | 25,217 |
def _antnums_to_blpair(antnums):
"""
Convert nested tuple of antenna numbers to baseline-pair integer.
A baseline-pair integer is an i12 integer that is the antenna numbers
+ 100 directly concatenated (i.e. string contatenation).
Ex: ((1, 2), (3, 4)) --> 101 + 102 + 103 + 104 --> 101102103014.
... | 47cbdee6212ae4a2857df3578b5755c98d928d55 | 25,221 |
def get_user_html(user):
"""Return standard HTML representation for a User object"""
return (
'<a title="{}" href="mailto:{}" data-toggle="tooltip" '
'data-placement="top">{}'
'</a>'.format(user.get_full_name(), user.email, user.username)
) | d988e872266767ea23f23836dcd588d74b0060a8 | 25,222 |
from typing import Dict
from typing import Any
def dict_without(dictionary: Dict[Any, Any], without: Any) -> Dict[Any, Any]:
"""
Remove a key from a dictionary and return the copy without.
"""
new = dictionary.copy()
new.pop(without)
return new | 4008e7e56690363e58da41f272e93ebf88ccd907 | 25,224 |
def map_rows_to_cols(rows, cols):
"""
Returns a list of dictionaries.
Each dictionary is the column name to its corresponding row value.
"""
mapped_rows = []
for row in rows:
mapped_rows.append({cols[i]: row[i] for i in range(len(cols))})
return mapped_rows | 9efb7d48f69d5bab8d910cbedd75f4c4d001ef7b | 25,227 |
def clean_side_panel(sidepanel):
"""
Cleans the SidePanel data and stores it in a dict.
Parameter:
sidepanel: html-sidepanel extracted using bs4
Returns:
data: dict of extracted data
"""
data = dict()
for x in sidepanel:
x = x.text.strip().replace('\n', '')
... | c9fab309b64b788283e0848a0777fd3ef80014ad | 25,228 |
from typing import OrderedDict
def object_attributes_to_ordered_dict(obj, attributes):
"""Returns the specified attributes from the object in an OrderedDict."""
dict = OrderedDict()
object_vars = vars(obj)
for attribute in attributes:
dict[attribute] = object_vars[attribute]
return dict | 2aa1e75669bbe13f8d3fa238dc0c2bb681aa8b72 | 25,232 |
def _get_object_info_from_revision(revision, known_type):
""" returns type and id of the searched object, if we have one part of
the relationship known.
"""
object_type = revision.destination_type \
if revision.source_type == known_type \
else revision.source_type
object_id = revision.destination_... | e8f73296f0d7080c6290148142dd3d2902646ed1 | 25,234 |
def get_transitions(sequence):
"""
Extracts a list of transitions from a sequence, returning a list of lists containing each transition.
Example
--------
>>> sequence = [1,2,2,1,2,3,2,3,1]
>>> ps.get_transitions(sequence)
[[1, 2], [2, 1], [1, 2], [2, 3], [3, 2], [2, 3], [3, 1]]
"""
transitions = []
for pos... | 25c2e7de0f4701517c1f41f466a3710a7f124c4d | 25,240 |
import traceback
def exception_to_string(e: Exception) -> str:
""" Convert exception to printable string """
stack = traceback.extract_stack()[:-3] + traceback.extract_tb(e.__traceback__)
pretty_out = traceback.format_list(stack)
return f"{pretty_out}\n {e.__class__} {e}" | b5b0e873dd3ad2d923d0cc16de5ab4016e73565e | 25,242 |
def get_dependent_nodes(nodes):
"""Get all dependent nodes connected to the list of nodes.
Looking for connections outside of the nodes in incoming argument.
Arguments:
nodes (list): list of nuke.Node objects
Returns:
connections_in: dictionary of nodes and its dependencies
co... | 3a436fa704226f7466761a2b87a71ba91ca419b3 | 25,245 |
import math
import torch
def gaussian_probability(sigma, mu, data):
"""Returns the probability of `data` given MoG parameters `sigma` and `mu`.
Arguments:
sigma (BxGxO): The standard deviation of the Gaussians. B is the batch
size, G is the number of Gaussians, and O is the number of
... | 5757e051af16b692fba9e483990df1d5c4fd3870 | 25,247 |
def length(head) -> int:
"""
The method length, which accepts a linked list
(head), and returns the length of the list.
:param head:
:return:
"""
i = 0
if head is None:
return 0
while head.next is not None:
head = head.next
i += 1
return i + 1 | f1ad7c64dc15620340f505671281e59267eb4b2b | 25,248 |
def Mabs2L(Mabs,MUVsun=5.5):
"""
Converting absolute magnitude(s) to luminosity in erg/s
Using a default absolute magnitude of the sun (in UV) of 5.5 from http://www.ucolick.org/~cnaw/sun.html
"""
Lsun = 3.839e-11 # 1e44 erg/s
Lobj = 10**((MUVsun-Mabs)/2.5)*Lsun # Luminosity in er... | 85a6f7b1e58dbc086a7dd36659e76b37849a8b04 | 25,249 |
def list_prod(lst):
"""
Calculate the product of all numbers in a python list.
"""
prod = 1
for itm in lst:
prod *= itm
return prod | b0f5911e6eeb289aae7efe7f1fe99a2ca0f83cc4 | 25,251 |
def convert_member(member_str):
"""
Convert member data from database to member id list
:param member_str: Data from Class database
:type member_str: str
:return: a list of member id as integer
:rtype: list
>>> print(convert_member("1,2,50,69"))
[1, 2, 50, 69]
"""
if (member_st... | fec4081104c3cb4574e255c8408164062a287963 | 25,256 |
def is_palindrome(s):
"""
What comes in:
-- a string s that (in this simple version of the palindrome
problem) contains only lower-case letters
(no spaces, no punctuation, no upper-case characters)
What goes out: Returns True if the given string s is a palindrome,
i.e., r... | 41409a3681c6f5c343f19fc53823415852243d45 | 25,258 |
def number_of_pluses_before_an_equal(reaction):
"""
Args:
reaction (str) - reaction with correctly formatted spacing
Returns (int):
number_of - the number of pluses before the arrow `=>`
Example:
>>>number_of_pluses_before_an_equal("C6H12O6 + 6O2=> 6CO2 + 6H2O")... | f532ee41dee797d7c2ae1639fae9f1cb61c3f037 | 25,260 |
import random
def generate_chromosome(min_length_chromosome, max_length_chromosome, possible_genes, repeated_genes_allowed):
""" Function called to create a new individual (its chromosome). It randomly chooses its length (between min_length_chromosome and min_length_chromosome), and it randomly chooses genes amon... | aae0356538958bfe180b3f0abade7afd5dc2e7f7 | 25,261 |
def binary(x: int, pre: str='0b', length: int=8):
"""
Return the binary representation of integer x
Input:
x: an integer of any size
pre: the prefix for the output string, default 0b
length: length of the output in binary if its representation has smaller length
defau... | 287e5bb87f31b71ad7ccd1cf65fab729794eeef4 | 25,262 |
import inspect
def library(scope=None, version=None, converters=None, doc_format=None, listener=None,
auto_keywords=False):
"""Class decorator to control keyword discovery and other library settings.
By default disables automatic keyword detection by setting class attribute
``ROBOT_AUTO_KEYWO... | 78b3a7c2423d0b594d5d8f4e564b929f2ef7148a | 25,265 |
def false(*args):
"""
>>> false(1)
False
>>> false(None)
False
"""
return False | cb960acdc5ddb7a2a54d1a69165fc684674b34fe | 25,266 |
def reflection_normal(n1, n2):
"""
Fresnel reflection losses for normal incidence.
For normal incidence no difference between s and p polarisation.
Inputs:
n1 : Refractive index of medium 1 (input)
n2 : Refractive index of medium 2 (output)
Returns:
R : The Fresnel
Doctests:
... | db3e1779628116ce2d82a91dada64aa2d8ff4463 | 25,269 |
def _get_oauth_url(url):
"""
Returns the complete url for the oauth2 endpoint.
Args:
url (str): base url of the LMS oauth endpoint, which can optionally include some or all of the path
``/oauth2/access_token``. Common example settings that would work for ``url`` would include:
... | e2f81f8fa0aab74c41eb253e1a7e2291ff96e334 | 25,271 |
from pathlib import Path
from typing import List
def read_feastignore(repo_root: Path) -> List[str]:
"""Read .feastignore in the repo root directory (if exists) and return the list of user-defined ignore paths"""
feast_ignore = repo_root / ".feastignore"
if not feast_ignore.is_file():
return []
... | 57fa48fa61edfe9856d98171d54855a854c33743 | 25,281 |
from pathlib import Path
import math
def process(file: Path) -> int:
"""
Process input file yielding the submission value
:param file: file containing the input values
:return: value to submit
"""
heading = 90
east_west_pos = 0
north_south_pos = 0
instructions = [l.strip() for l... | 3ba2c0a9fd4457ea2b49d6aca983123d8af45e04 | 25,282 |
def give_same(value):
"""Return what is given."""
return value | 92e0b8b3e6d40120fbe1d860ff74c220fbdfaec5 | 25,288 |
def process_mutect_vcf(job, mutect_vcf, work_dir, univ_options):
"""
Process the MuTect vcf for accepted calls.
:param toil.fileStore.FileID mutect_vcf: fsID for a MuTect generated chromosome vcf
:param str work_dir: Working directory
:param dict univ_options: Dict of universal options used by almo... | 083859b8ef25f8b0f1c89f0542286a692aef98c0 | 25,289 |
def retrieve_longest_smiles_from_optimal_model(task):
"""
From the optimal models that were trained on the full data set using `full_working_optimal.py`,
we retrieve the longest SMILES that was generated.
Parameters
----------
task : str
The task to consider.
Returns
-------
... | 5692b6e5bf322b0a6df67f9ad5ac699429ba9711 | 25,297 |
import re
def all_collections(db):
"""
Yield all non-sytem collections in db.
"""
include_pattern = r'(?!system\.)'
return (
db[name]
for name in db.list_collection_names()
if re.match(include_pattern, name)
) | 1b8220ac493036995695fc9ccf9ac74882677b4d | 25,300 |
def single_line_paragraph(s):
"""Return True if s is a single-line paragraph."""
return s.startswith('@') or s.strip() in ('"""', "'''") | 1e1febf21479b65920423268d93e5571de72b4ef | 25,301 |
def num_words_tags(tags, data):
"""This functions takes the tags we want to count and the datafram
and return a dict where the key is the tag and the value is the frequency
of that tag"""
tags_count = {}
for tag in tags:
len_tag = len(data[data['Tag'] == tag])
tags_count[tag] = le... | 9c6fddfcbdd1958e1c43b9b9bf8750bacacc3a31 | 25,307 |
def generate_pyproject(tmp_path):
"""Return function which generates pyproject.toml with a given ignore_fail value."""
def generator(ignore_fail):
project_tmpl = """
[tool.poe.tasks]
task_1 = { shell = "echo 'task 1 error'; exit 1;" }
task_2 = { shell = "echo 'task 2... | a79d0f24a3edc9fa8689cd0c33cef9e8f8121252 | 25,309 |
def parseConfig(s):
"""Parses a simple config file.
The expected format encodes a simple key-value store: keys are strings,
one per line, and values are arrays. Keys may not have colons in them;
everything before the first colon on each line is taken to be the key,
and everything after is considered a spa... | 259fdcef0eabeb410b2c2f79c50bb5985b5ce5f7 | 25,311 |
def parse_args(args):
"""
Parses the command line arguments. For now, the only arg is `-d`, which
allows the user to select which database file that they would like to use.
More options might be added in the future or this option might be changed.
"""
if args[0] == "-d":
return ' '.join(... | b251103d2d73f63ff795ddad82de8040d8e81ec4 | 25,312 |
def path_filter(path):
# type: (str) -> str
"""
Removes the trailing '/' of a path, if any
:param path: A parsed path
:return: The parsed path without its trailing /
"""
return path[:-1] if path and path[-1] == "/" else path | 4b449dfe2f840a25bec605464e6a8dbaeaf9afed | 25,319 |
import json
def to_javascript(obj):
"""For when you want to inject an object into a <script> tag.
"""
return json.dumps(obj).replace('</', '<\\/') | 2fba6a30eb19fd0b8fcc4295c3994ad6fa82b02f | 25,324 |
def parse_years(years):
"""Parse input string into list of years
Args:
years (str): years formatted as XXXX-YYYY
Returns:
list: list of ints depicting the years
"""
# Split user input into the years specified, convert to ints
years_split = list(map(int, years.split('-')))
... | 5296bd2f9e49a4a1689c813dd0e8641ea9a5c16f | 25,326 |
def dict_from_string(s):
"""
Inverse of dict_to_string. Takes the string representation of a dictionary and returns
the original dictionary.
:param s: The string representation of the dictionary
:return: [dict] the dictionary
"""
l = s.replace("[", "").replace("]", "").split("_")
d = {x.... | b16677d1d39cfe74b53a327e2bcd85b6f16ee8de | 25,329 |
def get(columns, table):
""" Format SQL to get columns from table
Args:
columns (tuple): column names
table (str): table name to fetch from
Returns:
str: sql string
"""
columns = tuple([columns]) if isinstance(columns, str) else columns
return "SELECT {c} FROM {t}".form... | 7c4bacad2121f66782e551d440d602e381d77b89 | 25,330 |
import inspect
import functools
def onetimemethod(method):
"""Decorator for methods which need to be executable only once."""
if not inspect.isfunction(method):
raise TypeError('Not a function.')
has_run = {}
@functools.wraps(method)
def wrapped(self, *args, **kwargs):
"""Wrapped m... | 8133ee826ea57bbf05e01bac81757e22f0e4c072 | 25,333 |
from typing import Tuple
import math
def rotation_y_to_alpha(
rotation_y: float, center: Tuple[float, float, float]
) -> float:
"""Convert rotation around y-axis to viewpoint angle (alpha)."""
alpha = rotation_y - math.atan2(center[0], center[2])
if alpha > math.pi:
alpha -= 2 * math.pi
if... | 785ee46456e373b28e5fcb4edd3a81a3e344abda | 25,337 |
def _normalize(vec):
"""Normalizes a list so that the total sum is 1."""
total = float(sum(vec))
return [val / total for val in vec] | 31ca018d688a5c28b89071e04049578737cd027d | 25,344 |
def to_float(string):
"""Converts a string to a float if possible otherwise returns None
:param string: a string to convert to a float
:type string: str
:return: the float or None if conversion failed and a success flag
:rtype: Union[Tuple[float, bool], Tuple[None, bool]]
"""
try:
r... | 00f3e16765aad9dc79e73cb687676893a743cc7f | 25,345 |
def month_add(date, months):
"""Add number of months to date"""
year, month = divmod(date.year * 12 + date.month + months, 12)
return date.replace(year=year, month=month) | 8252e82f8b7dae41a6d3dee8e6bc58b00c376aa7 | 25,349 |
def obtain_Pleth(tensec_data):
""" obtain Pulse Pleth values of ten second data
:param tensec_data: 10 seconds worth of heart rate data points
:return PlethData: Pulse Pleth unmultiplexed data
"""
PlethData = tensec_data[0::2]
return PlethData | 45159ae768aa8dfa0f67add0951fecb346a8557b | 25,351 |
def get_policy(crm_service, project_id, version=3):
"""Gets IAM policy for a project."""
policy = (
crm_service.projects()
.getIamPolicy(
resource=project_id,
body={"options": {"requestedPolicyVersion": version}},
)
.execute()
)
return policy | 984f40daa2a5e5334d7aa1adb3920c56f7a13a9b | 25,353 |
def get_log_data(lcm_log, lcm_channels, end_time, data_processing_callback, *args,
**kwargs):
"""
Parses an LCM log and returns data as specified by a callback function
:param lcm_log: an lcm.EventLog object
:param lcm_channels: dictionary with entries {channel : lcmtype} of channels
... | 6e2a57f04af2e8a6dc98b756ff99fab50d161ffe | 25,354 |
from typing import OrderedDict
def stats(arr):
"""
Return the statistics for an input array of values
Args:
arr (np.ndarray)
Returns:
OrderedDict
"""
try:
return OrderedDict([('min', arr.mean()),
('max', arr.max()),
... | 2243b48e129096c76461ea6a877a6b2a511d21d0 | 25,356 |
from typing import Callable
from typing import Iterable
from typing import Optional
from typing import Any
def find(predicate: Callable, sequence: Iterable) -> Optional[Any]:
"""
Find the first element in a sequence that matches the predicate.
??? Hint "Example Usage:"
```python
member = ... | 32060a3bd3b578bb357e68dad626f71d0c8ea234 | 25,360 |
def get_final_values(iterable):
"""Returns every unique final value (non-list/tuple/dict/set) in an iterable.
For dicts, returns values, not keys."""
ret = list()
if type(iterable) == dict:
return(get_final_values(list(iterable.values())))
for entry in iterable:
if (type(entry) ... | 466dd8542c87f8c03970ca424c608f83d326c2cb | 25,361 |
def yiq_to_rgb(yiq):
"""
Convert a YIQ color representation to an RGB color representation.
(y, i, q) :: y -> [0, 1]
i -> [-0.5957, 0.5957]
q -> [-0.5226, 0.5226]
:param yiq: A tuple of three numeric values corresponding to the
luma and chrominance.
:return: RGB ... | 0ede6cfacc368a3d225fe40b0c3fe505f066233b | 25,365 |
def read_y_n(inp):
""" Takes user's input as an argument and translates it to bool """
choice = input(inp)
if choice.lower() in ['y', 'yep', 'yeah', 'yes']:
return True
return False | cf1baee8d4b3e533ff0216c3d94e1bf6ed17a202 | 25,369 |
def delim() -> str:
"""80 char - delimiter."""
return '-' * 80 + '\n' | d74e847836632d3a7f7e2705d5b1dee0210d0161 | 25,371 |
def from_aws_tags(tags):
"""
Convert tags from AWS format [{'Key': key, 'Value': value}] to dictionary
:param tags
:return:
"""
return {tag['Key']: tag['Value'] for tag in tags} | a58931a29302154cc01656ece403d1468db1a6ab | 25,374 |
def index_nearest_shape(point, r_tree, shape_index_dict):
"""Returns the index of the nearest Shapely shape to a Shapely point.
Uses a Shapely STRtree (R-tree) to perform a faster lookup"""
result = None
if point.is_valid: # Point(nan, nan) is not valid (also not empty) in 1.8
geom = r_tree.nea... | 08153395ec03d9f0496f3bc16a0a58c2e1d09d60 | 25,380 |
def example_globus(request):
"""Globus example data."""
return {
'identity_provider_display_name': 'Globus ID',
'sub': '1142af3a-fea4-4df9-afe2-865ccd68bfdb',
'preferred_username': 'carberry@inveniosoftware.org',
'identity_provider': '41143743-f3c8... | 61c489bf3bdd66330c634326af895d0454a64406 | 25,383 |
def join_col(col):
"""Converts an array of arrays into an array of strings, using ';' as the sep."""
joined_col = []
for item in col:
joined_col.append(";".join(map(str, item)))
return joined_col | f6386d99e69e3a8c04da2d7f97aa7fb34ac9044c | 25,386 |
def read_words_from_file(f):
""" Reads a text file of words in the format '"word1","word2","word3"' """
txt = open(f).read()
return list(map(lambda s: s.strip('"'), txt.split(","))) | 669aeebd2cbfeb67cdc0cd65da2e58fdefa3bfe6 | 25,389 |
def to_ordinal(number):
"""Return the "ordinal" representation of a number"""
assert isinstance(number, int)
sr = str(number) # string representation
ld = sr[-1] # last digit
try:
# Second to last digit
stld = sr[-2]
except IndexError:
stld = None
if stld != '1'... | 5974aa3abf05c9e200ec1d6fc05bdecc231d2b22 | 25,390 |
def mutate(codon, alt, index):
"""
Replace (mutate) a base in a codon with an
alternate base.
Parameters
----------
codon : str
three letter DNA sequence
alt : str
alternative base
index : int
index of the alt base in codon (0|1|2).
... | 6db054a599846e104aa7bc8a4c565d37dad3b56e | 25,393 |
import calendar
def get_date_label(time):
"""Returns a nice label for timestamped months-years"""
split = [int(x) for x in time.split("-")]
return f"{calendar.month_abbr[split[1]]} {str(split[0])}" | 6495818e104e88f66119ab2cfdfcf6ac1756bc0d | 25,397 |
def _modify_payloads(checks, values, clear):
"""
Set or add payloads to checks.
:param checks: list of check instance
:param values: list of payloads with keys
:param clear: boolean flag if clearing the predefined payloads
:return: list of check instance
"""
for key, payloads in values.i... | 799c93803131f32cfa6a7524d1ed20873c129f27 | 25,398 |
def split(arr, splits=2):
"""Split given array into `splits` smaller, similar sized arrays"""
if len(arr) < splits:
raise ValueError("Can't find more splits than array has elements")
new_size = int(len(arr) / splits)
return ([arr[n * new_size:(n + 1) * new_size] for n in range(splits - 1)]
... | 13d75bd5a15013e4d91fab9cca2d21e8bcc5e5f8 | 25,402 |
def float_to_digits_list(number):
"""Convert a float into a list of digits, without conserving exponant"""
# Get rid of scientific-format exponant
str_number = str(number)
str_number = str_number.split("e")[0]
res = [int(ele) for ele in str_number if ele.isdigit()]
# Remove trailing 0s in fron... | 34a0f2e54899d7410bc6a3035c0fb3d599b9b3eb | 25,403 |
def make_cmd_invocation(invocation, args, kwargs):
"""
>>> make_cmd_invocation('path/program', ['arg1', 'arg2'], {'darg': 4})
['./giotto-cmd', '/path/program/arg1/arg2/', '--darg=4']
"""
if not invocation.endswith('/'):
invocation += '/'
if not invocation.startswith('/'):
invocat... | 19b969dc5a6536f56ba1f004b5b1bdc97ca0812f | 25,407 |
def f_call_1_1_1_kwds(a, /, b, *, c, **kwds):
"""
>>> f_call_1_1_1_kwds(1,2,c=3)
(1, 2, 3, {})
>>> f_call_1_1_1_kwds(1,2,c=3,d=4,e=5) == (1, 2, 3, {'d': 4, 'e': 5})
True
"""
return (a,b,c,kwds) | 8ce4616af2ca6985590c705d291f3408efcb8d34 | 25,409 |
def get_required_availability_type_modules(scenario_id, c):
"""
:param scenario_id: user-specified scenario ID
:param c: database cursor
:return: List of the required capacity type submodules
Get the required availability type submodules based on the database inputs
for the specified scenario_i... | fbcdb1954c0364dd967a82d3d5eb968597c1db0a | 25,410 |
import torch
def ipca_transform(dataloader, components):
"""
Transform data using incremental PCA.
RH 2020
Args:
dataloader (torch.utils.data.DataLoader):
Data to be decomposed.
components (torch.Tensor or np.ndarray):
The components of the decomposition.
... | ed0cca90c0cfe2bd5cb2f4b0fed19aa320744410 | 25,411 |
def _position_is_valid(position):
"""
Checks if given position is a valid. To consider a position as valid, it
must be a two-elements tuple, containing values from 0 to 2.
Examples of valid positions: (0,0), (1,0)
Examples of invalid positions: (0,0,1), (9,8), False
:param position: Two-element... | 8ac576f8bc856fdb587ade30d43ee86e7c7be1c1 | 25,413 |
def generate_numbers(partitions):
"""Return a list of numbers ranging from [1, partitions]."""
return list(range(1, partitions + 1)) | 8c1ad09496c4cbddb53c8b93d162d78e3e41b60e | 25,417 |
def yes_or_no(question):
"""Creates y/n question with handling invalid inputs within console
:param question: required question string
:type question: String
:return: True or False for the input
:rtype: bool
"""
while "the answer is invalid":
reply = str(input(question + " (y/n): ")... | e2ff75c0fdd40ef015ae703fc54d0e6d215fb0e5 | 25,424 |
from datetime import datetime
import pytz
def date_block_key_fn(block):
"""
If the block's date is None, return the maximum datetime in order
to force it to the end of the list of displayed blocks.
"""
return block.date or datetime.max.replace(tzinfo=pytz.UTC) | 33c4553704200e5355cd7d6807cd596192a2264b | 25,428 |
def extract_entities(input_data_tokens, entity_dict):
"""Extracts valid entities present in the input query.
Parses the tokenized input list to find valid entity values, based
on the given entity dataset.
Args:
input_data_tokens: A list of string tokens, without any punctuation,
ba... | 516d0d9ae0df4a318808125b7e44bc327ecb8cff | 25,434 |
import math
def spiral(radius, step, resolution=.1, angle=0.0, start=0.0, direction=-1):
"""
Generate points on a spiral.
Original source:
https://gist.github.com/eliatlarge/d3d4cb8ba8f868bf640c3f6b1c6f30fd
Parameters
----------
radius : float
maximum radius of the spiral from th... | cf7f6e22ef1f776bba9ed827b7f7243a45dde21b | 25,438 |
def hash_combine_zmw(zmw):
"""
Generate a unique hash for a ZMW, for use in downsampling filter.
"""
mask = 0xFFFF
upper = (zmw >> 16) & mask
lower = zmw & mask
result = 0
result ^= upper + 0x9e3779b9 + (result << 6) + (result >> 2)
result ^= lower + 0x9e3779b9 + (result << 6) + (res... | d26ddb5c11a555eb3072fc2db23a3876d1751db4 | 25,443 |
def RecMult(num_1, num_2):
"""
Takes in two nonnegative numbers and return the multiplication result of the two numbers without using the multiplication operator *
Examples:
>>> RecMult(0,500)
0
>>> RecMult(500,0)
0
>>> RecMult(1,500)
500
>>> RecMult(... | 5012a5ca27a263d7f26da26842e62ba9d0e5c7ab | 25,445 |
def csv_list(csv_str):
"""
Parser function to turn a string of comma-separated values into a list.
"""
return [int(i) for i in csv_str.split(",")] | 674c75f980bc8d7b47c5ab28e9afd7a586d1c917 | 25,446 |
def read_config_file(fname):
"""
Reads the config file in and outputs a dictionary for the
program to run through.
"""
d = {}
with open(fname, 'r') as ptr:
for line in ptr:
splitline = line.split()
key = splitline[0]
value = ' '.join(splitline[1:])
... | 942175fae143b87ff57df08041b94465ac5c8eb1 | 25,447 |
def cp_max_calc(Ma):
"""
Calculates the maximum pressure coefficient for modified Newtonian flow
Inputs:
Ma: Free stream mach number
Outputs:
CpMax: Maximum pressure coefficient
"""
k = 1.4
PO2_pinf = (((k+1)**2 * Ma**2)/(4*k*Ma**2 - 2*(k-1)))**(k/(1-k)) * \
... | 61d91f52234347baaa3f04bd2b82f97ffa6a9fb2 | 25,451 |
def safe_decode(txt):
"""Return decoded text if it's not already bytes."""
try:
return txt.decode()
except AttributeError:
return txt | 2952daf31e29f45a25b6bb70aab89db08280e848 | 25,452 |
def fromHex( h ):
"""Convert a hex string into a int"""
return int(h,16) | ffae24cdade04d3ab4098f13643098dff2c69ef2 | 25,459 |
import json
import requests
def groupRemove(apikey,groupid):
"""
Removes the group and moves all containers to group 0 (ungrouped)
apikey: Your ApiKey from FileCrypt
groupid: the group ID(!) you want to delete
"""
data={"api_key":apikey,"fn":"group","sub":"remove","id":str(groupid)}
return json.loads(requests.... | ce5e444624d4b071261212f901b364c06169dcfb | 25,460 |
from typing import List
def inner(v: List[float], w: List[float]) -> float:
"""
Computes the inner product of two vectors.
Args:
v: The first vector.
w: The second vector.
Returns:
The inner product.
"""
output: float = sum([i * j for i, j in zip(v, w)])
return ou... | ed15537cee3c4f3daacdd395e7dd5c74b7b800bf | 25,463 |
def display_plan(plan):
"""Print out the payment plan name and details from stripe API plan object"""
return (f"{plan.metadata.display_name} - ${plan.amount / 100:.2f} "
f"USD per {plan.interval}") | 34831cc91f141a5254d76af793f0527a2cdee403 | 25,466 |
from typing import Any
from pathlib import Path
def sanitize_path(v: Any) -> Any:
"""Sanitize path.
Parameters:
v : Maybe a Path. If ``v`` is a ``Path`` object, it is converted to a string.
Returns:
The sanitized object.
"""
if isinstance(v, Path):
return str(v)
else:... | 581c235cdf3c9099103bf5820b578cf25b9392ca | 25,476 |
def remove_key(vglist,key):
"""
Accepts a list of dictionaries (vglist) and a list of keys.
Returns a list of dictionaries with each of the specified keys removed for all element of original list.
"""
new_list = []
for row in vglist:
for item in key:
row.pop(item,None)
new_list.append(row)
r... | 4bb1410b21829478851b68fce36158a9080f016f | 25,477 |
def keys_to_camel_case(value):
"""
Transform keys from snake to camel case (does nothing if no snakes are found)
:param value: value to transform
:return: transformed value
"""
def str_to_camel_case(snake_str):
components = snake_str.split("_")
return components[0] + "".join(x.t... | cefb6f4cb75e3d39ae8742b44239ee5a3f2b7b87 | 25,478 |
def prune_completions(prefix, all_test_names):
"""Filter returning only items that will complete the current prefix."""
completions = set()
for test_name in all_test_names:
if test_name.startswith(prefix):
next_break = test_name.find('.', len(prefix) + 1)
if next_break >= 0:... | ad75ecc065dadddfb277329320ae888cf1e3535a | 25,481 |
import click
def validate_jaccard(ctx, param, value):
"""Ensure Jaccard threshold is between 0 and 1"""
if value is None:
return value
try:
jaccard = float(value)
assert jaccard <= 1
assert jaccard >= 0
return jaccard
except (ValueError, AssertionError):
... | 78dd5ca99f4fc2b5cdc50b3eaea6adb33a789c0a | 25,482 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.