content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import torch
def angle(x, eps=1e-11):
"""
Computes the phase of a complex-valued input tensor (x).
"""
assert x.size(-1) == 2
return torch.atan(x[..., 1] / (x[..., 0] + eps)) | 8cfbf6c9aefddfcb7de5af3d1fca89f7fb3dfd32 | 32,184 |
def progressive_step_function_maker(start_time, end_time, average_value, scaling_time_fraction=0.2):
"""
Make a step_function with linear increasing and decreasing slopes to simulate more progressive changes
:param average_value: targeted average value (auc)
:param scaling_time_fraction: fraction of (en... | 066ae4415c942248511c04b6732f98587f2f524f | 32,186 |
def _GetVocabulary(vocab_filepath):
"""Maps the first word in each line of the given file to its line number."""
vocab = {}
with open(vocab_filepath, 'r') as vocab_file:
for i, line in enumerate(vocab_file):
word = line.strip('\r\n ').split(' ')[0]
if word:
vocab[word] = i
return vocab | 2db9fd70180e9fc2c64e604609fc007a533f2aa9 | 32,194 |
def filter_to_region(node, contig=None, coords=None):
"""Return True iff a node is within a given region (and region is specified)."""
((seq, coord), miss) = node
if contig and seq != contig:
return False
if coords and coord < coords[0]:
return False
if coords and coord > coords[1]:
... | bbbde3a35d464883de4e92c62f2a574eda11ff2f | 32,197 |
def is_setuptools_enabled(pkginfo):
"""Function responsible to inspect if skeleton requires setuptools
:param dict pkginfo: Dict which holds the package information
:return Bool: Return True if it is enabled or False otherwise
"""
entry_points = pkginfo.get("entry_points")
if not isinstance(entr... | 1faf21c804aa0b0a5b681d09ca4577d15a264ae7 | 32,198 |
def add_docusaurus_metadata(content: str, id: str, title: str, hide_title) -> str:
"""
Add docusaurus metadata into content.
"""
return f"---\nid: {id}\ntitle: {title}\nhide_title: {hide_title}\n---\n\n" + content | 00b3e9f583565d38e03e361957c942b16d1e270a | 32,199 |
def orb_rot_meta(name):
"""Parse metadata from orbital rotation variable name
Args:
name (str): optimizable variable name
Return:
dict: metadata
Example:
>>> name = "spo-up_orb_rot_0000_0002"
>>> orb_rot_meta(name)
>>> {'prefix': 'spo-up', 'i': 0, 'j': 2}
"""
useful = name.replace('orb_... | 8bcb658e9daf51d31aae33789dc86db5c33d2158 | 32,202 |
def _to_gj_point(obj):
"""
Dump a Esri JSON Point to GeoJSON Point.
:param dict obj:
A EsriJSON-like `dict` representing a Point.
:returns:
GeoJSON representation of the Esri JSON Point
"""
if obj.get("x", None) is None or \
obj.get("y", None) is None:
retu... | 8ee9299be34fe7402eb350589a58a5fdb471c20a | 32,205 |
def sign(amount: float | int) -> str:
"""Returns a string representing the sign of the given amount."""
if amount < 0:
return "-"
elif amount > 0:
return "+"
else:
return "" | 53014ab61ff46242a9a17b9b43ac7562a4fed8b2 | 32,209 |
def even_numbers(maximum):
"""The even_numbers function returns a space-separated string of all positive
numbers that are divisible by 2, up to and including the maximum that's passed
into the function. For example, even_numbers(6) returns “2 4 6”."""
return_string = ""
for x in range(2, maximum + 1, 2):
return_... | 241056401ae8b2dc8b906d63cdd5507b6957cdb4 | 32,210 |
def _remove_border_columns(axs, col_size):
"""Removes the border columns, returning the remaining columns."""
num_cols = axs.shape[1]
border_indices = list(range(col_size, num_cols, col_size+1))
border_axs = axs[:, border_indices].reshape(-1)
[ax.remove() for ax in border_axs]
data_indices = [co... | fb1dd856010352b0442b32dca98481f323669bbd | 32,211 |
def sdfHasProp(mol, sdfprop):
"""
sdfHasProp() returns a boolean that indicates the presence of property sdfprop in molecule mol
"""
sdfkeyvals = mol["keyvals"]
return sdfprop in [pair[0] for pair in sdfkeyvals] if sdfkeyvals else False | baf19e34452c7904501462fb79db0f52dd35cc00 | 32,212 |
def flatten_dict(d, tld="") -> dict:
"""Flatten the given dict recursively while prepending the upper level key to all the lower level keys separated by a dot (.)"""
new_dict = {}
for k, v in d.items():
if isinstance(v, dict):
lower = flatten_dict(v, tld=f"{tld}{k}.")
new_dic... | ed44559d4a3083c51f85a55a07b820d058272412 | 32,213 |
def ndvi_filter_date(image_directory):
"""A function that extracts the date of image collection from the imagery path name
Parameters
----------
directory: directory to file including study
site e.g: "'HARV/landsat-crop/LC080130302017031701T1-SC20181023151837'"
Returns
-------
... | 57246532c67e7757dfe704f796ecd51986f2dd39 | 32,216 |
def get_top_reactions(reactions, threshold):
"""
We get all the posts with reactions above a threshold.
If there are > 5 posts, we take those 5.
Any more than 9 posts, we take the top 9.
:param reactions: List of reactions for each post.
:param threshold: The minimum number of reactions for the ... | b90ecaee2739717bfa23a727c9c6d854345943e1 | 32,218 |
import re
def remove_header_units( headers ):
"""
Removes units from headers.
Headers are enclosed in parenthesis.
:param headers: List of headers.
:returns: List of headers with units removed.
"""
headers = [
re.sub( '\(.*\)', '', h ).strip()
for h in headers
]
... | f05d6c86610efe192badec32fbc5077e0ed267d7 | 32,226 |
def change_centre_variant_3(centre):
"""Variant of 'change_centre' function to generate '-3' designs."""
return (centre[0] * 0.99, centre[1] * 0.96) | b3c48bf018fe885a383724145b9826113cce55e6 | 32,227 |
def not_0(upper, lower):
"""Fills both values to whichever is not equal to 0, or leaves in place."""
# Note that I compare the values to zero istead of using if not lower
# This is because the values coming in can be anything, including an
# empty list, which should be considered nonzero
if upper ==... | d436f764d79f1febe5dbfbf2407d5921ea06e2ab | 32,228 |
def repos_split(repos_relpath):
"""Split a repos path into its directory and basename parts."""
idx = repos_relpath.rfind('/')
if idx == -1:
return '', repos_relpath
return repos_relpath[:idx], repos_relpath[idx+1:] | 3bd1d76f75664ac28d03277214b5cd9f2bdcaf05 | 32,234 |
def file_size(path):
"""Return the size of a file"""
f = open(path)
f.seek(0,2)
return f.tell() | 915a8225c0d084efee7262383131d51ce5335aa3 | 32,236 |
def convert_dict_to_text_block(content_dict):
"""
Convert the given dictionary to multiline text block
of the format
key1: value1
key2: value2
"""
message = ""
for k, v in content_dict.items():
message += "{}: _{}_\n".format(k, v)
return message | 980822572c30d5af392ded834bece095c79815ce | 32,240 |
def check_emotes(line, emotes=[]):
"""Checks if a specific lines contains at least one emote."""
_line = str(line).split()
for word in _line:
_word = word
try:
_word = _word.split(':')[1]
_word = _word.split('\\')[0]
except IndexError:
pass
... | 6bb870f19e08262b71ce39c82f9253b7abe4fc2a | 32,244 |
import requests
def get_bytes_from_url(url): # pragma: no cover
"""
Reads bytes from url.
Args:
url: the URL
Returns:
the bytes
"""
req = requests.get(url)
return req.content | bf00ec24300167cea4f75df809d65f1991af4ea8 | 32,247 |
def TrimBytes(byte_string):
"""Trim leading zero bytes."""
trimmed = byte_string.lstrip(chr(0))
if trimmed == "": # was a string of all zero byte_string
return chr(0)
else:
return trimmed | fa6a57e7799819790410a4e7c2a96ba4253ca88b | 32,250 |
def open_text(fname):
"""
open and read a text file line by line.
convert to and return the list
parameters:
fname: string, full path to the file
"""
with open(fname, 'rb') as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of ... | c8d21244e9409fe3c8c719bd993654dc7f0a4a6b | 32,259 |
def attestation_attestation_provider_show(client,
resource_group_name=None,
provider_name=None):
""" Show the status of Attestation Provider. """
return client.get(resource_group_name=resource_group_name,
p... | 682c7945adc7f71156135d6115d078c3bf2e4a5f | 32,263 |
from typing import Literal
def escape_triple_quotes(string: str, single_quote: Literal["'", '"'] = '"') -> str:
"""Escape triple quotes inside a string
:param string: string to escape
:param single_quote: single-quote character
:return: escaped string
"""
assert len(single_quote) == 1
quo... | 078e7d2ea832cb06626172e1133dcbeeaa6b7aa5 | 32,264 |
def calculate_test_values(
total_words, ocr_recognized_words,
tp, tn, fn
):
"""
Calculates the model test values :
TP : True Positive (There are words and every word has been recognized)
TN : True Negative (There is no word and no word has been recognized)
FP : False Positive (There ... | e0de958ff308ac3c6a1425203ff3b92b1ecb5fca | 32,265 |
import pkg_resources
import csv
def load_dict() -> dict:
"""
Loads reference data to dictionary.
:return: dictionary of the syllable reference data
"""
file_name = "data.csv"
file_path = pkg_resources.resource_filename(__name__, file_name)
words = {}
with open(file_path, newline="") a... | 8260366a4efaf0d2b1ab14d96c20728b1e50ffa3 | 32,266 |
def return_code_from_exception(exception):
"""Returns the exit code that would result of raising the exception."""
if exception is None:
return 0
if isinstance(exception[1], SystemExit):
return exception[1].code
return 1 | de92ca34d3959a59b6c485ad2cdaf2f1d4628a8e | 32,272 |
def first_neg(x):
"""
Finds index of first negative number in a list
"""
res = [i for i, x in enumerate(x) if x < 0]
return None if res == [] else res[0] | ddde2f4b6d19ca5b80d956fdf9f4c8b3f8b40335 | 32,274 |
import random
def backoff_time(attempt, retry_backoff=2., max_delay=30.):
"""Compute randomized exponential backoff time.
Args:
attempt (int): attempt number, starting at zero.
Keyword Args:
retry_backoff(float): backoff time on the first attempt.
max_delay(float): maximum returned value.
"""
... | 907e636dc60a81fa9d7d0ebf5c42841b828a693c | 32,275 |
def get_fresh(old_issue_list, new_issue_list):
"""Returns which issues are not present in the old list of issues."""
old_urls = set(x['url'] for x in old_issue_list)
return [x for x in new_issue_list if x['url'] not in old_urls] | b79313c53f66694038871bd94969b8b297c211a7 | 32,278 |
from typing import List
def count_increases(measurements: List[int]) -> int:
"""Count the number of times the depth measurement increases."""
total = 0
past = 9999999 # Make the first comparison arbitrarily large.
for measurement in measurements:
if measurement > past:
total += 1
... | 97ad846b0547a3f989805a5deacc0619f45b1cb3 | 32,279 |
import math
def distance_calc(point1, point2):
"""
to calculate the distance of 2 points
:param point1: pt1
:param point2: pt2
:return: the distance
"""
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) | 47be46da7e8251ff15fd2c5eb1b8be7d11d4a416 | 32,284 |
def clean_reg_name(reg, list):
"""
Clean the name of the registers by removing any characters contained in
the inputted list.
"""
for char in list:
reg = reg.replace(char, '')
return reg | 70bcd35e498c61c4ab1d53896d85fcd4fb74b5ff | 32,286 |
def count_crickMAX(args):
"""Count the number of sequences in the Crick fasta file"""
with open(args.crick, 'r') as crick_in:
count = 0
for line in crick_in:
if line.startswith('>'):
count +=1
return count | c4937613b917107f74aa6658719d3e6e243eebd2 | 32,289 |
import re
def should_ignore(ignore_list, url):
"""
Returns True if the URL should be ignored
:param ignore_list: The list of regexs to ignore.
:param url: The fully qualified URL to compare against.
"""
for pattern in ignore_list:
compiled = re.compile(pattern)
if compiled.sea... | 03cc80a4611434ebc04d92885698f61c0871cb0a | 32,294 |
async def evaluate_requested_value(laid_card, input_foo):
"""
Function used to evaluate requested value of cards when player play jack special card.
:param laid_card: tuple with last played card
:param input_foo: function used to ask player about value
:return: string object of requested value or No... | e3bb40ca5b3f16cef09d8847ddf4de7311e1a66e | 32,295 |
def apply_multiplicities(data):
"""
Takes in the Data class of scattering data returned by convert_to_numpy()
and applies the multiplicity to each intensity.
Sets the multiplicity to 1 to avoid accidental double-use.
Parameters
----------
data : Data
Returns
-------
data: Data
... | 89904a9f2602ded84d96de92f8f1da6b53420179 | 32,297 |
def beta_pruning_terminal_state(state, depth_remaining, time_remaining):
""" Terminal state returns True when we reach a terminal state,
or when we run out of time or depth we're allowed to search
:param state: The state to evaluate if it is in a terminal state
:param depth_remaining: The remaining dep... | e78801a07cc571697a35997ef084c0356e68981b | 32,298 |
def _urljoin(*parts):
"""Concatenate url parts."""
return '/'.join([part.strip('/') for part in parts]) | 4886102b52461944f3c63ab7c0695218698cb47a | 32,300 |
def parse_qualifier_block(text):
"""Parse qualifiers from qualifier block.
Qualifiers are split by newline -> 21 spaces -> slash
If value, Remove leading/trailing ", leading newline -> 21 spaces
Otherwise it's boolean, e.g. /pseudo, so set True
Store qualifiers of same type in lists, otherwise ju... | 843b9cd472d16716baf7969f9e62f539d8a0e986 | 32,301 |
def file_to_dataset(file):
"""Example function to derive datasets from file names"""
if "ZJet" in file:
return "Z"
elif "WJet" in file:
return "W"
elif "HToInvisible" in file:
return "Hinv" | 4e759054df3889e3d6f1ca1b0d3ed080f035d233 | 32,303 |
def identity(arg):
"""
Simple identity function works as a passthrough.
"""
return arg | e702e3af1a4894c124686667038d6d7ead37a4b6 | 32,305 |
def _get_node_count(graph_entry):
""" Get number of nodes"""
return graph_entry.vcount() | e5e9992aadfa0d2f84c698b1ceeae0c5f500c72e | 32,306 |
def find_person(data: list, lineno: int) -> dict:
"""
Function to find a person in a list of dictionaries representing
individuals in the CPS
"""
for person in data:
if person["a_lineno"] == lineno:
return person
# raise an error if they're never found
msg = f"Person with... | c568ba1ee56f016f6f082a9a9a65b20cf399968a | 32,308 |
def fuzzy_list_match(line, ldata):
"""
Searches for a line in a list of lines and returns the match if found.
Examples
--------
>>> tmp = fuzzy_list_match("data tmp", ["other", "data", "else"])
>>> print(tmp)
(True, "data")
>>> tmp = fuzzy_list_match("thing", ["other", "else"])
>>... | 8cbc92634859b991ac77b6bfab7c8825b9b108bb | 32,309 |
def tikznode(x, y, text, modifier=""):
"""
Return string for TikZ command to draw a node containing the text at (x,y), with optional `modifier` string to set draw style.
"""
return f"\\draw ({x}, {y}) {modifier} node{{{text}}};" if not (text == "") else "" | 173d13a038bcda3da75aa8d203f63fce5f22ba92 | 32,310 |
def get_literal_list(f):
"""
return the literals of the formula
@param f:
@return: set of the literals
"""
literal_list = []
for claus in f:
literal_list += claus.literals
return literal_list | 6f33e09e9e0fbb5c0c2991997c6de7bef0e284e6 | 32,313 |
def distance(x0, y0, x1, y1):
"""distance between points"""
dx = x1 - x0
dy = y1 - y0
dist = ((dx ** 2) + (dy ** 2)) ** 0.5
return dist | 6e857156f16e5d1bfd8a26686f1df921dfa60b62 | 32,314 |
import re
def reduceBlank(text, keepNewLines=False):
"""
Strip a string and reduce all blank space to a unique space. If you set keepNewLines as True, it will keep a unique '\n' at each blank space which contains a '\n' or a '\r'
"""
if text is None:
return None
text = text.strip()
... | 9203db3cb6bf3d1dccf5b175725a21e1e94ae812 | 32,321 |
import torch
def generate_uniform_mask(features, missing_rate):
"""
Parameters
----------
features : torch.tensor
missing_rate : float
Returns
-------
mask : torch.tensor
mask[i][j] is True if features[i][j] is missing.
"""
mask = torch.rand(size=features.size())
... | d47b7997ce9014264f89e2a1afffec12b4f4a4bb | 32,322 |
def GrossRet(r,delta):
"""Compute the gross return on saving
Args:
r (float): rental rate of capital
delta (float): capital depreciation rate
Returns:
(float): gross return on saving
"""
return 1+r-delta | cb9ede129b9ce8d578b3d9343ec95b5e90da56c0 | 32,326 |
def get_dhcp_server(network=None, asset=[]):
"""Return IP address of DHCP server based on network or asset.
Args:
network: string, white, green or blue
asset: string, asset name
Return:
dhcp_server: string, IP address
"""
if network == 'blue' or asset[:1] == 'b':
dhcp_server = '172.16.2.10'... | e6c6a7f8410a4c2151ffb104eca2da380cbbe151 | 32,328 |
from pathlib import Path
def get_image_filenames(images_directory, image_band="i", check_band=False):
"""
Retrieves a list of all available filenames for a given directory, and a given band.
WARNING: Optimized for HSC filename format (ex: HSC-I_9813_4c3.fits).
"""
image_filenames = []
images =... | 61e9d1a396570fed6fbaa22ba0b0958f08988037 | 32,330 |
def create_skeleton(segments, html):
"""
Create skeleton file
:param segments: Translation segemnts
:type segments: list
:param html: source html document
:type html: str
:return: document skeleton
:rtype: str
"""
for i, seg in enumerate(segments, 1):
html = html.replace... | a7b17830b3e5ac9a45a198a4675e26de34ee7ce1 | 32,331 |
def med_min_2darray(a):
"""Takes in a list of lists of integers and returns the minimum value."""
return min(min(inner) for inner in a) | c30a7588a11e2c23829fe73b6d84ffdaee8fb321 | 32,334 |
def define_title(overlap_kind):
"""
This function sets the specification of the title of the plots.
:param bool overlap_kind: the boolean that determines if the overlap
is per pixel or shoebox
:returns: title
"""
if overlap_kind:
title = "per pixel"
els... | 60b08193f083277eacf7314e88831deab23940a4 | 32,335 |
import sqlite3
def read_metadata_table(db_file_name):
"""Read data from the metadata table of DB"""
conn = sqlite3.connect(db_file_name)
c = conn.cursor()
#Read all rows from metadata TABLE
c.execute('SELECT * FROM metadata')
metadata_contents = c.fetchall()
conn.close()
return metad... | f743f49c7608816e02d110ddd8e224b110fbe4cf | 32,336 |
import math
def lenofb64coding(initlen):
"""
Calculates the length of a Base64 encoded string of data of the initial length initlen
"""
x = math.ceil(initlen * 4 / 3)
while x % 3 > 0:
x += 1
return x | 950231737c6ed7e30cef5d838b964c796ca1d273 | 32,337 |
import math
def quadratic(a, b, c):
"""Solves the quadratic equation
ax^2 + b + c = 0
(-b + sqrt(b^2 - 4ac)) / 2a
"""
x = (math.sqrt((b * b) - (4 * a * c)) - b) / (2 * a)
return x | 8089c4667826f32c35ade7df7e5aa7369873d9a5 | 32,338 |
def md_heading(text, level=0):
"""
Create title/heading.
Level 0 means document title, level 1-3 - heading 1-3.
"""
if level >= 3:
return text
if level == 0:
return "{} {}".format("#", text)
return "\n{} {}\n".format((level + 1) * "#", text) | 024c9193f41cebea944571492cda0ebc5e29ff29 | 32,341 |
def get_doc(collection, doc_id):
"""Retrieve a Firestore doc, with retries to allow Function time to trigger"""
doc = collection.document(doc_id).get()
if doc.exists:
return doc | 37d97f47f1c556cb7009e23d1c04f46c67902a49 | 32,343 |
def edges_removed(G, Gp):
"""Returns a list of edges which are the edges of G set minus the edges of Gp."""
return list(set(G.edges()) - set(Gp.edges())) | 3ffc961c3deb0d24ecad74e70cd6056ab223d96b | 32,347 |
def word(word_time):
"""An accessor function for the word of a word_time."""
return word_time[0] | 3bdb79a49d7ad4ec594f567bc37911d4675bceee | 32,349 |
def col_to_dict(col, include_id=True):
"""Convert SchemaColumn to dict to use in AddColumn/AddTable actions."""
ret = {"type": col.type, "isFormula": col.isFormula, "formula": col.formula}
if include_id:
ret["id"] = col.colId
return ret | d7c10eb07daaf1af14c73f51192f5d1a5b7bd19b | 32,354 |
def _is_datastore_valid(propdict, datastore_regex, ds_types):
"""Checks if a datastore is valid based on the following criteria.
Criteria:
- Datastore is accessible
- Datastore is not in maintenance mode (optional)
- Datastore's type is one of the given ds_types
- Datastore match... | 1575286766f594f3c330cae13bc0fcbf4f892fdd | 32,355 |
def actual_power(a: int, b: int):
"""
Function using divide and conquer to calculate a^b.
It only works for integer a,b.
"""
if b == 0:
return 1
if (b % 2) == 0:
return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
else:
return a * actual_power(a, int(b / ... | 9bdca5a91f063806511c329ff29e0fd340db2ab7 | 32,360 |
def initial_fragment(string, words=20):
"""Get the first `words` words from `string`, joining any linebreaks."""
return " ".join(string.split()[:words]) | 5b390cb5f98c9e940f2a964101b9593f0fa1ffb8 | 32,365 |
def get_switch_name(number):
"""Get a mock switch name."""
return "Mock Switch #" + str(number) | 2af6c522cffc4be117945c22897797df11f95dbf | 32,366 |
def _GetPreviousVersion(all_services, new_version, api_client):
"""Get the previous default version of which new_version is replacing.
If there is no such version, return None.
Args:
all_services: {str, Service}, A mapping of service id to Service objects
for all services in the app.
new_version: ... | f9e1f4d9d9bbb5a26156343096bfd614a4de78fd | 32,372 |
def convert_ug_to_pmol(ug_dsDNA, num_nts):
"""Convert ug dsDNA to pmol"""
return float(ug_dsDNA)/num_nts * (1e6 / 660.0) | 0a5df438fe317e78151634fc99a0e5e67af7fafd | 32,374 |
def only_call(variant):
"""Ensures the Variant has exactly one VariantCall, and returns it.
Args:
variant: nucleus.genomics.v1.Variant. The variant of interest.
Returns:
The single nucleus.genomics.v1.VariantCall in the variant.
Raises:
ValueError: Not exactly one VariantCall is in the variant.
... | 434bdb7628d3ffdcfb74d1c1532d00cafc142b8c | 32,383 |
def pod_index(room):
"""
Return index of first pod in room.
"""
for i, pod in enumerate(room):
if pod:
return i
return len(room) | 46f7f92fbec93bcc862cffdf5bfffc83c79363be | 32,387 |
import logging
def check_errors(response):
"""
Checks for an error response from SQS after sending a message.
:param response: The response from SQS.
:return: The response after checking and logging Errors.
"""
if response.get('ResponseMetadata', '').get('HTTPStatusCode', '') is not 200:
... | fada181a4270ed4ebc913dd9696f327cc6c46ddb | 32,389 |
def pad_number(number, padding=3):
"""Add zero padding to number"""
number_string = str(number)
padded_number = number_string.zfill(padding)
return padded_number | fb3ff474b644d998d855e5fb0765c0af287954d3 | 32,401 |
from typing import List
def filter_import_names(names: List[str], exclude: List[str]) -> List[str]:
"""
filter the given import names by the list of (sub)folders / imports to exclude.
:param names: list of import names.
:param exclude: list of (sub)folders/imports to exclude.
:return: list of filt... | e9c2cef3bddad161729beb27138c46d5e9bb58f5 | 32,402 |
import six
def str_(value):
""":yaql:str
Returns a string representation of the value.
:signature: str(value)
:arg value: value to be evaluated to string
:argType value: any
:returnType: string
.. code::
yaql> str(["abc", "de"])
"(u'abc', u'd')"
yaql> str(123)
... | c3d375c26c1f471173d6fd24e6eaa3ad6cc5a576 | 32,404 |
def property_to_py_name(cpp_struct_name):
"""Returns the name the property should have in the Python api,
based on the C++ struct name."""
first_underscore = cpp_struct_name.find('_')
assert first_underscore != -1
return cpp_struct_name[first_underscore + 1:] | a17d952af4170e7d987e50c0e4ce53f0938b4116 | 32,406 |
def letter_score(letter):
"""Gets the value of a letter
E.g. A = 1, B = 2, C = 3, ..., Z = 26
"""
letter = letter.upper()
score = ord(letter) - ord('A') + 1
return score | ba7b71e6546afbd20cfb4af7dd7135559b724562 | 32,407 |
import re
def extract_jobs_flags(mflags):
"""Extracts make job flags from a list of other make flags, i.e. -j8 -l8
:param mflags: string of space separated make arguments
:type mflags: str
:returns: list of make jobs flags
:rtype: list
"""
if not mflags:
return []
# Each line... | 2c259c53a03c7f601d81650ff994590381437611 | 32,414 |
def project_with_revision_exists(project_name, project_revision, working_dir):
"""Check if a Quartus project with the given name and revision exists.
Parameters
----------
project_name : str
Name of the Quartus project
project_revision : str
Name of the project revision
working_... | b4755866a5136235a49f51eca21a7ec6f18f1654 | 32,423 |
def data_from_results(result_iter, method, lip_estimator, time_or_value='value',
avg_or_stdev='avg'):
""" Given a list of experiment.Result or experiment.ResultList objects
will return the time/value for the lip_estimator of the method
for result (or avg/stdev if resultList objects)
e.g., data_from_resul... | dbaa44dd714fbca1dfc3a55df5bc1d9ba88e375b | 32,424 |
def generate_predefined_split(n=87, n_sessions=3):
"""Create a test_fold array for the PredefinedSplit function."""
test_fold = []
for s in range(n_sessions):
test_fold.extend([s] * n)
return test_fold | 317eacc78b77dafca402a8903bc1ee431e15ab4d | 32,425 |
def listish(x):
"""
Does it smell like a list?
>>> listish(1)
False
>>> listish((1,2,3))
True
>>> listish([1,2,3])
True
"""
result = True
try:
len(x)
except TypeError:
result = False
return result | ade3c54325f3510734dcbe106b4c483bcd48e0b4 | 32,426 |
import re
def get_ipv4_routes(route_table):
"""
The route table has several types of routes in it,
this will filter out all but the ipv4 routes.
The filters out the default route
Returns a list of lists (line by line route output)
"""
only_ipv4_routes = []
for item in route_table:
... | 6f10210361bcc86c1932bee211def6b0a97f6884 | 32,432 |
from typing import List
from pathlib import Path
from typing import Optional
def construct_matlab_script(
filepaths: List[Path],
fail_warnings: bool,
enable_cyc: bool,
enable_mod_cyc: bool,
ignore_ok_pragmas: bool,
use_factory_default: bool,
checkcode_config_file: Optional[Path] = None,
) ... | 363a664205ea3cadc7772f83840e2225d15d0418 | 32,435 |
def unique(x):
"""
Removes duplicates while preserving order.
"""
return list(dict.fromkeys(x).keys()) | 2ee45e1b5e91a722d348d7970fb765d04f0bc33b | 32,438 |
import re
def format_number(n, thousands=",", decimal="."):
"""Format a number with a thousands separator and decimal delimiter.
``n`` may be an int, long, float, or numeric string.
``thousands`` is a separator to put after each thousand.
``decimal`` is the delimiter to put before the fractional port... | f93c8c19dca24f26e30c148f6e0ae7042e9b91f8 | 32,443 |
def is_phrase_a_substring_in_list(phrase, check_list):
"""
:param phrase: string to check if Substring
:param check_list: list of strings to check against
:return: True if phrase is a substring of any in check_list, otherwise false
>>> x = ["apples", "bananas", "coconuts"]
>>> is_phrase_a_subs... | 1f543ede3fd4b001369d3a90db9950b987fc2bbb | 32,445 |
from typing import Tuple
def convertId2DocxCoord(cell_id: int, nb_col: int) -> Tuple[int, int]:
"""Find the XY coordinate of a know point
Args:
cell_id (int): the index of cell
nb_col (int): the number columns of table
Returns:
tuple: the XY coordinate corresponding to the index ... | d939a31bcb66e611c8f8f6777428e86048d88f13 | 32,450 |
def divide(numerator: float, denominator: float) -> float:
"""
Divides two numbers and returns result.
:param numerator: numerator
:param denominator: denominator
:return: sum of two numbers
>>> divide(4, 2)
2.0
>>> divide(4, -2)
-2.0
>>> divide(4, 0)
Traceback (most recent... | 0135e6e8caf4606321ba76be63fb65b3f3a12a66 | 32,452 |
def more_than_three(number=''):
""" Returns True if there are more than three consecutive numerals (ex: IIII) """
prev = ''
counter = 0
for letter in number:
if prev == letter:
counter += 1
else:
counter = 1
if counter > 3:
return True
... | e402175e347690d087da2726b934ff60f39cbc59 | 32,453 |
import tokenize
def is_comment_token(token1):
"""
Returns True if the token1 is a comment token, False otherwise.
Since there is an incompatibility between Python versions,
this function resolves it.
Some more information about incompatibility:
Python 3.6:
TokenInfo(type=59 (ENCODING), s... | e312dd859ba8d9c72266e02fc30af59e3f691b6b | 32,459 |
def _has_collision_with_bbs(existing_bbs, new_bb):
"""
Checks if the new rectangle (new_bb) collides with some existing rectangles.
"""
a_left = min([x[0] for x in new_bb])
a_right = max([x[0] for x in new_bb])
a_bottom = min([x[1] for x in new_bb])
a_top = max([x[1] for x in new_bb])
fo... | 87f4b207c8256479347606e0f096d53a3075c4d4 | 32,460 |
def check_region(region: str):
"""Checks and validates region from config.
Regions can only be 'EUR', 'JAP', or 'USA', as defined by
Dolphin Emulator.
Args:
region (str): the geographic region of the game's saves
Returns:
str: region, if valid
Raises:
Exception: if the... | 01af2f7d98bef0a7bd1e64a399d290ec6ac74c95 | 32,465 |
def get_buckets(ciphertext, key_length):
"""Breaks ciphertext into buckets for each key character
Args:
ciphertext (int array): Array representing the ciphertext.
key_length (int): The size of the key.
Returns:
Array of int arrays. Each int array represents parts of the ciphertext ... | ef1ef677c8802a337074a59a201fd8c580a84839 | 32,468 |
import logging
def init_log(level):
"""Initialize the logging interface"""
format = '%(asctime)-15s %(levelname)s: %(message)s'
logging.basicConfig(format=format)
logger = logging.getLogger('vmi-unpack')
logger.setLevel(level)
return logger | 3f7dfd22f46cd6b4773323bca9d058909071677f | 32,470 |
from typing import Dict
def make_lang_specific_replace_map(lang: str = 'en') -> Dict[str, str]:
"""Create a language specific replace map."""
replace_map = {}
if lang == 'ro':
# Remove diacritics for romanian
replace_map['Ş'] = 'S'
replace_map['ş'] = 's'
replace_map['Ș'] ... | b0607f9c1256e237abcf4e281a6650fcf03cb256 | 32,473 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.