content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def allCategoriesJSON():
"""
Generates JSON for all categories
"""
categories = db_session.query(Category).all()
return jsonify(categories=[c.serialize for c in categories]) | cd07bdff7d7d69be152fc2ebb3f248ad77eaacd4 | 2,901 |
def get_rrule(rule, since, until):
"""
Compute an RRULE for the execution scheduler.
:param rule: A dictionary representing a scheduling rule.
Rules are of the following possible formats (e.g.):
{'recurrence': '2 weeks', 'count': 5, 'weekdays': ['SU', 'MO', 'TH']}
= run every 2 weeks... | e4e6548f23a832b7bd5e23174b08b9134821134f | 2,902 |
def site_id(request):
"""Site id of the site to test."""
return request.param if hasattr(request, 'param') else None | 98f6e5af07f7c2b70397cbd1ee54fc2df66e7809 | 2,903 |
def parse(limit_string):
"""
parses a single rate limit in string notation
(e.g. '1/second' or '1 per second'
:param string limit_string: rate limit string using :ref:`ratelimit-string`
:raise ValueError: if the string notation is invalid.
:return: an instance of :class:`RateLimitItem`
"""... | 2d5a3c618bd70693c1e296b77185387b302cffe0 | 2,904 |
def change_balance(email):
"""Change a user's balance."""
if not isinstance(request.json.get('change'), int):
abort(400, {'message': 'The change in innopoints must be specified as an integer.'})
user = Account.query.get_or_404(email)
if request.json['change'] != 0:
new_transaction = Tra... | 4500a192a51eaa548a6d2ca7807c66ac0042b75c | 2,905 |
def contact_infectivity_asymptomatic_40x70():
"""
Real Name: b'contact infectivity asymptomatic 40x70'
Original Eqn: b'contacts per person normal 40x70*infectivity per contact'
Units: b'1/Day'
Limits: (None, None)
Type: component
b''
"""
return contacts_per_person_normal_40x70() * i... | 8b0ffa0b2d3b54d6802881d14524cd8a10d5329a | 2,906 |
def generate_resource_link(pid, resource_path, static=False, title=None):
"""
Returns a valid html link to a public resource within an autogenerated instance.
Args:
pid: the problem id
resource_path: the resource path
static: boolean whether or not it is a static resource
ti... | c2523e254d93ecc36198ffea6f2f54c48dfe529d | 2,907 |
def make_cointegrated(seed, n_samples, gamma):
"""
cointegrated pair:
- x0_t = x0_t-1 + gauss[:, 0]
- x1_t = gamma * x0_t + gauss[:, 1]
for various gamma.
cf: Hamilton [19.11.1, 19.11.2]
"""
np.random.seed(seed)
x0 = np.random.randn(n_samples).cumsum()
x1 = gamma * x0 + ... | 8b7ee2b414a19a9e2dc73ab5cdb98f44c3d75ddf | 2,908 |
import random
def web_index():
"""主页"""
news = db.session.query(HotHomeNews).to_dicts
home = list()
hot = list()
temp = 30
for index, i in enumerate(news):
temp -= random.randint(0, 2)
i['date'] = '2021-04' + '-' + str(temp)
if i['hot'] == 1:
hot.append(i)
... | 24a39493a8b864fa7789a455fa292e13a665ba3f | 2,909 |
def test_parametrize():
"""Tests parametrizing a function"""
@arg.parametrize(val=arg.val('vals'))
def double(val):
return val * 2
assert double(vals=[1, 2, 3]) == [2, 4, 6]
# This should result in a lazy bind error
with pytest.raises(arg.BindError):
double(val=1)
# Parti... | 82202cb99f48f47ac21c4350008b3bf54f43666a | 2,910 |
def F_to_C(Tf):
"""convertit une temperature de Fahrenheit en Celsius"""
Tc = (Tf-32)*5/9
return Tc | 9264ac7b0d03bc5d44e716656bafac8a1f112978 | 2,911 |
def generate_mdn_sample_from_ouput(output, test_size,distribution = 'Normal',
params = None):
"""
Using the output layer from the prediction on a fitted mdn model
generate test_size number of samples. (Note output corresponds to a
one-dimensional output).
Paramete... | 6851b03b1877e0d0fdc24edca98f386db29a8733 | 2,912 |
def infer_folding_rates(clusters, activation_energies, prefactors, G, temperatures):
"""
Takes Arrenius parameters and uses detailed balance to compute folding rates
"""
print('Inferring unknown folding rates from detailed balance...')
Nclusters = len(clusters)
folding_rates=np.nan*np.zeros((Nc... | 0c986bdb7c05f8aef973598dd01913fc35f1cd75 | 2,913 |
def create_cry_nqubit(qc: qiskit.QuantumCircuit, thetas: np.ndarray):
"""Create control Control-RY state
Args:
- qc (qiskit.QuantumCircuit): init circuit
- thetas (np.ndarray): parameters
Returns:
- qiskit.QuantumCircuit
"""
for i in range(0, qc.num_qubits - 1, 2):
... | 9238d6a6d4e3ed7c66f065ed502cc3236c71abd7 | 2,914 |
def get_region(h5_dset, reg_ref_name):
"""
Gets the region in a dataset specified by a region reference
Parameters
----------
h5_dset : h5py.Dataset
Dataset containing the region reference
reg_ref_name : str / unicode
Name of the region reference
Returns
-------
val... | 189fab43233d58f734e6ed616aa0d198c16bc21e | 2,915 |
def butter_bandpass_filter(data, lowcut, highcut, sample_rate, order):
"""
Bandpass filter the data using Butterworth IIR filters.
Two digital Butterworth IIR filters with the specified order are created, one highpass filter for the lower critical
frequency and one lowpass filter for the higher critica... | 52f9a400e3027223a8370c966cf88e74e878ebf3 | 2,917 |
import torch
def _check_tensor_info(*tensors, size, dtype, device):
"""Check if sizes, dtypes, and devices of input tensors all match prescribed values."""
tensors = list(filter(torch.is_tensor, tensors))
if dtype is None and len(tensors) == 0:
dtype = torch.get_default_dtype()
if device is N... | 1a00aa0e09e520a23591d9fd461422f7b0acf0e2 | 2,918 |
def generate_dataset(df, n_past, n_future):
"""
df : Dataframe
n_past: Number of past observations
n_future: Number of future observations
Returns:
X: Past steps
Y: Future steps (Sequence target)
Z: Sequence category"""
# Split the dataframe with respect to IDs
series_ids =... | f11e769499576223f778b669ccff8d973f4a8039 | 2,919 |
from typing import Optional
from typing import Tuple
from typing import Literal
from typing import Union
def upsampling2D(
inputs: Optional[tf.Tensor] = None,
size: Tuple[int, int] = (2, 2),
mode: Literal['pad', 'nearest', 'bilinear'] = 'nearest',
name: Optional[str] = None,
) -> Union[tf.Tensor, Resa... | 5f2a7f642442abcbf1075d8296fa026e2e639744 | 2,921 |
def moderator_name():
"""Return the name of the test game moderator."""
return 'Hannah' | 55132bc74510ee9c3c2a74048bf35bae94b9a6ef | 2,923 |
def reversebits2(max_bits, num):
""" Like reversebits1, plus small optimization regarding bit index
calculation. """
rev_num = 0
high_shift = max_bits - 1
low_shift = 0
for _ in range(0, (max_bits + 1) // 2):
low_bit = (num & (1 << low_shift)) >> low_shift
high_bit = (num &... | cbc41754928f758d689ea6b0241205a9a1c02ccd | 2,925 |
from typing import Tuple
from typing import Type
from typing import Dict
import typing
def _get_builder_cls(
ds_to_build: str,
) -> Tuple[Type[tfds.core.DatasetBuilder], Dict[str, str]]:
"""Infer the builder class to build.
Args:
ds_to_build: Dataset argument.
Returns:
builder_cls: The dataset cla... | 4f655c7df8d205683d295987c719eb7d4909df83 | 2,926 |
def keypoints_to_bbox(keypoints_list, image):
"""Prepare bboxes from keypoints for object tracking.
args:
keypoints_list (np.ndarray): trtpose keypoints list
return:
bboxes (np.ndarray): bbox of (xmin, ymin, width, height)
"""
bboxes = []
img_h, img_w = image.shape[:2]
for ... | b144fecaf4c2996a945240c62a93e2a3e6dafd04 | 2,927 |
def view():
""" WIP: View admins. """
if current_user.is_admin():
admins = UserMetadata.select().where(UserMetadata.key == 'admin')
postcount = SubPost.select(SubPost.uid, fn.Count(SubPost.pid).alias('post_count')).group_by(SubPost.uid).alias(
'post_count')
commcount = SubPo... | cd2e265b83cdf0028c6b0798b87e7bd26cd799f5 | 2,928 |
def get_market_offers(session, ids, base_market_url=BASE_MARKET_URL):
"""\nMain function for interaction with this library.
\nProvided a sequence of Character Ids, returns a dictionary of offers for each. \
Requires a session which has already authenticated with Urban Rivals.
\nOptional: provide a base ... | a526a6f79d95f8ebc5228ebac7367c5e846cfcfc | 2,929 |
def band_listing(request):
"""A view of all bands."""
bands = Band.objects.all()
return render(request, 'bands/band_listing.html', {'bands': bands}) | 11f9305784f812b481dcbb908086feedd87dd618 | 2,930 |
from typing import Optional
def check_mismatched_bracket_type(path: str) -> Optional[BracketErrorType]:
"""
Check for miss matched brackets
:param path: path to file
:return: Type of miss match or None if there is none
"""
file_as_string = utils.read_file(path)
brackets_count = utils.count... | edd10b89865f9c17cc915875bb7ab557cc85d5b7 | 2,931 |
from typing import Union
from typing import Tuple
import requests
import re
def get_rank(
day: int = day_idx,
year: int = year
) -> Union[None, Tuple[str]]:
"""
Returns the rank for the current day.
Arguments
---------
day -- The day to get the rank for.
year -- The year ... | c9d50857a0eb5574b971c8cf7a4e5458eb1320fc | 2,932 |
def get_taste(dm):
"""
Get the classification of a matrix defining a tangent vector field of the
form:
| R | t |
| - - - |
| 0 | 0 |
:param dm: input tangent matrix
:return: number from 1 to 6 corresponding to taste. see randomgen_linear_by_taste.
"""
rot... | 38b986478564b118d97126b451af514b14c0e155 | 2,933 |
from typing import Tuple
def _check_removal_required(submission: Submission, cfg: Config) -> Tuple[bool, bool]:
"""
Check whether the submission has to be removed and whether this is reported.
Note that this function returns a Tuple of booleans, where the first
is to signify whether the submission is... | a00ae21d233add5fd36b0343a3ef45bd0a11632b | 2,935 |
def subjects(request, unique_id,form=None):
"""
Enlists all the subjects of a classroom ,
subjects can be added by admins
"""
classroom = get_object_or_404(Classroom,unique_id=unique_id)
#querysets
members = classroom.members.all()
subjects = Subject.objects.filter(classroom=classroom)
... | 322dd5e4c31225e66db9dcaa3cb7c6ad337ba963 | 2,936 |
from typing import Dict
def retrieve_settings(skill_id: str) -> JSONStructure:
"""Retrieves skill's settings by leveraging the mycroft-api skill
Send `skillmanager.list` message and wait for `mycroft.skills.list`
message to appear on the bus.
:param skill_id: Skill ID to retrieve the settings
:t... | 5b6ec4b5d52563ab05005967ee21a6acfdaed9c3 | 2,937 |
def make_project(alias='project', root=None, **kwargs):
"""Initialize a project for testing purposes
The initialized project has a few operations and a few jobs that are in
various points in the workflow defined by the project.
"""
init(alias=alias, root=root, template='testing')
project = sig... | 0e0e5eb9a4ceaf780fee0072811bd161bb362af8 | 2,938 |
def _get_sensors_data(driver_info):
"""Get sensors data.
:param driver_info: node's driver info
:raises: FailedToGetSensorData when getting the sensor data fails.
:returns: returns a dict of sensor data group by sensor type.
"""
try:
ipmicmd = ipmi_command.Command(bmc=driver_info['addre... | 7268d7a700dc4aede1e7cddc0be978168d4f0b79 | 2,939 |
def dominates(lhs, rhs):
"""Weak strict domination relation: lhs =] rhs and lhs [!= rhs."""
lhs_rhs = try_decide_less(lhs, rhs)
rhs_lhs = try_decide_less(rhs, lhs)
return rhs_lhs is True and lhs_rhs is False | 80cc4af907b393b0e07d34de3549524ec33ed8ba | 2,940 |
def complex_to_xy(complex_point):
"""turns complex point (x+yj) into cartesian point [x,y]"""
xy_point = [complex_point.real, complex_point.imag]
return xy_point | 2984b70c3015cb69a0f7dfd62bd022bb26310852 | 2,941 |
def setup_mock_accessory(controller):
"""Add a bridge accessory to a test controller."""
bridge = Accessories()
accessory = Accessory.create_with_info(
name="Koogeek-LS1-20833F",
manufacturer="Koogeek",
model="LS1",
serial_number="12345",
firmware_revision="1.1",
... | 5be787d14b17b4bdd79c4550131aa4ca48362056 | 2,942 |
def match_array_placeholder(loc, term, element):
"""Determine if the JSPEC array placeholder matches the JSON element.
Args:
loc (str): The current location in the JSON
term (JSPECArrayPlaceholder): The JSPEC array placeholder.
element (obj): The Python native object representing a JSON... | 1f00c51ba4e6b7de5d6675ed12a97b4b63b98781 | 2,943 |
def get_mask_index(timeDict, mask='Spine', use_B=False, noise_th=None):
"""
:param timeDict: timeDict to use
:param mask: options are 'Spine' and 'Dendrite'
:param use_B: Make masksB etc.
:param noise_th: if None will return all mask index if float will return mean noise < then threshold
:retur... | 2a7c2c7546091a549ff0a48035889432c96a7554 | 2,944 |
def coverageSection(*coverItems):
"""Combine multiple coverage items into a single decorator.
Args:
*coverItems ((multiple) :class:`CoverItem`): coverage primitives to be
combined.
Example:
>>> my_coverage = coverage.coverageSection(
... coverage.CoverPoint("x", ...),
... | f0430c64d8e3c09e8b2ea2c12c43cb1c61ce5cce | 2,945 |
from typing import List
from typing import Type
def get_operator_metatypes() -> List[Type[OperatorMetatype]]:
"""
Returns a list of the operator metatypes.
:return: List of operator metatypes .
"""
return list(PT_OPERATOR_METATYPES.registry_dict.values()) | 880bdef8e7b015af99eb75f48b46189918e823d1 | 2,946 |
def fnl_fix_first_line(preprocessor: Preprocessor, string: str) -> str:
"""final action to ensures file starts with a non-empty
non-whitespace line (if it is not empty)"""
while string != "":
pos = string.find("\n")
if pos == -1:
if string.isspace():
return preprocessor.replace_string(0, len(string), stri... | 40526f43538e99adc3ea42e6cab00284193fb927 | 2,947 |
def rf_rasterize(geometry_col, bounds_col, value_col, num_cols_col, num_rows_col):
"""Create a tile where cells in the grid defined by cols, rows, and bounds are filled with the given value."""
jfcn = RFContext.active().lookup('rf_rasterize')
return Column(jfcn(_to_java_column(geometry_col), _to_java_column... | 0281830fed2c556656e84270f2cf8289d779ade1 | 2,948 |
from typing import Tuple
def balance_generic(array: np.ndarray, classes: np.ndarray, balancing_max: int, output: int, random_state:int=42)->Tuple:
"""Balance given arrays using given max and expected output class.
arrays: np.ndarray, array to balance
classes: np.ndarray, output classes
bal... | 7912f5d5aa98ccab58e8ae0605d4af929e9501ee | 2,949 |
def jsexternal(args, result, **kwds):
"""Decorator to define stubbed-out external javascript functions.
This decorator can be applied to a python function to register it as
the stubbed-out implementation of an external javascript function.
The llinterpreter will run the python code, the compiled interp... | b9bb7fd801fb600fd1b81c0b7392c1c67401f4fc | 2,950 |
def get_icon(filename):
""" """
icon = get_image_path(filename)
if icon:
return QIcon(icon)
else:
return QIcon() | 0db1c20776939d0a57c00a45987b607bb5df7f4b | 2,951 |
from typing import Union
def permission_confirm(perm_key_pair: list) -> Union[bool, str, None]:
"""Converts string versions of bool inputs to raw bool values."""
if perm_key_pair[1].strip() == 'true': pi = True
elif perm_key_pair[1].strip() == 'false': pi = False
elif perm_key_pair[1].strip() == 'none... | c1827694019dd999f71d54be148dfe2abf5aeb4e | 2,952 |
def _parse_policy_controller(configmanagement, msg):
"""Load PolicyController with the parsed config-management.yaml.
Args:
configmanagement: dict, The data loaded from the config-management.yaml
given by user.
msg: The Hub messages package.
Returns:
policy_controller: The Policy Controller co... | ceeedffe2dc1f484b32cd11c6e983c733687f349 | 2,953 |
from typing import Any
import json
def _type_cast(type_cast: Any, content_to_typecast: bytes, func_dict: dict) -> Any:
"""
Basis for type casting on the server
If testing, replace `func_dict` with a dummy one
Currently NOT guarenteed to return, please remember to change this API
"""
if type_ca... | de7121ea1f29448bcd7ab44d60d6a64bbdba59d0 | 2,954 |
from pathlib import Path
import appdirs
def get_data_dir() -> Path:
"""
Get the pda data dir
"""
app_name = "pda"
app_author = "StarrFox"
cache_dir = Path(appdirs.user_data_dir(app_name, app_author))
cache_dir.mkdir(parents=True, exist_ok=True)
return cache_dir | 183aff585c0208bb5e7c2a4bfd5810c378a948e2 | 2,956 |
def is_gradle_build_python_test(file_name):
"""
Return True if file_name matches a regexp for on of the python test run during gradle build. False otherwise.
:param file_name: file to test
"""
return file_name in ["gen_all.py", "test_gbm_prostate.py", "test_rest_api.py"] | 27b683a9062e09aec89be23f5f8e9dd41e9b870d | 2,958 |
def ppis_as_cxs(ppis, cxs):
"""
Use the complex number to both prefix the protein id and add as an
attribute. Copy the original ids to the end for mapping in cytoscape.
"""
ppis = ppis_label_cxs(ppis, cxs)
# Requires that the last column be a list of complex ids. Replace that.
def pfx(id, cx... | e245e0b4bba1a2c59242f1de2c0205fed5331a67 | 2,959 |
import requests
def patch_get(monkeypatch, mockresponse):
"""monkeypatch the requests.get function to return response dict for API calls. succesful API responses come from Tradier website.
:param mockresponse: [description]
:type mockresponse: [type]
:return: [description]
:rtype: [type]
:yie... | 54c927b421fe0e26023b4020a0fadc489e134429 | 2,960 |
def get_context() -> RequestContext:
""" See GlobalContextManager.get_context()
"""
return global_context_manager.get_context() | 4427202db724e62a45e5701a0376498e5ea39954 | 2,962 |
def sched_yield(space):
""" Voluntarily relinquish the CPU"""
while True:
try:
res = rposix.sched_yield()
except OSError as e:
wrap_oserror(space, e, eintr_retry=True)
else:
return space.newint(res) | 310efda027b47c41cd0a9e33357824de148219a0 | 2,963 |
def preformatted(s):
"""Return preformatted text."""
return _tag(s, "pre") | 29385a10c72fe38628077c81760e251dd2f25e72 | 2,964 |
def jitter_colors(rgb, d_brightness=0, d_contrast=0, d_saturation=0):
"""
Color jittering by randomizing brightness, contrast and saturation, in random order
Args:
rgb: Image in RGB format
Numpy array of shape (h, w, 3)
d_brightness, d_contrast, d_saturation: Alpha for blending ... | 7e447bf7670ba234856a42dfb81f8664bb2d4fa2 | 2,965 |
def split_numpy_array(array, portion=None, size=None, shuffle=True):
"""
Split numpy array into two halves, by portion or by size.
Args:
array (np.ndarray): A numpy array to be splitted.
portion (float): Portion of the second half.
Ignored if `size` is specified.
size (i... | cf956ed9dd4855a3785280bd92d9552cd19145ea | 2,966 |
from typing import Sequence
from typing import Optional
from typing import Any
def constraint_layer(
stencils: Sequence[np.ndarray],
method: Method,
derivative_orders: Sequence[int],
constrained_accuracy_order: int = 1,
initial_accuracy_order: Optional[int] = 1,
grid_step: float = None,
dt... | 6194edb56db15c1a8a46d5c7947fe7784966666c | 2,967 |
def parse_excel_xml(xml_file=None, xml_string=None):
"""Return a list of the tables (2D arrays) in the Excel XML.
Provide either the path to an XML file, or a string of XML content.
"""
handler = ExcelHandler()
if xml_file is not None:
parse(xml_file, handler)
elif xml_string is not Non... | 8fef6b38576281421e51da1d7bc47750b62e6316 | 2,968 |
def load_stt_plugin(module_name):
"""Wrapper function for loading stt plugin.
Arguments:
module_name (str): Mycroft stt module name from config
Returns:
class: STT plugin class
"""
return load_plugin(module_name, PluginTypes.STT) | e321d65af7ba2c04dbd3be79321ced26a0622cc6 | 2,969 |
def predict_label(model, data, as_prob=False):
"""Predicts the data target
Assumption: Positive class label is at position 1
Parameters
----------
name : Tensorflow or PyTorch Model
Model object retrieved by :func:`load_model`
data : DataCatalog
Dataset used for predictions
... | 440aa695a281aeac83afbfe96cf0925fdf24faf1 | 2,970 |
def show_subpath(subpath):
"""
使用转换器,为变量指定规则为 path类型(类似 string ,但可以包含斜杠)
"""
# show the subpath after /path/
return 'Subpath %s' % escape(subpath) | a8f924d77f6c6b3b759897f4b22ee8b14aafd7d7 | 2,971 |
def backward_propagation(parameters, cache, X, Y):
"""
Implement the backward propagation using the instructions above.
Arguments:
parameters -- python dictionary containing our parameters
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
X -- input data of shape (2, number of example... | 567f6a087854e19e3049b53773a272c7c13409f2 | 2,972 |
def MakeCdfFromHist(hist, name=''):
"""Makes a CDF from a Hist object.
Args:
hist: Pmf.Hist object
name: string name for the data.
Returns:
Cdf object
"""
return MakeCdfFromItems(hist.Items(), name) | 52fd379383b3099b9764fe6e3590b5909ba04edc | 2,973 |
def box_iou(boxes, clusters):
"""
Introduction
------------
计算每个box和聚类中心的距离值
Parameters
----------
boxes: 所有的box数据
clusters: 聚类中心
"""
box_num = boxes.shape[0]
cluster_num = clusters.shape[0]
box_area = boxes[:, 0] * boxes[:, 1]
#每个box的面积重复9次,对应9个聚类中心
b... | bffdab02c3746be5a7ade1b86bf39d03bce4c3c5 | 2,974 |
def addr(arr):
""" Get address of numpy array's data """
return arr.__array_interface__['data'][0] | 910c893dc47e3f864e915cdf114c3ed127f3ea43 | 2,975 |
def rank_five_cards(cards):
"""Returns an (array) value that represents a strength for a hand.
These can easily be compared against each other."""
# List of all card values
values = sorted([card.number for card in cards])
# Checks if hand is a straight
is_straight = all([values[i] == values... | 912625b50d33dd7c4fef41e15e018eb3f86a0911 | 2,976 |
def _get_wmi_wbem():
"""Returns a WMI client connected to localhost ready to do queries."""
client, _ = _get_win32com()
if not client:
return None
wmi_service = client.Dispatch('WbemScripting.SWbemLocator')
return wmi_service.ConnectServer('.', 'root\\cimv2') | 2b888b391f3bf148e4b13abc8b54c1ad3f97cfff | 2,977 |
def join_arrays(a, b):
"""
Joining Arrays Row-wise
Parameters
----------
a : array
One of the arrays
b : array
Second of the arrays
Returns
-------
arr : array
Joined two arrays row wise
"""
return (np.r_[a, b]) | 7bc3b5824573a8323834280ce709cd7ebe6f9639 | 2,979 |
def psvd(a: np.ndarray):
"""Photonic SVD architecture
Args:
a: The matrix for which to perform the svd
Returns:
A tuple of singular values and the two corresponding SVD architectures :math:`U` and :math:`V^\\dagger`.
"""
l, d, r = svd(a)
return rectangular(l), d, rectangular(r... | ae59e40f4ad45f97d1770b904619f4066030d3af | 2,980 |
def vmatrix(vma):
""" write a variable zmatrix (bohr/radian) to a string (angstroms/degree)
"""
assert automol.zmatrix.v.is_valid(vma)
vma_str = automol.zmatrix.v.string(vma)
return vma_str | 12132cfab4c06716836ca7834a14ac5525fc663c | 2,981 |
def quote_etag(etag_str):
"""
If the provided string is already a quoted ETag, return it. Otherwise, wrap
the string in quotes, making it a strong ETag.
"""
if ETAG_MATCH.match(etag_str):
return etag_str
else:
return '"%s"' % etag_str | 114734b88502194050fa10ff13b8a20bdae60b4e | 2,982 |
def dummy_func_1(input_array):
"""
a sample fitness function that uses the closeness of fit to a polynomial with random coefficients to calculate
fitness (loss)
Args:
input_array(array): iterable of 16 floats between 0 and 1
Returns:
loss(float): an approximation of how close the p... | eb89a86107f763b0f6c166f2b430ae62a8e68227 | 2,983 |
import logging
from datetime import datetime
def validation_loop(sess, model, ops, handles, valid_summary_writer, external=False):
""" Iterates over the validation data, calculating a trained model's cross-entropy. """
# Unpack OPs
batch_loss_op, sentence_losses_op = ops
# Initialize metrics
vali... | 72f532bccc1f184dcc3d7ab91d88e0a293d9914b | 2,984 |
import requests
import json
import urllib
def register_geoserver_db(res_id, db):
"""
Attempts to register a GeoServer layer
"""
geoserver_namespace = settings.DATA_SERVICES.get("geoserver", {}).get('NAMESPACE')
geoserver_url = settings.DATA_SERVICES.get("geoserver", {}).get('URL')
geoserver_u... | 42bc90904a305964a9d37779e85004843b03c8d1 | 2,986 |
def move_file(source,destination):
"""perform mv command to move a file from sourc to destination
Returns True if move is successful
"""
#print("MOV:"+source+"-->"+destination)
mv_cmd=['mv',source,destination]
if not getReturnStatus(mv_cmd):
return False
return True | d79e559fa988da8e1adfe215684187148733e352 | 2,987 |
def _freedman_diaconis_bins(a):
"""Calculate number of hist bins using Freedman-Diaconis rule."""
# From http://stats.stackexchange.com/questions/798/
a = np.asarray(a)
iqr = stats.scoreatpercentile(a, 75)-stats.scoreatpercentile(a, 25)
h = 2*iqr/(len(a)**(1/3))
bins=int(np.ceil((a.max()-a.min()... | f3e7ebc5da021ac6518a1e501eefbfa3b06c14e6 | 2,988 |
def to_ascii_bytes(string):
"""Convert unicode to ascii byte string."""
return bytes(string, 'ascii') if PY3 else bytes(string) | adca8c49f27f53334ae19a393d5dc00a7592f7db | 2,989 |
def matrix_conv_both_methods_from_avg(n_realz, input_folder, mapping,
v_tuple, t_tuple,
prefix='real_', numbered=True, verbose=False):
"""
Convergence of the aggregate transition matrix both considering the frequency and not considering... | f67885b779bde4477de655ba5b4b00bde6a597eb | 2,991 |
def zipper(sequence):
"""Given a sequence return a list that has the same length as the original
sequence, but each element is now a list with an integer and the original
element of the sequence."""
n = len(sequence)
rn = range(n)
data = zip(rn,sequence)
return data | af7f0c495d920e54ea033696aefc27379b667102 | 2,992 |
def normalizeRows(x):
"""
Implement a function to normalizes each row of the matrix x (to have unit length)
Argument:
x -- A numpy matrix of shape (n, m)
Returns:
x -- The normalized (by row) numpy matrix
"""
x_norm = np.linalg.norm(x, ord=2, axis=1, keepdims=True)
x = x / x_norm
... | f305aafa614121c0948725bc064e255ab44595f3 | 2,993 |
def weat_p_value(X, Y, A, B, embd, sample = 1000):
"""Computes the one-sided P value for the given list of association and target word pairs
Arguments
X, Y : List of association words
A, B : List of target words
embd : Dictonary of word-to-embedding for all words
... | 7c66eaa825d9e2b84ff1a49fa81de9a872ce3271 | 2,994 |
def toggle_nullclines():
"""Make an interactive plot of nullclines and fixed points of
the Gardner-Collins synthetic toggle switch.
"""
# Set up sliders
params = [
dict(
name="βx", start=0.1, end=20, step=0.1, value=10, long_name="beta_x_slider",
),
dict(
... | 613303946b3abff9902e060dee952e9303fa3b52 | 2,995 |
def is_chinese_word_add_number(s):
"""中文混数字"""
if len(s) == 0:
return False
else:
for w in s:
if is_chinese(w) == False and is_number(w) == False:
return False
return True | a6524d31c4fbeb866406eec0617fd99f88ba40a0 | 2,996 |
def get_rack_id_by_label(rack_label):
"""
Find the rack id for the rack label
Returns:
rack_id or None
"""
rack_id = None
session = persistent_mgr.create_database_session()
rack = persistent_mgr.get_rack_by_label(session, rack_label)
if rack:
rack_id = rack.rack_id
se... | 332df032e05fd8e3dde47dd1513bc6f5c381cfa3 | 2,997 |
import torch
def cat(xs: torch.Tensor, lx: torch.Tensor) -> torch.Tensor:
"""Cat the padded xs via lengths lx
Args:
xs (torch.FloatTensor): of size (N, T, V)
lx (torch.LongTensor): of size (N, ), whose elements are (lx0, lx1, ...)
Return:
x_gather (torch.FloatTensor): size (lx0+l... | 60e27c001b39c6b3afe0bbe3c3743bcd817e9fbf | 2,998 |
def rule(n: int) -> dict:
"""Implement one of the 256 rules of elementary cellular automata.
Args:
n: The id of the rule (1-256).
Returns:
A mapping from a tuple of 3 cellvalues to a single cell value.
"""
assert n > 0 and n < 257, "must choose a rule between 1 and 256"
val... | e423675cb3fba18b62e42a7509274b13ee8eeb0f | 2,999 |
def rouge_l_sentence_level(evaluated_sentences, reference_sentences):
"""Computes ROUGE-L (sentence level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/ rouge-
working-note-v1.3.1.pdf.
Calculated according to:
R_lcs = LCS(X,Y)/m
P_lcs = LCS(X,Y)/n
... | 168b3202baa5e8d185d5d181b3b468b810cf92fd | 3,001 |
import numpy as np
from scipy.signal import medfilt, medfilt2d
def median(array, width=None, axis=None, even=False):
"""Replicate the IDL ``MEDIAN()`` function.
Parameters
----------
array : array-like
Compute the median of this array.
width : :class:`int`, optional
Size of the ne... | 829d3c00055c57a5368d366dac04731353ace5e6 | 3,002 |
def stitch_frame(frames, _):
"""
Stitching for single frame.
Simply returns the frame of the first index in the frames list.
"""
return frames[0] | 833ceb66f9df61e042d1c936c68b8a77566545c4 | 3,003 |
def project_add():
"""
Desc: 新增项目接口
"""
form_data = eval(request.get_data(as_text=True))
pro_name, remark = form_data['projectName'], form_data['remark']
user_id = get_jwt_identity()
response = ProjectM().add_project(user_id, pro_name, remark)
return response | b03a07e129f5c52b70a6db3c687318225090318b | 3,004 |
def end_of_next_month(dt):
"""
Return the end of the next month
"""
month = dt.month + 2
year = dt.year
if month > 12:
next_month = month - 12
year+=1
else:
next_month = month
return (
dt.replace(
year=year, month=next_month, day=1
) - ... | 0ee3ac845275cc0a101f2cd1603d2de268ef9108 | 3,005 |
def test_build_dynamic__with_location_mobility_data(monkeypatch):
"""
Ensure dynamic mixing matrix can use location-based mobility data set by the user + Google.
"""
def get_fake_mobility_data(*args, **kwargs):
vals = {"work": [1, 1.5, 1.3, 1.1]}
days = [0, 1, 2, 3]
return vals,... | a85722c24f57918f16e35ee2ae57cefdd23824fb | 3,008 |
def margin_to_brightness(margin, max_lead=30, pct_pts_base=0):
""""Tweak max_lead and pct_pts_base to get the desired brightness range"""
return int((abs(margin) / max_lead) * 100) + pct_pts_base | d6f101c52ddee9f520e36e31fac7042e0aba3992 | 3,009 |
def RotateFullImage2D(src, dst, angle, scale=1.0,
interp=InterpolationType.linear):
"""\
Rotate an image resizing the output to fit all the pixels.
Rotates an image clockwise by a given angle (in degrees). The values of
unknown pixels in the output image are set to 0. The output I... | faedd430ae87f32e56c13ad50125051daa5994f3 | 3,010 |
def render_practice_text_field_validation1(request):
"""テキストフィールドのバリデーションの練習"""
template = loader.get_template(
'webapp1/practice/vuetify-text-field-validation1.html')
# -----------------------------------
# 1
# 1. host1/webapp1/templates/webapp1/prac... | 714093e2b606cab0bbfb094025b5608d781f8aab | 3,011 |
def hlc3(high, low, close, offset=None, **kwargs):
"""Indicator: HLC3"""
# Validate Arguments
high = verify_series(high)
low = verify_series(low)
close = verify_series(close)
offset = get_offset(offset)
# Calculate Result
hlc3 = (high + low + close) / 3.0
# Offset
if offset != ... | 16bb3e49f5017f13c84046dce880dd3f022eb15e | 3,013 |
async def findID(context: Context, dueDateID: str = ""):
"""Find Due date !ass find subject_name """
if not dueDateID:
return await notEnoughArgs(context)
try:
dueDates = DueDateData().findById(context, dueDateID)
if len(dueDates) == 0:
return await context.send(... | a6aab2219fcb29e073ccb5d73e440dd7a42163b9 | 3,014 |
def front_page() -> HTML:
"""
Renders the front page
"""
return render_template("frontPage.html") | 2ec04c4c24b1aade9f7389b29bd91985b657fc67 | 3,015 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.