content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _get_cols_to_format(show_inference, confidence_intervals):
"""Get the list of names of columns that need to be formatted.
By default, formatting is applied to parameter values. If inference values
need to displayed, adds confidence intervals or standard erros to the list.
"""
cols = ["value"]... | cb0a4a17113fd36a92eb69173f4386a880cdf162 | 580,601 |
def delete_health_check_by_id_parser(root, connection):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.delete_health_check_by_id` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection c... | a4d35728a0ad79c40107157469be4923d7581149 | 580,603 |
def prepare_data_to_save(raw_data: list, status: str) -> list:
"""
Change data from function get_data_from_country() to format ready to save as
.csv file.
Parameters
----------
raw_data: list, required
List of data produced by get_data_from_country() function.
status: str, required
... | f303669450997fd5a930b517b72037bf93b96192 | 580,604 |
import math
def polar(x, y):
"""
returns r, theta(degrees)
"""
r = (x ** 2 + y ** 2) ** .5
theta = math.degrees(math.atan2(y,x))
return r, theta | 8e8605cd810f4fc340b88d375f72c48cc5be28a2 | 580,610 |
def sizeof(*x, seps=True, prec=1):
"""Returns the largest string size of all objects in x, where x is a
sequence of string or numeric values.
Args:
*x: The objects to test.
seps: Whether to include separators (,.) in the size.
prec: Precision of float values.
"""
if isin... | 73fe734628c1eb37b43c19e43465348a094e9b48 | 580,616 |
def characterLevelIndex(X, digits_word):
"""
Map each character present in the dataset into an unique integer. All digits are mapped into a single array.
:param X: Data to retrieve characters from
:param digits_word: Words regrouping all digits
:return: A dictionary where each chara... | 535491f7835ff4d108f3373e17c7eb5865fd21e2 | 580,617 |
def reformat_element_symbol(element_string):
"""
Reformat the string so the first letter is uppercase and all subsequent
letters lowercase.
Parameters
----------
element_string : str
Inputted element symbol
Returns
-------
str
Returned reformatted element symbol
... | 603b6e221b9bfce9ed053f55e79f610ed87a711e | 580,624 |
def remove_duplicates(hashtags):
"""Removes duplicates from given hashtag list
Parameters:
hashtags (list): list of hashtags
Returns:
List of hashtags without duplicate entries
"""
result = list(dict.fromkeys(hashtags))
return result | 7b637a6da0871744b9e66022abf352a2cdccab04 | 580,626 |
def D_theo(D0, T, Tc, mu):
"""
Calculates the theoretical value for spinwave stiffness D as a function of temperature
Parameters
----------
D0 : float
spin-wave stiffness at 0 K meV/angstroem^2
T : float
temperature of the system in K (needs to be <= Tc)
Tc : ... | eee972b571bbe7605b75e86fbf5bb644404c1f3d | 580,629 |
import typing
def fill(length: int, character: typing.AnyStr = b"A") -> typing.AnyStr:
"""Generate b"AAA..." padding
Args:
length (int): The length of padding.
character (str or bytes, optional): The character to fill.
Returns:
str or bytes: The string by repeating `character` for... | 9431604faaa20f5fc3c0510b4399d4ad7e8b22c8 | 580,632 |
def manhattan(x_one, y_one, x_two, y_two):
"""Distance as defined by the Manhattan formula for the ((x1, y1), (x2, y2)) case."""
return abs(x_one-x_two) + abs(y_one-y_two) | 02792251716cde40702d1ce12c357b3a9bd6a7be | 580,633 |
import six
def computed_values(d):
"""
Computes a new `dict` that has callable values replaced with the return values.
Simple example:
>>> compute_values({"foo": lambda: "bar"})
{"foo": "bar"}
Arbitrarily deep structures are supported. The logic is as follows:
1. If the value i... | 98fc09355c1ba8b3543e22d43e826a2a23569004 | 580,637 |
def decode_float(value):
"""Decode a float after checking to make sure it is not already a float, 0, or empty."""
if type(value) is float:
return value
elif value == 0:
return 0.0
elif not value:
return None
return float(value) | 6bf499633b9a8ad7f669b899c15452f88efa88bc | 580,638 |
from typing import List
import random
def shuffled(lst: List[str]) -> List[str]:
"""
Return a shuffled copy of the input list. The input list is not modified.
"""
copy = lst[:]
random.shuffle(copy)
return copy | 0901273bffa72278d3ee5692be549cf7e697da7a | 580,641 |
def print_list(items):
"""Return TeX lines of an itemize element."""
lines = []
lines.append('\\begin{itemize}\n')
for item in items:
lines.append('\\item ' + item + '\n')
lines.append('\\end{itemize}\n')
return lines | d8367251fe47ee3fc70bb2e6b43ac4951d6f9132 | 580,642 |
import hashlib
def public_torrent_filename(blob_uuid):
""" Returns the filename for the given blob UUID in a public image. """
return hashlib.sha256(blob_uuid).hexdigest() | bfd82e718ca66b25616bf37060d26b89a64fcd05 | 580,648 |
def index_exists(es, index_name: str):
"""Does index exist?
Args:
index_name: index to check for existence
"""
return es.indices.exists(index=index_name) | 83dbaa45b33912f36b842a2f079bd516456b2dd2 | 580,651 |
def int_to_range(value, shift=0):
"""
Converts ``value`` to ``range(shift, value + shift))`` if ``value`` is ``int``,
returns ``value`` unchanged otherwise.
"""
return list(range(shift, value + shift)) if isinstance(value, int) else value | 8a79cd4c0d17b644b10c1bd4d87a3cb53ec5ea05 | 580,652 |
def linkcode_resolve(domain, info): # type: ignore
"""Return github.com link for module."""
if domain != "py" or "module" not in info:
return None
filename = info["module"].replace(".", "/")
if filename == "python_awair":
filename += "/__init__.py"
else:
filename += ".py"
... | 9a3637cb2e12a530b2052b89a71e95e2722928e5 | 580,654 |
def format_title(title):
"""
Replace in a title the characters prohibited in the names of files
:param title: book title
:return: formatted title
"""
interdit = ["/", '\\', ":", "*", "\"", "<", ">", "?", "|"]
forma = str(title)
for k in interdit:
forma = forma.replace(k, "")
... | d4fc50ac079ecbf1045ac69b8121d7e283428e96 | 580,656 |
def tag_to_text(tag):
"""
:param tag: Beautiful soup tag
:return: Flattened text
"""
out = []
for item in tag.contents:
# If it has a name, it is a tag
if item.name:
out.append(tag_to_text(item))
else:
# Just text!
out.append(item)
... | 27bc95e6bb5f9c0182fe3d96fbea504c7b1da9b5 | 580,657 |
def boolify(val):
"""
Returns a boolean even if 'val' is a string or already a boolean
>>> boolify(None)
False
>>> boolify(False)
False
>>> boolify('')
False
>>> boolify(u'')
False
>>> boolify('False')
False
>>> boolify('True')
True
>>> boolify('true')
... | 0f9495fcb8b8b0335489d8b4c536c1121f6115df | 580,659 |
def check_lost(positions):
"""Checks if any blocks are above the screen."""
for pos in positions:
x, y = pos
if y < 1:
return True
return False | 1f967a43fbf5eabd3448837f8c11c42880c8bf4a | 580,660 |
from typing import Dict
async def health() -> Dict[str, str]:
"""Basic health endpoint"""
return {"status": "UP"} | 36d614add92606facf2b0a1604b5ec08212ad8c9 | 580,663 |
def extract_doctype(doc_id):
"""Extract the doctype from the doc_id. Lowercased to match the doctype in ES."""
doctype = doc_id[0 : doc_id.find("_")].lower()
return doctype | ee81e3af4a2ba5eb13f2d8dd3b4e2e2ceba75314 | 580,665 |
def per_mill(pop, num):
"""Returns number per million if population exists."""
if pop:
return num * 10**6 / pop
else:
return None | 3a8107b1b4480efc3b015c4e98afe2c2df571b42 | 580,668 |
def get_epsiode_ids(episode_metas):
"""
Creates a list of all IMDB ID for the epsiodes inside
of a list of episode metadatas.
"""
ids = []
for ep in episode_metas:
ids.append(ep['imdb_id'])
return ids | 9969a2a04ae30f44e18d5ef54bcf7db267ace955 | 580,670 |
def apply_ops(input, ops):
"""
Apply series of operations in order on input. `ops` is a list of methods
that takes single argument as input (single argument functions, partial
functions). The methods are called in the same order provided.
"""
output = input
for op in ops:
output = op... | 72f8954121410151d5f9497668b484dc7d1aab74 | 580,675 |
from typing import Tuple
from typing import Optional
def id_from_mention(mention: str) -> Tuple[int, Optional[str]]:
"""Get an ID from a mention
Any mention is supported (channel, user...).
Args:
mention: A mention to be stripped.
Returns:
A tuple containing the parsed ID and the ty... | 6e9c43e33fdcb86366765c9779b8c6c036650886 | 580,679 |
import string
import random
def gen_rand_str(length=8, s_type='mixed', prefix=None, postfix=None):
"""
生成指定长度的随机数,可设置输出字符串的前缀、后缀字符串
:param length: 随机字符串长度
:param s_type:
:param prefix: 前缀字符串
:param postfix: 后缀字符串
:return:
"""
if s_type == 'digit':
s = string.digits
elif... | 6afd76d08dc49c93c0bb22b594fcab02a860fec8 | 580,682 |
import mimetypes
def guess_extension(mimetype):
"""Finds the right filename extension (e.g. ``'.png'``) for
the given ``mimetype`` (e.g. :mimetype:`image/png`).
:param mimetype: mimetype string e.g. ``'image/jpeg'``
:type mimetype: :class:`str`
:returns: filename extension for the mimetype
:r... | ddbcaa9ce4e46f2d2bd508e3f85d86778ba6bb03 | 580,683 |
import sqlite3
def team_stats(conn, team_id):
"""Returns the teams statistics as a dictionary"""
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute("SELECT * FROM teams WHERE id=?", (team_id,))
stat = c.fetchone()
return dict(zip(stat.keys(), stat)) | e14bae9203220cb732fe90feb379bb131e70c4db | 580,685 |
def midi_to_frequency(midi_note):
""" Converts a midi note to a frequency.
::Examples::
>>> midi_to_frequency(21)
27.5
>>> midi_to_frequency(26)
36.7
>>> midi_to_frequency(108)
4186.0
"""
return round(440.0 * 2 ** ((midi_note - 69) * (1./12.)), 1) | 5425988f239390902f44c5146ae7d1ad2b514623 | 580,686 |
def parse_parameter(text: str) -> str:
"""
Args:
text (str): Parameter in step define surround with: 【】, such as "search 【laptop】 with Google"
Returns:
(str): Parameter string, such as laptop
"""
return text[1:-1] | 262c14fa25e0751e9f77c32ebece6bdcce2b96da | 580,692 |
def apply_adapter(sampler, adapter):
""" Applies an adapter to the given sampler
Parameters
----------
sampler: a sampling function to adapt.
adapter: the adapter to apply to the sampling function.
Returns
-------
sample: a sampling function
"""
def sample():
data = sa... | 20038d4b7ee0dc69ffb997b559bbfb9047a7dd5e | 580,695 |
import re
def maybe_isbn(query):
"""check if a query looks like an isbn"""
isbn = re.sub(r"[\W_]", "", query) # removes filler characters
return len(isbn) in [10, 13] | e88b13f5c263e5db201fe75167510df8683e8441 | 580,701 |
from operator import add
def _aggreggate_explainer_values_dict(values, provenance):
"""Aggregates explainer values across features created from a common feature.
For example, let's say the pipeline has a natural language featurizer that creates the columns: LSA_1, LSA_2, PolarityScore,
MeanCharacter, and... | 7cffda88127c555cd28f3c9bf79b44bebec41fed | 580,704 |
def training_set_read_parser(rec):
"""Parses each training/eval read in biopython-parsed format.
Species taxon ids are assumed to be available in read names.
(E.g. for read with name >NC_018018.1|999|GCF_000265505.1-200000,
999 is parsed as its species taxon id.)
Returns:
seq: string, the D... | cd7cb5cf5009c9256ec25725b02e4d0b18cc75e8 | 580,706 |
def BuildDependencyHashFromDependencies(deps):
"""Builds a hash for searching dependencies by the namespaces they provide.
Description:
Dependency objects can provide multiple namespaces. This method enumerates
the provides of each dependency and adds them to a hash that can be used
to easily resolve ... | aa18cd40940e983df3d3592e6b979269f25f5fbe | 580,710 |
import requests
def get_filesize(url):
"""
Issue a HEAD request to retrieve file size without downloading it
"""
try:
response = requests.head(url)
except:
return None
if "Content-Length" in response.headers: # case-insensitive
return int(response.headers["Cont... | 337c24efa458a6e6515031daafa6d481ef4dd735 | 580,713 |
def get_sorted_lib_book_lists(lib_idx, sorted_lib_book_lists, remain_day, lib_daily_ships):
"""
Helper function to get a list of sorted Book List with Library Index
Args:
lib_idx: Library Index
, sorted_lib_book_lists: List of Full Book List sorted by score
, remain_day: Remaing Day... | 8d5ddd7a857c3e8916e463c17f872f3ddac7d05a | 580,714 |
import io
import yaml
def parse_frontmatter(path):
"""Parses frontmatter from a file and returns a dictionary object
Parameters
----------
path: str | os.PathLike
Returns
-------
yaml: dict
dictionary representation of yaml found in frontmatter
"""
buffer = io.StringIO()
... | 7e575974eb380529ac964fa21e7ad3167961aebe | 580,720 |
def window(ind, abs_time, low, high):
"""
Find coincident events in the given window.
Get offsets from the current index ind in abs_time that are in the
relative time window defined by low and high.
Parameters
----------
ind : int
Current index for abs_time.
abs_time : ndarray... | d1936ea9ed532a3ead29c34d7e82236156482fb1 | 580,722 |
def parse_home(d):
""" Used to parse name of home team.
"""
return str(d.get("tTNaam", "")) | 8c485fa67af2fc8660b52e465ba6cbf8955cfdae | 580,726 |
def int_to_be_bytes(x):
"""Convert an integer to an array of four integer values representing the big endian byte encoding."""
return [(x >> 24) & 0xff, (x >> 16) & 0xff, (x >> 8) & 0xff, x & 0xff] | 69c2464b56fcc93ea4b5e0bb28622bcfe0341f60 | 580,727 |
def pathsplit(path):
"""Split a /-delimited path into a directory part and a basename.
:param path: The path to split.
:return: Tuple with directory name and basename
"""
try:
(dirname, basename) = path.rsplit(b"/", 1)
except ValueError:
return (b"", path)
else:
retu... | df5beffc3897f5efa38f0f22c7cc251587773cae | 580,728 |
def read_row(width):
"""Reads one row of integers interpreted as booleans."""
row = [int(field) != 0 for field in input().split()]
if len(row) != width:
raise ValueError('wrong row width')
return row | 3d1b57189e007eb9176a493a3bcc767ca5f50abd | 580,729 |
import math
def Ub_calc(Ua):
"""Convert phase A quantity to Phase B."""
return Ua*pow(math.e,1j*(-(2/3)*math.pi)) #Shift by -120 degrees | 926bcbe1872ee8264c47e272c13f78e38b8c2d48 | 580,735 |
def alpha(idx: int) -> float:
"""
Calculate alpha.
Args:
idx: index of position
Returns:
value
"""
return 1 / (2 ** 0.5) if idx == 0 else 1 | 0f7a0407c626326849e59d223f7bf82b5e033f3c | 580,736 |
def toxiproxy_api_url(request):
""" The url to use to connect to Toxiproxy API.
"""
return request.config.getoption('TOXIPROXY_API_URL') | 17de2874e964b36589dec55e3995cdda282b828f | 580,738 |
def formatData(cast):
"""Formats IMDb cast in the following format:
actor's normalized name, character's full name, actor's full name,
IMDb.com character page, separated with commas.
Parameters
----------
cast : `dict`
IMDB cast with actor normalized names as keys.
Returns
----... | 4b8f1b83fe21849ba8fb388855b4f4165442637b | 580,740 |
import collections
def ordered_dict_constructor(loader, node):
"""OrderedDict constructor for PyYAML."""
return collections.OrderedDict(loader.construct_pairs(node)) | 6f4d5d41e41b7c0b19dbd6a83b8ff2f1e1d30eee | 580,742 |
import contextlib
import socket
def pick_unused_port(host):
""" Return a port that is currently unused.
There is a race condition here in that the returned port can be grabbed
by any other process. This should only be used for testing.
"""
with contextlib.closing(
socket.socket(socket.AF_... | c62807310af0dc16beb28c5186e7e7f2646c54f0 | 580,745 |
def is_capacity_empty(capacity):
"""
Check for an empty Capacity object to detect for empty Excel rows.
:param capacity: Capacity
:return: Boolean
"""
if capacity.ap is None \
and capacity.capacity is None:
return True
return False | e40374765f2266433fd1eed910d8cd686def41ef | 580,746 |
def function_with_multiline_call(x):
"""Docstring."""
return range(
x,
x + 1,
) | ea3c6de64dd0d1ca9e2001d87ffdd9f39d762bc4 | 580,750 |
def H(value):
"""Step function of H(x)=1 if x>=0 and zero otherwise. Used for the
temporal laplacian matrix."""
if value >= 0:
return 1
return 0 | 0fdfc8c1c6b48a2330fcc6e9a04a10b6e93b1a18 | 580,752 |
def batch_size() -> int:
"""The number of ranked lists to process"""
return 10 | a9f4b79a0726cbc56217e714cbef8d28b726b414 | 580,755 |
def rotate(s, n):
"""
Circularly rotate s by n positions.
"""
return s[n:] + s[:n] | 2c1b85d55612b446438312f99a9cae08ac83fcd9 | 580,760 |
import math
def angle(vector1, vector2):
"""Return the angle between two vectors"""
x1, y1 = vector1
x2, y2 = vector2
inner_product = x1*x2 + y1*y2
len1 = math.hypot(x1, y1)
len2 = math.hypot(x2, y2)
return math.acos(inner_product/(len1*len2)) | d8c27e8f42ec432dc568a8a1310281a0f34fead6 | 580,766 |
def editor_bot(base_editor_bot):
"""
Set up EditorStack with CodeEditor containing some Python code.
The cursor is at the empty line below the code.
Returns tuple with EditorStack and CodeEditor.
"""
editor_stack, qtbot = base_editor_bot
text = ('a = 1\n'
'print(a)\n'
... | 2bf7cd47df7ad6a08c5e663017f4684a86088095 | 580,767 |
def has_snapshot_with_keys(snapshots, keys):
""" Test if a snapshot with the given subset of keys exists """
return any( set(keys).issubset(set(s.keys())) for s in snapshots ) | 1e216ef3b677cf3f2a2e24c96a4f4f8a7fc4df52 | 580,772 |
def _WrapAccumulatorCellFn(accumulator_layer, cell_fn):
"""Wrap a cell_fn to propagate accumulators."""
def WrappedCellFn(theta, state0, inputs):
"""cell_fn wrapped to propagate accumulators."""
accumulator_layer.SetAccumulatorValues(state0.accumulators)
# The underlying cell_fn has no knowledge of acc... | 8d7e35f60600f1f305e72ab01e215e9ccc4db91b | 580,774 |
def _get_coord_map(ndim):
"""Extract target coordinate from coords array (for map_coordinates).
Notes
-----
Assumes the following variables have been initialized on the device::
coords (ndarray): array of shape (ncoords, ndim) containing the target
coordinates.
c_j: variabl... | 40a1098a6e5cb8f21ee8edbf74e6dd38c8650c37 | 580,781 |
def name2abs_names(system, name):
"""
Map the given promoted, relative, or absolute name to any matching absolute names.
This will also match any buried promotes.
Parameters
----------
system : <System>
System to which name is relative.
name : str
Promoted or relative varia... | 82cada55a62119327f1f0479ffc276c06bb6a8e7 | 580,783 |
def set_bond_order(molecule, bond_index, bond_order):
"""Set the bond order of a bond for a specified index.
Assign bond_order (whether it's a single/double/triple bond) to the bond
present at the bond_index.
Parameters
----------
molecule : Molecule
The molecule to which the bond belo... | 2eb7edaebe014231274fe883c983b02d45f7ecb7 | 580,785 |
def compute_pareto_front(costs: list):
"""
Find rows of entries in the Pareto front.
Parameters
----------
costs: list of arrays
List of arrays of costs.
Returns
-------
front_ids: list of ints
List of row indices of elements from the pareto front.
"""
front_ids ... | e144848f4db96014d097edd2b38b8cf69610754b | 580,786 |
def has_permissions_for_app(request, search_app, is_export=False):
"""
Checks if the user has permission to search for records related to a search app.
This is done by checking if the user has at least one of the permissions in the
view_permissions attribute on the search app.
If is_export is True... | 2e6d6270eb3c342ea93e261a40cd58597a7048e6 | 580,788 |
def decompose_trans(trans):
"""
Decompose SE3 transformations into R and t, support torch.Tensor and np.ndarry.
Input
- trans: [4, 4] or [bs, 4, 4], SE3 transformation matrix
Output
- R: [3, 3] or [bs, 3, 3], rotation matrix
- t: [3, 1] or [bs, 3, 1], translation matrix
"""
... | 511c1b6d838bfcce18e399fee78f1d1aa30030a0 | 580,796 |
def get_render_engine(option):
""" RenderEngineを取得
Args:
option (Dictionary): Compositing設定
Returns:
str: RenderEngineのタイプ
"""
return option["render_engine"] | ca41289c616b72c7dbb7fcd4c7a987a0ca8933f9 | 580,797 |
def _startswith(value):
"""
Maps to `string.startswith`.
"""
return lambda v: v.startswith(value) | 9fe86b1e0b33a1f1332816e5663a3fa7a939a5c7 | 580,799 |
def celsius_to_kelvin(temp):
"""
From Celsius (ºC) to Kelvin (K)
"""
return temp + 273.15 | 613921d212e95e801b18a5e362dad0db9311378c | 580,800 |
def _has_same_url(data_from_db:tuple, data:tuple):
"""
Returns true if two data share the same url.
Else returns false.
This method is craeted for comparing facebook data as
_is_same_data return false for same article where
pic url are different.
"""
if data_from_db == None:
return False
temp = tuple(data_f... | 58d717f0332f123e5db17203e656c4abf46632e5 | 580,801 |
def blendcolors(rgb1, rgb2, prop):
"""
Blends two rgb colors so that prop comes from rgb2 and (1-prop) from rgb1,
where prop should be a proportion in the interval 0.0 - 1.0.
"""
return tuple(map(lambda c1, c2: int(round(c1 + (c2 - c1) * prop)), rgb1, rgb2)) | f199996cd24064b293b06468cbba78c9a4d25fc5 | 580,806 |
import re
def tosymbol(ident):
"""Replace illegal python characters with underscores
in the provided string identifier and return
"""
ident = str(ident)
ident = ident.replace(' ', '_')
ident = re.sub('[^a-zA-Z0-9_]', '_', ident)
if ident and ident[0].isdigit():
return ''
return... | 4d3027f150162d0f90ce369bb5290801a3488df7 | 580,807 |
def clean_unit(unit_str):
"""remove brackets and all white spaces in and around unit string"""
return unit_str.strip().strip('[]').strip() | 5ef9194628fc7fecf14b76dde1551eb020c4b1d2 | 580,809 |
def get_overridden_methods(cls):
"""
Returns a set of all overridden methods of the class ``cls``.
"""
# collect all attributes inherited from parent classes
parent_attrs = set()
for base in cls.__bases__:
parent_attrs.update(dir(base))
# find all methods implemented in the clas... | 64b29e9ac0d3bf8976b09f381c685b9fae1d052f | 580,811 |
import json
def model_comment(comment_type, text, other=None):
"""
Print model comment in the form accepted by the Klever error trace parser from VRP. This simple comment contains
short json to parse.
For example:
/* LDV {"action": "REGISTER", "type": "DISPATCH_BEGIN", "comment": "Register TTY ca... | 90f78818f175f475515c70e09af9806d16b8a2d8 | 580,812 |
def is_valid_zip(zip_code):
"""Returns whether the input string is a valid (5 digit) zip code
"""
return (len(zip_code) == 5) and zip_code.isdigit() | b8509c0915b04108cb0b5232ee1cf049eb147b80 | 580,813 |
def ListServerCas(sql_client, sql_messages, instance_ref):
"""Calls the list server CAs endpoint and returns the response."""
return sql_client.instances.ListServerCas(
sql_messages.SqlInstancesListServerCasRequest(
project=instance_ref.project, instance=instance_ref.instance)) | d6f386213ce1ce1f5a32919db5f438845eb0374b | 580,814 |
def powers(n, k):
"""Computes and returns a list of n to the powers 0 through k."""
n_pows = []
for i in range(k+1):
n_pows.append(n**i)
return n_pows | 0006f187ccd896efde23ebff0c25e5cf8af6c903 | 580,816 |
def count_true_args(*args):
"""Count number of list of arguments that evaluate True."""
count = 0
for arg in args:
if (arg):
count += 1
return(count) | e5a14238b33747dadd1d59ae10bba15201a52af0 | 580,817 |
import requests
def assess_ontology_url(ontology_url):
"""Access an ontology URL from the metadata convention
:param ontology_term: URL from the metadata convention
:return: True if successful, or None
"""
response = requests.get(ontology_url)
if response.status_code == 200:
return Tru... | f6ed133ab3282b8cdb7cdcc50127302f5e9630ea | 580,818 |
import torch
def valid_epoch_clf(data_loader, model, loss_type, device):
"""
Input:
- data_loader: torch DataLoader previously created
- model: torch model previously trained
- loss_type: loss function previously created/instantiated
- device: 'gpu' or 'cpu'
Output:
- Mean... | eda94e1c8800cb45e1b0b66cff68bca75fb9540e | 580,820 |
def get_hrs_mins(time_seconds):
"""
Converts seconds to hours and minutes
------------------------------------------------
Args:
time_seconds (int) -- numbers of seconds
Returns:
hrs (int) -- number of complete hours included in time_seconds
mins (int) -- number of complete... | ee702e58db31a7b933c0a626455e30bfb9bfda92 | 580,823 |
def hasPrecedence(operator1, operator2):
"""Checks if operator2 has precedence over operator1
Args:
operator1 (str): first operator
operator2 (str): second operator
Returns:
(bool): true if operator2 has precedence over operator1 else false
"""
if operator2 == '(' or operat... | 219d8fb53009ba298709cde94fd8917a7572283a | 580,826 |
def padder(str_list, extra=0):
"""Return a function to pad elements of a list."""
length = max(len(str(s)) for s in str_list) + extra
def pad(string):
string = str(string)
padding = max(0, length - len(string))
return string + (padding * ' ')
return pad | ba85ce713a7869a26b57ec3691d571549e975dfb | 580,828 |
from typing import List
def get_monolingual_default_bucket_key(buckets: List[int]) -> int:
"""
Returns the default bucket from a list of buckets, i.e. the largest bucket.
:param buckets: List of buckets.
:return: The largest bucket in the list.
"""
return max(buckets) | f7d02d1f46f8c9e3cea48c861d326ac29d6b67a3 | 580,829 |
def isOuterLoop(newFace):
"""NewFace is in the exterior iff all its incident elements are None."""
for i in newFace.incidentElements:
if i: return False
return True | f9a4ca7943e6a5361f546e82f4b9f789ac2c4982 | 580,831 |
def _read_description(description_file):
"""Reads the description and transforms it into trivial HTML."""
with open(description_file) as f:
return "\n".join("<p>" + line + "</p>" for line in f.readlines()) | 8b45709c680bebc667b79453b7e6b30328a13a02 | 580,833 |
def bodyFixed_to_trackSpeeds(velocity, angular_velocity, track_width,
right_track_max=100, right_track_min=-100,
left_track_max=100, left_track_min=-100):
"""
Function maps speeds issued in the body-fixed system frame to the
necessary skid-steering ... | 2d490230197b995210a898ec5283727aa4c5ddbe | 580,834 |
def is_file_like(obj):
"""Check if the object is a file-like object, per PANDAS' definition.
An object is considered file-like if it has an iterator AND has a either or
both `read()` / `write()` methods as attributes.
Parameters
----------
obj : object
Object to check for file-like prop... | d453d9326bbd5288213b8880fa91680da44bfd10 | 580,835 |
def s3_list_objects_v2(
s3_obj,
bucketname,
prefix="",
delimiter="",
max_keys=1000,
con_token="",
fetch_owner=False,
):
"""
Boto3 client based list object version2
Args:
s3_obj (obj): MCG or OBC object
bucketname (str): Name of the bucket
prefix (str): Li... | 1b329a14d1497386761832d263d99735ec6c658b | 580,837 |
def str_event(event):
"""Get a nice string of an Event."""
result = f"-----Event @ t={event.time}\n"
result += f"type: {event.type}\n"
result += f"agent: {event.agent.id}\n"
return result | f230711d7414bb50c13c5759dca45a8830fb06c1 | 580,839 |
def _calc_ti2(eff, n_gre, tr_gre, ta, tb, tc, a1, a2):
"""Calculate TI2 for MP2RAGE sequenc.e"""
return ta + tb + (3 / 2) * n_gre * tr_gre | c218b7117299d8c18211c6382a556f41c3c14eec | 580,841 |
from typing import List
from typing import Optional
from typing import Match
import re
def _filter_complex_words(words: List[str]) -> List[str]:
"""Filters the given list of words of 'complex' words.
'Complex' words are defined as those having 3 or more consecutive consonants or vowels.
:param words: Li... | b76420d7a04c147374398f344ba40651bc5e900c | 580,842 |
def remove_comment_lines(stream, comment_char="#"):
"""Removes commented out lines from stream, e.g., those starting with '#'.
Parameters
----------
stream : iterable of str
Lines from which comments should be excluded.
comment_char : str
Lines beginning with this character will be ... | 24ab698e68a7a6cf0237189f195917c7c9ba629e | 580,844 |
import string
def format_filename(s):
"""Take a string and return a valid filename constructed from the string.
Uses a whitelist approach: any characters not present in valid_chars are
removed. Also spaces are replaced with underscores.
Note: this method may produce invalid filenames such as ``, `.` or `..`
Whe... | f2b42efa3a19201a6ed3b9b3df2278009c3a4a66 | 580,845 |
def get_relevant_actions(all_actions, goals):
"""
Returns a subset of actions which have at least one of the goals
in their effects
"""
relevant = []
for a in all_actions:
if len(a.effects.intersection(goals)) > 0:
relevant.append(a)
return relevant | 891b81213eb742090c03aaeafd784923cfd70e29 | 580,850 |
def bytes2human(n, format="%(value).1f%(symbol)s"):
"""Converts n bytes to a human readable format.
>>> bytes2human(1023)
'1023.0B'
>>> bytes2human(1024)
'1.0KiB'
https://github.com/giampaolo/psutil/blob/master/psutil/_common.py
"""
symbols = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'E... | 97bf3783408b337b8abd5afe05e866766249c15b | 580,851 |
from typing import List
def pad_batch(context_tokens: List[List[int]], pad_id: int, pad_len: int):
"""
pads context lengths in context_tokens with pad_id to equal neox_args.seq_length,
and returns the padded batch and the new lengths.
context_tokens: list of lists of tokens
pad_id: int, integer t... | f447ad215acb21fcd95c427dce043426d7224594 | 580,852 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.