content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def reshape(spectra):
"""Rearrange a compressed 1d array of spherical harmonics to 2d
Args:
spectra (np.ndarray): 1 dimensional storage of 2d spherical modes
Returns:
np.ndarray:
2-dimensional array of the reshaped input with zonal and meridional
wavenumber coordina... | af6bf177a860dd8f7d37a9d3586ab54f76e05a1f | 25,300 |
def dict_factory(cursor, row):
"""
This method is used to convert tuple type to dict after execute SQL queries in python.
:param cursor:
:param row:
:return:
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | 4f44cb368cff38db313e476a9b3a3bcabcca3bb3 | 25,301 |
import torch
def predict_batch(model, x_batch, dynamics, fast_init):
"""
Compute the softmax prediction probabilities for a given data batch.
Args:
model: EnergyBasedModel
x_batch: Batch of input tensors
dynamics: Dictionary containing the keyword arguments
for the rel... | 61102cfa3bcb3e7d52e9f3eca8c97db4d726c1a7 | 25,302 |
def render_openapi(api, request):
"""Prepare openapi specs."""
# Setup Specs
options = dict(api.openapi_options)
options.setdefault('servers', [{
'url': str(request.url.with_query('').with_path(api.prefix))
}])
spec = APISpec(
options['info'].pop('title', f"{ api.app.cfg.name.ti... | 96e49080a6c66f05210676c71a6e169f4caeca95 | 25,303 |
def apply_transformations(initial_representation: list, events: list) -> float:
"""Apply the transformations in the events list to the initial representation"""
scale = 1
rot_angle = 0
trans_vector = [0, 0]
for item in events:
for event in item["events"]:
if event["type"] == "TR... | a96be8bafe3b3cde3411f9c8efbf95629319b3cb | 25,304 |
def affine_transform(transform, points):
"""
Transforms a set of N x 2 points using the given Affine object.
"""
reshaped_points = np.vstack([points.T, np.ones((1, points.shape[0]))])
transformed = np.dot(affine_to_matrix(transform), reshaped_points)
return transformed.T[:,:2] | b976466d688003c7822f363949168d4acb6addb0 | 25,305 |
from datetime import datetime
def get_current_time_in_millisecs():
"""Returns time in milliseconds since the Epoch."""
return get_time_in_millisecs(datetime.datetime.utcnow()) | 17348e6c4994b3da0669be0ab39a7e8b01fd0e1c | 25,306 |
def _convert_named_signatures_to_signature_def(signatures):
"""Convert named signatures to object of type SignatureDef.
Args:
signatures: object of type manifest_pb2.Signatures()
Returns:
object of type SignatureDef which contains a converted version of named
signatures from input signatures object
... | f48f573860d7a4fc2f1d480e4c34fbe33c701481 | 25,307 |
import math
def get_test_paths(paths, snaps):
"""
Return $snaps paths to be tested on GLUE
"""
if snaps == -1:
return paths
interval = len(paths) * 1. / snaps
test_paths = []
for i in range(1, snaps+1):
idx = int(math.ceil(interval * i)) - 1
test_paths.append(paths[... | a2ac1f89740e85b6322e553559850c0e686a28c8 | 25,308 |
def is_success(code):
"""Return that the client's request was successfully received, understood, and accepted."""
return 200 <= code <= 299 | 8a6e64c0f218ca5a866a444c730e1ebf7628727e | 25,309 |
def is_palindrome_v3(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v3('noon')
True
>>> is_palindrome_v3('racecar')
True
>>> is_palindrome_v3('dented')
False
>>> is_palindrome_v3('')
True
>>> is_palindrome_v3(' ')
True
"""
... | 70f3393e39b30198879dbc5856c0c73b4be9601d | 25,310 |
from typing import BinaryIO
def read(fd: BinaryIO) -> Entity:
"""Read mug scene from `fd` file object.
Args:
fd: File object to read from.
Returns:
Root entity.
"""
if fd.read(4) != b'MUGS':
raise ValueError("not a valid mug file format")
return read_recursive(fd) | 2cb0b695ec1d75987940e862226166be22bad91d | 25,311 |
def transform(x,y):
"""
This function takes an input vector of x values and y values, transforms them
to return the y in a linearized format (assuming nlogn function was used
to create y from x)
"""
final = []
for i in range(0, len(y)):
new = y[i]#/x[i]
final.append(2 ** new)... | 119db625f5ebf469794bf3bdacd20a1c70ccd133 | 25,312 |
def _GRIsAreEnabled():
"""Returns True if GRIs are enabled."""
return (properties.VALUES.core.enable_gri.GetBool() or
properties.VALUES.core.resource_completion_style.Get() == 'gri') | 55713933090509944dc42333bb478c11db9a4176 | 25,313 |
def fatorial(n, show=False):
"""
-> Calcula o Fatorial de um número
:param n: O número a ser calculado.
:param show: (opcional) Mostrar ou não a conta.
:return: O valor do Fatorial de um número n.
"""
contador = n
resultado = guardado = 0
print('-' * 35)
while contador >= 0:
... | ddb4d91b3813e270e746bb0d463a5da595366b86 | 25,314 |
def start_job(job, hal_id, refGenome, opts):
"""Set up the structure of the pipeline."""
hal = hal_id
# Newick representation of the HAL species tree.
newick_string = get_hal_tree(hal)
job.fileStore.logToMaster("Newick string: %s" % (newick_string))
tree = newick.loads(newick_string)[0]
rero... | 5ddade182d045d7a6384d7e6c8d133650dafebbd | 25,315 |
import os
def user_base(username):
"""Base path of user files"""
return os.path.join(BASE['user'], username) | afa3acffe821c1da92a133bc71966ee2c8e10593 | 25,316 |
import argparse
def get_args(arg_input):
"""Takes args input and returns them as a argparse parser
Parameters
-------------
arg_input : list, shape (n_nargs,)
contains list of arguments passed to function
Returns
-------------
args : namespace
contains namespace with k... | 25b01282deef981197b2c7b62d33211a3200e787 | 25,317 |
def cleanup_databases():
"""
Returns:
bool: admin_client fixture should ignore any existing databases at
start of test and clean them up.
"""
return False | 63fa94389609b8e28779d1e9e55e9b1ecde502b6 | 25,318 |
import sys
def _round_down(rough_value, increment, minimum=None, maximum=None):
"""Utility method for rounding a value down to an increment.
Args:
rough_value: A float. The initial value to be rounded.
increment: The increment to round down to.
minimum: Optional minimum value, default is increment.
... | 2246258fee06817f84647eb8a404a4230c89e8d3 | 25,319 |
def document_index_list(request, document_id):
"""
Show a list of indexes where the current document can be found
"""
document = get_object_or_404(Document, pk=document_id)
object_list = []
queryset = document.indexinstancenode_set.all()
try:
# TODO: should be AND not OR
Per... | fcf8a9f135f0117221b32ebe13ec358cea527cf8 | 25,320 |
def spot_centroid(regions):
"""Returns centroids for a list of regionprops.
Args:
regions (regionprops): List of region proposals (skimage.measure).
Returns:
list: Centroids of regionprops.
"""
return [r.centroid for r in regions] | f53f403dddf0af123afd207e33cc06254a0f2538 | 25,321 |
import os
def FindChromeSrcFromFilename(filename):
"""Searches for the root of the Chromium checkout.
Simply checks parent directories until it finds .gclient and src/.
Args:
filename: (String) Path to source file being edited.
Returns:
(String) Path of 'src/', or None if unable to find.
"""
cu... | 562dfa55da0e74402c6dca4ca51eea1ecbd4b0bc | 25,322 |
def one_election_set_reg(request, election):
"""
Set whether this is open registration or not
"""
# only allow this for public elections
if not election.private_p:
open_p = bool(int(request.GET['open_p']))
election.openreg = open_p
election.save()
return HttpResponseRedirect(settings.SECURE_U... | 5486c8b277528204260189f1f248aadc20cd9354 | 25,323 |
def overrides(conf, var):
"""This api overrides the dictionary which contains same keys"""
if isinstance(var, list):
for item in var:
if item in conf:
for key, value in conf[item].items():
conf[key] = value
elif var in conf:
for key, value in c... | 18375dc43a0d684feaf9089756ecb45eb5a366f3 | 25,324 |
def annual_to_daily_rate(rate, trading_days_in_year=TRADING_DAYS_IN_YEAR):
"""
Infer daily rate from annual rate
:param rate: the annual rate of return
:param trading_days_in_year: optional, trading days in year (default = 252)
:return: the daily rate
"""
return subdivide_rate(rate, trading_... | a93ce4e3b0ba247f37b5a867025670a7f064022e | 25,325 |
def make_hashable(data):
"""Make the given object hashable.
It makes it ready to use in a `hash()` call, making sure that
it's always the same for lists and dictionaries if they have the same items.
:param object data: the object to hash
:return: a hashable object
:rtype: object
"""
if... | e4b88978ddee6d4dfc354845184a0e80b1f434bf | 25,326 |
from typing import Dict
from typing import Tuple
def prepare_model_parameters(
parameters: Dict[str, FloatOrDistVar], data: DataFrame,
beta_fun, splines, spline_power
) -> Tuple[Dict[str, FloatLike], Dict[str, NormalDistVar]]:
"""Prepares model input parameters and returns independent and dependent param... | c68692148115aa8aa5b9a0b600d6b335cd7ed99f | 25,327 |
import logging
def paper_features_to_author_features(
author_paper_index, paper_features):
"""Averages paper features to authors."""
assert paper_features.shape[0] == NUM_PAPERS
assert author_paper_index.shape[0] == NUM_AUTHORS
author_features = np.zeros(
[NUM_AUTHORS, paper_features.shape[1]], dtyp... | 6394c57d2b48461287cc77cca021d25c377efaae | 25,328 |
def set_chart_time_horizon(request) -> JsonResponse:
"""
Set the x-axis (time horizon) of a chart.
API Call:
/set_chart_time_horizon?
monitor_name=<monitor name>&
value=<time horizon to set>
:param request: HTTP request that expects a 'monitor_name' and 'value' argument. 'value... | 94eb982090da2e761032aa5fef4f210c2ff312ee | 25,329 |
def get_single_io_arg(info):
"""
Get single input/output arg from io info
:param info:
:return:input/output arg
"""
if 'valid' not in info:
raise ValueError("Json string Errors, key:valid not found.")
if info['valid']:
check_arg_info(info)
del info['valid']
de... | 6062f5e1ea61d6a999d106e40e72610b2373b26a | 25,330 |
from typing import Dict
from typing import Any
def new_credentials(
client_id: str, consumer_secret: str, data: Dict[str, Any]
) -> Credentials:
"""Create Credentials from config and json."""
return Credentials(
access_token=str_or_raise(data.get("access_token")),
token_expiry=arrow.utcnow... | 2f582de9863ed15122678d8268c5f2a9c8a0484e | 25,331 |
def get_chains(table, ipv6=False):
""" Return the existing chains of a table """
iptc_table = _iptc_gettable(table, ipv6)
return [iptc_chain.name for iptc_chain in iptc_table.chains] | 659119d90befb241a205f2a70eeafc273098a91a | 25,332 |
import os
import glob
def check_file(file):
"""
检查本地有没有这个文件,相关文件路径能否找到文件 并返回文件名
"""
# 如果传进来的是文件或者是’‘, 直接返回文件名str
if os.path.isfile(file) or file == '':
return file
# 如果传进来的就是当前项目下的一个全局路径 查找匹配的文件名返回第一个
else:
files = glob.glob('./**/' + file, recursive=True)
# 验证文件名是否... | 9a1d3283a26a1fcdca67622413dc4fc8e887fbee | 25,333 |
def unscale_fundamental_matrix(fundamental_matrix, M):
"""
Unscale fundamental matrix by coordinate scaling factor
:param fundamental_matrix:
:param M: Scaling factor
:return: Unscaled fundamental matrix
"""
T = np.diag([1 / M, 1 / M, 1])
unscaled_F = T.T.dot(fundamental_matrix).dot(T)
... | 968c924870a93363cf78bfcc593b5c4367375692 | 25,334 |
def initialize_server_request(request):
"""Shortcut for initialization."""
# Django converts Authorization header in HTTP_AUTHORIZATION
# Warning: it doesn't happen in tests but it's useful, do not remove!
auth_header = {}
if 'Authorization' in request.META:
auth_header = {'Authorization': r... | f844a677e48a933401dbd6028ce7faf8e58e77cd | 25,335 |
from .sky_coordinate import SkyCoord
from typing import Sequence
def _parse_coordinate_arg(coords, frame, units, init_kwargs):
"""
Single unnamed arg supplied. This must be:
- Coordinate frame with data
- Representation
- SkyCoord
- List or tuple of:
- String which splits into two value... | 6ed456c07b407476a9c02d7d87c9351d27fb7513 | 25,336 |
from typing import Tuple
def build_names(dependency: Dependency, version_in_url: bool = True) -> Tuple[RemoteResolver, str, str]:
"""
A function to build directory and file names based on the given dependency..
:param dependency: the dependency to create the file container for.
:param version_in_url:... | 83a3c063e69a6a8e16e0af6f2e6f43d9f423cd3e | 25,337 |
def convert_apc_examples_to_features(examples, label_list, max_seq_len, tokenizer, opt=None):
"""Loads a data file into a list of `InputBatch`s."""
configure_spacy_model(opt)
bos_token = tokenizer.bos_token
eos_token = tokenizer.eos_token
label_map = {label: i for i, label in enumerate(label_list,... | 8eb8570e4d6f2f5fa22583ff216cbf216ac10145 | 25,338 |
from datetime import datetime
from pathlib import Path
def write_output(opts: AppOptions, out_lines):
"""
Writes the modified document lines to a new file with "MODIFIED" and
a date_time tag added to the file name. Returns the file name.
"""
ds = datetime.now().strftime("%Y%m%d_%H%M%S")
out_n... | 613bb6a3290e8a86eb8c945248b6088db3e9dc91 | 25,339 |
def ssh_pub_key(key_file):
"""Creates a string of a public key from the private key file.
"""
key = paramiko.RSAKey(filename=key_file)
pub = "{0} {1} autogenerated by polyphemus"
pub = pub.format(key.get_name(), key.get_base64())
return pub | bf46c62031a7d761278612e5835b829a32f7fbe2 | 25,340 |
def _variable_with_weight_decay(name, shape, stddev, wd, use_xavier=True, use_zeros=False, init=None):
"""Helper to create an initialized Variable with weight decay.
Note that the Variable is initialized with a truncated normal distribution.
A weight decay is added only if one is specified.
Args:
name: na... | a3d43147508bd10040521dc59cfc49de81bbb70b | 25,341 |
def build_mobile_vit(config):
"""Build MobileViT by reading options in config object
Args:
config: config instance contains setting options
Returns:
model: MobileViT model
"""
model = MobileViT(in_channels=config.MODEL.IN_CHANNELS,
dims=config.MODEL.DIMS, # XS:... | 7c8eb92214240b922f4df242f937ba05985c3d2c | 25,342 |
def _openSerialPort(comport):
"""Opens the serial port name passed in comport. Returns the stream id"""
#debuglog.info("Check if serial module is available in sys {}".format(sys.modules["serial"]))
s = None
try:
s = serial.Serial(
port=comport,
baudrate=115200,
... | 738512c801b01b9ce1234f2800bb3312f7f8caba | 25,343 |
from functools import reduce
from bs4 import BeautifulSoup
def search_youtube(query, retries = 4, max_num_results = -1):
""" Unlimited youtube search by web scrapping """
transformed_query = reduce(lambda s_ant, s_sig : s_ant + '+' + s_sig, query) if len(query) != 0 else ''
scrapped_data = []
num_of_r... | 119305a5e6ad562fa9f537d42fd36617338b2472 | 25,344 |
import sys
def Pull( display_sentinel,
json_filename,
result_filename,
first=False,
output_stream=sys.stdout,
):
"""Called prior to committing a change pushed from a client to the local repository"""
return _Impl( display_sentinel,
json_filenam... | 2eab49d028b66a0daff18786bd99827134fce96e | 25,345 |
from typing import List
from typing import Tuple
from typing import OrderedDict
def define_empty_source_parallel_buckets(max_seq_len_target: int,
bucket_width: int = 10) -> List[Tuple[int, int]]:
"""
Returns (source, target) buckets up to (None, max_seq_len_target). Th... | 3e5261191c5a55f4d82ee84b9000e0996e06c9f9 | 25,346 |
def _hue_scaling(args):
"""return scaled hue values as described in
http://dlmf.nist.gov/help/vrml/aboutcolor
args : ndarray of args / angle of complex numbers between in the open
interval [0, 2*pi)
q : scaled values returned in the interval [0, 1)
"""
q = 4.0*_np.mod((args/(2*_np.pi... | 42fa445d5e790eed13d692613771d02cc55fad94 | 25,347 |
from qharv.inspect import axes_pos
def get_orbs(fp, orbs, truncate=False, tol=1e-8):
""" return the list of requested Kohn-Sham orbitals
Args:
fp (h5py.File): wf h5 file
orbs (list): a list of 3-tuples, each tuple species the KS state
by (kpoint/twist, spin, band) i.e. (ik, ispin, ib)
truncate (... | d4b7bf639b81f1d776f29bb736a51b7b8684c42d | 25,348 |
def geturlcgivars(baseurl, port):
"""
Extract CGI variables from baseurl
>>> geturlcgivars("http://host.org/base", "80")
('host.org', '80', '/base')
>>> geturlcgivars("http://host.org:8000/base", "80")
('host.org', '8000', '/base')
>>> geturlcgivars('/base', 8000)
('', '8000', '/base')
... | 116ace2bb8275de5faddb4c40e9de05d8a7aee95 | 25,349 |
import json
def insert_rails(file_path, half_gauge, drive_right = True, mr = 12.5, copy = True): # TODO - print 'progress messages' for done steps
"""
Deduces all rails' vertices from graph data and adds them to the json blueprint
half_gauge represents distance between center of the road and of the vehic... | 90973eb4a9ff6560d5865f1d3e513f9af2fdd804 | 25,350 |
def prepare_log_for_upload(symbolized_output, return_code):
"""Prepare log for upload."""
# Add revision information to the logs.
app_revision = environment.get_value('APP_REVISION')
job_name = environment.get_value('JOB_NAME')
components = revisions.get_component_list(app_revision, job_name)
component_revi... | 78e41f67be726f2fb0fb4fb59aa23d124a371055 | 25,351 |
import math
def bucketize(point, bucket_size):
"""floor the point to the next lower multiple of bucket_size"""
return bucket_size * math.floor(point / bucket_size) | ff152cb5b646df1fe883bd943033c05e83623f31 | 25,352 |
def find_unit(df):
"""find unit in the df, add column to df indicating which token contains unit
and return the unit as string."""
doc_unit = ""
# thousand = "(\$)(0){3}|thousand|€(\s*)thous|TEUR|T(\s*)€|Tsd|Tausend"
# million = "millions|million|£(\s*)m|$(\s*)m|€(\s*)m|mn|mio(\s*)€|in(\s+)mio|MM|\d... | a46eede3e5dc928f90969ff89df15c5e0039991d | 25,353 |
import torch
def regular_channels(audio ,new_channels):
"""
torchaudio-file([tensor,sample_rate])+target_channel -> new_tensor
"""
sig ,sr =audio
if sig.shape[0 ]==new_channels:
return audio
if new_channels==1:
new_sig =sig[:1 ,:] # 直接取得第一个channel的frame进行操作即可
else:
... | 5b055d965f35fc4cf0f434b34e8f579f321fee89 | 25,354 |
from typing import Union
from typing import Callable
def is_less_than(maximum: Union[int, float, Decimal]) -> Callable[[Union[int, float, Decimal]], bool]:
"""
:param maximum: A number
:return: A predicate that checks if a value is less than the given number
"""
def predicate(i: Union[int, float, ... | 9f381ae1901581f24af1f3b51f9d64a3b976d6e9 | 25,355 |
def a_function(my_arg, another):
"""
This is the brief description of my function.
This is a more complete example of my function. It can include doctest,
code blocks or any other reST structure.
>>> a_function(10, [MyClass('a'), MyClass('b')])
20
:param int my_arg: The first argument of ... | 8624edfe3ec06b53e065a6672c3b21682cdefe06 | 25,356 |
import os
def substitute_vars(oldList, runSet=None, task_file=None):
"""
This method replaces special substrings from a list of string
and return a new list.
"""
keyValueList = []
if runSet:
benchmark = runSet.benchmark
# list with tuples (key, value): 'key' is replaced by 'va... | 7074d333d3dbffdc8d70f250cbef6bdb2abbdc0c | 25,357 |
from datetime import datetime
def _safe_filename(filename):
"""
Generates a safe filename that is unlikely to collide with existing objects
in Google Cloud Storage.
``filename.ext`` is transformed into ``filename-YYYY-MM-DD-HHMMSS.ext``
"""
filename = secure_filename(filename)
date = date... | 2ea94c9d18240cf1f1c4dadd19f2bd87b39e6538 | 25,358 |
import os
def load_model(model_name, data_dir=''):
"""
Load and return a trained model
@param model_name: base name for saved files
@param data_dir: directory containing trained model
"""
# load json and create model
json_file = open(os.path.join(data_dir, '%s.json' % model_nam... | 3522fe0bc1e222c0d714b665bc2259476af59404 | 25,359 |
import collections
def _make_with_custom_variables(func, variables):
"""Calls func and replaces any trainable variables.
This returns the output of func, but whenever `get_variable` is called it
will replace any trainable variables with the tensors in `variables`, in the
same order. Non-trainable variables w... | a36923223d22b6b09d9697da3a072c3eef4e739a | 25,360 |
def create_loss_and_learner(
model, labels, learning_rate,
momentum_coef=0.0, wdecay=0.0, nesterov=False,
gradient_clip_norm=None, gradient_clip_value=None):
"""
Auxiliary function to create loss function (cross entropy and softmax)
and trainer using stochastic gradient descent with ... | 49669aa109f748b13b3c52efea7cbadb94d492b7 | 25,361 |
import os
import sys
def get_opentsdb_config():
"""Read and parse Open TSDB config from config.ini"""
if os.path.exists(os.path.abspath(os.path.join(__file__, os.pardir, "config.ini"))):
config_parser = ConfigParser.SafeConfigParser()
config_parser.read(os.path.abspath(os.path.join(__file__, o... | 05c47aebb9cc06632eff079ecf621ad3c6f2b82d | 25,362 |
def mesh_subdivide_tri(mesh, k=1):
"""Subdivide a mesh using simple insertion of vertices.
Parameters
----------
mesh : Mesh
The mesh object that will be subdivided.
k : int
Optional. The number of levels of subdivision. Default is ``1``.
Returns
-------
Mesh
A ... | 54912f1777dc1d508a9ab55289e90bcb28b9586f | 25,363 |
import cartopy.crs as ccrs
def make_projection(proj_params):
"""
turn a set of proj4 parameters into a cartopy laea projection
introduced in read_resample.ipynb
Parameters
----------
proj_params: dict
dictionary with parameters lat_0, lon_0 datum and ellps
Returns... | 1852115888107b5ae9353dd746d56fb3896c1992 | 25,364 |
import pandas
import logging
def _shape(df):
""" Return DataFrame shape even if is not a Pandas dataframe."""
if type(df) == pandas.DataFrame or type(df) == pandas.Series:
return df.shape
try:
shape = (len(df), len(df.columns))
except Exception as e:
logging.error(e)
ra... | d5af0e3f92ee649091d9fc8b904e60931fb0f2f7 | 25,365 |
from typing import List
from pathlib import Path
def hvplot_line(
df, title, x, y: List[str], output_dir: Path, vlines=None, save_figure=True, **kwargs
):
"""Draw line splot with optional vertical lines.
Example:
hvplot_line(
df,
title=col,
x="t... | 1f7400bc12b492648074b2cb2dc52835cb509a1e | 25,366 |
def load_zstack(fn):
"""
Returns zstack, [zmin, zmax]
"""
with open(fn, "rb") as f:
d = np.fromfile(f,dtype=header_dtype,count=1,sep="")
version, shape, zrange = d[0]
zstack = np.fromfile(f,dtype='<f4',sep="").reshape(shape)
return zstack, zrange | 19fd400b0b341569b448e45d482df264310c9cf7 | 25,367 |
def parseFile(path):
"""
Read sections headed by :SectionName into lists by section name in a dictionary
blank lines, line preceeding and ending whitespace and #Comments are stripped
"""
d={}
currentList=None
f = open(pathPrefix()+path, 'r')
for t in f.readlines(... | db5a73b5a46fc1026df775de994da150d33e3aad | 25,368 |
def setName(name):
"""
Sets the name of the robot.
This is cleared with a power cycle and displayed on the robot screen during idle times
Name will be shortened to 11 characters
Args:
name (any): Name to set for the robot. Will be cast to a string
Returns:
None
"""
name = ... | 5f1e12635df0cf4c95b3ce90e97a51492a477914 | 25,369 |
import subprocess
def get_cmd_output(cmd):
"""Run a command in shell, and return the Unicode output."""
try:
data = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as ex:
data = ex.output
try:
data = data.decode("utf-8")
... | f1ac61b45b2adb404b50c5001e8737db2c0a9c95 | 25,370 |
def twoBodyCMmom(m_0, m_1, m_2):
"""relative momentum for 0 -> 1 + 2"""
M12S = m_1 + m_2
M12D = m_1 - m_2
if hasattr(M12S, "dtype"):
m_0 = tf.convert_to_tensor(m_0, dtype=M12S.dtype)
# m_eff = tf.where(m_0 > M12S, m_0, M12S)
# p = (m_eff - M12S) * (m_eff + M12S) * (m_eff - M12D) * ... | 5b8576dc33a4570f976efc1bab67a432032b02ff | 25,371 |
def svn_repos_post_commit_hook(*args):
"""svn_repos_post_commit_hook(svn_repos_t repos, apr_pool_t pool) -> char"""
return _repos.svn_repos_post_commit_hook(*args) | bbb9eb6fe81e80ef4729791448e5abe1d7b6ab12 | 25,372 |
import os
def get_window_size():
"""Return the window width and height"""
width = os.popen(
"xrandr --current | grep '*' | uniq | awk '{print $1}' | cut -d 'x' -f1").read().strip(
"\n")
height = os.popen(
"xrandr --current | grep '*' | uniq | awk '{print $1}' | cut -d 'x' -f2").rea... | 7d28746f6c1805e31d93b4c934b9442a19d4cfa1 | 25,373 |
def slot_selection_is_free(effect):
"""
all slots ar selected when participant applies
"""
activity = effect.instance.activity
return activity.slot_selection == 'free' | 153efa36dda70de02613201540d97e8f22f2bdd9 | 25,374 |
def get_consumption_tax(amount, tax_rate, decimal_type):
"""消費税を取得する。
:param amount:
:param tax_rate:
:param decimal_type:
:return:
"""
if not amount:
return 0
return get_integer(decimal_type, float(amount) * float(tax_rate)) | d982d2ebc65770477a9ec06e1305115ecf2eab9e | 25,375 |
def homology(long_sequence, short_sequence):
"""
Cross-compare to find the strand of long sequence with the highest similarity with the short sequence.
:param long_sequence: str
:param short_sequence: str
:return ans: str, the strand of long sequence with the highest similarity with the short sequen... | 1865e7b60cfce3b1ca4e7884377a5a218ecba96a | 25,376 |
def oneliner_to_phylip(line):
"""Convert one-liner to phylip format."""
seqs = line.strip(";\n").split(',')
label_seqs = zip(seqs[:-1:2], seqs[1::2])
taxa_count = len(label_seqs)
seq_length = len(label_seqs[0][1])
# pad all names to length of longest name + 1 space
max_name_length = max([len... | 783d9e68172d4d30de44564b88001d30af4d8e45 | 25,377 |
def get_final_histogram(n_states, logfile, temp):
"""
This function analyzes the log file and performs the following tasks:
1. Output the counts of each lambda state at the last time frame (for plotting histogram)
2. Estimate the uncertainty of free energy difference from the final histogram
Parane... | a72ecd4aa6b47e2c8d1368a03ea5b5887abc27c2 | 25,378 |
import logging
def create_sql_delete_stmt(del_list, name):
"""
:param del_list: list of records that need to be formatted in SQL delete statement.
:param name: the name of the table
:return: SQL statement for deleting the specific records
"""
sql_list = ", ".join(del_list)
sql_stmt = f"DEL... | aec744198f1b0dd30836f431ac51a4080911f8ae | 25,379 |
def parse_track(trackelement):
"""Extract info from every track entry and output to list."""
print(trackelement)
if trackelement.find('artist').getchildren():
#artist info is nested in loved/banned tracks xml
artistname = trackelement.find('artist').find('name').text
artistmbid = ... | e5cd49d765885fd0e701864831f9a2958076ca93 | 25,380 |
from typing import Mapping
def _coord_matrix(model, pos, noutp):
"""
Create an array representing inputs and outputs of a simple model.
The array has a shape (noutp, model.n_inputs).
Parameters
----------
model : `astropy.modeling.Model`
model
pos : str
Position of this m... | 841b2ba8df26e424f2fcafc0d3180c3409078896 | 25,381 |
def showp2rev(context, mapping):
"""Integer. The repository-local revision number of the changeset's
second parent, or -1 if the changeset has no second parent."""
ctx = context.resource(mapping, 'ctx')
return ctx.p2().rev() | 854225fca900e5e46ecd18efeab9fc8d3e1f9168 | 25,382 |
from typing import Optional
def puan_kam(text: str = 'สวัสดี',
first: Optional[bool] = None,
keep_tone: Optional[bool] = None,
all: Optional[bool] = False,
skip_tokenize: Optional[bool] = None):
"""Puan kum (ผวนคำ) is a Thai toung twister, This API convert strin... | 5b49aab2437a906ea23122722a45bb472011bbbb | 25,383 |
import sys
import importlib
def _flask_app_from_location(module_name: str) -> flask.app.Flask:
"""
:param module_name: String specifying path and module name as well as
actual flask app attribute. e.g., /path/to/module:flask_app
"""
module_and_app_name: str = (module_name.split('/')[-1])
mod... | 8115c6df3a45990954f541de5c8b18d639f7a1f7 | 25,384 |
import wx
def get_app_wx(*args, **kwargs):
"""Create a new wx app or return an exiting one."""
app = wx.GetApp()
if app is None:
if 'redirect' not in kwargs:
kwargs['redirect'] = False
app = wx.PySimpleApp(*args, **kwargs)
return app | ad4f79e57562e199833d0d948934ec6e9211eea4 | 25,385 |
def do_part_1():
"""
Solve the puzzle.
"""
data = input_lines(1)
total = 0
for line in data:
val, op = interpret_line(line)
total = op(total, val)
print(total)
return total | af8c96a3963bf2732b0281a2b425da73a1ab26e5 | 25,386 |
def handle_rpc_errors(fnc):
"""Decorator to add more context to RPC errors"""
@wraps(fnc)
def wrapper(*args, **kwargs):
try:
return fnc(*args, **kwargs)
except grpc.RpcError as exc:
# lnd might be active, but not possible to contact
# using RPC if the wal... | 4f1cb19918fa5410bef4f14540a35c9f75d113bd | 25,387 |
import ast
def _check_BoolOp_expr(boolop, t, env):
"""Boolean Operations."""
assert boolop.__class__ is ast.BoolOp
op = boolop.op
es = boolop.values
assert op.__class__ in bool_ops, "%s not in bool ops" % cname(op)
# (BoolOp) assignment rule.
return all(check_expr(e, t, env) for e in e... | 528f55894a60ec8f781e5600a82f32697382e4bb | 25,388 |
def get_matproj(dbpath, cutoff, api_key, dataset_properties):
"""
Args:
dbpath (str): path to the local database
cutoff (float): cutoff radius
api_key (str): personal api_key for materialsproject.org
dataset_properties (list): properties of the dataset
Returns:
Atoms... | d40b3578a5ac315e1b4d5180113d517d88b5305b | 25,389 |
def parse_change_values_from_opts(opts):
"""
Convert optparse style options into a dictionary for changing.
:param opts: optparse style options
:returns: a dictonary with change values to filter devices,
supported parameters are ip, port, replication_ip,
replication_port
... | d8168163c308b510f12a5cd2baf9dd800b80912a | 25,390 |
def chooseMove(board,gameState):
"""called once per turn. Calls either escapeTrail or approachOpponent to determine move choice"""
def escapeTrail():
"""returns a command to move to the next space if we are in danger of an explosion Trail, or None if we are safe"""
# if we are not currently on a... | 139a85264b388e9faf9e007af37c153f3985347c | 25,391 |
def xr_linear_trends_2D(da, dim_names, with_nans=False):
""" calculate linear trend of 2D field in time
! slow, use xr_2D_trends instead
input:
da .. 3D xr DataArray with (dim_names) dimensions
dim_names .. tuple of 2 strings: e.g. lat, lon dimension names
output:
da_trend ... | ba948729cd8e8bde037ad91bde788443cd7eb54c | 25,392 |
def sanitize_email(email):
"""
Returns an e-mail address in lower-case and strip leading and trailing
whitespaces.
>>> sanitize_email(' MyEmailAddress@example.com ')
'myemailaddress@example.com'
"""
return email.lower().strip() | b99e9c38db4fe889e1d0a9175d6535c4790f2f43 | 25,393 |
import numba
def draw_perm_reps(data_1, data_2, func, size=1, args=()):
"""
Generate permutation replicates of `func` from `data_1` and
`data_2`
Parameters
----------
data_1 : array_like
One-dimensional array of data.
data_2 : array_like
One-dimensional array of data.
... | 6a5e46e39ace1815297812fbe17acd7db7fb89db | 25,394 |
import os
from bs4 import BeautifulSoup
def construct(template_name, parameter_dict, path=""):
"""Construct an HTML file using a given template and parameters.
Handles all necessary tasks for generating finished HTML files in output directory.
Likely the tuscon function that the user will call most often... | 07ed889df234bd9622e6ba85f29bdf6c12a9b0c1 | 25,395 |
def get_attachment_form(parser, token):
"""
Get a (new) form object to upload a new attachment
Syntax::
{% get_attachment_form for [object] as [varname] %}
{% get_attachment_for for [app].[model] [object_id] as [varname] %}
"""
return AttachmentFormNode.handle_token(parser, token) | 5ae8c049eef6618f358755e5363520a3bc126780 | 25,396 |
def greet(name):
"""Greet message, formatted differently for johnny."""
if name == "Johnny":
return "Hello, my love!"
return "Hello, {name}!".format(name=name) | 86efdaccd65a870fd80e402491e9468669cdcd40 | 25,397 |
import numpy
def get_naca_points(naca_digits, number_of_points=100,
sharp_trailing_edge=True,
abscissa_map=lambda x: 0.03*x+0.97*x**2,
verbose=False):
"""
Return a list of coordinates of NACA 4-digit and 5-digit series
airfoils.
"""
if verbose:
def explain(*s):
... | ec7f4b2c0104639e727febc6ea1a0ab0f1575f9e | 25,398 |
def get_request_now():
"""
When constructing the SOAP request, the timestamps have to be naive but with localtime values.
E.g. if the current offset is utc+1 and the utc now is 2016/03/30 0:00, the SOAP endpoint expects 2016/03/30 1:00
without tzinfo. That's pretty ugly but ¯\_(ツ)_/¯
In order to do... | 8563eeb9757a7d09b7a0c3253e64cb30443aaa55 | 25,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.