content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def is_subsequence(needle, haystack):
"""Are all the elements of needle contained in haystack, and in the same order?
There may be other elements interspersed throughout"""
it = iter(haystack)
for element in needle:
if element not in it:
return False
return True | 1b3c1d66258bc3ae66e52c9eacfe1dbfed345c87 | 44,464 |
def is_safe(value: str) -> bool:
"""Evaluate if the given string is a fractional number safe for eval()"""
return len(value) <= 10 and all(c in "0123456789./ " for c in set(value)) | 115cfe5c2c429154ba4af454e9769bf0ec33c059 | 502,713 |
import mimetypes
def get_extension(mime_type: str) -> str:
"""From a ``mime_type`` return a corresponding file extension, or empty."""
extensions = sorted(mimetypes.guess_all_extensions(
mime_type, strict=False))
return extensions[0] if extensions else '' | 351c8bafcd2ba7f2428445750344d1463e989a1e | 568,503 |
def split_seq(seq, n_chunks):
"""Split the given sequence into `n_chunks`. Suitable for distributing an
array of jobs over a fixed number of workers.
>>> split_seq([1,2,3,4,5,6], 3)
[[1, 2], [3, 4], [5, 6]]
>>> split_seq([1,2,3,4,5,6], 2)
[[1, 2, 3], [4, 5, 6]]
>>> split_seq([1,2,3,4,5,6,7]... | e97c07506f8b477d3c6a43ff57948b5661ed8d78 | 508,297 |
def crop_keypoint_by_coords(keypoint, crop_coords, crop_height, crop_width, rows, cols):
"""Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the
required height and width of the crop.
"""
x, y, a, s = keypoint
x1, y1, x2, y2 = crop_coords
cropped_... | 5a2365a611275fea4d0f5d031127426c88c43905 | 3,625 |
from typing import Callable
def firstDerivative(f: Callable, x: float, h: float=1e-7) -> float:
"""Function to numerically approximate the first derivative about a point
`x`, given a function `f(x)` which takes a single float as its argument.
This function uses the central finite difference method, comput... | b6ef9862ea62b0a31fd67c438742340b3f9942e1 | 64,555 |
import json
def merge_json_data(old_data: str, new_data: str) -> str:
"""Merge to dictionaries encoded as JSON."""
if not old_data:
return new_data
data = json.loads(old_data)
data.update(json.loads(new_data))
return json.dumps(data) | 0b89b21528c5b848734e076004ba0db5480602f0 | 167,854 |
from typing import Optional
def read_text_file(file_name: str) -> Optional[str]:
"""
Reads file and returns its text
:param file_name: name of a file to read
:return: text of the file
"""
if not file_name:
return None
# encoding='utf-8-sig' is used for omitting \ufeff symbol
... | 982a1322c8fee216f3bc2364bbae3b5f6bfa348f | 227,557 |
def test_command(source):
"""
Creates a command to be run via subprocess
:param source: str|None
:return: list
"""
command = ['pytest', '--cov', source] if source is not None else ['pytest', '--cov']
return command | a9ba6b11b500f0ce7816a5471048209854f7cb65 | 268,840 |
def classifyCharacter(c):
""" return 0 for delimiter, 1 for digit and 2 for alphabetic character """
if c in [".", "-", "_", " "]:
return 0
if c.isdigit():
return 1
else:
return 2 | 6f319904860921d4b520706ec98db7de1f44ba24 | 477,999 |
from typing import List
import csv
def read_result_csv(file_path: str) -> List:
"""
Method to read in the first line of a csv to an array.
:param file_path: Path to csv file.
:return: Returns array containing the first line of the csv
"""
with open(file_path, mode='r') as file:
... | 021604a5f89664fedb5271556c9435e5c0a1e48a | 526,432 |
def getKeyPath(parent, keyPath):
"""
Allows the getting of arbitrary nested dictionary keys via a single
dot-separated string. For example, getKeyPath(parent, "foo.bar.baz")
would fetch parent["foo"]["bar"]["baz"]. If any of the keys don't
exist, None is returned instead.
@param parent: the o... | 66765c1ddaf820fe5950c394e5cb41f6b6c88e77 | 456,190 |
import re
def parse_td_links(ctx, raw_links, doc_id):
"""
Parsing links contained in the last <td> elements.
returns: list of tuples
i.e. [(url, type), (url, type)]
"""
links = []
# https://regex101.com/r/7iAqds/1
links_n_types_patt = re.compile(r"href='(.*?)'.*?title='(.*?)'")
for... | 7a9e78bcbae06fcb6e6fd1f1773f375b0a0e1f6b | 171,621 |
def single_function_to_run(batch, function_to_run):
"""
apply a list of functions on a batch of data
"""
for fn in function_to_run:
batch = fn(batch)
return batch | 6bf769541346177b45156c8d1c9c93318f3fddf1 | 671,083 |
def isnamedtuple(x):
"""
Utility to check whether something is a named tuple
Since a namedtuple is basically a tuple with some additional metadata, we can't just do an `isinstance` check
Based on https://stackoverflow.com/questions/2166818/how-to-check-if-an-object-is-an-instance-of-a-namedtuple/2166841... | 7ca9bdcd264cf1d4fdae01f9a8cc0f2ff4d9dd32 | 86,483 |
from math import sqrt
def distance(p1, p2):
"""Return the Euclidean distance between `p1` and `p2`"""
return sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2) | d1c28fb056c83e5d3cde7d1cbeda178670ffe6b0 | 311,183 |
def parse_boolean(value):
"""Parses a boolean from test i.e. from "0", "yes", "false"
etc.
"""
return value.lower() in ("1","yes","true") | 094af647683fe5aaefe2d2ba6ce17409c6cd6fb4 | 417,399 |
from datetime import datetime
def get_iso_from_local_time(user_datetime: datetime):
"""
outputs the provided datetime into an ISO date format string
:param user_datetime: the datetime in the user's TZ
:type user_datetime: datetime
:return: provided datetime formatted into a ISO string
:rtype: ... | cbe0d5fcd3a5ffadcee3c8e2609712610a327ed2 | 233,026 |
from pathlib import Path
def existing_git_repo(path: Path) -> bool:
"""Check if a git repository exists
:param Path path: Repo path
:return: True, if .git directory exists inside path
"""
return path.is_dir() and Path(path / '.git').is_dir() | 60d00eab72c23fbe7fdd4a7ad0868e081c712247 | 90,036 |
import torch
def angles_to_rotation_matrix(yaw, pitch, roll, degrees=True):
""" Convert pitch, yaw, roll angles to a right-handed rotation matrix. It can be used to post-multiply
row vectors: rotated = vector * R.
Based on RotationMatrix.m from the AFLW2000 and 300W LP datasets.
:param p... | e11bf54b1be4744cdde30466631fc7a547d5a0db | 412,813 |
import inspect
def _accepts_args(fn, *args, **kwargs):
"""Returns True if `fn` can accept `*args` and `**kwargs`."""
try:
inspect.signature(fn).bind_partial(*args, **kwargs)
return True
except TypeError:
return False | 0b912c5398999347b1aaf36931988689c36d2dce | 583,397 |
import time
def check_cli_output_with_mocker(dut, mocker_object, command, max_wait_time, key_index=0):
"""
Check the command line output matches the mocked data.
:param dut: DUT object representing a SONiC switch under test.
:param mocker_object: A mocker instance.
:param command: The command to b... | f16c1d691dcd614d27bcc79a5e57a8eeeab82eaf | 600,990 |
from typing import Callable
from typing import Dict
def loop(setup: Callable, cond: Callable, func: Callable) -> Dict:
"""A for loop like in C, C++, Rust, etc. Every function gets a dictionary for talking between them.
Args:
setup (Callable): The function that gets called before the loop
cond... | 335a3b60be6f26f0e25fd2464c3f31a3302f5e0d | 132,205 |
def getColor (value):
"""Returns a color name dependent on value.
:param value: The integer that determines the color
:type value: int
:return: The color appropriate to the integer
:rtype: str
"""
if 95 <= value <= 100:
return "darkred"
if 90 <= value <= 94:
return "red"... | c6424852283ece3bff1909190fb1eef8c44cbda9 | 182,009 |
def mb_to_hgt(Psta, mslp=1013.25): # METERS
"""Convert millibars to expected altitude, in meters."""
return (1-(Psta/mslp)**0.190284)*44307.69396 | dbe2df667e54f80031f162f6d3e9aeb9fcee15f4 | 22,392 |
def create_entities_dict(name, face_entity_list, solid_entity_list, main_object=None):
"""
Helper method for creating an entities dictionary.
:param name: name of the collection of entities
:param face_entity_list: [face_entity_1, ..., face_entity_n]
:param solid_entity_list: [solid_entity_1, ...,... | 9902f4142c8651f709a72c495f3a88f7dc7791b3 | 247,055 |
def format_sc(n):
"""Return a LaTeX scientifc format for a float n.
Parameters
----------
n: float.
Returns
-------
str.
scientific writing of n in LaTeX.
"""
a = "%.2E" % n
b = a.split('E')[0] + ' '
p = str(int(a.split('E')[-1]))
if p == '0':
return b
... | 081147c97b9fdad46651b862a7c9bfc2d7f388d7 | 210,845 |
import torch
def get_attention_mask(input_ids):
"""Get the default attention mask.
Args:
input_ids: Ids representing the input tokens, used for the mask length.
Returns:
extended_attention_mask: The attention mask to be used with the model.
"""
attention_mask = torch.ones_like(input_ids)
# We cr... | 343fd58fd65cfcd00892d2b88be5ef87060a6c7c | 430,860 |
def to_iso639_part1(language_code):
"""
Convert codes like "en-us" to "en"
"""
return language_code.split('-', 1)[0] | 53192b1a7b0263cca5bb9c714fc01be4b4b3b1ae | 48,116 |
def get_gjson(gdf):
"""
Generates geojson from geopandas.GeoDataFrame
"""
gjson = gdf.to_json()
return gjson | a4af1516d3dd2a8ce38f1769b699c2d23627b941 | 273,711 |
def read_clan_ranking(rankings, clan_tag, clan_stats, attr_name):
"""
Sets global or local clan ranking info on a clan history object
:param list rankings:
:param str clan_tag:
:param ClanHistory clan_stats:
:param str attr_name: must be in (local, global, local_war, global_war) - see backend.mo... | 38f1a7ec05407f1e4bc241dd45685cc5cf54d085 | 429,319 |
def repository_url(datastore_client, name):
"""Returns the URL of a repository, given its short name.
If a repository moved locations or has multiple locations, a repository can
have multiple URLs. The returned URL should be the current canonical one.
Args:
datastore_client: The client to use fo... | 0546335ddf8c539a017190d7269615385983a1ce | 199,841 |
def isMyNumber(guess):
"""
Procedure that hides a secret number.
:param guess: integer number
:return:
-1 if guess is less than the secret number
0 if guess is equal to the secret number
1 if guess is greater than the secret number
"""
secretnum = 5
if guess == secretnum:
... | df7527c0da298450d9f3f7b33b7f3b1067c3a275 | 200,044 |
import time
def readable_time(timestamp=None):
"""
Return a human-friendly string of a timestamp
e.g.
timestamp: 1582029001.6709404
readable time: Tue Feb 18 20:30:01 2020
Args:
timestamp: a UNIX timestamp
Returns:
str, a human-friendly readable string of the arg... | f4ae90175a321aacec5fff8b1445b480fd1894bd | 141,001 |
def collect_all_accessible(auth_api, object_types = ["Role", "Organization", "EntitySet", "PropertyTypeInEntitySet"], permissions = ["OWNER", "READ", "WRITE"]):
"""
Creates a dict with outputs of get_all_accessible_at_permission_level over various object_types and permission levels
Output format is dict({
... | 3ed9d39dad5ae383186dcdeb2f7d376b472800c1 | 485,109 |
def append_results(results, base, c, conf):
"""Append results before calculating metrics."""
results.append({'truth name': base['name'],
'model name': c['name'],
'path': c['path'],
'location': conf['location'],
'var': c['var']}
... | c9911e970217c021486e69dd2f031316b4e45ea6 | 56,579 |
def add_intercept(X):
"""Add all 1's column to predictor matrix"""
X['intercept'] = [1]*X.shape[0]
return X | 3ddc9baae14d87eeac29060c34428ed53a922477 | 70,658 |
from typing import Union
from datetime import datetime
def to_dt(s: Union[datetime, str]):
"""Convert an ISO 8601 string to a datetime."""
if isinstance(s, str):
try:
return datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%f")
except ValueError:
return datetime.strptime(s, "%Y-... | 8d5e175aac4e3d717e3cd0d67aaa54377dd07d1e | 454,178 |
from typing import Any
def _infer_flat_input_shape(n_args: int) -> tuple[Any, ...]:
"""Compute a shape of inputs that function are not tuples.
Args:
n_args: a number of inputs.
Returns:
a shape of inputs.
"""
return tuple([()] * n_args) | 817f65cece9db7c5c5428abba791c31ea641532a | 372,113 |
import fractions
def _frame_num_to_drop_frame_num(
frame_number: int,
timebase: fractions.Fraction,
) -> int:
"""
_frame_num_to_drop_frame_num converts a frame-number to an adjusted frame number for
creating drop-frame tc.
Algorithm adapted from:
https://www.davidheidelberger.com/2010/06/... | 0b4239cec8ed675a3a15c75588e4ccb93cad2462 | 479,564 |
import re
def select_structs(innerclass_list):
"""Select structures from innerclass list.
Args:
innerclass_list: raw list with unions and structures
extracted from Dogygen's xml file.
Returns:
Doxygen directives with structures selected from the list.
Not... | 844156fb1b3eddfcb81affb59e8e6d9911c93483 | 620,782 |
def shake_shake_eval(xa, xb):
"""Shake-shake regularization in testing mode.
Args:
xa: Input, branch A.
xb: Input, branch B.
Returns:
Mix of input branches.
"""
# Blend between inputs A and B 50%-50%.
return (xa + xb) * 0.5 | 68eca94d4bf8ea75427297b0324dac9cf7eb10c4 | 610,177 |
import random
def generate_uuid_readable(length=9):
""" Create a new random uuid suitable for acting as a unique key in the db
Use this when it's an ID a user will see as it's a bit shorter.
Duplicates are still unlikely, but don't use this in situations where
a duplicate might cause probl... | 857478e749ebcc01dc4d78777404813bddc19863 | 273,936 |
import string
def _clean_up_string_entry(entry):
"""Remove leading and trailing whitespace and quote marks."""
return entry.strip(string.whitespace + '"\'') | d296974953f0b59f899ae40b3d32629da97cf98b | 438,373 |
def count_receive(link_counters):
"""Find the receive count in the counters returned by a CommunicationLink."""
for processor in link_counters.values():
if 'receive' in processor:
return processor['receive'] | e869ae163a2d06afd36c7005dc5b47fef7e67abe | 476,216 |
def myreplace(old, new, s):
""" Replace all occurrences of old with new in s. """
s = " ".join(s.split())
return new.join(s.split(old)) | 837ffc3bfa4fa26e3886e168106f12b087a42d36 | 289,312 |
def batch_tokenize(tokenizer, attacked_text_list):
""" Tokenizes a list of inputs and returns their tokenized forms in a list. """
inputs = [at.tokenizer_input for at in attacked_text_list]
if hasattr(tokenizer, "batch_encode"):
return tokenizer.batch_encode(inputs)
else:
return [tokeniz... | 317fb8b113ff2c83dcaa2d50dd933d187a6f0609 | 502,553 |
def source_dx_dy(source_pos_x, source_pos_y, cog_x, cog_y):
"""
Compute the coordinates of the vector (dx, dy) from the center of gravity to the source position
Parameters
----------
source_pos_x: X coordinate of the source in the camera
source_pos_y: Y coordinate of the source in the camera
... | 4dc959fb557268121a2288789a227a8a08a28c83 | 178,068 |
def get_field_on_block(block, field_name, default_value=None):
"""
Get the field value that is directly set on the xblock.
Do not get the inherited value since field inheritance
returns value from only a single parent chain
(e.g., doesn't take a union in DAGs).
"""
try:
if block.fiel... | 6f48a89a4684869b2b5ceec0a276b5f8117f70f4 | 71,486 |
def clean(line):
"""
Extract elements from line, add fixed format
:param line: checked line(string)
:return: String with elements
"""
result = ''
for element in line.split(';'):
result += element.strip(' ') + ';'
if result[0] == ';':
result = result[1:]
return result[... | 8abe287b8ad39861d8f228b26c708fe9049c905d | 266,370 |
import math
def get_line_ori(x_0, y_0, x_1, y_1):
"""Returns the orientation of a vector defined by two points in 2D space.
Parameters
----------
x_0 : float
X coordinate of first point
y_0 : float
Y coordinate of first point
x_1 : float
X coordinate of second point
... | d884ad1068d7abc926ce1e3fd327e277257f1ec5 | 345,288 |
def get_repo_name(url: str) -> str:
"""
Get the name of the repo.
:param url: The URL on which the name of the repo will be retrieved.
:return: The name of the repo.
"""
return url.split('https://github.com/')[1].split('/')[1] | d2f7c14e424b0233b6867ae8311b4177c379b61a | 639,951 |
def extractFolders(folders):
"""
convert a string of folders to a list of tuples (db , schema, node)
:param folders: a string containing folders db-schema-node seperated by ,
:return: a list of tuples (db , schema, node)
"""
output = []
folderList = folders.split('-')
for folder in fol... | b5ba5e2ce3fcbc33e51fea06d2019c36b65aaece | 639,240 |
def convert_to_str(value):
"""convert True/False to yes/no and all values to strongs"""
if isinstance(value, bool):
if value:
return "yes"
return "no"
return str(value) | dfa9dbaa31e18ec8c1433dd81e80b578fd8fe541 | 107,191 |
import pickle
def restore_object(filename):
"""
Read a `pickle` file and returns the saved objects.
"""
try:
with open(filename, 'rb') as bkp:
reading = pickle.load(bkp)
except (FileNotFoundError, PermissionError):
message = 'There was a problem reading the pickle.\n'
... | 93d1de6e21bfbf393a29db72113c6e1d954f791f | 124,480 |
def is_verb(tok):
"""
Is this token a verb
"""
return tok.tag_.startswith('V') | a42e92596de719d55810bbe8012f7418cc7d9be8 | 688,772 |
from collections import namedtuple
def tol_cset(colorset=None):
"""
Discrete color sets for qualitative data.
Define a namedtuple instance with the colors.
Examples for: cset = tol_cset(<scheme>)
- cset.red and cset[1] give the same color (in default 'bright' colorset)
- cset._fields give... | c6edc57be76c8f53cc897f7be58156a1b326fb40 | 54,738 |
def count_files_per_issue(aggregated):
"""Count the number of files for each issue.
:param aggregated: {issue: [file, ...], ...}
>>> i = count_files_per_issue(dict((('TEST-1111', ('A', 'B', 'C')), ('TEST-1112', ('A', 'D')))))
>>> i.sort()
>>> i
[('TEST-1111', 3), ('TEST-1112', 2)]
"""
... | 72b2ade5f169b381ae7492330cca8fec0271e89f | 339,987 |
def find(nda, obj):
"""returns the index of the obj in the given nda(ndarray, list, or tuple)"""
for i in range(0, len(nda)):
if(nda[i] == obj):
return i;
return -1; | 39e7c58809299259fbeae523f81264295766d64b | 169,478 |
def isanyinstance(o, classes):
"""calls isinstance on a list of classes.
true if any matches"""
for cls in classes:
if isinstance(o, cls):
return True
return False | 3a8a006e92e7e343d8cad429c798ca31e103143a | 59,761 |
def time_in_words(h, m):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/the-time-in-words/problem
Given the time in numerals we may convert it into words, as shown below:
----------------------------------------------
| 5:00 | -> | five o' clock |
| 5:01 | -> | one m... | 85f2247f01df36ef499105a9940be63eee189100 | 706,995 |
import math
def hsv_to_rgb(hue, saturation, value):
"""
Convert HSV color (hue, saturation, value) to RGB (red, green, blue)
@param hue: 0=Red, 1/6=Yellow, 2/6=Green, 3/6=Cyan, 4/6=Blue, etc.
@param saturation: 0.0=Monochrome to 1.0=Fully saturated
@param value: 0.0=Black to 1.0=Max br... | 8f571b14168e220d30042049cdf29fae76cf955b | 533,259 |
def small_angle_diff(a1, a2):
""" Helper function for getting smallest angle difference between two angles """
return abs((a1 - a2 + 180) % 360 - 180) | 80fd2b471a7ac85c05547e528762bab12fef3fc3 | 352,176 |
def array_class_from_type(name):
"""
Given a DataTypeClass class name (such as "BooleanType"), return the
corresponding Array class name.
"""
assert name.endswith("Type")
return name[:-4] + "Array" | bbc9601c232c89f4361cee712ccfbcd2ca192229 | 243,876 |
def _prefix_master(master):
"""Convert user-specified master name to full master name.
Buildbucket uses full master name(master.tryserver.chromium.linux) as bucket
name, while the developers always use shortened master name
(tryserver.chromium.linux) by stripping off the prefix 'master.'. This
function does ... | c4a4f715d1b17733bf6d2d2bae89143f62fdbc87 | 294,553 |
from datetime import datetime
def age(yob):
""" Accepts year of birth and returns the persons age. """
return datetime.now().year - yob | 9e16e3739055fe410a2661d896530f99b30a6692 | 172,957 |
def objects_to_dictionaries(iterable, fields):
"""
Convert an iterable into a list of dictionaries; fields should be set
to a comma-separated string of properties for each item included in the
resulting list; e.g. for a queryset:
{{ queryset | objects_to_dictionaries:"id,name" }}
will retu... | 767fa53729ac32fa05fc237f7dac9d0f91ee50fc | 229,880 |
def _get_json_safely(response):
"""
Check for JSON response errors, and if all clear,
return the JSON data
"""
json = response.json() # get the JSON
if "error" in json:
raise ValueError(json["error"][0])
return json | 9ae0085f512b89cc4f457c78f5ab8670d7e6165e | 200,580 |
def celctorank(celsius):
""" This function converts celsius to Rankine, with celsius as parameter."""
rankine = (celsius + 273.15) * 1.8
return rankine | 8f43b8ae84bb7106b30961774624ecffb9f92c74 | 142,078 |
def get_accuracy(data_path):
"""
Load & parse the accuracy data file
accuracy data format:
model:hg_s2_mobile_tiny_192_192;dataset:MPI
Epoch 0:0.03907726641313506
Epoch 1:0.3704370004326737
...
return:
label: training model + dataset, used ... | 8ac6daccca3a5c13bc3b7dabd4a7cb5e8a743b45 | 139,813 |
from typing import Counter
def sum_dicts(a, b):
"""Merge dictionaries, summing their values.
For example:
a = {"x": 1, "y": 1}
b = {"x": 1, "z": 1}
returns {"x": 2, "y": 1, "z": 1}
Args:
a (dict)
b (dict)
Returns:
dict
"""
return Counter(a) + ... | 77b17417e53c0cebe8ee254697db639abc858f11 | 532,042 |
def _trim_zero_to_3_digits_or_less(trim: bool, exponent: int, ticker: str) -> str:
"""Returns a string representation of the number zero, limited to 3 digits
This function exists to reduce the cognitive complexity of pretty_ether
"""
if trim:
zero = "0"
else:
if exponent == -1:
... | 3a710a1da03daa43bf0ddaefb54f9b9ef613d10d | 445,857 |
from typing import List
import random
def choose_seq_indices(
input_seqs: int,
proportion: float = 1.0,
max_records: int = 10000) -> List[int]:
"""Generate a list seq indices.
Args:
input_seq (int): number of input_sequences
proportion (float): proportion of seqs to extract
... | abc47c52361a02481e55e81f093052e5e5465f29 | 580,302 |
from typing import Dict
def load_env_file(filename: str) -> Dict[str, str]:
"""Load environmental variables from a `.env` file."""
result = {}
with open(filename) as f:
for line in f.readlines():
if line.startswith('#') or not line.strip():
# Skip this line. It's a comm... | ffa4a6b99612e8dced78024c1d089958620cca7f | 261,852 |
def _getpricestring(amount, denom):
"""Return a human-readable price string"""
return '{:g} {}'.format(
amount,
denom + 's' if denom in ('Key', 'Weapon') and amount != 1 else denom) | 195f47283f9cc88a89c32d29cda55b643d71be0f | 213,717 |
import requests
def query_test_run(sotest_url, testrun_id):
""" Queries the status of a test run """
url = "{}/api/query/{}".format(sotest_url, testrun_id)
r = requests.get(url)
return r.json() | a6195066dd6814379a253d85288e2c20f9589846 | 158,755 |
def load_dat(filename: str) -> list:
"""
Loads the contents of the DAT data file into a list with each line of the file
into an element of the list.
"""
with open(file = f'{filename}.dat', mode = u'r') as dat_file:
return dat_file.read().split(u'\n') | 25f13fedb8bb0d2927e794b20691c648b8502bc5 | 70,920 |
def get_set_members(instance, sets):
"""Get set members relative to a list of sets
:param instance: Pyomo Instance
:param sets: List of strings with the set names
:return: A list with the set members
"""
sm = []
for s in sets:
sm.append([v for v in getattr(instance, s).data()])
r... | cb590a248cc01e86611dcfe6b701183f89d2b5b5 | 499,947 |
def is_desired_post(post):
"""Determine if a post is a request, self post, or link to an untested host.
- Request posts usually have extra text, overlays, etc that need to be
removed from the image, so we'll ignore those.
- Fufilled requests require parsing the comments for all edited versions of
... | 83a67f0c086f352d3575660b1fc4ea165a0278ac | 460,733 |
def ev_strip(short):
"""Strip zeros, taking into account E / V codes.
"""
if short.startswith("E") or short.startswith("V"):
return short[0] + short[1:].lstrip("0")
else:
return short.lstrip("0") | 9070feb4f55ebb2cda4eb1047a5002368321919a | 288,828 |
import struct
def unpack_int(data):
"""Extract an int from 4 bytes, big endian."""
return struct.unpack(">i", data[:4])[0] | 4c322a0d2a85077f3b80d85f65bfc57f3d182869 | 54,405 |
import string
def remove_punct(target):
"""
Removes punctuation from a text.
Arguments:
target: interable object containing text.
Returns:
punctuation striped text
"""
output=target.translate(str.maketrans(string.punctuation,
' ' * len(string.punctuation)... | d65e57cbb05e23b7029cb79fe89a885cfcceaf98 | 360,733 |
def comp_hex(x):
"""
Get the components of a hex RGB color as strings (`"00"` to `"ff"`).
"""
return x[0:2], x[2:4], x[4:6] | ce47cd13b1e68fb68b8063fa92006f27b796b766 | 393,265 |
def get_spectral_characteristics_for_lid(local_identifier, label):
""" Search a PDS4 label for Spectral_Characteristics of a data structure with local_identifier.
Parameters
----------
local_identifier : str or unicode
The local identifier of the data structure to which the spectral characteris... | 5195e85055122c86312177464ba34f716f79a2fc | 284,859 |
def matrix_get_translation(m):
"""
Get translation component of a 4x4 matrix.
:param m: Matrix
:return:
"""
r = range(3)
return [m[i][3] for i in r] | a42c24f8a2fa38806e6b74e4c52f6f2926d8aca5 | 434,048 |
def _subject_member_format(member_ref):
"""Format a member ref for consumption outside of this module."""
return {
'id': member_ref['id'],
'subject_id': member_ref['subject_id'],
'member': member_ref['member'],
'can_share': member_ref['can_share'],
'status': member_ref['s... | 24c6ad6123aebb3f0268c7eeed805ccd1a3e5aab | 606,039 |
def count_newlines(x: str, before=True) -> int:
"""
Count the number of newlines from front or back.
Here all newlines are counted while ignoring whitespace.
Stop at first character that is not newline or whitespace.
If there are no non-newline or whitespace characters, return
infinite number o... | 2396bc072f518c5fff86b74d99086aedcb9cbe1a | 251,442 |
def substitute_variables(cmd, variables):
"""Given a cmd (str, list), substitute variables in it."""
if isinstance(cmd, list):
return [s.format(**variables) for s in cmd]
elif isinstance(cmd, str):
return cmd.format(**variables)
else:
raise ValueError(f"cmd: {cmd}: wrong type") | 3a6bbf276c161daf6508c3a8614eb9840d7e3f3c | 375,881 |
def does_flavor_exist(nova_client, flavor_name):
"""
Check if flavor exists
"""
for flavor in nova_client.flavors.list():
if flavor.name == flavor_name:
return True
return False | bdd853f606bcdb94c92c4417363bf9d0b8d2c36a | 667,428 |
def construct_node_config(*, name: str,
remote_fs: str = '/tmp',
executors: int = 2) -> dict:
"""
Args:
- name: Node name
- remote_fs: Remote node root directory
- executors: Number of node executors
Returns:
- dict: return... | 2c7255d380c4c080f829dcef613cd772620a0299 | 81,313 |
def count_words(wordlst: list):
"""
count words in tweet text from list of list, dict, or str
:param wordlst: list of tweets
:return: word count, tweet count
"""
wrd_count: int = 0
tw_count: int = 0
for tw in wordlst:
if isinstance(tw, dict):
tw_wrds: list = tw['text'... | 8f75a6424de22190fafd9cd97bd03decbb5e95c3 | 448,332 |
import itertools
def is_valid_ean13(s):
"""Check whether a string is a valid EAN-13.
EAN = `European Article Number
<https://en.wikipedia.org/wiki/European_Article_Number>`_
The string must not contain any separators; only the characters ``0-9``
are allowed and the length of the string must be 1... | 86327e93a68040dd181ef77be75cbb3e7196e82b | 166,812 |
import json
def _names_to_bytes(names):
"""Reproducibly converts an iterable of strings to bytes
:param iter[str] names: An iterable of strings
:rtype: bytes
"""
names = sorted(names)
names_bytes = json.dumps(names).encode('utf8')
return names_bytes | 461850e92363fdb53d508b37d3e4e311a994e4d4 | 503,225 |
def _to_z_score(scaled_score, expected_score, test):
""" Turn scaled and expected score to a z score
:param scaled_score: scaled score, result from raw_to_scaled function
:param expected_score: expected score, result from get_expected_score function
:param test: test of interest
:return: z-score fo... | ccfe2686481809a4ddc4bbb5e94c4ec4fe5c6318 | 146,432 |
def pstres(self, key="", **kwargs):
"""Specifies whether prestress effects are calculated or included.
APDL Command: PSTRES
Parameters
----------
key
Prestress key:
OFF - Do not calculate (or include) prestress effects (default).
ON - Calculate (or include) prestress effe... | 507c1599b5a1a70788d248942c1f993e62e0065f | 524,297 |
def prevent_bad_replacement(overrides_dict, df):
"""Checks that there is not any values equal to the placeholder-values which are used
as keys in the overrides dict. If they did exist, this would cause a bad replacement.
It is very unlikely that this is needed, but just here as an extra safety step... | 11f2fc459d2bd471681eb5846131c4baa84ef273 | 461,715 |
from typing import Dict
from typing import List
def sort_dict_desc(word_dict: Dict) -> List:
"""Sort the dictionary in descending order.
:param word_dict: the dictionary of word.
:return: sorted list of dictionary.
"""
# sort by value
# word_dict.items() to get a list of (key: value) pairs
... | 87ea93145b7d4d7a867845a52ae3ef1c8403075d | 54,121 |
def represent(item):
"""Represents callables and values consistently
Args:
item: The item to represent
Returns:
Item representation
"""
return repr(item.__name__) if callable(item) else repr(item) | d98f2f0cf1979b833908bc539486fb2b12669dd1 | 154,984 |
from textwrap import dedent
def authorized_keys(tmpdir):
"""Return the filename of an authorized_keys file"""
authorized_keys_file = tmpdir.join("authorized_keys")
authorized_keys_content = dedent(
r'''
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6N/eQ1L0MxzzXgVpnnJCn6x+g+3434/ABLgG6IXbekYqBDWFOUfjslt... | a7d39c1dc4b2b9d5088e8f829db90bd79bba9d18 | 394,266 |
def _check_git_access(req, dataset):
"""Validate HTTP token has access to the requested dataset."""
user = 'user' in req.context and req.context['user'] or None
# Check that this request includes the correct token
if user != None and 'dataset:git' in user['scopes'] and user['dataset'] == dataset:
... | 61c027d637f7040e33d64f0799c993c5c979827c | 623,836 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.