content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def timeseries_table(request, model_uuid):
"""
View the "Timeseries" page
Parameters:
model_uuid (uuid): required
Returns: HttpResponse
Example:
http://0.0.0.0:8000/<model_uuid>/timeseries_table/
"""
model = Model.by_uuid(model_uuid)
can_edit = model.handle_view_access(reques... | 410b5bdac6a2bb926d98ddd540e065b9d7d01831 | 3,602,441 |
def _initialize_variogram_model(X, y, variogram_model,
variogram_model_parameters, variogram_function,
nlags, weight, coordinates_type,network=None):
"""Initializes the variogram model for kriging. If user does not specify
parameters, calls automat... | abd50d84eeef20df802e5033db3a79a4cb40e7d7 | 3,602,442 |
def is_specific_hemorrhage(df):
"""If a specific hemorrhage present or suspected,
then hemorrhage NOS changed to absent."""
hemorrhages = [
"epidural_hemorrhage",
"subarachnoid_hemorrhage",
"subdural_hemorrhage",
]
present = ["present", "suspected"]
specific_hemorrhage ... | 404a8162e9225055bf1b3ea493d6529ea5e90767 | 3,602,443 |
def polynomial(degree, coeffs):
"""
>>> fourth = polynomial(4, [3,6,2,1, 100])
>>> fourth(3) # 3*(3**4) + 6*(3**3) + 2*(3**2) + 1*(3**1) + 100
526
>>> third = polynomial(3, [2, 0, 0, 0])
>>> third(4) # 2*(4**3) + 0*(4**2) + 0*(4**1) + 0
128
"""
def h(x):
result = 0
... | b7f84aabe99e853e57dd7204aecd7bef03655668 | 3,602,444 |
def contentaddress(key, mem, beta):
"""Content address
Parameters
----------
key : `[batch_size, word_size]`
mem : `[batch_size, mem_size, word_size]`
beta : `[batch_size, 1]`
Returns
-------
`[batch_size, mem_size]`
"""
key_ = expand_dims(key, axis=2)
norm_mem = norm(m... | 5edac65914c9814322cd8a0a454506c0e383c9fc | 3,602,445 |
def hsv2rgb(img):
""" Use matplotlib to convert hsv to rgb (TA allowed) """
return (hsv_to_rgb(img.astype(np.float32) / 255.) * 255).astype(np.uint8) | 262ec15ab3e5ba21b3514973d93b5889becf534a | 3,602,446 |
def cybereason_driver():
"""Generate Cybereason Driver for testing."""
driver = CybereasonDriver()
_cr_pre_checks(driver)
return driver | 1d984d2db26fd8aeb6c48cafab7451435c89d11d | 3,602,447 |
def all_forms_list(*args, **kwargs):
"""Returns a list/tuple of all possible word form descriptors for the given
part-of-speech and other restrictions. This caches the result."""
key = (args, tuple(sorted(kwargs.items())))
if key in all_forms_cache:
return all_forms_cache[key]
forms = tuple... | f289b301d7f57b21ac9933003317a2d09d1f6986 | 3,602,448 |
def patch(url, body=None, **kwargs):
"""patch performs a HTTP PATCH request."""
return request('PATCH', url=url, body=body, **kwargs) | 4049f91bbe1ee5fb15d3a2c6534a44893e60b682 | 3,602,449 |
def opportunity_outlook_gain(X, threshold=1):
"""Calculate opportunity outlook gain
Value for existing capabilities is NaN.
Args:
X (pandas.DataFrame): [locations x activities]
threshold (float, optional): Binarisation threshold for location
quotient.
Returns:
pand... | 1b5b625aa9f90fc4c75f4450b00024949bba0f1d | 3,602,450 |
def new_format_converter(df, logger):
"""Returns a dataframe."""
df = df.rename(columns={"Plant Name": "Hour"})
df["Hour"] = df["Hour"].astype(str)
df = df.reset_index(drop=True)
df = df.set_index("Hour")
total_index = df.columns.get_loc("Total (MW)")
df = df.iloc[:, total_index:]
try:... | d18178046e12a074fdfa05c8ad4dbdbe9993d003 | 3,602,451 |
def conv2d_grad_backend(x, dy, padding, stride):
"""Performs the gradient of a discrete 2d convolution of x with w."""
dilated_dy = np.zeros([dy.shape[0], dy.shape[1], stride[0], dy.shape[2], stride[1], dy.shape[3]])
dilated_dy[:, :, 0, :, 0, :] = dy
dy = dilated_dy.reshape([dy.shape[0], dy.shape[1] * s... | 59c95f92ba6874923d188066856a968a08962e0d | 3,602,452 |
def TETMajScale(frequency, octaveDivider):
"""Cross references a traditional major scale with a new TET chromatic scale.
Returns an array of 8 frequencies."""
standard = StandardMajScale(frequency)
newTET = TETChromaticScale(frequency, octaveDivider)
newScale = []
for i in range(len(standard)):
... | e54705e30c0eaccf5bc52f98380786c15698f5a8 | 3,602,453 |
import torch
def calc_loss(x_pred, x_output, num_output, pri=True):
"""Focal loss
:param x_pred: prediction of primary network (either main or auxiliary)
:param x_output: label
:param pri: is primary task output?
:param num_output: number of classes
:return: loss per sample
"""
if not... | 7433df267911d136d0b03ce3d922e7650d1c93d6 | 3,602,454 |
def _BackslashEscape(s):
"""Double up backslashes.
Useful for strings about to be globbed and strings about to be IFS escaped.
"""
return s.replace('\\', '\\\\')
# Similar to GlobEscape and splitter.Escape().
escaped = ''
for c in s:
if c == '\\':
escaped += '\\'
escaped += c
return escap... | 4c107203117d699c65fd00158913914ae6530b97 | 3,602,455 |
import collections
def _collect_traces(raw_traces, trace_factory):
"""Postprocesses pytype's opcode traces."""
out = collections.defaultdict(list)
for op, symbol, data in raw_traces:
out[op.line].append(trace_factory(op.name, symbol, data))
return out | 6f656073c17c9c5c1d6a33c37dd6a23a5525aa64 | 3,602,456 |
def intrange(arg):
""" convert a command-line argument to a list of integers """
acceptable_chars = [str(x) for x in range(10)]
acceptable_chars.append("-")
partial = []
first = None
msg = "Could not convert {0} to index range.".format(arg)
err = TypeError(msg)
for char in arg:
... | 8d3bbe9b32207ae2c18080601761b84c9e87ec9f | 3,602,457 |
def inside_or_on_line_2d(p1, p2, reference_point, pt, tol=None):
"""Tests whether a point is on the same side of a line as a reference point, or on the line itself.
Assumes reference_point is not on the line (within tol).
Points are represented as (x, y, z) triples.
Args:
p1: The first point d... | 58aa202c5333bedbbb7139128d93f6e057d45ee8 | 3,602,458 |
import string
def create_row_object_stack():
"""Extract every stacking object in a client call"""
l_row = environment.get_cursor_row()
non_splittable_characters = string.ascii_letters + string.digits + "_"
l_col = complete_start() - 1
l_col = environment.previous_non_white_character_in_row(l_row, ... | 9c370710cd4a0610c33d41410268d2bf3117ff16 | 3,602,459 |
from summit_core import find_closest_date, search_for_attr_value
import logging
def match_lines_to_runs(lines, runs):
"""
This takes a list of PaLine and GcRun objects and matched them by date, within a tolerance.
When matching objects, it WILL modify their parameters and status if warranted.
:param ... | 49ad2c4648c68042fcc14a027ace95902ea24efa | 3,602,460 |
def update_dict(new_dict):
""" update configs dict
"""
if new_dict["method"] == "dichotomy":
default_dict = DICHOTOMY_DICT.copy()
elif new_dict["method"] == "sphere_tracing":
default_dict = SPHERE_TRACING_DICT.copy()
elif new_dict["method"] == "gradient_descent":
default_dict... | 79d0f6f676c6ca11b1d40445145d399a78beb893 | 3,602,461 |
def protein_binding_hairpin(N, target='none', ligand='theo', pam=None):
"""
Randomize the region 5' of the hairpin in the hopes of creating a sequence
that is partially complementary to the aptamer. Presently, this strategy
is intended for protein binding aptamers like MS2 that aren't expected to
... | 6391ae7b2926a468c3e4d5789c04079a64af3f26 | 3,602,462 |
def rfcavity(fam_name, length, voltage, frequency, phase_lag=0.0):
"""Create a RF cavity element.
Keyword arguments:
fam_name -- family name
length -- [m]
voltage -- [V]
frequency -- [Hz]
phase_lag -- [rad]
"""
ele = _trackcpp.rfcavity_wrapper(
fam_name, length, frequency, v... | 504cd5d017d75f706c391be05b06cc83a746a56e | 3,602,463 |
def add_api_token_to_response(response, user):
"""Generate API token and add it to the response (both as a `token` key in
the response if it was json and by setting a cookie named API_TOKEN_COOKIE.
"""
token = generate_api_token(user)
if hasattr(response, 'data'):
response.data['token'] = to... | 6f2ced2209246e6c0b3d33b044e28f8e3a98b14b | 3,602,464 |
def coords_from_outcar( filename='OUTCAR' ):
"""Finds and returns Cartesian coordinates from the OUTCAR file.
Args:
filename (:obj:'str', optional): the name of the ``OUTCAR`` file to be read. Default is `OUTCAR`.
Returns:
(np.array): The Cartesian coordinates as found in the ``OUTCA... | 2c98bc2bfa895aeefda30eedaf586b92ec01edc5 | 3,602,465 |
def model_fn(features, labels, mode):
"""The model_fn argument for creating an Estimator."""
model = Model()
image = features['image']
training = mode == tf.estimator.ModeKeys.TRAIN
angle_logits, predicted_throttle = model(image, training=training)
predicted_angle = tf.argmax(input=angle_logits,... | 6453da36ec0af25d3b347ae1ecc27d6e7b9550b1 | 3,602,466 |
def multiPlot(plotArray, title='', xlabel='', ylabel='', xscale='linear', yscale='linear'):
"""
plotArray is of the form: [[X1, Y1], [X2, Y2]]
Where Xi, Yi are arrays of of the values to plot.
"""
plt.clf()
figure = plt
figure.title(title)
figure.xlabel(xlabel)
figure.ylabel(... | bbfd7147f094e6c92a3644128e0788c22ccea9bf | 3,602,467 |
def dUdT_n_dimensional(sto):
"""
Dimensional entropic change of the negative electrode open-circuit potential [V.K-1]
"""
return pybamm.FunctionParameter(
"Negative electrode OCP entropic change [V.K-1]", sto, c_n_max
) | d9a13427e05b221548798231b63e0eb0f74ddb84 | 3,602,468 |
def set_problem_availability(pid, disabled):
"""
Updates a problem's availability.
Args:
pid: the problem's pid
disabled: whether or not the problem should be disabled.
Returns:
The updated problem object.
"""
problem = api.problem.get_problem(pid=pid)
if len(proble... | 139256d3326bda05d93fda082533e79ead3b8c26 | 3,602,469 |
import pickle
def load_pickle(fname):
"""
Load an ephemeris pickle file
Parameters
----------
fname (str) : path and name of the pickle file
Returns
----------
Dictionary of Segments
"""
f = open(fname, 'rb')
data = pickle.load(f)
f.close()
dc = {}... | cb6d82118b4b92340017adb51bf7277772ae40b8 | 3,602,470 |
def get_t1(close, timestamps, num_days):
"""Return horizontal timestamps
Note
----
Not include the case to hit the vertical line at the end of close.index
Parameters
----------
close: pd.Series
timestamps: pd.DatetimeIndex
num_days: int
The number of forward dates for verti... | c619249649401695d48fb00718b898b181513a2b | 3,602,472 |
def compute_difference_metrics(initial_output, final_output, tmp_results):
"""
Given NN output before and after removal, all absolute difference metrics are stored.
:param initial_output: model.forward(x)
:param final_output: model.forward(x_salient_pixels_removed)
:param tmp_results: object to sto... | 90e80ddd9797288ead39331462ab09c7f9689095 | 3,602,473 |
def search_peaks(x_data, y_data, height=0.1, distance=10):
"""
从给定的光谱数据中寻找峰值
Look for peaks in the given spectral data
:param x_data: 光谱数据x数据,Spectral X-axis data
:param y_data:谱数据y数据,Spectral Y-axis data
:param height:峰值高度阈值.Peak height threshold
:param distance:峰之间的最小水平距离,如果距离小于指定值,会从高... | c3fc9b41beafd8c699bfef633441a2c05a80d8e6 | 3,602,474 |
from jinfo.sequence import BaseSeq
import re
from typing import List
def seq_list_from_fasta(file_path: str, seq_obj: ANY_SEQ = BaseSeq) -> List[ANY_SEQ]:
"""
Parse a multifasta file
Returns list of BaseSeq objects
"""
with open(file_path, "r") as text_file:
fasta_str = text_file.read()... | 3ae91e7feb022eea9ee58d9a5b46625845c4f52b | 3,602,476 |
def make_projector_info(info):
"""Make an SSP operator using the measurement info
Calls make_projector on good channels.
Parameters
----------
info : dict
Measurement info
Returns
-------
proj : array of shape [n_channels, n_channels]
The projection operator to apply t... | 246cb1677ff33a85c7a287556c8f79ed1e0ae6c1 | 3,602,478 |
import re
def read_accounts_file(account_file):
""" Process each line in the specified account file looking for account
definitions. An account definition is a line containing the word
'account' followed by a valid account name, e.g:
account Expenses
account Expenses:Utili... | f917958201cd66f6b04bd9307611bb282b25f3f6 | 3,602,479 |
def _FieldOrExtensionValues(message, field_or_extension):
"""Retrieves the list of values for the specified field or extension.
The target field or extension can be optional, required or repeated, but it
must have value(s) set. The assumption is that the target field or extension
is set (e.g. _HasFieldOrExtens... | 1dd483a71825b04bb76df84ec334674833151c40 | 3,602,480 |
def create_encoder(backbone_options: config_pb2.ModelOptions.BackboneOptions,
bn_layer: tf.keras.layers.Layer,
conv_kernel_weight_decay: float = 0.0) -> tf.keras.Model:
"""Creates an encoder.
Args:
backbone_options: A proto config of type
config_pb2.ModelOptions.Back... | bf536761ddf2c37240927718e12c38f2c5f1a65c | 3,602,481 |
def forceresolution( numgridptscuberoot,
lengthcuberoot ) :
"""
returns the force resolution of the PM part in units of
the input boxsize
args:
numgridptscuberoot:
lengthcuberoot :
return :
force resolution (distance) in units usef for the
box size
"""
return lengthcuberoot/numgridptscuberoot | d14760ac863bd1409b9df40fe0ff19ff44b508ca | 3,602,484 |
from typing import Dict
def fixture_color_name(theme: Dict[str, str]) -> str:
"""Return a random color name."""
return choice(list(theme)) | a197406acf8c57e0c7c8bc1d321c2a70d133119a | 3,602,485 |
def find_transformation_full(lines):
"""
Finds alignment transform. Very slow and distortionable
:param lines:
:return:
"""
if len(lines) == 0:
return
bounds = lines[0].chars[0].refined_box
for ln in lines:
for ch in ln.chars:
bounds = [min(bounds[0], ch.refin... | 9abe40d45478a06e566f6d2d048280229d9c233b | 3,602,486 |
import requests
def fetch(url: str):
""" Simply fetch any URL given, and convert from bytes to string """
r = requests.get(
url, headers={
"User-Agent": read_json()["user_agent"],
"Content-Type": "text/html; charset=UTF-8",
}
)
text = r.content.decode("utf-8")
... | 63c85b952a9e9bb703cc9d16cd4d5259713458f6 | 3,602,487 |
def compute_cost(X, y, w):
"""
Calculates mean square error cost.
:param X: design matrix
:type X: np.ndarray(shape=(N, d))
:param y: regression targets
:type y: np.ndarray(shape=(N, 1))
:param w: weights
:type w: np.array(shape=(d,))
:return: cost
:rtype: float
"""
# ... | 3614b58712af327ee919a1a0826057943ebfde05 | 3,602,488 |
def set_up_folder_name_1M ( model_file , date_run ):
"""
Produce log_file, plot_folder based on model_file (file name ending with _sd.pt)
If model_file is epoch_1_sd.pt, date_run is 0913: plot_folder 'plot_2d_epoch_1', log file 'log_0913_2d_epoch_1'
"""
# if model_file == '': model_pure = f'ep{ep_in... | d7dd24789476279ea8d5fe0b32627aa049731ef7 | 3,602,489 |
def kfl_random_monotonic_initializer(shape,
scale,
monotonicities,
init_min=0.5,
init_max=1.5,
dtype=tf.float32,
... | 7230365e40fe763e891bdb79c7d3fe6f582d6371 | 3,602,490 |
def percentage_of_peaks_found(known_peaks, association_matrix, knownhdf5_filename):
"""
This function takes in a list of classified peaks, and returns a percentage of
how many of the material's peaks are found in the unknown spectrum.
This can be used as a metric of confidence.
Parameters:... | cabb18b1dd2375ff042ee43f9c9910fb87a4c432 | 3,602,491 |
def iterencode(data, ensure_ascii=False, **kwargs):
"""
Returns a generator that yields each string representation as available.
"""
if 'indent' not in kwargs:
kwargs['separators'] = (',', ':')
return JSONEncoder(ensure_ascii=ensure_ascii, **kwargs).iterencode(data) | 0f88abef47b79562f64816e768793fc3a69ba4a3 | 3,602,493 |
from typing import List
import glob
def get_all_file_from_directory(directory: str, file_dsc: str) -> List[str]:
""" Get paths of all files matching file_dsc in directory """
template = f"{directory}{file_dsc}"
file_paths = glob.glob(template)
return file_paths | 7a3115793a5a59bc8f6ee655315ea87857338c47 | 3,602,494 |
import configparser
def read_options(config_path):
"""Чтение конфигурационного файла и установка глобальных переменных из cfg.py
:param config_path: путь к конфигурационному файлу
:return: True or False
"""
config = configparser.ConfigParser()
if config.read(config_path, encoding='utf-8'):
... | 328d63bc72c52684b6e824dccae7a2fa17d49569 | 3,602,495 |
def update_slu(client_name: str, model_name: str):
"""
Update SLU config.
"""
json_config_data_provider = JSONAPIConfig(config_dict=request.json)
config = json_config_data_provider.generate()
CLIENT_CONFIGS[model_name] = config
MODEL_PREDICT_APIS[model_name] = convert_config_to_predict_wrap... | fc09fd0bf6f08b3f035098f5b5029377704ab526 | 3,602,496 |
from . import __version__
from datetime import datetime
def appendExportRecord(item, user, metadataProperty, status=None):
"""
Append information about the current export to an item's exported record. Return the most
recent export record.
:param item: the Girder item to add export history to
:par... | b21cbfc80ff29352b4aafb5458a402fbe8ef133f | 3,602,497 |
def naked(val):
""" Given a string strip off all white space & quotes """
return val.strip(' "\'\t') | 1875b38f05fa0c8b540ece0265354293f275b3ea | 3,602,498 |
def get_hex_slug(length=16, case_convertor=None):
"""
gets a slug from a uuid as hex string.
:param int length: length of generated slug.
defaults to `16` if not provided.
the maximum length is `32`.
:param function case_convertor: a callable to be used as... | c39a46d9035508aaf5f444acae776d4962f0740d | 3,602,499 |
def scsplit(*args, stratify, test_size = 0.3, train_size = 0.7, continuous = True, random_state = None):
"""
Create stratfied splits for based on categoric or continuous column.
For categoric target stratification raw sklearn is used, for continuous target
stratification binning of the target variable ... | ac2dabfa2a069d48714ab5d10f4bf3886a87cd33 | 3,602,500 |
def cache_function(length=settings.CACHE_TIMEOUT):
"""
A variant of the snippet posted by Jeff Wheeler at
http://www.djangosnippets.org/snippets/109/
Caches a function, using the function and its arguments as the key, and the return
value as the value saved. It passes all arguments on to the functi... | 52b235dcadf0a8bc63ada71c31fad13b6d6d6664 | 3,602,501 |
def is_prime(num: int) -> bool:
"""Determines whether the given number is prime or not"""
if num == 2:
return True
elif num % 2 == 0:
return False
else:
sq = int(sqrt(num)) + 1
for i in range(3, sq, 2):
if num % i == 0:
return False
return ... | 382dc191d603eff1acbc734d60f68c90198a6279 | 3,602,502 |
def maybe_future(x):
"""Converts ``x`` into a `.Future`.
If ``x`` is already a `.Future`, it is simply returned; otherwise
it is wrapped in a new `.Future`. This is suitable for use as
``result = yield gen.maybe_future(f())`` when you don't know whether
``f()`` returns a `.Future` or not.
"""
... | 1ad320d6aa57005e62987f211977eac2c8481d6c | 3,602,503 |
from typing import Dict
def truvari_precision(
logits: np.ndarray,
one_hot_targets: np.ndarray,
) -> Dict[str, float]:
"""Computes genotype-level precision.
Reference events are not considered.
Args:
logits: float array; Output of model in shape [batch, ..., num_classes].
one_hot_targets: Mult... | ed0c4e9c2be81b0e80c158d8f514e44fb1ad1f4d | 3,602,505 |
import re
def _applyReplacements(cfile, replacements):
""" Applies custom replacements.
@param str cfile
@param list replacements - list of dicts with keys "match", "replacement", and (optional) "is_regex"
"""
for rep in replacements:
if not rep.get('with_extension', False):
... | 82797c5388f1aaf3d5983e2e938ef4f075ccaf97 | 3,602,506 |
def face_by_point3d(point3d_data):
"""Find a face with given serialized point3d that sits on that face"""
point_on_face = point3d(point3d_data)
app = adsk.core.Application.get()
design = adsk.fusion.Design.cast(app.activeProduct)
for component in design.allComponents:
try:
entiti... | 8d571bbb932151a70d744f11860c371950e01736 | 3,602,507 |
def fwhm(*columns):
"""Calculate an estimate of full width at half maximum.
The search starts a the 'left' end of the data.
Returns a tuple ``(fwhm, xpeak, ymax, ymin)``:
* fwhm - full width half maximum
* xpeak - x value at y = ymax
* ymax - maximum y-value
* ymin - minimum y-value
"... | 53dbabb74e0d85f445d2d80456ba82c4637f00a3 | 3,602,508 |
def diff_argsort(matrices, x, sigma=0.1, softmax=softmax, transpose=False):
"""Return the smoothed, differentiable ranking of each element of x. Sigma
specifies the smoothing of the ranking. Note that this function is deceptively named,
and in the default setting returns the *ranking*, not the argsort.
... | 91a80bcda3d964379d3efd0034a80c86ba6de911 | 3,602,509 |
from datetime import datetime
def roundTime(dt, roundTo=5 * 60):
"""Round a datetime object to any time laps in seconds
dt : datetime.datetime object, default now.
roundTo : Closest number of seconds to round to, default 5 minutes.
"""
seconds = (dt - dt.min).seconds
# '//' is a floor division... | 4d965988864118efa07e993797f188b5fcdf9986 | 3,602,512 |
def create_psf_3d(
psf,
true_energy_bins,
source_offset_bins,
fov_offset_bins,
):
"""
Create a ``gammapy.irf.PSF3D`` from pyirf outputs.
Parameters
----------
psf: astropy.units.Quantity[(solid angle)^-1]
Point spread function array, must have shape
(n_energy_bins, n... | 67f3142b4fbf62535fdfc94b83691485ca1c352c | 3,602,513 |
def meta_nonempty_object(x):
"""Create a nonempty pandas object from the given metadata.
Returns a pandas DataFrame, Series, or Index that contains two rows
of fake data.
"""
if is_scalar(x):
return _nonempty_scalar(x)
else:
raise TypeError(
"Expected Pandas-like Ind... | a9d6c6581dad4a3e87b9928796769dd6baf8113c | 3,602,514 |
import pathlib
def get_project_root() -> pathlib.Path:
"""Returns project root folder."""
return pathlib.Path(__file__).parent | 0870689f7933b4e4d765b7ea66f0e457f3bee542 | 3,602,515 |
def pourier_tarantola(V, E0, B0, B1, V0):
"""Pourier-Tarantola equation from PRB 70, 224107"""
eta = (V/V0)**(1./3.)
squiggle = -3.*np.log(eta)
E = E0 + B0*V0*squiggle**2/6.*(3. + squiggle*(B1 - 2))
return E | 7462748a674450ebe689406c173b28a3b88a6676 | 3,602,517 |
def polarization_decomp(bx,by, flipz=False):
"""
INPUTS
bx, by (Float arrays)
Transverse field components
flipz (Boolean)
If False, wave is assumed to be propagating along the z direction defined
by the given x and y directions and the right-hand rule. If True, the wave
is assumed t... | 46f128b245b2e69d6898626185f711f27f1e0f64 | 3,602,518 |
import json
def meeting_log_version_from_file(file_object):
"""
returns version number for a given file object (or None, if version cannot be identified)
:param file_object:
:return:
"""
last_pos = file_object.tell() # keep current position
first_line = file_object.readline()
... | 821c310a7e50f679ef2d27f3ea4e56b4b5b4e54d | 3,602,520 |
def write_tx(sql: str, data: any):
""" 写事务 """
connection = connection_pool.connection()
cursor = connection.cursor()
result = cursor.execute(sql, data)
try:
connection.commit()
except RuntimeError as error:
connection.rollback()
log.error('事务提交失败!已回滚')
raise err... | cb157d7993d78336c52654c241d16117c7cc5d2c | 3,602,521 |
def recall_board(state, boards_played, p1=1, p2=2):
"""Determine if board (or equvialent) has been seen before."""
# Check if the board (or eqivalent) has been seen before.
for trans_number in range(8):
trans_state = board_transform(state, trans_number)
key = nd3_to_tuple(trans_state)
... | 35f3cd31d22a15a814d8b746635fa54bb32e3bb4 | 3,602,522 |
def cd_task(mode, window, mouse, slots, slot_size, targets, prechange, fillers, items_per_array, trials, prechange_dur, ISI):
"""
Present the 6AFC memory task or a change detection task.
:param mode: A string indicating what kind of trial to run. All modes but "unstudied" use a familiar object in
... | 1edfd46ead1e81c35ba3d8f96b01ded7a30c9af3 | 3,602,523 |
def handler(store, default=True, internal=False, passive=False):
""" Decorator for setting up a handler.
This puts the handler into the handler store which can then be used
to look up all handlers and information about them such as which are default,
passive, etc.
Currently there are two handler s... | cf7c4c8847539be57c5680d87f80414bb6ab0164 | 3,602,524 |
from typing import IO
def give_cmd(file: IO[str], force: str, interactionId: int = 0, where: Range = None, expr: str = ''):
"""Fill a goal.
"""
return ('give', {'file': file, 'interactionId': interactionId, 'where': where}) | 53eab593f2983b012f7859325e58101d896547ba | 3,602,526 |
from typing import List
from datetime import datetime
def get_current_time_info(
epm: Epm, sec_elapsed: float) -> List[int]:
"""Returns the current day, month and hour given the seconds elapsed since the simulation started.
Args:
epm (opyplus.Epm): EnergyPlus model object.
sec_elapsed... | f1cc87fa0f68ca50bceaa5c132c7f56c92d41468 | 3,602,527 |
def isTreeKey(key):
"""
Return True if the object, corresponding to the key, inherits from TTree
"""
classname = key.GetClassName()
cl = ROOT.gROOT.GetClass(classname)
return cl.InheritsFrom(ROOT.TTree.Class()) | 3f44e341f11fdd3be184300805f0fa60f54adcff | 3,602,529 |
def virtual_interface_get_by_uuid(context, vif_uuid):
"""Gets a virtual interface from the table.
:param vif_uuid: the uuid of the interface you're looking to get
"""
vif_ref = _virtual_interface_query(context).\
filter_by(uuid=vif_uuid).\
first()
return ... | f1042df9dd21ff362eafda4c06245f11504aafce | 3,602,530 |
def human_readable_filesize(size):
"""Convert file size in bytes to human readable format
Args:
size (int): Size in bytes
Returns:
str: Human readable file-size, i.e. 567.4 KB (580984 bytes)
"""
if size < 1024:
return "{} bytes".format(size)
remain = float(size)
fo... | c8eefdf9145bfb5c937b740fec9e6b437704aa5b | 3,602,531 |
def interchanging_key_and_value(x):
"""creating a function for interchanging key and value"""
return(x[1],x[0]) | 6478d48d698bb741ff2a24634b5b833ef624f79f | 3,602,532 |
def random_d14_psd(request):
"""
Create a random instance of the D14 PSD.
"""
boundaries = {"intercept_parameter" : (6, 12),
"mass_weighted_diameter" : (-2, -4),
"mass_density" : (-12, -2)}
cls = request.param
psd = cls(1.0, 1.0, 917.0)
low, high = boun... | e455a7bdf5277070205e6e173147d47c3fedfdfb | 3,602,533 |
def _encrypt(key,block,n=32,endian="!"):
"""Encrypt one single block of data.
Only use if you know what to do.
Keyword arguments:
key -- the key for encrypting (and decrypting)
block -- one block plaintext
n -- cycles, one cycle is two rounds, more cycles
-> more security and slowne... | 46694170a6a4aeabad16516480958a4b1632141e | 3,602,534 |
def read_system(path, ignore_resnames=(), ignh=None, modelidx=None):
"""
Read a system from a PDB or GRO file.
This function guesses the file type based on the file extension.
The resulting system does not have a force field and may not have edges.
"""
system = System()
file_extension = pa... | 31c5ba7256d69a92b4f0109e2b0878cf9fc43e32 | 3,602,535 |
import math
def unifDiag(matrix, tol = 1e-4):
"""
Parameters:
-matrix: square and symmetric matrix (should be checker outside)
-tol: tolerance parameter to be equal to a certain value
This function makes uniform the diagonal of the symmetric square matrix
in parameter.
It returns... | f3a1f8c76d997493617a0b5dc341a7ae01015f96 | 3,602,536 |
def main(input, output):
"""
input : str - such as open("Example.class", "r").read()
output : file - such as stdout or anything with a method write(str)
"""
# this is a bound variable :|
index = [0]
def str2hex(string):
return "".join(hex(ord(c))[2:].zfill(2) + " " for c i... | 773ccfb419347a6e4f3306d61ba7ab3808c4732b | 3,602,537 |
def position_by_contract_id(account_id: str, contract_id: str) -> dict:
"""Returns a list of all positions matching the conid. For portfolio models the
conid could be in more than one model, returning an array with the name of
model it belongs to.
/portfolio/accounts or /portfolio/subaccounts
must ... | efecb102888d38fae862693f4a972c85c6dba8b9 | 3,602,539 |
import re
def tokenize(s):
"""
tokenize
"""
#数字替换为<num>
s = re.sub('\d+', '<num>', s).lower()
tokens = s.split(' ')
return tokens | 0f76b68c75c474a4f4ee692ae1124127b93ebf6e | 3,602,540 |
def category(id):
"""
"""
category = Category.query.get(id)
pitch = Pitch.get_pitch(id)
form = PitchForm()
title = 'pitches'
return render_template('category.html', category = category, pitch = pitch, title = title, pitch_form = form) | ca50cdc22e993f077d0ffc03db14dad204407caa | 3,602,541 |
def uuid(value):
"""Return true if UUID is valid, otherwise - false."""
return const.UUID_RE.match(value) is not None | 61aa3f12b289c79ec8e7d64e1f2b694c3f4e6480 | 3,602,542 |
import dateutil
def convert_datetime(string):
"""Converts a string into a date object"""
the_date = dateutil.parser.parse(string).replace(tzinfo=utc)
return the_date | aeca0be4a53c6950735cd77875021729ace259dc | 3,602,543 |
import glob
def loadImages(dataPath):
"""
load all Images in the folder and transfer a list of tuples. The first
element is the numpy array of shape (m, n) representing the image.
The second element is its classification (1 or 0)
Parameters:
dataPath: The folder path.
Returns:
... | 978c6fdaa42ec98402cc81dd03fc2d378b421fd3 | 3,602,546 |
import re
def tokenize(text):
"""
Funnction tokenize the input text.
Input--> text: text to be tokenized, as string
Output--> lemmatized: List of words of cleaned text, as list
"""
stop_words = stopwords.words("english")
lemmatizer = WordNetLemmatizer()
# Norma... | 57cd766ce65224793ac573658ec360635fb8297c | 3,602,547 |
import time
def is_auth_token_valid(token: Secret, jitter: int = 0) -> bool:
"""Returns if the token is still valid (within some jitter window)"""
if token.token_life == -1:
return True
now = int(time.time())
latest_token_life = token.token_created + token.token_life - jitter
return latest... | 53f769b9ba91450ef342cc5ec7e3cab419facaf8 | 3,602,551 |
def make_generic_function_spec(abi_array):
"""
Generates ETHFunctionSpec for each function found in ABI.
:param abi_array: contract Ethereum ABI
:return: list of ETHFunctionSpec
"""
def obj_type(obj_name):
for type_ in ['actions', 'tables']:
for curr_obj in abi_array[type_]:... | 5633d7faf081fea5b3fa2d49e026fa1dff00f89f | 3,602,552 |
import unittest
def createUnitTest(pkg, test_file):
"""
Unit test factory. Constructs a unittest class based on the roslaunch
@param pkg: package name
@type pkg: str
@param test_file: rostest filename
@type test_file: str
"""
# parse the config to find the test files
config = ro... | 55aaa38b878c0fa3f9a44728be99079a6354569f | 3,602,553 |
def is_initialized():
"""
Checking if bagua global communication state has been initialized
"""
global _global_state
return _global_state is not None | 8a5ecfbefdde903dc52e7c3aab9343d16bcb678c | 3,602,554 |
from typing import Generator
def to_list(x, repeat=1):
"""convert x to list object
Args:
x: any object to convert
repeat: if x is to make as [x], repeat `repeat` elements in the list
"""
if isinstance(x, (Generator, tuple, set)):
return list(x)
elif isinstance(x, list):
return x
e... | 79841d76cd0eba5a2e92fc0992516f59113c3f9b | 3,602,555 |
def normalize_path(path, omit_empty=True, case_sensitive=True, case_normalization="lower", sep=None, force=False):
"""
Split and normalize generic path into individual path entries.
Args:
path: Generic path. Lists and tuples (possible nested) are flattened;
strings are split accordi... | 9eaf10de3a9b374ce8f87eceafe8a88750a81a80 | 3,602,557 |
def try_key(dict_to_try, key_for_dict):
"""Either returns key value or empty string."""
if key_for_dict not in dict_to_try:
return ''
return dict_to_try[key_for_dict] | a7486bd4933301278941fb7ee2001890221fcbd9 | 3,602,558 |
from typing import Union
def parse_statement(
source: str, config: PartialParserConfig = _DEFAULT_PARTIAL_PARSER_CONFIG
) -> Union[SimpleStatementLine, BaseCompoundStatement]:
"""
Accepts a statement followed by a trailing newline. If a trailing newline is not
provided, one will be added. :func:`parse... | 6030b6c19120539735dcc17449240ccf890dc4d1 | 3,602,559 |
import json
def iblinds_v2_state_fixture():
"""Load the iBlinds v2 node state fixture data."""
return json.loads(load_fixture("zwave_js/cover_iblinds_v2_state.json")) | beed8a829e26252257beafe25c7a9cab0e21725c | 3,602,561 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.