content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import itertools
def get_duplicate_labelling(labelled_diags):
""" Returns diagrams sharing a Label object with other diagrams.
:param labelled_diags: List of Diagrams with Label objects assigned
:return failed_diag_label: List of Diagrams that share a Label object with another Diagram
"""
failed... | a178cb44bdd247231768af6064f6f89ae636824b | 575,100 |
def splitcomma(source, sep=","):
"""split comma-separated string into list of elements,
stripping whitespace.
"""
source = source.strip()
if source.endswith(sep):
source = source[:-1]
if not source:
return []
return [ elem.strip() for elem in source.split(sep) ] | f430fc5279def7f4747d2aa3d70137bcd9210004 | 575,101 |
def split_args(args, required=0, optional=0):
"""
splits the args string by comma and removes left and right whitespace.
enforces that the amount of args is >= required and <= required+optional.
if it is not then an error message is printed and None is returned
"""
args = [x.strip() for x in arg... | 888e92fa5baa4193bc6bda1790da751e7561196f | 575,103 |
def __get_nodes(graph, nodes, resolution, id_offset):
"""
Parses a set of nodes from JSON and add the node features and id to
the given graph. If a resolution if given, applies a normalization
to the (x,y) values
:param graph: networkx graph
:param dict nodes: dictionary of nodes
:param lis... | 6a2ad7e3538fb9291ac73dcbd749210c25efd439 | 575,107 |
def _remove_pos_tags(sent):
"""
Args:
sent - list of (word, pos) tuples
Returns:
A list of only lexical items.
Convert a list of (word, pos) tuples back to a list of only words.
"""
output = []
for word_pos in sent:
output.append(word_pos[0])
return output | f58e56a68238fb6378889875c9897de3378a4f05 | 575,108 |
import posixpath
def legacy_uptests_command(proc_path, proc, host, port, user):
"""
Build the command string for uptesting the given proc inside its lxc
container.
"""
cmd = "/uptester %(folder)s %(host)s %(port)s" % {
'folder': posixpath.join('/app/uptests', proc),
'host': host,
... | 2e33b1e057cee69d5d6584b27111d79c60d957f7 | 575,112 |
def split(oEditor, partlist,
NewPartsModelFlag="Model",
SplitPlane='XY',
WhichSide="PositiveOnly",
SplitCrossingObjectsOnly=False,
DeleteInvalidObjects=True):
"""
Splits specified objects along a plane.
Parameters
----------
oEditor : pywin... | 5d665d04056ed8df3139fe0e9bd2554e691f69c4 | 575,113 |
def _drop_id_marker(s):
"""Drop the first character of str"""
return s[1:] | 580956ebe172c271ba972af0ac146d4e636f052f | 575,114 |
import re
def text_in_page(tmp_proj, page_path, text):
"""
Test if string exists in page.
"""
page = tmp_proj / "site" / page_path
assert page.exists(), "%s does not exist" % page_path
contents = page.read_text(encoding="utf-8")
return re.search(text, contents) | 5b05a7eb946c48be06c9e0ad066a2b7f2f885c82 | 575,117 |
import torch
def reduceByDepth(rgb_images, depth_images, max_depth=None):
""" For each pixel in a scene, select the object closest to the camera.
Parameters
----------
rgb_images : torch.tensor of float, shape (batch_size, img_height, img_width)
depth_images : torch.tensor of float, shape (batch_... | c9ab622299612025117ca5bba28250f64322e80c | 575,123 |
def apply_downsampling(seq, step, filter_global=False, filter_local=False, **kwargs):
""" Apply Down Samplings
Args.
-----
- seq : list [e.g. np.ndarray(), pd.DataFrame]
- step : integer, Spaceing between values
Return.
-------
- lsit of donwsampled `seq`
"""
seq_list = []
... | f2b9d9375bc9ad8ea41271044079c2d89005da9e | 575,125 |
import logging
def write_bigquery_to_file(bigquery_filepath, query_string):
"""Writes BigQuery query string to a file.
Args:
bigquery_filepath: (str) Output file path.
query_string: (str) BigQuery query string to write to file.
Returns:
(bool) True if query was written to file successf... | c48c70738a55ae9d9f581fa847c100db7dbd4496 | 575,127 |
from email.parser import Parser
def message_from_string(s, *args, **kws):
"""Parse a string into a Message object model.
Optional _class and strict are passed to the Parser constructor.
"""
return Parser(*args, **kws).parsestr(s) | 599f3db4c956ab18c39b59917db393f95780160c | 575,128 |
def set_header_field(headers, name, value):
""" Return new headers based on `headers` but with `value` set for the
header field `name`.
:param headers: the existing headers
:type headers: list of tuples (name, value)
:param name: the header field name
:type name: string
:param value: the ... | fc1562667b5b0e4b2184ba031a8d8f353c5704e7 | 575,134 |
from re import T
from re import I
def m_id(typ, idx):
"""Generate match id """
return {T: typ, I: idx} | dfbcaad3e2c3a58aaacf264ee424770f955e5dac | 575,135 |
import math
def get_range(start, stop, step=None) -> range:
"""Returns a range object given floating point start and
stop values (the optional step must be an int). If
step is none, it will be set to 1 or -1 depending on the
relative values of start and stop.
"""
if start < stop:
star... | 5718e4d463c8229ef86935efce21e4f446fdaba9 | 575,136 |
def repr_type(t):
"""
Convert type to string representation.
"""
return str(t) | aab68a0d63ad86a0cf9d0e749db8f1460878889d | 575,139 |
def split_seq(seq,size):
""" Split up seq in pieces of size """
return [seq[i:i+size] for i in range(0, len(seq), size)] | 9e14d68794e657bb5ab91218ae9b9764eca05c33 | 575,140 |
def strip_json_array(typename):
""" Strip json array enclosing brackets from a typename.
[int] -> int
"""
if typename and typename.startswith('[') and typename.endswith(']'):
return typename[1:-1]
return typename | c2c91626da698b84076eb157cb3342d4ce805f86 | 575,141 |
def transpose(headers, rows):
"""
Return transposed headers and rows (i.e. switch columns and rows).
"""
ret_headers = ['Attribute', 'Value']
ret_rows = []
for header in headers:
ret_row = [header]
ret_rows.append(ret_row)
for row in rows:
assert len(headers) == len(r... | 06b7c03316f479a1d1afd12150f484fa9db23cea | 575,144 |
def match_value(df, col1, x, col2):
""" Match value x from col1 row to value in col2. """
return df[df[col1] == x][col2].values[0] | 6735924eb39792f6c61ea193c87b31638ef4589b | 575,145 |
def convert_ck_list_to_select_data(i):
"""
Input: {
lst - CK list object
(add_empty) - if 'yes', add empty line
(sort) - if 'yes', sort by name
(value_uoa) - if !='', find uoa and return uid
(ignore_remote) - if ... | e4b6af9ad83a8d5b71ae0dac6f56edeb224bb670 | 575,149 |
def calculate_intersection(p1, p2, q1, q2):
"""Return the 2D geometrical intersection of segments [p1, p2] and [q1, q2]
inputs:
- p1, p2: 2D points that define the first segment
- q1, q2: 2D points that define the second segment
"""
num_s = float((p1[0] - q1[0]) * (q1[1] - q2[1]) - (p1[1] -... | 66badb561bb8473e494eb246385e7b4d2b80ebcb | 575,157 |
def dict_union(*dicts):
"""Returns a union of the passed in dictionaries."""
combined = dicts[0].copy()
for d in dicts:
combined.update(d)
return combined | 68e5e4787b6db67ee33ac985a43f2e9d4c4936af | 575,159 |
import asyncio
def get_event_loop() -> asyncio.AbstractEventLoop:
"""Return the running event loop if exists, otherwise creates a new one."""
return asyncio.get_event_loop_policy().get_event_loop() | 3fd3e75d9b565427868b810e67fba6e2087b41e6 | 575,160 |
def quote_text(text):
"""Quote text by prepending '>'-characters to each line"""
lines = []
for line in text.splitlines():
if line.startswith('>'):
line = '>' + line
else:
line = '> ' + line
lines.append(line)
return '\r\n'.join(lines) | 0f742998ec1c1d30f8083782b1e7c04cd4eb4530 | 575,169 |
def get_value(hw_lst, level1, level2, level3):
"""Get an specific value from the hardware inventory."""
for entry in hw_lst:
if level1 == entry[0] and level2 == entry[1] and level3 == entry[2]:
return entry[3]
return None | 23221006e1b07806b9c7a1d711922477e6fde64e | 575,170 |
def contains_any(needles, haystack):
""" Returns True if any of the needles are in haystack
>>> contains_any([1, 2, 3], [50, 37, 12, 1])
True
>>> contains_any([1, 2, 3], [50, 37, 12])
False
"""
for needle in needles:
if needle in haystack:
return True
return False | 8aa2f6db3ae814dc100c279c61435794aeed278a | 575,171 |
def is_empty_row(row):
"""Returns True if all cells in a row evaluate to False
>>> is_empty_row(['', False, ''])
True
>>> is_empty_row(['', 'a', ''])
False
"""
return not any(row) | c458bb507273104421817f35da4b1d5e2a8f3606 | 575,175 |
def convert_green(string):
"""Return green text"""
return f"{string}" | 3b0f86ec22e5959fa2545138615757b6c808abf3 | 575,179 |
def get_lhs(equation: str) -> str:
"""Get the left-hand side of the equation.
Args:
equation: The string of the equation to be solved.
Returns:
A string of the left-hand side of the equation.
"""
index = equation.find("=")
return equation[:index] | 11ae13b8658ab519d97a732bc37db35e4eec993d | 575,193 |
def normalizeXRI(xri):
"""Normalize an XRI, stripping its scheme if present"""
if xri.startswith("xri://"):
xri = xri[6:]
return xri | 90bf432a84f62e056d6bfc74d0c0f988adf1b80a | 575,194 |
def returnInput(*args):
"""
This is a function that returns exactly what is passed to it. Useful to hold a place in the dataflow without modifying the data.
"""
return args | 9815b34d650ab7adce6bacf7a1f39b81768ee3a7 | 575,200 |
def correct_ttime_values(df, update_val=999):
"""Update travel times between TAZs so that when travel is impossible, ttime is very large.
This is necessary because in some of the original files, ttime=0 when travel between TAZs is impossible
Use for when the original matrix is not missing any TAZ pairs.
... | b19797682674ee3e0d998d72beabda252db37d8d | 575,203 |
def general_poly(L):
"""
L, a list of numbers (n0, n1, n2, ... nk)
Returns a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0
"""
def poly(L, base):
'''
'''
polySum = 0
exponent = len(L)-1
for ... | 9b772a4164841532c8167519460ad83e22c26fab | 575,204 |
def list_check(lst):
"""Are all items in lst a list?
>>> list_check([[1], [2, 3]])
True
>>> list_check([[1], "nope"])
False
"""
counter = []
for each in lst:
if isinstance(each, list):
counter.append(True)
else:
counter.appen... | e3dd483d57f153c102ecd2d2592491ec36afd077 | 575,212 |
def clean(history):
"""Clean up records from source database.
Receives a list of record and sanityze them in order for them to be
properly imported to qutebrowser. Sanitation requires adding a 4th
attribute 'redirect' which is filled with '0's, and also purging all
records that have a NULL/None dat... | 42383274daa6ca3ea4b7d6a4b300da0c4debc955 | 575,213 |
def finesse_coefficient(R):
"""Finesse coefficient of the etalon
Parameters
----------
R : np.float64
Reflectance of the etalon mirrors
Returns
-------
np.float64
Finesse coefficient of the etalon
"""
return 4 * R / (1 - R)**2 | 0c73672f7586b9e0aaee30fa62d22700c35c6f55 | 575,214 |
def msf(magnitude):
"""
Magnitude scaling factor
:param magnitude: Earthquake moment magnitude
:return: float
"""
magnitude_sf = 10. ** 2.24 / magnitude ** 2.56
return magnitude_sf | a323858cba5be92588e689bf65be71a8852eaa01 | 575,215 |
import random
def get_greeting(person):
""" Get a random greeting, greeting *person* """
greetings = ["hello!", "hi", "namaste", "privet", "konichiwa", "nihao!"]
return f"{random.choice(greetings).title()}, {person}." | b917af2dbe5f81c27631125e2e765fa76c5a030c | 575,217 |
def update_has_changed_the_analysis(form, form_dict):
"""Return ``True`` if the update from form_dict to form has changed the morphological analysis of the form."""
try:
old_syntactic_category_name = form_dict['syntactic_category'].get('name')
except AttributeError:
old_syntactic_category_na... | f9042dc17cbc4fb4c54758b29bf9d102ef961afd | 575,220 |
def nth_item(n, generator):
"""Returns the `n`-th item yielded by `generator`.
Item numbering starts from 0.
"""
for x in range(n):
next(generator)
return next(generator) | 667e52ecacc4d62188bbcb52f4ecf951b49627d3 | 575,225 |
from typing import OrderedDict
def _get_format_order(input_format: str):
"""Return order of <artiste>, <album>, <track>, <year> in input_format."""
unordered_dictionary = {input_format.find("<artiste>"): "artiste",
input_format.find("<track>"): "track",
... | 2c246cc67cff8ec7dd68e971848a86a2761d305c | 575,228 |
def collect_train_and_val_data(splits_per_class, split_index):
"""
Collect validation and training data from split according to split_index
Normally, we collect 1 split for training and the remaining for validation
- splits_per_class - list containing the splits
- split_index - index to get for tr... | 2bb527f8196429ff36eacf0f45512d50b32ff535 | 575,232 |
def _current_sc_dir(sc_dir, grid):
"""Return current direction(s) for semicoarsening.
Checks which directions can actually still be halved and adjusts ``sc_dir``
if necessary for this particular grid.
Parameters
----------
grid : TensorMesh
Current grid; a :class:`emg3d.meshes.TensorM... | caf11034f152ba66c388f4ba9bfe67082323e660 | 575,233 |
def lcstr(astr):
"""Convert a string to lower-case"""
return astr.lower() | caa9d251d7fa4dd065d520f5219a53e5ea052258 | 575,241 |
def polstring_version_required(str_in):
"""
What SICD version does the pol string require?
Parameters
----------
str_in : None|str
The tx/rcv polarization string.
Returns
-------
tuple
One of `(1, 1, 0)`, `(1, 2, 1)`, `(1, 3, 0)`
"""
if str_in is None or str_in... | ecfc9b367acb57b4f83a5e05dbd3fe420a1fd402 | 575,246 |
def scan_spectrum_file(filename):
"""
go over mgf file and return list with all spectrum titles
"""
titles = []
f = open(filename)
while 1:
rows = f.readlines(10000)
if not rows:
break
for row in rows:
if row[0] == "T":
if row[:5] == "TIT... | 73507ee27c6157acceee038a8cd50c7a87683113 | 575,247 |
import torch
def reduce_sign_any(input_tensor, dim=-1):
"""A logical or of the signs of a tensor along an axis.
Args:
input_tensor: Tensor<float> of any shape.
axis: the axis along which we want to compute a logical or of the signs of
the values.
Returns:
A Tensor<float>, which as th... | 72dde84d97a8744c880bd7bbc92cb020cbe0d156 | 575,253 |
import yaml
def readYAML(filename):
"""Reads and returns YAML data from file."""
with open(filename, "r") as f:
data = yaml.load(f, yaml.SafeLoader)
return data | 0ebcd20b39e117df4aa8c2799401712a1be5fd44 | 575,256 |
def get_predicate_indices(predicate, inverted):
"""
Gets the indices of the predicate's input and output.
:param predicate: the predicate
:type predicate: Predicate
:param inverted: if the predicate is inverted
:type inverted: bool
:return: the input and output indices
:rtype: (list[int... | 4248d4587072b42d477a2431a35f34a0b39a1e4d | 575,257 |
def razlika(n):
"""Poišče razliko med vsoto kvadratov prvih n števil in kvadratom vsote prvih n števil"""
vsota_kvadratov = 0
kvadrat_vsote = 0
for i in range (n + 1):
vsota_kvadratov += i ** 2
kvadrat_vsote += i
return abs(kvadrat_vsote ** 2 - vsota_kvadratov) | cd9becabcfa936d93420366c23910076093ad804 | 575,258 |
def tint_red(text: str) -> str:
"""Tints a given text red.
:param text: The text to be tinted
:type text: str
:returns: The same text but tinted red
:rtype: str
"""
return ("\x1b[31m%s\x1b[0m" % text) | 4e01164d55c075f1b7145d083ce44a0d07670ed7 | 575,261 |
def _add_path(root_path, relative_path):
"""Add another level to an LDAP path.
eg,
_add_path ('LDAP://DC=gb,DC=vo,DC=local', "cn=Users")
=> "LDAP://cn=users,DC=gb,DC=vo,DC=local"
"""
protocol = "LDAP://"
if relative_path.startswith(protocol):
return relative_path
if root_... | 5f58ece8e509837ab3c058ad7ae993f3ab08df87 | 575,263 |
import requests
from bs4 import BeautifulSoup
def get_ansible_modules(url):
""" This function returns a dictionary which each key is the name of an ansible module and the value is its description """
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
span_list = soup.fin... | 453163c3fa01895ec8ed04331fd57c717f5454a9 | 575,265 |
def __shellquote(s):
"""
Quote and escape the supplied string for use in shell expressions.
"""
return "'" + s.replace("'", "'\\''") + "'" | 37cfa7840b925a7297125b6733465e7e254b7629 | 575,266 |
from typing import Optional
def build_netloc(host: str, port: Optional[int]) -> str:
"""
Build a netloc from a host-port pair
"""
if port is None:
return host
if ":" in host:
# Only wrap host with square brackets when it is IPv6
host = f"[{host}]"
return f"{host}:{port}... | af65332da6c275dc39b6cc4b2b74eef42c4fe02b | 575,268 |
from pathlib import Path
import ast
import re
def get_entry_point(filename: Path, prefix: str, import_path: str) -> list[str]:
"""Returns the entry point string for a given path.
This looks for LIBTBX_SET_DISPATCHER_NAME, and a root function
named 'run'. It can return multiple results for each file, if m... | 62ce384267fb5f80ff86969d8d08d42b1fcbfdd8 | 575,284 |
from pathlib import Path
def force_create_file(file_name: str, suffix: str="") -> Path:
"""
Creates the new file with the given name to disk, returning the
associated object. If the given file already exists, an incremented number
is appended until the new file can be created.
Raises:
`OS... | e717e89f45b3475003e967f8c4a3879dc3ccfc49 | 575,290 |
def _getNextCurrControl(curr_control, res_control, max_control):
"""Compute the next possible control instruction
Args:
curr_control (list of int|str): last executed control
res_control (list of int|str): resolution control
max_control (list of int|str): maximum control
Returns:
... | 22d336354d55787ad5e425a46ab8cf9e08c25f11 | 575,293 |
def bg_repeat(value):
"""Convert value to one of: ('no-repeat', '')."""
if value == 'no-repeat':
return value
return '' | 5d60476b2879c5db2708542c7517edb23248e9b5 | 575,294 |
from datetime import datetime
def date_to_epoch(dt):
""" datetime object to UNIX epoch timestamp in a string """
return str((dt - datetime(1970, 1, 1)).total_seconds()) | ed7436edd0a369a4bc6dad6431c7b31b796bf206 | 575,297 |
import torch
def densify_features(x, shape):
"""
Densify features from a sparse tensor
Parameters
----------
x : Sparse tensor
shape : Dense shape [B,C,H,W]
Returns
-------
Dense tensor containing sparse information
"""
stride = x.tensor_stride
coords, feats = x.C.lon... | 4ef60f15a1bae846009ddfa76595fa9121fc3035 | 575,298 |
def unit(x):
"""
Optimizes the rendering of time.
.. runpython::
:showcode:
from jupytalk.benchmark.mlprediction import unit
print(unit(34))
print(unit(3.4))
print(unit(0.34))
print(unit(0.034))
print(unit(0.0034))
print(unit(0.00034))
... | 19231cf1f1afdcff69211e627bd97f0de23d4efa | 575,300 |
def error(A, v, f):
"""Compute the error, given A, v, and f.
"""
return f-A@v | 9aac6efd6fcd45dbcfbd1368b09944cf5299803e | 575,304 |
def dotted_prefixes(dotted_name, reverse=False):
"""
Return the prefixes of a dotted name.
>>> dotted_prefixes("aa.bb.cc")
['aa', 'aa.bb', 'aa.bb.cc']
>>> dotted_prefixes("aa.bb.cc", reverse=True)
['aa.bb.cc', 'aa.bb', 'aa']
:type dotted_name:
``str``
:param reverse:
... | e46a1a01286776538ff131609284536693ba379d | 575,308 |
def rotor_energy(J, B, D=0.0):
""" Expression for a linear/prolate top with
centrifugal distortion.
parameters:
---------------
J - integer quantum number
B - rotational constant in MHz
D - CD term in MHz
returns:
--------------
state energy ... | bfe4d12ccb566cc3b8400a9fcf1a9335b46b4cb3 | 575,312 |
from typing import Union
from pathlib import Path
def is_binary(path: Union[Path, str]) -> bool:
"""Return true if the given filename is binary.
Args:
path (pathlib.Path): File to check
Returns:
bool: True if file appears to be binary, False otherwise
"""
if isinstance(path, str)... | 543d72dd0710222717b20cf50c2efb9d9e12bc9c | 575,316 |
import random
import glob
def sample_malwares(num_to_sample):
"""
Sample a certain number of malwares from the given directory.
Args:
num_to_sample: the number of malwares that needs to be sampled
Returns: the list of malware directories.
"""
malware_dirs = random.sample(glob.glob... | 8f898e76886a20d4811a9a9895045c32ea37e1c0 | 575,317 |
import json
def read_info(infile_path):
""" Load JSON file given path.
Utility function to read the JSON file from infile_path.
Parameters
----------
infile_path : str
Absolute path to json file.
Returns
-------
info : dict
Deserialised json file through the json.loa... | 99da48fd1aed026dfb66fd0c1db4c36ed696053b | 575,322 |
def hit_or_stand(player_hand,deck_1):
"""
Function to give Player a choice to HIT or STAND.
"""
global player_playing
while True:
temp = input("HIT OR STAND? : ")
if temp == '':
print("Please Choose a valid option.\n")
if temp[0].lower() == 'h... | 92ac7de9e92aa119c11e4d01ac5c817f4b1c4a0b | 575,324 |
def from_dict(x: dict) -> int:
""" Converts a dictionary containing the prime factors and powers of an integer into it's integer form."""
res = 1
for p, r in x.items(): res *= p**r
return res | 8fab9139694b5fb19cc2a3e3b3ca08e136c32e32 | 575,325 |
def company(x):
"""
Return company code from given Upc code.
:param x: "Upc" column of DataFrame
:return: company code
"""
try:
p = x[:6]
if p == "000000":
return x[-5]
return p
except:
return -9999 | 521dcfffad51515f037914e01be6b4df0539ab76 | 575,326 |
import inspect
def transform(csv_row: dict, typed_dict) -> dict:
"""Transform CSV field values into types specified on a TypedDict subclass.
Skips fields that are not defined on the subclass.
:param csv_row: Row from csv.DictReader
:param typed_dict: A TypedDict subclass.
:type typed_dict: Subc... | 412cef96ba2d1b3ca4d19bc9dac384d7f1d62381 | 575,329 |
def add_ngram(sequences, token_indice, ngram_range=2):
"""
Augment the input list by appending n-grams values
:param sequences:
:param token_indice:
:param ngram_range:
:return:
Example: adding bi-gram
>>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]]
>>> token_indice = {(1, 3): 1337, ... | bf3600ab76c08d31b2f471880a6da648276491ef | 575,330 |
def single_fscore_PR(prec, rec, beta):
""" Computes an F-score from a precision and recall score """
betasq = beta ** 2
if prec == 0. or rec == 0.:
return 0.
return (1+betasq) / (1./prec + betasq/rec) | c5e032d8161a967bdac5e78467d0b321385eee17 | 575,331 |
def directory_skeleton(param_dict, proj_dict):
"""
Creates the directory skeleton for the current project
Parameters
----------
param_dict: python dictionary
dictionary with `project` variables
proj_dict: python dictionary
dictionary with info of the project that uses the
... | c10320f8b5fdfac1716351cdd0dc98d79f683b13 | 575,332 |
import re
def removeSpecialChars(stringToChange):
"""Given a string, removes all non-alphanumeric characters"""
reg = re.compile('[^a-zA-Z0-9]')
return reg.sub('', stringToChange) | f0203f169f16785d5ee6e37bf43e4a864b5489c2 | 575,333 |
from typing import Tuple
def depth_range2depth_inv_range(depth_range: Tuple[float, float]) -> Tuple[float, float]:
"""It converts a depth range into the inverse depth range.
Args:
depth_range: 2-tuple specifying the depth range.
Returns:
The inverse depth range 2-tuple.
"""
asse... | 077a263c3c360b2121f89aa6f49a78263c8fb1d4 | 575,335 |
import importlib
def import_provider_module(provider_type):
"""
Return the module for a provider.
"""
tasks = importlib.import_module('provider.' + provider_type)
return tasks | 6948bf705f91c20563e7898b09fbf949c933d876 | 575,338 |
import requests
import json
def request_post_json(url: str, data_: dict) -> dict:
"""Get JSON object version of reponse to POST request to given URL.
Args:
url: URL to make the POST request.
data_: payload for the POST request
Returns:
JSON decoded response from the POST call.
Empty dict is ... | feeda69f9a2f02a0195d6400602f379f2920c907 | 575,340 |
import re
def _matches_criteria(responses, match_criteria):
"""Checks if response dict matches match criteria.
There are two categories of values in match_criteria: bool and regexp/str.
Bools must match exactly, while regexp must find a match in the response
value.
Args:
responses (dict): device respo... | 9e34a7592c55043d471e3b459281a323c54d4eef | 575,342 |
def topic_name(topic_id: int) -> str:
"""Conventional format for naming topics in tables"""
return f"topic_{topic_id}" | bb4bc79b923780395449afcbcdd04577ea135471 | 575,343 |
def _set_ghparameters(parlist, default, deg_gh) :
""" Set up the parameters given a default
if the Input does not have the right size (deg_gh) it fills in the rest
with the default
Input is :
==========
: param parlist : the input parameters you wish to set
: param default : the default wh... | 30bc809fdf3aa6b8fbe94f4e4bcd32f0fd1cdbae | 575,345 |
def _get_bads_from_tsv_data(tsv_data):
"""Extract names of bads from data read from channels.tsv."""
idx = []
for ch_idx, status in enumerate(tsv_data['status']):
if status.lower() == 'bad':
idx.append(ch_idx)
bads = [tsv_data['name'][i] for i in idx]
return bads | b8f7583fc45b45e241ee51fead8b30108b6af07e | 575,347 |
def validate_start(value):
"""Validate "start" parameter."""
if value not in ("watch", "exec"):
raise ValueError('Must be "exec" or "watch"')
return value | c67aa83eff2f88ed23162520654ed04b55d3f474 | 575,350 |
import json
def _parse_json(json_path: str, start_label=0, predicate=lambda json: True):
"""
Parses json file to the format required by DALI
Args:
json_path: path to json file
start_label: the label, starting from which DALI will assign consecutive int numbers to every transcript
p... | e5cc1bce0b1912ad3c8a154cb706b439e7f86511 | 575,353 |
def transtree_to_coords_lists(transtree):
"""
Each leaf represents a list of translocations of shown by the read.
For each leaf, return a list of two or more coords from root to the leaf.
"""
ret=[]
for leaf in transtree.leaves[::-1]:
nodes = leaf.to_root[::-1]
if len(nodes)>=2:
... | 6d71666cc8f59af2a68184878ad12045b83440ad | 575,359 |
def _linear_func(x,deriv,xo,yo):
"""Evaluate a linear function"""
return deriv*(x-xo)+yo | 53311e2f05b9cf3cd01acde8bb30e59520d8a71d | 575,361 |
def get_output_shape(data):
"""Returns output shapes."""
return (3,) | e418bbf96679dd37856c8734a3f095d691667ced | 575,363 |
def prepare_check(data):
"""Prepare check for catalog endpoint
Parameters:
data (Object or ObjectID): Check ID or check definition
Returns:
Tuple[str, dict]: where first is ID and second is check definition
"""
if not data:
return None, {}
if isinstance(data, str):
... | 8da7291f208e7e4d6acdee691c59534d8632598a | 575,367 |
def get_where_operator(conds):
"""
[ [where_column, where_operator, where_value],
[where_column, where_operator, where_value], ...
]
"""
where_operator = []
for cond in conds:
where_operator.append(cond[1])
return where_operator | 09e9777e161614a782e2897c07939ce053dfb8c3 | 575,368 |
import torch
import math
def rotate(x, angle):
"""Rotate a 2D tensor by a certain angle (in degrees)."""
angle = torch.as_tensor([angle * math.pi / 180])
cos, sin = torch.cos(angle), torch.sin(angle)
rot_mat = torch.as_tensor([[cos, sin], [-sin, cos]])
return x @ rot_mat | eb333583fc63e1955c2b1b7c5af1698a84fda2da | 575,371 |
def get_pos_tags(doc, n):
"""Get POS-tagged tokens in the format of a list of
(token, POStag) pairs for all sentences in doc.
Returns upos (Universal part-of-speech) tag only, not
xpos (treebank-specific part of speech)"""
def getpos(i):
tokens = []
for token in doc.sentences[i].w... | 4a9ce8711e173a6e04b96f1853b72f69bc85bdda | 575,374 |
def line_to_dict_format(row: list):
"""
This function converts a pandas dataframe row to a dictionary
"""
latitude = row[0]
longtitude = row[1]
quality2 = row[2]
quality1 = row[3]
a2_rssi = row[4]
quality2_std = row[5]
quality1_std = row[6]
a2_rssi_std = row[7]
past_date... | 47cf47a3f24d18f318a878f180115b5a6c4b27e1 | 575,377 |
def make_edges(nodes, directed=True):
"""
Create an edge tuple from two nodes either directed
(first to second) or undirected (two edges, both ways).
:param nodes: nodes to create edges for
:type nodes: :py:list, py:tuple
:param directed: create directed edge or not
:type directe... | e0938b63be32c8854416785584dd3abeaecbd795 | 575,380 |
def string_name(value: str, characters: str = ".") -> str:
"""
Find and replace characters in a string with underscores '_'.
:param value: String to be validate
:param char: Characters to be replaced
:return value: Re-formatted string
"""
for char in characters:
value = value.repla... | d20c42b859a61c2b5b523263f8548c8988dd4348 | 575,381 |
def _process_nugget(nugget):
"""
Take raw nugget input and convert to a value and a string
:param nugget: Input nugget. Can be a float (fixed nugget) or a string
(nugget is inferred via fitting)
:type nugget: float or str
:returns: Tuple containing nugget value (float) and nu... | 7e15d5e1ed171e85c77485928d9f468190b25a2c | 575,384 |
def each_item(*validators):
"""
A wrapper which applies the given validators to each item in a field
value of type `list`.
Example usage in a Schema:
"my_list_field": {"type": Array(int), "validates": each_item(lte(10))}
"""
def validate(value):
for item in value:
for v... | fdae19fae7952dd1b9430b36d04e8965b32139c8 | 575,385 |
def number_of_nodes(G):
"""Return the order of a graph = number of nodes."""
return G.number_of_nodes() | e9bfbbf03ba43a930fd22fd2f007f14938f810c6 | 575,386 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.