content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def fahr_to_celsius(temp_fahr):
"""Convert temperature from Fahrenheit to Celsius"""
temp_celsius = (temp_fahr - 32) * 5 / 9.0
return temp_celsius | 2889d002d3a72765035de2a4ccd642206ff4b8ca | 649,266 |
from typing import OrderedDict
def parse_info(soup):
"""Parse rent and detail descriptions from soup
Arguments:
soup: the soup object to parse from
Returns:
information (dict): parsed information
"""
info = OrderedDict()
infoSection = soup.select("div.detailInfo.clearfix")[... | cc72820d263d2bfc1a80b8b274d437f4139e48cd | 649,268 |
def fix_line_breaks(s):
"""
Convert \r\n and \r to \n chars. Strip any leading or trailing whitespace
on each line. Remove blank lines.
"""
l = s.splitlines()
x = [i.strip() for i in l]
x = [i for i in x if i] # remove blank lines
return "\n".join(x) | 8ac0a9cd1bb14e0817746e5f9c70623ee3667a97 | 649,271 |
import hashlib
def shasha(msg):
"""SHA256(SHA256(msg)) -> HASH object"""
res = hashlib.sha256(hashlib.sha256(msg).digest())
return res | 30803e76020efe6557faf280b8599535ccd002e5 | 649,273 |
def get_data_types_query() -> str:
"""
Define custom data types inside a database.
"""
# Define data types.
query = """
CREATE TYPE AssetClass AS ENUM ('futures', 'etfs', 'forex', 'stocks', 'sp_500');
CREATE TYPE Frequency AS ENUM ('minute', 'daily', 'tick');
CREATE TYPE ContractType AS ... | 736a30b7d59c664392cb2427d69c20ae26955ece | 649,275 |
def utrue(x,y):
"""
Return true solution for a test case where this is known.
This function should satisfy u_{xx} + u_{yy} = 0.
"""
utrue = x**2 - y**2
return utrue | b68913ee0aa9b72da40f21b4db19334540fd21f5 | 649,276 |
def consists_of(seq, types):
"""
Check that the all elements from the "seq" argument (sequence) are among the types passed as the "types" argument.
@param seq: The sequence which elements are to be typed.
@param types: A tuple of types to check.
@type types: tuple
@return: Whether the check ... | b422f89a7c22505fc75bcaa9e3d28a787ed1dff6 | 649,280 |
def get_unique_value(query_set, field_name, value):
"""Gets a unique name for an object corresponding to a particular
django query. Useful if you've defined your field as unique
but are system-generating the values. Starts by checking
<value> and then goes to <value>_2, <value>_3, ... until
... | 8463da63f71afd8721326888df0c9ec0c3566bc7 | 649,282 |
def bias_term(ci, ref, meta_dict, n_range):
"""
Compute the bias term to be subtracted off the cross spectrum to compute
the covariance spectrum. Equation in Equation in footnote 4 (section 2.1.3,
page 12) of Uttley et al. 2014.
Assumes power spectra are raw (not at all normalized, and not Poisson-... | 181393530b8998e06e1a34196b2e2061dad0b677 | 649,292 |
import itertools
def contains_peroxide(structure, relative_cutoff=1.2):
"""
Determines if a structure contains peroxide anions.
Args:
structure:
Input structure.
relative_cutoff:
The peroxide bond distance is 1.49 Angstrom. Relative_cutoff * 1.49
stipul... | 5db51989f823b3a6cc113267371459e8cf37d920 | 649,296 |
def calculate_param_b(
operating_frequency: float,
atmosphere_height_of_max: float,
atmosphere_semi_width: float,
atmosphere_max_plasma_frequency_squared: float) -> float:
"""
Calculates the B parameter following Hill 1979
"""
atmosphere_base_height = atmosphere_height_of... | b5bbbd7e12d72e05cf5342ca8baa6fc76c393c40 | 649,298 |
def get_snapshot_run_correlation_id(test_run_name, snapshot_type):
"""Returns the qualified string to use as correlation id.
Keyword arguments:
test_run_name -- the test run name for this run
snapshot_type -- either 'full' or 'incremental'
"""
return f"{test_run_name}_{snapshot_type}" | bccc40d43bc39c74f655557dc975b22083476513 | 649,299 |
def prune_cells(grid):
"""Given a grid, scan each row for solved cells, and remove those
numbers from every other cell in the row.
Note that 'grid' can be an iterable of rows, columns, or 3x3 squares.
Since the component cells (sets) are modified in-place it still works
if you rearrange things.... | ad7231f12e44eacef2ec83e69d493e7a5ce54dd1 | 649,300 |
def _copy_cursor(cursor):
"""Returns a new cursor with the same properites that won't affect the original
@cursor: any cursor that hasn't already been iterated over
@return: new cursor with same attributes
"""
new_cursor = cursor.collection.find()
new_cursor.__dict__.update(cursor.__dict__)
... | 992dc2f2ee085f335b3e046d51a0d4c443c2b4b8 | 649,301 |
def _build_link_header(links):
"""
Builds a Link header according to RFC 5988.
The format is a dict where the keys are the URI with the value being
a dict of link parameters:
{
'/page=3': {
'rel': 'next',
},
'/page=1': {
'rel': ... | 47b6fb8b69693400a60af8b6b75fd079c4884f14 | 649,304 |
def after_request(response):
"""Define acceptable response headers."""
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,POST')
return response | 709061cd1bae2dad04cc34170d745261d0223f1e | 649,305 |
import torch
def scale_model(model, scale):
"""Scale the parameters of a model.
Args:
model (torch.nn.Module): the models whose parameters will be scaled.
scale (float): the scaling factor.
Returns:
torch.nn.Module: the module with scaled parameters.
"""
params = model.na... | e28508ac7375c47183a02e4a12334eedbcd15c01 | 649,307 |
def printXYZ(self):
"""Print X, Y, and Z components."""
return ("[%f, %f, %f]" % (self.x, self.y, self.z)) | 79c585f7314fae60f641ae891f28114b2b353dd5 | 649,308 |
def _check_columns(df_to_check, cols) -> None:
"""Check that a list of required column names is in a data frame
Args:
df_to_check: A DataFrame to check columns on.
cols (Iterable[str]): Required columns.
Returns:
None
Raises:
ValueError: if required cols are not a subset... | e0efe284662e65cbcbce6e13184bf71554600088 | 649,311 |
def is_classdef(leaf):
"""
Returns true if the leaf is the beginning of a class definition
"""
return leaf.type == 'keyword' and leaf.value == 'class' | af9fa0b81549bd451d0a10e8f291dada7cca7bc8 | 649,314 |
def get_play_speed(ctx):
"""获取机器人运行速度
Args:
ctx (context.Context): 登陆上下文
Retures:
Success (int): 机器人运行速度
Failure (None): None
"""
return ctx.tran.request("GET", "/v2/paramservice/robot/playspeed")["data"] | 659960220f64cc953143e319e82782703236e39e | 649,318 |
from typing import List
def sieve_of_eratosthenes(n: int) -> List[int]:
"""
Simple Sieve of Eratosthenes algorithm to return all primes up to n.
:param n: the upper bound on the primes
:return: the list of primes in order
>>> sieve_of_eratosthenes(0)
[]
>>> sieve_of_eratosthenes(1)
[]... | 64a3282033b6c1957268957c51f081ce377f0089 | 649,323 |
import errno
def _recv(sock, size):
"""sock.recv() with retry on EINTR"""
while True:
try:
return sock.recv(size)
except IOError as e:
if e.errno != errno.EINTR:
raise | dd4518e7914c39307bfb84e4cfa542367d90bb81 | 649,325 |
def oncePerStep(sprite, game, name):
""" Utility for guaranteeing that an event gets triggered only once per time-step on each sprite. """
name = "_"+name
if hasattr(sprite, name):
# bounce only once per timestep, even if there are multiple collisions
if sprite.__dict__[name] == game.time:
... | 503871c04c4ca983828ecd8c2872220ee5200b11 | 649,328 |
import requests
import json
def post_json(url, data):
"""Helper method send HTTP POST requests to Elasticsearch."""
return requests.post(
url,
data=json.dumps(data),
headers={'Content-Type': 'application/json'},
) | 80b778c8ec620037c92f02f460309a309acdd70c | 649,331 |
def build_site_url(site,url,secure=False):
"""
Build an absolute URL for a given site
"""
protocol='http'
if secure:
protocol='https'
return u'%s://%s%s' % (protocol,site.domain,url) | 3ed73ba22a0ed82c781a968f9c549903867b516f | 649,332 |
def _CodepointString(unicode_text):
"""Converts unicode string to string of integers in uppercase hex.
Integers correspond to the codepoints within the string. Each integer is
followed by a space.
Args:
unicode_text: unicode string
Returns:
string
"""
return " ".join("%04X" % ord(c) for c in un... | 579e3bdb41d3091c07ca80c7219ee58b7539340e | 649,333 |
def get_tables(client, dataset):
"""
Get the names of all tables in a bigquery dataset.
client: bigquery connection
dataset: a connected bigquery dataset
Returns a list of all tables in the dataset
"""
return [table.table_id for table in client.list_tables(dataset)] | bc4baca1a5f2609996b6458348fcf19746c13db4 | 649,335 |
def store_true(arg, _, args, acc):
"""
lambda that store a True boolean value on the parser result
"""
acc[arg] = True
return args, acc | 84f6cb94905a03b1952ce62fc8e6bea354866016 | 649,339 |
def hour_decimal(dt):
""" For example, the time 12:45 becomes 12.75 """
return dt.hour + dt.minute/60 | 7ad56d4e8d38a9c2e108fca64dbc1d1409beceeb | 649,341 |
import json
import base64
def get_token_claim(jwt, claim):
"""Extract a claim from a JWT token without validating it."""
# Directly decode the base64 claims part without pulling in any JWT libraries
# (since we're not validating any signatures).
claims = jwt.split(".")[1]
# Pad the JWT claims bec... | 7fa9f3db03e9fea9e2bda5bd5cd888b232f82e3f | 649,342 |
from pathlib import Path
def _path_datafile(filename):
"""
Get absolute path to toolbox datafile
:param filename: relative pathname of datafile
:type filename: str
:raises ValueError: File does not exist
:return: Absolute path relative to *roboticstoolbox* folder
:rtype: str
Get the ... | f41d76ddafa624786a8ec0c13f2ca09f69391d8e | 649,343 |
from urllib.parse import quote, urlsplit, urlunsplit
def idna2ascii(url):
"""Converts unicode url to ascii"""
parts = urlsplit(url)
return urlunsplit((
parts.scheme,
parts.netloc.encode('idna').decode('ascii'),
quote(parts.path),
quote(parts.query, '='),
quote(parts... | 01670623f4e19ac2e56d7ebdc65e1135ccaa0b64 | 649,344 |
from typing import Any
from typing import Callable
def apply_to_all(dictionary: dict[Any, Any], func: Callable[[Any], Any]) -> Any:
"""Recursively apply a callable to all elements (keys + values) of a dictionary."""
if type(dictionary) != dict:
return func(dictionary)
return {func(k): apply_to_all... | ba50df69abf4d0c12bcc9e5e343e4281721c9fec | 649,347 |
def xrsplit(array):
"""
Split an array to a list of all the components.
Parameters
----------
array: xarray.DataArray
Array to split.
Returns
-------
sp_list: list of xarray.DataArrays
List of shape 0 xarray.DataArrays with coordinates.
"""
sp_list = [sa for sa... | b8b1ec8e1db3bc487fde02f3547ada1598a15963 | 649,351 |
from datetime import datetime
def now() -> int:
"""
Get UNIX-style time since epoch in seconds.
Returns
-------
int
Time since epoch in seconds.
"""
return int(datetime.now().timestamp() * 1000) | 3c3bc17cc366c0fad3c07405cfa42ad695ef25ec | 649,352 |
def netInputIndex(s, current, x, y):
"""
Helper function for gameToNetInput. Get the index of the list to update
:param s: The piece at the position being looked at
:param current: The currently selected piece, None if no piece is selected
:param x: The x coordinate of the position being looked at
... | b87688d50ac96d9bf243c3c452b1f3378b08d01d | 649,354 |
def get_missing_face_hierarchical_keywords(iptc_data, face_list=None):
"""Checks if keywords need to be added for faces. Returns the keywords that need
to be added."""
missing_keywords = []
if face_list == None:
face_list = iptc_data.region_names
for name in face_list:
# Look for ... | db7698eb9c1a72ef9a7714a5e3e3e03c315c8277 | 649,355 |
def find_period(traj):
"""Find approximate period of oscillation using the last two
peak event times in voltage"""
try:
evs = traj.getEventTimes('peak_ev')
return evs[-1] - evs[-2]
except:
return 0 | f66c210d2d3d60c62c027a3329e7aa3bd0f7cf93 | 649,358 |
def dB2gain(dB):
"""Convert dB to multiplicative gain"""
return 10.0**(dB/20.0) | bf20d65d124e42c4f1453b18bc17e6aef75a4678 | 649,362 |
from datetime import datetime
def to_unixtime(t):
"""Return float of total seconds since Unix time."""
return (t - datetime(1970, 1, 1, 0, 0, 0)).total_seconds() | 4e0d70e0283bacd2ec025432113e5004778e23d5 | 649,363 |
from pathlib import Path
from typing import List
def read_filelist(filepath: Path) -> List[str]:
"""
Read a list of files from a file (one file per line). Lines beginning with # are ignored
:param filepath: The path of the file containing filenames
:return: A list of filenames as strings
"""
a... | 2c08fd7f7885c52dee6e523746d55d9b9ef88828 | 649,364 |
def getSeqLens(fastaf):
"""Return a table with length in kilobases for each seq in fastaf."""
lenout = {}
curRec, curLen = None, 0
with open(fastaf) as ff:
for line in ff:
line = line.strip()
if len(line) == 0:
continue
if line[0] == '>':
... | b52958a82c2f6b8edea4177303c936fa2dc956ad | 649,368 |
import json
def make_series_key(key, tags, attributes):
"""Utility function for making a series key POST body, used mainly for
the series creation API endpoint.
:param string key: the series key
:rtype: string"""
return json.dumps({'key': key, 'tags': tags, 'attributes': attributes}) | 3a8c5a94e10472a9d82d6857eba9ec8376eaebce | 649,369 |
def _get_macro_edge_reversal_conflicts_with_existing_descriptor(
reverse_base_class_name, reverse_target_class_name, existing_descriptor
):
"""Return a (possibly empty) list of reversal conflicts relative to an existing macro edge."""
errors = []
if reverse_base_class_name != existing_descriptor.base_cl... | b41a0cef1c4e295f8748cd6babe8a13c1938e546 | 649,370 |
def generate_db_url(user, password, host, db_name, protocol = "mysql+pymysql"):
"""
Utility function for generating database URL
This function generates a database URL with the mysql and pymysql protocol for use with pandas.read_sql()
Parameters
----------
user : str
The username for the... | 173e4c130145f3ab47489331adb0668438a912bf | 649,371 |
def _env_to_bool(val):
"""
Convert *val* to a bool if it's not a bool in the first place.
"""
if isinstance(val, bool):
return val
val = val.strip().lower()
if val in ("1", "true", "yes", "on"):
return True
return False | 4cb6e5d1fbf4b79b4e8c0f4a57b24c0ed65d7c23 | 649,372 |
from typing import Union
def maybeint(string: str) -> Union[str, int]:
"""
Try to cast a string to a int
:param str string: to cast
:return: int(string) or string in case cast fails
"""
try:
return int(string)
except ValueError:
return string | 187d2366332e45cade255566f467f500e71a4c7c | 649,373 |
import pickle
def read_from_pickle(fn):
"""
Function to read data from a pickled file
Parameters
----------
fn : str
File directory.
data : any type, but recommend dictionary
data to read.
Returns
-------
data : same as data
Read in this variable.
"""
... | a8ba2d2ceeb9baa22fdcc3f62ed0ee21d69d2628 | 649,380 |
def htons(x):
"""Convert 16-bit positive integers from host to network byte order."""
return (((x) << 8) & 0xFF00) | (((x) >> 8) & 0xFF) | 3a46a9e2bc54bb4e77076065e7741a9e5ae3a0ed | 649,384 |
from typing import Sequence
def _parse_info(lines:Sequence[str]) -> dict:
"""Parse info.txt and return dictionary with relevant data"""
auto = lines[0] == "AUTO"
yaw, pitch, roll = map(float, lines[1].split(" "))
fov = float(lines[5])
return dict(
auto=auto,
fov=fov,
yaw=ya... | 3ddbdf5c134837276729135e3f07244e8bf41f81 | 649,387 |
def project_nonneg(values, imag_eps=1e-10, real_eps=1e-10, real_trunc=0.0):
"""Check that values are real and non-negative
:param np.ndarray values: An ndarray of complex or real values (or
a single value). `values` is modified in-place unless `values`
is complex. A single value is also accepte... | 2db645bbf22039507bf813050ab8c36a80f79e9c | 649,388 |
def get_leaves_with_labels(tree):
"""
Return leaves in the tree, as well as their labels
>>> from ptb import parse
>>> t = parse("(4 (4 (2 A) (4 (3 (3 warm) (2 ,)) (3 funny))) (3 (2 ,) (3 (4 (4 engaging) (2 film)) (2 .))))")
>>> get_leaves_with_labels(t)
[('A', 2), ('warm', 3), (',', 2), ('... | 384fa89e89da0de61acc338570344ac027feb488 | 649,392 |
def as_dictionary_of_dictionaries(labels, means, cov_diags):
""" Dictionary storing one dictionary of parameters per category. """
assert len(labels) == len(means) == len(cov_diags)
all_params = dict()
for label, mean, cov_diag in zip(labels, means, cov_diags):
category_params = dict()
... | c355f5ac3d2e8429bcf54e2420cf19c6c5efdd68 | 649,397 |
import requests
def request_api_key(username: str, email:str, description:str="I'd like to try it out.", referral_code: str="github_referred"):
"""
Request an api key
Make sure to save the api key somewhere safe. If you have a valid referral code, you can recieve the api key more quickly.
... | d234401ad1661bc660e7886f679b02cfaf33d289 | 649,398 |
def check_true(answer, label):
"""
Check if a given answer matches the label
:param answer: the probability output from the network
:type answer: float
:param label: the label integer as either a 1 or a 0
:type label: float
:return: 1 if classification is correct, 0 if incorrect
:rtype: ... | bf2ec6b3eab7a5c9cd6c0c5e5c1d3e7efd4b5223 | 649,399 |
def get_snapshots_from_text(query_output):
""" Translate expanded snapshots from `cali-query -e` output into list of dicts
Takes input in the form
attr1=x,attr2=y
attr1=z
...
and converts it to `[ { 'attr1' : 'x', 'attr2' : 'y' }, { 'attr1' : 'z' } ]`
"""
... | f6bfb56329c04ee8e325b5bd82ea417901420a58 | 649,406 |
def is_palindrome(s):
""" (str) -> boolean
Returns true if the argument is a palindrome else false
>>> is_palindrome("noon")
True
>>> is_palindrome("later")
False
>>> is_palindrome("radar")
True
"""
# converts (s) to lower case and assigns it to the variable word
word = s.low... | f20c0e3d09cba689f55369b218981da17eb33742 | 649,411 |
def xor(bytes1, bytes2):
"""
Xor two input bytes and return
Input: `bytes1`, `bytes2`: bytes need to xor.
Output: xor result
"""
return bytes([a ^ b for a, b in zip(bytes1, bytes2)]) | ac898cf412bb48482d2919a213934262e9d7ecda | 649,416 |
import random
def get_random_filename(file_list):
"""
Gets a random filename from inside the ZipFile object,
with the selected file extension
:return: arbitrary filename of selected type (extension)
"""
file_extension = '.xml'
filename_list = [x.filename for x in file_list if x.filename.en... | 4dfadfba53c40130928ee88f866c078e1c326f20 | 649,419 |
def deplen(deps):
"""Compute dependency length from result of ``dependencies()``.
:returns: tuple ``(totaldeplen, numdeps)``."""
total = sum(abs(a - b) for a, label, b in deps
if label != 'ROOT')
return (total, float(len(deps) - 1)) | b6dda009daa4b2e4cc677e1e0b492cb163cb49b6 | 649,420 |
import re
def _set_value(str_text, str_line, val):
"""
This function search for str_line in str_text and overwrites the whole
matching line with <str_line> str(val)
"""
str_text = re.sub('\n' + str_line + '.*',
'\n' + str_line + str(val),
str_text)
r... | e732bd26bbdcad3eed0c60201affc348565a1a5e | 649,423 |
def get_iam_service_account_email(project_id, account_id):
"""
Return the service account email given the id and project id
Args:
project_id (str): Project Identifier where service account lives
account_id (str): The account id originally provided during creation
Returns:
str: ... | d44073a7b14c6de2960027ac4d01a479388f6be3 | 649,426 |
def maximo(numero1, numero2):
"""Devolve o maior número"""
if numero1 >= numero2:
return numero1
else:
return numero2 | dfe172638a4578ecaed36c72bedd51374c356363 | 649,431 |
def mayan_tzolkin_date(number, name):
"""Return a Tzolkin Mayan date data structure."""
return [number, name] | 8cfd4120ea76de36e824311f1afab752beed84a3 | 649,435 |
from typing import Union
def dollar_str_formatting(val: Union[int, float]) -> str:
"""
Format dollar figures into $val trillion, $val billion, etc.
Parameters
----------
val: float
revenue amount
Returns
-------
str
formatted dollar figure
"""
val = abs(val)
... | 3871bc043935a7578140748b6328068cf96240d5 | 649,439 |
def key( *args ):
"""
join the arguments in the format of donkey
Arguments
---------
args: list of string
Examples
--------
>>>key( 'a', 'b', 'c' )
'a__b__c'
"""
return '__'.join( args ) | 9094dd19fd221073fe9cdac84a3616e71eb6fbcc | 649,440 |
import string
import secrets
def new_salt(n=12):
"""Generate a new salt."""
salt_chars = string.ascii_letters + string.digits
salt = [secrets.choice(salt_chars) for _ in range(n)]
return "".join(salt) | bde968e1c5168b9ecb835b3c9c3a7a32fccdf6e5 | 649,441 |
def obtain_reverse_codes(mapped, dst):
"""
Given the list of desired dst codes and an extensive map src -> dst,
obtain the list of src codes
:param mapped: Correspondence between src codes and dst codes [{"o", "to": [{"d", "e"}]}]
:param dst: Iterable of destination codes
:return: List of origi... | a7a46d76791dd00e3364a936dab8e4d9a3601105 | 649,442 |
def leniter(iterator):
"""leniter(iterator): return the length of an iterator, consuming it."""
if hasattr(iterator, "__len__"):
return len(iterator)
nelements = 0
for _ in iterator:
nelements += 1
return nelements | 49e0ce9f204e77292b1bc2e6f0121eaff4212285 | 649,443 |
def calc_center_pos(city, nodelist):
"""
Calculates center position for nodes in nodelist
Parameters
----------
city : object
city object of pycity_calc
nodelist : list (of ints)
List of node ids
Returns
-------
pos : tuple
Position tuple (x, y)
"""
... | 854d000c7ce11d149c9914016a8187ce459df162 | 649,444 |
import torch
def trilinear_composition(h_s, h_t, x, einsum=True):
"""
Trilinear composition as described in:
STAMP: Short-Term Attention/Memory Priority Model forSession-based Recommendation
Shapes:
b: batch
e: embedding
l: longest sequence length
v: vocabulary size
Parameters
... | cbeeff88ad144f72d2774fb47a4a7951e2fd503c | 649,446 |
def is_getter(attribute):
"""
Test if a method is a getter.
It can be `get` or `get_*`.
"""
return attribute.startswith('get') | 0f03a45671866b09d9cfa23766a8a33c16760e5c | 649,455 |
import functools
def _memo(fn):
"""Helper decorator memoizes the given zero-argument function.
Really helpful for memoizing properties so they don't have to be recomputed
dozens of times.
"""
@functools.wraps(fn)
def memofn(self, *args, **kwargs):
if id(fn) not in self._cache:
... | c59bd3203a3929411f5262b682a406a7ad2529a2 | 649,456 |
def verify_keyid_is_v4(signing_key_fingerprint):
"""Verify that the keyid is a v4 fingerprint with at least 160bit"""
return len(signing_key_fingerprint) >= 160/8 | 407d1408bda5845c94ec15813a4132f7d9bef878 | 649,458 |
def update_parameters_with_momentum(parameters, grads, v, beta, learning_rate):
"""
Update parameters using Momentum
-Because mini-batch gradient descent makes a parameter update after seeing just a subset of examples,
the direction of the update has some variance, and so the path taken by mini-batch gradient desc... | fd9f1e2e5b7d9f1f36eb58bb00add1c42d4c21b2 | 649,460 |
def get_queuelisting_perspective(display):
"""Retrieve the QueueListing perspective.
Args:
display: the display containing the loaded perspective
Returns:
QueueListing: the loaded QueueListing perspective
"""
display._active_perspective = 2
return display.perspectives[2] | 98568df298bde2050901a47743162f44a010698e | 649,462 |
def __html__(self):
"""
Returns the html representation of a string.
Allows interoperability with other template engines.
"""
return self | 0e6ac6ff63c652a2aec82915a8b0f2a9aefc9dc5 | 649,465 |
from typing import Iterable
def prep_sequence(value: str) -> Iterable[str]:
"""Split a sequence string into its component items.
Flex `notes` attribute is semicolon-delimited; other sequences use commas.
Empty string input interpreted as null data; returns empty list.
"""
sep = ";" if ";" in val... | b529f54f1c8ca820c5590106badb75b47c4cdbaa | 649,471 |
def get_expression(text, begin, separator):
"""Find the end of a expression or statement
An expression or statement ends at a new-line or at the separator,
unless the new-line or separator is encountered inside a string-literal or
inside matching bracket pairs.
@param text The total text being pars... | e7f04d67121f0d26732149654132b6e65fbb0b96 | 649,474 |
import json
def json_for(data):
"""
Serialize data to JSON.
"""
return json.dumps(data, indent=4, sort_keys=True) | 7c7f6446d656da3a5c46a982d3be55b1510d1334 | 649,475 |
def create_fifo_queue(
env,
queue_name,
content_based_deduplication=False,
message_retention_period=None,
visibility_timeout=None,
redrive_policy=None,
):
"""
Create a new FIFO queue. Note that queue name has to end with ".fifo"
- "content_based_deduplication" turns on automatic con... | be5bf39b6c1fa3ff46e9dae552580ec9ff65c0c5 | 649,478 |
def popget(d, key, default=None):
"""
Get the key from the dict, returning the default if not found.
Parameters
----------
d : dict
Dictionary to get key from.
key : object
Key to get from the dictionary.
default : object
Default to return if key is not found in dict... | df430a146f83186102ac5c87133faf190ff2af8a | 649,486 |
def is_even(x):
"""
takes an integer input
outputs true if int is even
else outputs false
"""
return x%2==0 | dfb2882b7c1af7cddf767c1a45622043e36da773 | 649,488 |
def get_ui_confirmation(message: str):
"""
Get user confirmation to a message
:param message: Message displayed to the user
:type message: ``str``
:return: User answer: (True: yes False: no)
:rtype: :``bool``
"""
print(message + " y/n")
while 1:
answer = input()
if ... | c49a6aaf724c784c874c029316263cabd5a0176f | 649,491 |
async def index():
""" returns index page """
return "see /docs for the api" | a50afb3d6d0f64fd38d5f9f227b2356e5fe753b3 | 649,501 |
from functools import reduce
import operator
def sum_seq(seq, fn=None):
"""Sum the elements seq[i], or fn(seq[i]) if fn is given.
Ex: sum_seq([1, 2, 3]) ==> 6; sum_seq(range(8), lambda x: 2**x) ==> 255"""
if fn:
seq = map(fn, seq)
return reduce(operator.add, seq, 0) | 86de138315e39577d61f2e68a9f0b5808f09eff3 | 649,508 |
from typing import List
def is_hat_shaped(learning_rates: List[float]):
"""
Check if the list of learning rates is "hat" shaped, i.e.,
increases then decreases
"""
# sufficient conditions:
# has both an increasing and decreasing segment
# decrease segment occurs after increasing segmen... | 5da66f5a367ccc75c82972d89dc5a92e875c409d | 649,511 |
def isdivisor(number: int, divisor: int) -> bool:
"""
判断一个数是否为约数
:param number: 被求数
:param divisor: 约数
"""
return (number % divisor) == 0 | 61afc336ba5d2b2fdaa6df9a833bdd12dca65564 | 649,513 |
def is_subclass(obj, superclass):
"""Safely check if obj is a subclass of superclass."""
try:
return issubclass(obj, superclass)
except Exception:
return False | 4812f0e245546446256d0d2e9a305167e87da08d | 649,515 |
def is_contributor(user):
"""Return whether the user is in the 'Registered as contributor' group."""
return (
user.is_authenticated and user.groups.filter(name="Registered as contributor").count() > 0
) | 843aebd7aeb924188136e00ac14b710305b1cfb8 | 649,517 |
def find_count_to_turn_out_to_all_zero_or_all_one(string):
"""
:param string: 0과 1을 포함하는 문자열
:return: 모든 1 또는 모든 0이 되기 위한 최소 변환 횟수
"""
count_to_zeros = 0
count_to_ones = 0
if string[0] == '0':
count_to_ones += 1
else:
count_to_zeros += 1
for i in range(len(string) ... | db5b64d87aaadc55cda902fbb2dee24206b59e9b | 649,519 |
def extract_initials(*forenames):
"""Return a list of initials for each name in the given forenames.
"""
initials = []
# To handle varargs
for forename in forenames:
# Allow polymorphism: forenames can be str or sequence of str
try:
names = forename.split()
except... | eb28b5ff9d363621e460111094d051780d40838a | 649,522 |
from typing import List
def join(row: List[List[str]]) -> List[str]:
"""Join together a row of puzzle pieces into a complete list of lines"""
res = []
for i in range(len(row[0])):
res.append('│')
for piece in row:
res[i] += piece[i]
return res | bfc5f701ed9f0ed611a92998c423870a00c60b4e | 649,523 |
def inv_to_dict(inventory):
"""Convert an inventory to a simple cost->number dict."""
return {pos.units.currency: pos.units.number for pos in inventory} | ef9395f477bcb66f7c062dd02b4e704bf0928282 | 649,526 |
def format_as_vars_file_param(pathname):
"""Accepts a pathname and returns a string formatted as a valid terraform var-file include argument"""
return "-var-file={pn}".format(pn=pathname) | 844f06ad1ea8617ed2c51fd45224cc71b510a203 | 649,527 |
def word_capitalize(word: str) -> str:
"""Capitalize the first letter of every word within a sentence."""
return ' '.join(map(str.capitalize, word.split())) | 2b693cd12413bb8aea8f705b8a4744f5eabedd58 | 649,531 |
def make_line(move):
"""(str) -> str
Determines the line between two dots specified in the string <move>
The <move> parameter is one of '01', '12', '03' etc. representing a line
connecting the dots in the pattern;
0---1---2
| | |
3---4---5
| | |
6---7---8
... | 20319fc50e90fdb20df90bf24bf10398119eb75d | 649,533 |
def get_entity_name(battle, entity):
"""
Determine the identifying string name of the given entity in the battle.
Arguments
---------
battle : Battle
The Battle instance representing the battle.
entity : CombatEntity, Player
The entity to determine the name of.
... | 3056608646f8dba3e0ea3310316b79397f5e6574 | 649,537 |
import uuid
def get_random_id() -> str:
"""
Generate a random ID string. The random ID will start with the '_'
character.
"""
# It is very important that these random IDs NOT start with a number.
random_id = '_' + uuid.uuid4().hex
return random_id | ad60f4618bdb13ea30f9b5fffef51d793c84973f | 649,540 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.