content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def add_upgrades(ws, cols, lnth):
"""
"""
for col in cols:
cell = "{}1".format(col)
ws[cell] = "='New_4G_Sites'!{}".format(cell)
for col in cols[:2]:
for i in range(2, lnth):
cell = "{}{}".format(col, i)
ws[cell] = "='New_4G_Sites'!{}".format(cel... | a5c33a59992976dfbdd775ce55c6017cef7d7f1d | 7,448 |
import torch
def vae_loss(recon_x, x, mu, logvar, reduction="mean"):
"""
Effects
-------
Reconstruction + KL divergence losses summed over all elements and batch
See Appendix B from VAE paper:
Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014
https://arxiv.org/abs/1312.6114
... | ecdabfd62d7e7c7aa858b36669a73e6081891f83 | 7,449 |
from functools import reduce
def Or(*args):
"""Defines the three valued ``Or`` behaviour for a 2-tuple of
three valued logic values"""
def reduce_or(cmp_intervala, cmp_intervalb):
if cmp_intervala[0] is True or cmp_intervalb[0] is True:
first = True
elif cmp_intervala[0] is No... | fc252c0129904d7ad58c18adad0b08c638b2bd11 | 7,450 |
def create_task():
"""Create a new task"""
data = request.get_json()
# In advanced solution, a generic validation should be done
if (TaskValidator._validate_title(data)):
TaskPersistence.create(title=data['title'])
return {'success': True, 'message': 'Task has been saved'}
# Simple... | e42b06ed297b589cacedae522b81c898a01d6b72 | 7,451 |
import socket
def get_socket_with_reuseaddr() -> socket.socket:
"""Returns a new socket with `SO_REUSEADDR` option on, so an address
can be reused immediately, without waiting for TIME_WAIT socket
state to finish.
On Windows, `SO_EXCLUSIVEADDRUSE` is used instead.
This is because ... | 6edbc0f0aaaeaebd9c6d0f31257de0b4dfe7df1c | 7,452 |
def get_systemd_services(service_names):
"""
:param service_names: {'service_unit_id': 'service_display_name'}
e.g., {'cloudify-rabbitmq.service': 'RabbitMQ'}
"""
systemd_services = get_services(service_names)
statuses = []
services = {}
for service in systemd_services:
is_servic... | 523efae5fb536c9326978d84ea9055aecf47da05 | 7,453 |
import datetime
from werkzeug.local import LocalProxy
def json_handler(obj):
"""serialize non-serializable data for json"""
# serialize date
if isinstance(obj, (datetime.date, datetime.timedelta, datetime.datetime)):
return unicode(obj)
elif isinstance(obj, LocalProxy):
return unicode(obj)
else:
raise Ty... | ea44a5d77e608f16458a1c3405665011f2d9c70c | 7,454 |
def _random_prefix(sentences):
"""
prefix random generator
input: list of input sentences
output: random word
"""
words = _word_dict(sentences)
return choice(words) | 7a81b5825bc0dc2ac4b75bff40a9b76af77486a3 | 7,455 |
def user_logout(*args, **kwargs):
# pylint: disable=unused-argument
"""
This endpoint is the landing page for the logged-in user
"""
# Delete the Oauth2 token for this session
log.info('Logging out User: %r' % (current_user,))
delete_session_oauth2_token()
logout_user()
flash('You... | baaeb1f1b353eaa75bc1d81cb72a9bb931398047 | 7,456 |
def redraw_frame(image, names, aligned):
"""
Adds names and bounding boxes to the frame
"""
i = 0
unicode_font = ImageFont.truetype("DejaVuSansMono.ttf", size=17)
img_pil = Image.fromarray(image)
draw = ImageDraw.Draw(img_pil)
for face in aligned:
draw.rectangle((face[0], face[... | 66adbbc42c4108855e1eea6494391957c3e91b4f | 7,457 |
from typing import Type
def is_dapr_actor(cls: Type[Actor]) -> bool:
"""Checks if class inherits :class:`Actor`.
Args:
cls (type): The Actor implementation.
Returns:
bool: True if cls inherits :class:`Actor`. Otherwise, False
"""
return issubclass(cls, Actor) | 1c3f5b4744cf9db91c869247ab297ffc10dcfc68 | 7,459 |
def unpickle(file):
""" unpickle the data """
fo = open(file, 'rb')
dict = cPickle.load(fo)
fo.close()
return dict | dbab180e31e7bff6ba965f48ee7a3018e2665763 | 7,460 |
def _calc_norm_gen_prob(sent_1, sent_2, mle_lambda, topic):
"""
Calculates and returns the length-normalized generative probability of sent_1 given sent_2.
"""
sent_1_len = sum([count for count in sent_1.raw_counts.values()])
return _calc_gen_prob(sent_1, sent_2, mle_lambda, topic) ** (1.0 / sent_1... | 7f84f1b0de67f9d6f631ad29aa1c614d6d3f13d6 | 7,461 |
def isomorphic(l_op, r_op):
""" Subject of definition, here it is equal operation.
See limintations (vectorization.rst).
"""
if l_op.getopnum() == r_op.getopnum():
l_vecinfo = forwarded_vecinfo(l_op)
r_vecinfo = forwarded_vecinfo(r_op)
return l_vecinfo.bytesize == r_vecinfo.b... | e34c6928c4fdf10fed55bb20588cf3183172cab1 | 7,462 |
import numpy
import math
def partition5(l, left, right):
"""
Insertion Sort of list of at most 5 elements and return the position of the median.
"""
j = left
for i in xrange(left, right + 1):
t = numpy.copy(l[i])
for j in xrange(i, left - 1, -1):
if l[j - 1][0] < t[0]:
break
l[j] = l[j - 1]
l[j] ... | 75c5c893c978e81a2b19b79c6000a2151ff6b088 | 7,463 |
def max_validator(max_value):
"""Return validator function that ensures upper bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check.
Args:
max_value: maximum value for new validator
"""
def valid... | 6957f507f7140aa58a9c969a04b9bde65da54319 | 7,464 |
def standalone_job_op(name, image, command, gpus=0, cpu_limit=0, memory_limit=0, env=[],
tensorboard=False, tensorboard_image=None,
data=[], sync_source=None, annotations=[],
metrics=['Train-accuracy:PERCENTAGE'],
arena_image='cheyang/arena_launcher:v0.5',
timeout_hours... | 2c2c6c014fe841b6929153cd5590fa43210964ed | 7,465 |
def load_randompdata(dataset_str, iter):
"""Load data."""
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = []
for i in range(len(names)):
with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f:
if sys.version_info > (3, 0):
objects.appen... | 353160ffd8b0474fc4c58532d1bcae80f4d6cbad | 7,466 |
def page_to_reload():
""" Returns page that is refreshed every
argument of content attribute in
meta http-equiv="refresh".
"""
val = knob_thread.val
year = int(val * 138./256 + 1880)
return (
"""<!DOCTYPE html>
<html>
<head><meta http-equiv="refresh" content=".2">
<style>
h1 {{color:... | 75c9a409a6dd936f23c9a54dae058fb7e8fd9e97 | 7,467 |
def svn_log_changed_path2_create(*args):
"""svn_log_changed_path2_create(apr_pool_t pool) -> svn_log_changed_path2_t"""
return _core.svn_log_changed_path2_create(*args) | f40cf409bfb458d35cb38ba76fa93c319803a992 | 7,468 |
def check_from_dict(method):
"""A wrapper that wrap a parameter checker to the original function(crop operation)."""
@wraps(method)
def new_method(self, *args, **kwargs):
word_dict, = (list(args) + [None])[:1]
if "word_dict" in kwargs:
word_dict = kwargs.get("word_dict")
... | d45b68ccccbd4f97e585c7386f7da6547fdd86d6 | 7,471 |
def env_observation_space_info(instance_id):
"""
Get information (name and dimensions/bounds) of the env's
observation_space
Parameters:
- instance_id: a short identifier (such as '3c657dbc')
for the environment instance
Returns:
- info: a dict containing 'name' (such as 'Di... | 2ee4b17a73ad49c6c63dc07f2822b0f2d1ece770 | 7,472 |
from typing import Set
from typing import Dict
def build_target_from_transitions(
dynamics_function: TargetDynamics,
initial_state: State,
final_states: Set[State],
) -> Target:
"""
Initialize a service from transitions, initial state and final states.
The set of states and the set of actions... | d1014560c05e6f3169c65725d94af20494d97f0a | 7,473 |
from typing import Optional
from datetime import datetime
def citation(dll_version: Optional[str] = None) -> dict:
"""
Return a citation for the software.
"""
executed = datetime.now().strftime("%B %d, %Y")
bmds_version = __version__
url = "https://pypi.org/project/bmds/"
if not dll_versio... | 1196e1de2c2431120467eac83701022f1b4d9840 | 7,474 |
def comment_pr_(ci_data, github_token):
"""Write either a staticman comment or non-staticman comment to
github.
"""
return sequence(
(comment_staticman(github_token) if is_staticman(ci_data) else comment_general),
post(github_token, ci_data),
lambda x: dict(status_code=x.status_c... | 548f854a37fe95b83660bc2ec4012cda72317976 | 7,475 |
from re import L
def response_loss_model(h, p, d_z, d_x, d_y, samples=1, use_upper_bound=False, gradient_samples=0):
"""
Create a Keras model that computes the loss of a response model on data.
Parameters
----------
h : (tensor, tensor) -> Layer
Method for building a model of y given p an... | 898e72f29a9c531206d0243b8503761844468665 | 7,476 |
import numpy
from datetime import datetime
def get_hourly_load(session, endpoint_id, start_date, end_date):
"""
:param session: session for the database
:param endpoint_id: id for the endpoint
:param start_date: datetime object
:param end_date: datetime object and: end_date >= start_date
:retu... | cf619b12778edfaf27d89c43226079aafc650ac4 | 7,477 |
def startend(start=None, end=None):
"""Return TMIN, TAVG, TMAX."""
# Select statement
sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]
if not end:
# Calculate TMIN, TAVG, TMAX for dates greater than start
results = session.query(*sel).\
... | 7b8f395fd177d5352b14c12902acea1a641c5df8 | 7,478 |
def configure_camera(config):
"""
Configures the camera.
:param config: dictionary containing BARD configuration
parameters optional parameters in camera.
source (default 0), window size (default delegates to
cv2.CAP_PROP_FRAME_WIDTH), calibration directory and
roi (region of... | 8accdaf9d710ff2ccff6d4ad5216611593e06ff0 | 7,479 |
def munsell_value_Moon1943(Y: FloatingOrArrayLike) -> FloatingOrNDArray:
"""
Return the *Munsell* value :math:`V` of given *luminance* :math:`Y` using
*Moon and Spencer (1943)* method.
Parameters
----------
Y
*luminance* :math:`Y`.
Returns
-------
:class:`np.floating` or :... | 7e419c8936fa49f35a5838aa7d3a5d99c93808f2 | 7,480 |
import functools
import traceback
def log_errors(func):
"""
A wrapper to print exceptions raised from functions that are called by callers
that silently swallow exceptions, like render callbacks.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*arg... | a15c26de36a8c784da0333382f27fc06b0ed78a0 | 7,481 |
def count_total_words(sentence_list):
"""
문장 리스트에 있는 단어를 셉니다.
:param sentence_list: 단어의 리스트로 구성된 문장 리스트
:return: 문장에 있는 단어의 개수
"""
return sum(
[count_words_per_sentence(sentence) for sentence in sentence_list]
) | 0abc550c26b40fd36d0b9540fc1cd001e40a7552 | 7,482 |
def translate_dbpedia_url(url):
"""
Convert an object that's defined by a DBPedia URL to a ConceptNet
URI. We do this by finding the part of the URL that names the object,
and using that as surface text for ConceptNet.
This is, in some ways, abusing a naming convention in the Semantic Web.
The ... | 2a6b99ca59216c97dc1cfd90f1d8f4c01ad5f9f2 | 7,483 |
def setSecurityPolicy(aSecurityPolicy):
"""Set the system default security policy.
This method should only be caused by system startup code. It should
never, for example, be called during a web request.
"""
last = _ImplPython._defaultPolicy
_ImplPython._defaultPolicy = aSecurityPolicy
retur... | 7063b83f1c2492b8684a43f64c9d2a49ae2ca61b | 7,484 |
import re
def map_sentence2ints(sentence):
"""Map a sentence to a list of words."""
word_list = re.findall(r"[\w']+|[.,!?;]", sentence)
int_list = [const.INPUTVOCABULARY.index(word) for word in word_list]
return np.array(int_list).astype(np.int32) | 6dcb2917c817aa2e394c313fb273d466b6fb1ea9 | 7,485 |
def get_api_key(
api_key_header: str = Security(
APIKeyHeader(name=settings.API_KEY_HEADER, auto_error=False)
)
) -> str:
"""
This function checks the header and his value for correct authentication if not a
403 error is returned:
- api_key_header = Security api header
https://git... | 50121c0d16455862552c58e7478ef383b68e71c7 | 7,486 |
def add_pred_to_test(test_df, pred_np, demo_col_list, days):
"""
derived from Tensorflow
INPUT:
- df (pandas DataFrame)
- group (string)
OUTPUT:
- show_group_stats_viz
"""
test_df = test_df.copy()
for c in demo_col_list:
t... | aec48bd6201e1a9a1ebd6f96c4c8b7cfd9304607 | 7,487 |
def getCriticality(cvss):
""" color convention fot the cells of the PDF """
if cvss == 0.0:
return ("none", "#00ff00", (0, 255, 0))
if cvss < 3.1:
return ("low", "#ffff00", (255, 255, 0))
if cvss < 6.1:
return ("medium", "#ffc800", (255, 200, 0))
if cvss < 9.1:
return... | a4167b2f576dcb361641f7fe0280c212673f0157 | 7,488 |
from typing import List
def combine_groups(groups: List[np.ndarray], num_features: int) -> np.ndarray:
"""
Combines the given groups back into a 2d measurement matrix.
Args:
groups: A list of 1d, flattened groups
num_features: The number of features in each measurement (D)
Returns:
... | 906c69fabcb62a60f12fd3c4bafc711aa971ad19 | 7,489 |
import functools
def skippable(*prompts, argument=None):
"""
Decorator to allow a method on the :obj:`CustomCommand` to be
skipped.
Parameters:
----------
prompts: :obj:iter
A series of prompts to display to the user when the method is being
skipped.
argument: :obj:`str`
... | 879106f4cc0524660fb6639e56d688d40b115ac4 | 7,490 |
import hashlib
def _cache_name(address):
"""Generates the key name of an object's cache entry"""
addr_hash = hashlib.md5(address).hexdigest()
return "unsub-{hash}".format(hash=addr_hash) | 6933b1170933df5e3e57af03c81322d68a46d91f | 7,492 |
def format_currency(
value: Decimal,
currency: str | None = None,
show_if_zero: bool = False,
invert: bool = False,
) -> str:
"""Format a value using the derived precision for a specified currency."""
if not value and not show_if_zero:
return ""
if value == ZERO:
return g.led... | 197dc15c799e1866526a944e0f1f8217e97cf785 | 7,493 |
def supplemental_div(content):
"""
Standardize supplemental content listings
Might not be possible if genus and tree content diverge
"""
return {'c': content} | b42e868ef32f387347cd4a97328794e6628fe634 | 7,495 |
def viewTypes():
"""View types of item when sent through slash command"""
user_id, user_name, channel_id = getUserData(request.form)
checkUser(user_id)
itemType = request.form.get('text')
try:
text = viewTypesItems(itemType)
except ItemNotInPantry:
reply = "Sorry! But either t... | aea7633a1092c68a5ccf3a5619eee9d74dafdca2 | 7,496 |
def load_and_preprocess():
"""
Load the data (either train.csv or test.csv) and pre-process it with some simple
transformations. Return in the correct form for usage in scikit-learn.
Arguments
---------
filestr: string
string pointing to csv file to load into pandas
Returns
... | 3202c4aaf76af0695594c39641dd4892b1215d97 | 7,497 |
from datetime import datetime
def _dates2absolute(dates, units):
"""
Absolute dates from datetime object
Parameters
----------
dates : datetime instance or array_like of datetime instances
Instances of pyjams.datetime class
units : str
'day as %Y%m%d.%f', 'month as %Y%m.%f', o... | ef823887ec410d7f7d0c5c54d12005ab35744c0c | 7,498 |
def Mix_GetNumMusicDecoders():
"""Retrieves the number of available music decoders.
The returned value can differ between runs of a program due to changes in
the availability of the shared libraries required for supporting different
formats.
Returns:
int: The number of available music ... | a91b84c42701cdaeb7f400a3091bb869e477ff06 | 7,499 |
from typing import Callable
def _concat_applicative(
current: KindN[
_ApplicativeKind, _FirstType, _SecondType, _ThirdType,
],
acc: KindN[
_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType,
],
function: KindN[
_ApplicativeKind,
Callable[[_FirstType], Callable[... | fb720d87f643592f3ebed01bd55364fec83e1b22 | 7,501 |
def goto_x(new_x):
"""
Move tool to the new_x position at speed_mm_s at high speed. Update curpos.x with new position.
If a failure is detected, sleep so the operator can examine the situation.
Since the loss of expected responses to commands indicates that the program does not know
the exact po... | fe49dde9349e18cea91d8f7ee1aae1f3545b5a04 | 7,502 |
def server_rename(adapter_id, server_id):
"""Renames a server using a certain adapter, if that adapter supports renaming."""
adapter = get_adapter(adapter_id)
if not adapter:
return output.failure("That adapter doesn't (yet) exist. Please check the adapter name and try again.", 501)
if not ada... | 55a25178a3ff9ec1e2e1d4a2f7cdd228bf0914cb | 7,503 |
def index():
""" Root URL response, load UI """
return app.send_static_file("index.html") | fd793fadf7ecaf8e2c435b377c264aaf6e4da1d2 | 7,505 |
def restore_capitalization(word, example):
"""
Make the capitalization of the ``word`` be the same as in ``example``:
>>> restore_capitalization('bye', 'Hello')
'Bye'
>>> restore_capitalization('half-an-hour', 'Minute')
'Half-An-Hour'
>>> restore_capitalization('usa', 'I... | 77b074acb4d95de5d88f37495786f6679fa5f54d | 7,506 |
def test_loss_at_machine_precision_interval_is_zero():
"""The loss of an interval smaller than _dx_eps
should be set to zero."""
def f(x):
return 1 if x == 0 else 0
def goal(l):
return learner.loss() < 0.01 or learner.npoints >= 1000
learner = Learner1D(f, bounds=(-1, 1))
simp... | 61d2efd80054729aafbe11d67873860f96f2198b | 7,507 |
def params_document_to_uuid(params_document):
"""Generate a UUID5 based on a pipeline components document"""
return identifiers.typeduuid.catalog_uuid(params_document) | 32366dd5fa2ff4acfe848a7a4633baba23a1e993 | 7,508 |
import typing
def modify_account() -> typing.RouteReturn:
"""IntraRez account modification page."""
form = forms.AccountModificationForm()
if form.validate_on_submit():
rezident = flask.g.rezident
rezident.nom = form.nom.data.title()
rezident.prenom = form.prenom.data.title()
... | e67b553f0c7051d5be4b257824f495f0a0ad9838 | 7,509 |
def fizzbuzz(end=100):
"""Generate a FizzBuzz game sequence.
FizzBuzz is a childrens game where players take turns counting.
The rules are as follows::
1. Whenever the count is divisible by 3, the number is replaced with
"Fizz"
2. Whenever the count is divisible by 5, the number is replaced... | b68b1c39674fb47d0bd12d387f347af0ef0d26ca | 7,510 |
def generate_lane_struct():
""" Generate the datatype for the lanes dataset
:return: The datatype for the lanes dataset and the fill values for the lanes dataset
"""
lane_top_list = []
for item in [list1 for list1 in lane_struct if list1.__class__.__name__ == "LaneTop"]:
lane_top_list.appen... | 698fadc8472233ae0046c9bbf1e4c21721c7de48 | 7,511 |
def notification_list(next_id=None): # noqa: E501
"""notification_list
Get all your certificate update notifications # noqa: E501
:param next_id:
:type next_id: int
:rtype: NotificationList
"""
return 'do some magic!' | 4fe4467f89ad4bf1ba31bd37eace411a78929a26 | 7,512 |
import requests
def SendPost(user, password, xdvbf, cookie, session, url=URL.form):
"""
根据之前获得的信息,发送请求
:param user: 学号
:param password: 密码
:param xdvbf: 验证码内容
:param cookie: 之前访问获得的cookie
:param session: 全局唯一的session
:param url: 向哪个资源发送请求
:return: response
"""
form_data = {... | 932d869f048e8f06d7dbfe6032950c66a72224fa | 7,514 |
def css_flat(name, values=None):
"""Все значения у свойства (по порядку)
left -> [u'auto', u'<dimension>', u'<number>', u'<length>', u'.em', u'.ex',
u'.vw', u'.vh', u'.vmin', u'.vmax', u'.ch', u'.rem', u'.px', u'.cm',
u'.mm', u'.in', u'.pt', u'.pc', u'<percentage>', u'.%']
"""
cu... | a992d261d234f9c4712b00986cb6ba5ba4347b8f | 7,515 |
def prepare_mqtt(MQTT_SERVER, MQTT_PORT=1883):
"""
Initializes MQTT client and connects to a server
"""
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_SERVER, MQTT_PORT, 60)
return client | a5015d80c5c0222ac5eb40cbb1ba490826fcebae | 7,516 |
def record_iterator_class(record_type):
"""
Gets the record iterator for a given type
A way to abstract the construction of a record iterator class.
:param record_type: the type of file as string
:return: the appropriate record iterator class
"""
if record_type == 'bib':
return Bib... | b1fbd393819055b9468a96b5ec7e44d3773dcf52 | 7,517 |
from typing import Any
def palgo(
dumbalgo: type[DumbAlgo], space: Space, fixed_suggestion_value: Any
) -> SpaceTransformAlgoWrapper[DumbAlgo]:
"""Set up a SpaceTransformAlgoWrapper with dumb configuration."""
return create_algo(algo_type=dumbalgo, space=space, value=fixed_suggestion_value) | 373f74ca675250b5a422ff965396a122c4b967fd | 7,519 |
def english_to_french(english_text):
"""
Input language translate function
"""
translation = language_translator.translate(text=english_text, model_id = "en-fr").get_result()
french_text = translation['translations'][0]['translation']
return french_text | ac9951d0362ccf511361dfc676b03f61f4fe8453 | 7,520 |
from typing import Sequence
def noise_get_turbulence(
n: tcod.noise.Noise,
f: Sequence[float],
oc: float,
typ: int = NOISE_DEFAULT,
) -> float:
"""Return the turbulence noise sampled from the ``f`` coordinate.
Args:
n (Noise): A Noise instance.
f (Sequence[float]): The point t... | f4af83726dd6f3badf2c2eaa86f647dd4ad71cb3 | 7,521 |
def mnist_loader(path="../../corruptmnist", n_files=8, image_scale=255):
"""
Loads .npz corruptedmnist, assumes loaded image values to be between 0 and 1
"""
# load and stack the corrupted mnist dataset
train_images = np.vstack(
[np.load(path + "/train_{}.npz".format(str(i)))["images"] for i... | a7e7328621819e0cbf163e1ef006df5183b6d25d | 7,523 |
def reduce_min(values, index, name='segmented_reduce_min'):
"""Computes the minimum over segments."""
return _segment_reduce(values, index, tf.math.unsorted_segment_min, name) | 473698ffd1295344dd8019b01b69d464f2db93b8 | 7,524 |
import glob
def _data_type(data_string: str):
""" convert the data type string (i.e., FLOAT, INT16, etc.) to the appropriate int.
See: https://deeplearning4j.org/api/latest/onnx/Onnx.TensorProto.DataType.html
"""
for key, val in glob.DATA_TYPES.items():
if key == data_string:
retu... | a0fce62a304ce8b61ad2ecf173b8723cf66f10c0 | 7,525 |
def bin_power(dataset, fsamp:int, band=range(0, 45)):
"""Power spec
Args:
dataset: n_epoch x n_channel x n_sample
fsamp:
band:
Returns:
n_epoch x n_channel x len(band)
"""
res = []
for i, data in enumerate(dataset):
res.append(power(data, fsamp=fsamp, ba... | e85815837d2cab8bd1b89132df29a439ec54bd34 | 7,526 |
import six
import base64
import zlib
def deflate_and_base64_encode(string_val):
"""
Deflates and the base64 encodes a string
:param string_val: The string to deflate and encode
:return: The deflated and encoded string
"""
if not isinstance(string_val, six.binary_type):
string_val = st... | 31fc19cf134bc22b3fc45b4158c65aef666716cc | 7,527 |
def smooth_reward_curve(x, y):
"""Smooths a reward curve--- how?"""
k = min(31, int(np.ceil(len(x) / 30))) # Halfwidth of our smoothing convolution
xsmoo = x[k:-k]
ysmoo = np.convolve(y, np.ones(2 * k + 1), mode='valid') / np.convolve(np.ones_like(y), np.ones(2 * k + 1), mode='valid')
downsample = max(int(np... | 3106cc75a8ceb58f29cded4353133eff7a737f8b | 7,528 |
def sdot(s):
"""Returns the time derivative of a given state.
Args:
s(1x6 numpy array): the state vector [rx,ry,rz,vx,vy,vz]
Returns:
1x6 numpy array: the time derivative of s [vx,vy,vz,ax,ay,az]
"""
mu_Earth = 398600.4405
r = np.linalg.norm(s[0:3])
a = -mu_Ear... | 4e79054e194b5395953fbda30794e819c6700feb | 7,529 |
def get_values(abf,key="freq",continuous=False):
"""returns Xs, Ys (the key), and sweep #s for every AP found."""
Xs,Ys,Ss=[],[],[]
for sweep in range(abf.sweeps):
for AP in cm.matrixToDicts(abf.APs):
if not AP["sweep"]==sweep:
continue
Ys.append(AP[key])
... | 8671d795410b8064fd70172da396ccbd4323c9a3 | 7,530 |
def geodetic2cd(
gglat_deg_array, gglon_deg_array, ggalt_km_array, decimals=2, year=2021.0
):
"""Transformation from Geodetic (lat, lon, alt) to Centered Dipole (CD) (lat, lon, alt).
Author: Giorgio Savastano (giorgiosavastano@gmail.com)
Parameters
----------
gglon_deg_array : np.ndarray
... | b5a3a8622051e05f31e3f087869b8bebfd213fd9 | 7,531 |
import pickle
def load_pickle(file_path):
"""
load the pickle object from the given path
:param file_path: path of the pickle file
:return: obj => loaded obj
"""
with open(file_path, "rb") as obj_des:
obj = pickle.load(obj_des)
# return the loaded object
return obj | 4770a152dad9c7d123f95a53642aff990f3590f7 | 7,532 |
def _expand_global_features(B, T, g, bct=True):
"""Expand global conditioning features to all time steps
Args:
B (int): Batch size.
T (int): Time length.
g (Tensor): Global features, (B x C) or (B x C x 1).
bct (bool) : returns (B x C x T) if True, otherwise (B x T x C)
Retur... | 9d0ab550147d8658f0ff8fb5cfef8fc565c5f3d3 | 7,533 |
def plot_CDF(data, ax=None, reverse=False, plot=True, **plotargs):
""" plot Cumulative Ratio. """
n_samples = len(data)
X = sorted(data, reverse=reverse)
Y = np.arange(1,n_samples+1)/n_samples
if plot or ax:
if ax is None:
fig, ax = plt.subplots()
ax.plot(X, Y, **plotarg... | 25d9a83a9b560a89137c0e4eb6cd63761f39901f | 7,535 |
def is_zsettable(s):
"""quick check that all values in a dict are reals"""
return all(map(lambda x: isinstance(x, (int, float, long)), s.values())) | ad51e7419a37bec071be6aa2c1a4e9d62bce913c | 7,536 |
from typing import Sequence
def initialize_simulator(task_ids: Sequence[str],
action_tier: str) -> ActionSimulator:
"""Initialize ActionSimulator for given tasks and tier."""
tasks = phyre.loader.load_compiled_task_list(task_ids)
return ActionSimulator(tasks, action_tier) | 8b54ae1c98d44839a33a8774de48e53f1ce9ca96 | 7,537 |
def import_sensitivities(input, file_location):
"""
Ratio is the C/O starting gas ratio
file_location is the LSR C and O binding energy, false to load the base case
"""
tol, ratio = input
try:
data = pd.read_csv(file_location + '/all-sensitivities/' + tol + '{:.1f}RxnSensitivity.csv'.f... | c0b0c9d740335032b4d196232c3166818aa77a1a | 7,539 |
import re
import ntpath
def extract_files_to_process(options, company_file):
"""Extract the files from the ENER zip file and the ITR/DFP inside of it,
and collect all the XML files
"""
force_download = options.get("force_download", False)
local_base_path = _doc_local_base_path(options, company_fi... | 963dd738224c36311791c54d964ae5b95d345a7f | 7,540 |
def merge(source, dest):
""" Copy all properties and relations from one entity onto another, then
mark the source entity as an ID alias for the destionation entity. """
if source.id == dest.id:
return source
if dest.same_as == source.id:
return source
if source.same_as == dest.id:
... | 9cb6963ba0e15e639915e27d7c369394d7088231 | 7,542 |
import json
import re
def create_summary_text(summary):
"""
format a dictionary so it can be printed to screen or written to a plain
text file
Args:
summary(dict): the data to format
Returns:
textsummary(str): the summary dict formatted as a string
"""
summaryjson = json.... | 3a8dd508b760a0b9bfe925fa2dc07d53dee432af | 7,543 |
from datetime import datetime
import random
def random_datetime(start, end):
"""Generate a random datetime between `start` and `end`"""
return start + datetime.timedelta(
# Get a random amount of seconds between `start` and `end`
seconds=random.randint(0, int((end - start).total_seconds())),
... | c3cf7a0fb616b9f157d5eb86b3d76f1cd811308f | 7,544 |
def maximo_basico(a: float, b: float) -> float:
"""Toma dos números y devuelve el mayor.
Restricción: No utilizar la función max"""
if a > b:
return a
return b | f98db565243587015c3b174cf4130cbc32a00e22 | 7,545 |
def listas_mesmo_tamanho(lista_de_listas):
"""
Recebe uma lista de listas e retorna 'True' caso todas as listas
sejam de mesmo tamanho e 'False', caso contrário
"""
tamanho_padrao = len(lista_de_listas[0])
for lista in lista_de_listas:
if(len(lista) != tamanho_padrao):
retu... | 3a405f36bf8cd906fc603e9774cc23e07738e123 | 7,546 |
def self_quarantine_policy_40():
"""
Real Name: b'self quarantine policy 40'
Original Eqn: b'1-PULSE(self quarantine start 40, self quarantine end 40-self quarantine start 40)*self quarantine effectiveness 40'
Units: b'dmnl'
Limits: (None, None)
Type: component
b''
"""
return 1 - fu... | 87ae16bd53bdd08a71231297949c3b995c7f9ba0 | 7,548 |
def knapsack_bqm(cities, values, weights, total_capacity, value_r=0, weight_r=0):
"""
build the knapsack binary quadratic model
From DWave Knapsack examples
Originally from Andrew Lucas, NP-hard combinatorial problems as Ising spin glasses
Workshop on Classical and Quantum Optimization; ETH Zue... | 0a00c5fbcf30e36b7d6a03b9edc4029582b001fd | 7,550 |
from typing import List
def nltk_punkt_de(data: List[str], model=None) -> List[str]:
"""Sentence Segmentation (SBD) with NLTK's Punct Tokenizer
Parameters:
-----------
data : List[str]
list of N documents as strings. Each document is then segmented
into sentences.
model (Defaul... | 10b924070ebcb3062c9b40f4f6ca0a3a006f8d2e | 7,551 |
def is_pattern_error(exception: TypeError) -> bool:
"""Detect whether the input exception was caused by invalid type passed to `re.search`."""
# This is intentionally simplistic and do not involve any traceback analysis
return str(exception) == "expected string or bytes-like object" | 623246404bbd54bc82ff5759bc73be815d613731 | 7,552 |
import pdb
def iwave_modes_banded(N2, dz, k=None):
"""
!!! DOES NOT WORK!!!
Calculates the eigenvalues and eigenfunctions to the internal wave eigenvalue problem:
$$
\left[ \frac{d^2}{dz^2} - \frac{1}{c_0} \bar{\rho}_z \right] \phi = 0
$$
with boundary conditions
"""
nz... | f4016fb4acd1c5aa024d8ac1e69262dec9057713 | 7,553 |
def parse_fastq_pf_flag(records):
"""Take a fastq filename split on _ and look for the pass-filter flag
"""
if len(records) < 8:
pf = None
else:
fastq_type = records[-1].lower()
if fastq_type.startswith('pass'):
pf = True
elif fastq_type.startswith('nopass'):
... | 9a46022aa6e07ed3ca7a7d80933ee23e26d1ca9a | 7,554 |
def rule_manager():
""" Pytest fixture for generating rule manager instance """
ignore_filter = IgnoreFilter(None, verbose=False)
return RuleManager(None, ignore_filter, verbose=False) | ce5e9ecf482b5dfd0e3b99b2367605d6e488f7e7 | 7,555 |
def zeros(fn, arr, *args):
"""
Find where a function crosses 0. Returns the zeroes of the function.
Parameters
----------
fn : function
arr : array of arguments for function
*args : any other arguments the function may have
"""
# the reduced function, with only the argument to be s... | 129a162912f86ee52fc57b1a3a46acaf402598f5 | 7,556 |
import math
def create_low_latency_conv_model(fingerprint_input, model_settings,
is_training):
"""Builds a convolutional model with low compute requirements.
This is roughly the network labeled as 'cnn-one-fstride4' in the
'Convolutional Neural Networks for Small-footprint Key... | 3b03e84c9af5a6d1134736d8757e15039bb196b8 | 7,557 |
def _format_author(url, full_name):
""" Helper function to make author link """
return u"<a class='more-info' href='%s'>%s</a>" % (url, full_name) | 50f001c2358b44bb95da628cc630a2ed3ea8ddfd | 7,560 |
def all_series(request: HttpRequest) -> JsonResponse:
"""
View that serves all the series in a JSON array.
:param request: The original request.
:return: A JSON-formatted response with the series.
"""
return JsonResponse([
_series_response(request, s)
for s in get_response(requ... | 01657615b53a4316a9ec0ad581e009928cfefed2 | 7,561 |
def stlx_powerset(s):
"""If s is a set, the expression pow(s) computes the power set of s. The power set of s is
defined as the set of all subsets of s."""
def powerset_generator(i):
for subset in it.chain.from_iterable(it.combinations(i, r) for r in range(len(i)+1)):
yield set(subset)... | 9297efa03636ff19da7aae4e60593bcc9933d6bb | 7,562 |
import copy
def get_entries_configuration(data):
"""Given the dictionary of resources, returns the generated factory xml file
Args:
data (dict): A dictionary similar to the one returned by ``get_information``
Returns:
str: The factory xml file as a string
"""
entries_configuratio... | db228df9062b8801f7edde5d1e2977ef1e451b5f | 7,563 |
def validinput(x0, xf, n):
"""Checks that the user input is valid.
Args:
x0 (float): Start value
xf (float): End values
n (int): Number of sample points
Returns:
False if x0 > xf or if
True otherwise
"""
valid = True
if x0 > xf:
valid = False
... | 096e0702eb8fe47486d4f03e5b3c55c0835807cd | 7,564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.