content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def german_weekday_name(date):
"""Return the german weekday name for a given date."""
days = [u'Montag', u'Dienstag', u'Mittwoch', u'Donnerstag', u'Freitag', u'Samstag', u'Sonntag']
return days[date.weekday()] | 7d2919c61438ec913abe38cccd924bb69f866655 | 5,578 |
def load_data(database_filepath):
"""
Input:
database_filepath - path of the cleaned data file
Output:
X and Y for model training
Category names
"""
# load data from database
engine = create_engine('sqlite:///{}'.format(database_filepath))
df = pd.read_s... | 8647722a0b97a8130bfadfa6dec45fb71c9e6fe3 | 5,579 |
from scipy.special import lpmn, factorial
def real_spherical_harmonics(phi, theta, l, m):
"""Real spherical harmonics, also known as tesseral spherical harmonics
with condon shortley phase.
Only for scalar phi and theta!!!
"""
if m == 0:
y = np.sqrt(
(2 * l + 1) / (4... | 5c12cf5263676fccc2dee40c54670ea5150e2cfc | 5,580 |
from typing import Callable
def get_replace_function(replace_multiple: bool) -> Callable:
"""given bool:replace_multiple flag,
return replace function from modifier
"""
if replace_multiple:
return distend.modifier.replace_multiple
else:
return distend.modifier.replace_single | 6bb05bb4dd8b28f8581e576aa0f086b55eb7cae6 | 5,581 |
def accuracy(X,Y,w):
"""
First, evaluate the classifier on training data.
"""
n_correct = 0
for i in range(len(X)):
if predict(w, X[i]) == Y[i]:
n_correct += 1
return n_correct * 1.0 / len(X) | bdc68859ec7d1f011dc04f641565e44aaeffe908 | 5,582 |
from typing import List
def reduce_matrix(indices_to_remove: List[int], matrix: np.ndarray) -> np.ndarray:
"""
Removes indices from indices_to_remove from binary associated to indexing of matrix,
producing a new transition matrix.
To do so, it assigns all transition probabilities as the given state in... | dac7755b63593044a7df1658d3205572a935e64d | 5,583 |
def kdj(df, n=9):
"""
随机指标KDJ
N日RSV=(第N日收盘价-N日内最低价)/(N日内最高价-N日内最低价)×100%
当日K值=2/3前1日K值+1/3×当日RSV=SMA(RSV,M1)
当日D值=2/3前1日D值+1/3×当日K= SMA(K,M2)
当日J值=3 ×当日K值-2×当日D值
"""
_kdj = pd.DataFrame()
_kdj['date'] = df['date']
rsv = (df.close - df.low.rolling(n).min()) / (df.high.rolling(n).m... | 7aa88cd6ee972063a2bd45b1b5b83da0255b336c | 5,584 |
def identity_func(x):
"""The identify (a.k.a. transparent) function that returns it's input as is."""
return x | 06e0296c338d68663aa87d08b21f84919be3f85e | 5,585 |
def make_choice_validator(
choices, default_key=None, normalizer=None):
"""
Returns a callable that accepts the choices provided.
Choices should be provided as a list of 2-tuples, where the first
element is a string that should match user input (the key); the
second being the value associat... | 65ac672f16a1031a9051bc4f6769c6b1b88db727 | 5,586 |
import time
def find_best_polycomp_parameters(samples, num_of_coefficients_range,
samples_per_chunk_range, max_error,
algorithm, delta_coeffs=1, delta_samples=1,
period=None, callback=None, max_iterations=0):
""... | 47f076634c50cc18c760b7c60909a2d63a19fd3e | 5,587 |
def moving_average(data, window_size=100): #used this approach https://stackoverflow.com/questions/11352047/finding-moving-average-from-data-points-in-python
"""
Calculates a moving average for all the data
Args:
data: set of values
window_size: number of data points to consider in window
... | 8f04d659081a68c4287024e2b6567f257f7b9d92 | 5,588 |
import re
def _change_TRAVDV_to_TRAVdashDV(s:str):
"""
Reconciles mixcr name like TRAV29/DV5*01 to tcrdist2 name TRAV29DV5*01
Parameters
----------
s : str
Examples
--------
>>> _change_TRAVDV_to_TRAVdashDV('TRAV29DV5*01')
'TRAV29/DV5*01'
>>> _change_TRAVDV_to_TRAVdas... | b5df8b51c96ca9695aecc0fcae4589f35b692331 | 5,589 |
def gen_event_type_entry_str(event_type_name, event_type, event_config):
"""
return string like:
{"cpu-cycles", PERF_TYPE_HARDWARE, PERF_COUNT_HW_CPU_CYCLES},
"""
return '{"%s", %s, %s},\n' % (event_type_name, event_type, event_config) | ca89c19b45f182b8a7ae74ab76f3f42bddf46811 | 5,590 |
def encode_rotate_authentication_key_script(new_key: bytes) -> Script:
"""# Summary
Rotates the transaction sender's authentication key to the supplied new authentication key.
May
be sent by any account.
# Technical Description
Rotate the `account`'s `DiemAccount::DiemAccount` `authentication_... | 6235409d0232e29d42de22a7bec2285adfd0db38 | 5,591 |
def retrieval_visualizations(model, savefig=True):
"""
Plots incremental retrieval contexts and supports, as heatmaps, and prints recalled items.
**Required model attributes**:
- item_count: specifies number of items encoded into memory
- context: vector representing an internal contextual state
... | 96c4534a5e3057fb1bfd15068eec8cc61767c01d | 5,592 |
from pathlib import Path
def get_force_charge() -> str:
"""
Gets the command object for the force charge command
Returns:
The command object as a json string
"""
force_charge = Path('force_charge.json').read_text()
return force_charge | c67277c62664419c3b4a19ae57ea6de027c60416 | 5,593 |
def prune_motifs(ts, sorted_dic_list, r):
"""
:param ts: 1-dimensional time-series either resulting from the PCA method or the original 1-dimensional time-series
:type ts: 1d array
:param sorted_dic_list: list of motif dictionaries returned from the emd algorithm, ordered by relevance
:type sorted_... | 4fef0a51da25503548f6df59e09705c731a7fc6c | 5,594 |
def xor_columns(col, parity):
""" XOR a column with the parity values from the state """
result = []
for i in range(len(col)):
result.append(col[i] ^ parity[i])
return result | 2eff4dbf3edf2b97410e7bef17c043a30b1f3aa8 | 5,595 |
def initiate_default_resource_metadata(aws_resource):
"""
:type aws_resource: BaseAWSObject
"""
if not isinstance(aws_resource, BaseAWSObject):
raise TypeError
try:
metadata = aws_resource.Metadata
if not isinstance(metadata, dict):
raise TypeError("`troposphere.... | 4a510dd5a69f2499b407396f34818c79eead7c6a | 5,596 |
def token_vault_single(chain, team_multisig, token, freeze_ends_at, token_vault_balances) -> Contract:
"""Another token vault deployment with a single customer."""
total = 1000
args = [
team_multisig,
freeze_ends_at,
token.address,
total,
0 # Disable the tap
]
... | b42857cb7becacde9d5638f18f6dd7625eabb182 | 5,597 |
import re
from typing import OrderedDict
def read_eep_track(fp, colnames=None):
""" read MIST eep tracks """
# read lines
f = open(fp, "r+")
s = f.readlines()
# get info
MIST_version = re.split(r"\s+", s[0].strip())[-1]
MESA_revision = re.split(r"\s*", s[1].strip())[-1]
Yinit, Zinit,... | 551c8e5ba05aec5f32d9184398427fb003db78ba | 5,599 |
def create_model():
"""ResNet34 inspired analog model.
Returns:
nn.Modules: created model
"""
block_per_layers = (3, 4, 6, 3)
base_channel = 16
channel = (base_channel, 2*base_channel, 4*base_channel)
l0 = nn.Sequential(
nn.Conv2d(3, channel[0], kernel_size=3, stride=1, pad... | fa9157c457b31b8bd0c3ca0b5dac8f68734486ec | 5,601 |
from typing import Union
from typing import Optional
def kv_get(key: Union[str, bytes],
*,
namespace: Optional[str] = None) -> bytes:
"""Fetch the value of a binary key."""
if isinstance(key, str):
key = key.encode()
assert isinstance(key, bytes)
retu... | 03be836a3d42f39f2b28b2f3ea557cdf39918bcd | 5,602 |
def construct_model(data, local_settings, covariate_multipliers, covariate_data_spec):
"""Makes a Cascade model from EpiViz-AT settings and data.
Args:
data: An object with both ``age_specific_death_rate`` and ``locations``.
local_settings: A settings object from ``cascade_plan``.
covar... | eb4287dcaceb1cf320bf8761143c96ffadc148b2 | 5,603 |
def set_off():
"""
Turns OFF the lamp.
"""
unicorn.set_status(False)
return OK | e82ab948a1656c343237a11e048c1ed38487353b | 5,604 |
def get_all_active_bets():
"""
Gets all the active bets for all
active discord ritoman users
"""
return session.query(LoLBets).filter(LoLBets.completed == false()).all() | 844b36b695bf67db3cff82711b9e17da3db20c8e | 5,605 |
def get_quantize_pos_min_diffs(inputs, f_min, f_max, q_min, q_max, bit_width):
"""Get quantize pos which makes min difference between float and quantzed. """
with tf.name_scope("GetQuantizePosMinDiffs"):
min_scale_inv = tf.math.divide(f_min, q_min)
max_scale_inv = tf.math.divide(f_max, q_max)
float_scal... | 63cc0b8ac370513ecfbe3068d02299a3d3016638 | 5,606 |
def _non_string_elements(x):
"""
Simple helper to check that all values of x are string. Returns all non string elements as (position, element).
:param x: Iterable
:return: [(int, !String), ...]
"""
problems = []
for i in range(0, len(x)):
if not isinstance(x[i], str):
p... | 974715622949157693084823a52a88973b51d100 | 5,607 |
from pathlib import Path
def configure_dirs(base_path: str, config_name: str, dataset_name: str) -> str:
"""
Performs configuration of directories for storing vectors
:param base_path:
:param config_name:
:param dataset_name:
:return: Full configuration path
"""
base_path = Path(base_... | b4791f836d0414ed582c3093b3dac1727f82a39c | 5,608 |
def config_entry_version_fixture():
"""Define a config entry version fixture."""
return 2 | cac78c1f02668c95ce918d6219cadd5f08ab21c9 | 5,609 |
def edge_dfs(G, source=None, orientation=None):
"""A directed, depth-first-search of edges in `G`, beginning at `source`.
Yield the edges of G in a depth-first-search order continuing until
all edges are generated.
Parameters
----------
G : graph
A directed/undirected graph/multigraph.... | 8e7f1ba137f0392768e5b814a8898842bf2e5c2f | 5,610 |
import hashlib
async def _md5_by_reading(filepath: str, chunk_size: int = DEFAULT_BUFFER_SIZE) -> str:
"""
Compute md5 of a filepath.
"""
file_hash = hashlib.md5()
async with async_open(filepath, "rb") as reader:
async for chunk in reader.iter_chunked(chunk_size):
file_hash.upd... | d42e3f6ba994bc35c32cab48cdc4b78e44f678d1 | 5,611 |
def client_authenticator_factory(mechanism,password_manager):
"""Create a client authenticator object for given SASL mechanism and
password manager.
:Parameters:
- `mechanism`: name of the SASL mechanism ("PLAIN", "DIGEST-MD5" or "GSSAPI").
- `password_manager`: name of the password manager... | 93fccb21f71a31fed953f6260f5906b240669033 | 5,612 |
def wait_for_cell_data_connection(
log,
ad,
state,
timeout_value=EventDispatcher.DEFAULT_TIMEOUT):
"""Wait for data connection status to be expected value for default
data subscription.
Wait for the data connection status to be DATA_STATE_CONNECTED
or DATA_STATE_D... | f2e2474af757c5a36cb054afe1f429638641f2e6 | 5,613 |
import configparser
def _parse_lists(config_parser: configparser.ConfigParser, section: str = '') -> t.Dict:
"""Parses multiline blocks in *.cfg files as lists."""
config = dict(config_parser.items(section))
for key, val in config.items():
if '/' in val and 'parameters' not in section:
... | d591a9eeb656dff9c4fbbce9964575cd7ce15352 | 5,614 |
def get_filename_pair(filename):
"""
Given the name of a VASF data file (*.rsd) or parameter file (*.rsp) return
a tuple of (parameters_filename, data_filename). It doesn't matter if the
filename is a fully qualified path or not.
- assumes extensions are all caps or all lower
"""
param_file... | f6eb5a64cf472f230c5806447d9c2ee8ae43a71d | 5,615 |
async def get_reposet(client, headers, reposet_id):
"""Get the reposet by id."""
url = f"https://api.athenian.co/v1/reposet/{reposet_id}"
return await do_request(client, url, headers) | b97262bf1f246bc563abe352f1122a9ad61705c3 | 5,616 |
def detect_os_flavour(os_type):
"""Detect Linux flavours and return the current version"""
if os_type:
# linux
try:
return platform.linux_distribution()[0]
except Exception, e:
return None
else:
# windows
return platform.platform() | 4ab3ebec3683fc99a99e70540ea29d049b54347d | 5,618 |
def straightenImage(im, imextent, mvx=1, mvy=None, verbose=0, interpolation=cv2_interpolation):
""" Scale image to make square pixels
Arguments
---------
im: array
input image
imextend: list of 4 floats
coordinates of image region (x0, x1, y0, y1)
mvx, mvy : float
number... | ab46e394011a8a2d9ed8974504e4e28b725ead78 | 5,619 |
import math
def H(r2, H_s, H_d, a_s, a_d, gamma_s, gamma_d, G, v):
"""
"""
pi = math.pi
sqrt = math.sqrt
r = sqrt(r2)
H2_s = H_s**2
H2_d = H_d**2
R2_s = r2 + H2_s
R2_d = r2 + H2_d
alpha_s = 1.0 if gamma_s == 1.0 else 4 * H2_s / (pi*R2_s)
alpha_d = 1.0 if gamma_d == 1.0 ... | 0fa1606212278def22075692a56468d41a8c7a3c | 5,620 |
from datetime import datetime
def parse_time(event_time):
"""Take a string representation of time from the blockchain, and parse it into datetime object."""
return datetime.strptime(event_time, '%Y-%m-%dT%H:%M:%S') | df5af3a20acbeaa8e7424291d26055d3f38219ed | 5,621 |
def addBenchmark(df):
"""Add benchmark to df."""
# Compute the inverse of the distance
distance_inv = (1. / df.filter(regex='^distance*', axis=1)).values
# Extract the value at the nearest station
values = df.filter(regex='value_*', axis=1)
# Compute the benchmark
numer = (distance_inv * ... | 62c63215d622c46bed8200f97ad55b985e2beb20 | 5,623 |
def is_file_like(f):
"""Check to see if ```f``` has a ```read()``` method."""
return hasattr(f, 'read') and callable(f.read) | 9eee8c8f4a6966d1db67fb4aa9149e2fbd390fb9 | 5,624 |
def _string_to_days_since_date(dateStrings, referenceDate='0001-01-01'):
"""
Turn an array-like of date strings into the number of days since the
reference date
"""
dates = [_string_to_datetime(string) for string in dateStrings]
days = _datetime_to_days(dates, referenceDate=referenceDate)
... | 114883cf0f2e48812a580c4cd8ae64671a4fc126 | 5,625 |
def safe_as_int(val, atol=1e-3):
"""
Attempt to safely cast values to integer format.
Parameters
----------
val : scalar or iterable of scalars
Number or container of numbers which are intended to be interpreted as
integers, e.g., for indexing purposes, but which may not carry integ... | cbaff1fb1568fd43a4dd3a7a2054a805788b912c | 5,626 |
def check_protocol(protocol):
"""
Check if a given protocol works by computing the qubit excitation probabilities
"""
qubit_weight = {}
qubit_weight[protocol[0][0][0]] = 1.0
for pair_set in protocol:
for i, j, p in pair_set:
qubit_weight[j] = qubit_weight[i] * (1.0 - p)
... | 8b9d0a8e329a340718d37bc79066be4a05cf2d20 | 5,627 |
def detachVolume(**kargs):
""" detachVolume your Additional Volume
* Args:
- zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2]
- id(String, Required) : Volume disk ID
* Examples : print(server.detachVolume(zone='KR-M', id='7f933f86-e8bf-4600-9423-09e8f1c84460'))
"""
my_apikey,... | 9c837559052fb41f4e40d18c211a497c7de3ca63 | 5,628 |
from typing import List
from typing import Type
from typing import Optional
from typing import Dict
from typing import Any
from typing import Callable
import time
import traceback
def observe(metric: str,
accept_on: List[Type[Exception]] = [], # pylint: disable=E1136
decline_on: List[Type[Exc... | 501fbaf8b4b3f77e334d7579834162f0393d1b5d | 5,629 |
import numpy
def spherical_to_cartesian(lons, lats, depths):
"""
Return the position vectors (in Cartesian coordinates) of list of spherical
coordinates.
For equations see: http://mathworld.wolfram.com/SphericalCoordinates.html.
Parameters are components of spherical coordinates in a form of sca... | 107899c23eeb7fb2cf79fbaa6650b4584543260a | 5,631 |
import time
def get_remote_webdriver(hub_url, browser, browser_ver, test_name):
"""
This functions returns remote web-driver instance created in selenoid
machine.
:param hub_url
:param browser: browser name
:param browser_ver: version for browser
:param test_name: test name
:return: re... | 2f467f38f2fda6e7f95343e842ea42c3bb551181 | 5,632 |
def process_images(rel_root_path, item_type, item_ids, skip_test, split_attr,
gen_image_specs_func, trafo_image_func,
trafo_image_extra_kwargs=None, img_obj_type=None,
img_attr=None, dimensions=(256, 256),
max_valset_size=10000):
"""
Th... | 9d9d6d53ed6a93c2c8b3f7c70d6cda54277b42b1 | 5,633 |
from typing import Callable
def get_transform_dict(args, strong_aug: Callable):
"""
Generates dictionary with transforms for all datasets
Parameters
----------
args: argparse.Namespace
Namespace object that contains all command line arguments with their corresponding values
strong_aug... | 17ecc3ee611a9fa73176f9a9f354e293d7e4cc39 | 5,635 |
def choose_first_not_none(*args):
""" Choose first non None alternative in args.
:param args: alternative list
:return: the first non None alternative.
"""
for a in args:
if a is not None:
return a
return None | fe3efba85251161cd0a6ecb50583cc443cd04dc0 | 5,636 |
def _format_compact(value, short=True):
"""Compact number formatting using proper suffixes based on magnitude.
Compact number formatting has slightly idiosyncratic behavior mainly due to
two rules. First, if the value is below 1000, the formatting should just be a
2 digit decimal formatting. Second, the number... | 3f2a2b034cbe1e8a3f21ded743ec328a692cc039 | 5,637 |
def matrix(mat,nrow=1,ncol=1,byrow=False):
"""Given a two dimensional array, write the array in a matrix form"""
nr=len(mat)
rscript='m<-matrix(data=c('
try:
nc=len(mat[0])
for m in mat:
rscript+=str(m)[1:-1]+ ', '
rscript=rscript[:-2]+'), nrow=%d, ncol=%d, by... | a28d91d797238857dd2ff58f24655504a936d4a7 | 5,638 |
from re import T
def all(x, axis=None, keepdims=False):
"""Bitwise reduction (logical AND).
"""
return T.all(x, axis=axis, keepdims=keepdims) | b01891385c2b41d42b976beaf0ee8922b632d705 | 5,639 |
def config_find_permitted(cookie, dn, in_class_id, in_filter, in_hierarchical=YesOrNo.FALSE):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("ConfigFindPermitted")
method.cookie = cookie
method.dn = dn
method.in_class_id = in_class_id
method.in_filter = in_filter
method.... | 0367fb6d208b4a03ea4c1cc79e14faabe038cba6 | 5,640 |
def reformat_medication_statuses(data: FilteredData) -> FilteredData:
"""
Reformats medication statuses to binary indicators.
Args:
data: The data containing medication statuses to reformat.
Returns:
Data with reformatted medication statuses.
"""
for j in data.medications.colu... | 4428d7e65893dfea33490de28e77dffe66562c31 | 5,641 |
import json
def list_daemons(dut):
"""Get daemon table from ovsdb-server."""
daemon_list = {}
c = ovs_vsctl + "--format json list daemon"
out = dut(c, shell="bash")
json_out = json.loads(out)['data']
# The output is in the following format
# [["uuid","19b943b0-096c-4d7c-bc0c-5b6ac2f83014"... | 35b28e8c38cd48a93f642b0e2820d0ff2ff87450 | 5,643 |
import math
import collections
def Cleanse(obj, encoding="utf-8"):
"""Makes Python object appropriate for JSON serialization.
- Replaces instances of Infinity/-Infinity/NaN with strings.
- Turns byte strings into unicode strings.
- Turns sets into sorted lists.
- Turns tuples into lists.
Arg... | e50e44bd3aa685838ea2e68537e2df288e9a058f | 5,644 |
import time
def wait_no_exception(lfunction, exc_class=None, exc_matcher=None):
"""Stops waiting on success."""
start_time = time.time()
if exc_matcher is not None:
exc_class = boto.exception.BotoServerError
if exc_class is None:
exc_class = BaseException
while True:
resul... | be5e9798570dd3f6ca6f9b78d136179f68a4ad3c | 5,645 |
def testapp(app, init_database):
"""Create Webtest app."""
testapp = TestApp(app)
#testapp = TestApp(app, extra_environ=dict(REMOTE_USE='test'))
# testapp.set_authorization(('Basic', (app.config['USERNAME'],app.config['PASSWORD'])))
# testapp.get_authorization()
return testapp | 01a579ae22c0eedfaac7d6dd5aeffd1b63f34612 | 5,646 |
def dois(self, key, value):
"""Translates dois fields."""
_identifiers = self.get("identifiers", [])
for v in force_list(value):
material = mapping(
MATERIALS,
clean_val("q", v, str, transform="lower"),
raise_exception=True,
)
doi = {
"... | b7635815c451856d249feebeb1084ad28f0357d9 | 5,647 |
def transition(src,
dest,
state=None,
permissions=None,
required=None,
commit_record=True,
**kwargs):
"""Decorator that marks the wrapped function as a state transition.
:params parameters for transition object, see docum... | 309ffca49c2dd2af4dabb084c5f642d40e9d34e8 | 5,648 |
def get_html(url):
"""Returns HTML object based on given Gumtree URL.
:param url: Offer URL.
:return: Offer HTML object.
"""
session = HTMLSession()
try:
r = session.get(url)
return r.html
except ParserError:
return None | 6fd3aa8e7f2ff81f912e0d7050872a6e2de14827 | 5,649 |
def _get_lattice_parameters(lattice):
"""Return basis vector lengths
Parameters
----------
lattice : array_like
Basis vectors given as column vectors
shape=(3, 3), dtype='double'
Returns
-------
ndarray, shape=(3,), dtype='double'
"""
return np.array(np.sqrt(np.do... | 405111d5052307dd995e64c2ff7936481db4f34d | 5,650 |
def save_batches(current_memory, id_tmp_dir, batch_num):
"""
batch_num : corresponds to the gradient update number
"""
target_csv = id_tmp_dir + "/batch" + str(batch_num) + ".csv"
obs_copy = deepcopy(current_memory['current_obs'])
reward_copy = deepcopy(current_memory['rewards'])
cur... | 311bf2c1083156dc26acb855f2cc61f142a1586b | 5,651 |
def ikrvea_mm(
reference_point: np.ndarray,
individuals: np.ndarray,
objectives: np.ndarray,
uncertainity: np.ndarray,
problem: MOProblem,
u: int) -> float:
""" Selects the solutions that need to be reevaluated with the original functions.
This model management is based on the following ... | f9959cf7ddfcc2aa3aa2fc8c3062cfb63082b242 | 5,652 |
def homepage(request):
"""Main view of app.
We will display page with few step CTA links?
:param request: WSGIRequest instance
"""
if logged_as_admin(request):
offers = Offer.objects.get_for_administrator()
else:
offers = Offer.objects.get_weightened()
return render(
... | 003e6f86ab09ede87e7f1c86910808c2da9c1e9d | 5,653 |
def add_dict(dct1, dct2):
"""Returns a new dictionaries where the content of the dictionaries `dct1`
and `dct2` are merged together."""
result = dct1.copy()
result.update(dct2)
return result | eba785e4d00534e94c1bdde413603d64e18aac05 | 5,654 |
import tempfile
from pathlib import Path
def edit_temp(contents="", name=""):
"""
Create a temporary file and open it in the system's default editor for the
user to edit. The saved contents of the file will be returned when the
editor is closed.
:param contents: Pre-fill the file with the given t... | 174acda4961cc945b917be6c66d1218d3e46914d | 5,655 |
def _new_primitive_control(
rabi_rotation=None,
azimuthal_angle=0.,
maximum_rabi_rate=2. * np.pi,
**kwargs):
"""
Primitive driven control.
Parameters
----------
rabi_rotation : float, optional
The total rabi rotation to be performed by the driven control.
... | dcaab9ace0269a0404435639d0e9e9e025f1013a | 5,656 |
from typing import Optional
from typing import Any
from typing import Tuple
def check_fit_params(
X: TwoDimArrayLikeType,
y: OneDimArrayLikeType,
sample_weight: Optional[OneDimArrayLikeType] = None,
estimator: Optional[BaseEstimator] = None,
**kwargs: Any
) -> Tuple[TwoDimArrayLikeType, OneDimArra... | f385fb9db06d1bd0ee0a9ecef74fbca8f0754a4d | 5,657 |
async def example_quest(request: web.Request) -> web.Response:
"""
Example quest handler that handles a POST request with a computer science trivia question
:param request: The request object
"""
# Verify that it is a POST request, since that's what this quest is supposed to handle
if request.... | fed5ad72d9343c1fd420d98e638bf3f0de995670 | 5,658 |
def get_record_base_model(type_enum):
"""Return the dimension model class for a DimensionType."""
dim_model = _DIMENSION_TO_MODEL.get(type_enum)
if dim_model is None:
raise DSGInvalidDimension(f"no mapping for {type_enum}")
return dim_model | dc232a173ea92bcb6ee2bafcd9eeae46862da5ec | 5,660 |
from io import StringIO
def sas_to_pandas(sas_code, wrds_id, fpath):
"""Function that runs SAS code on WRDS or local server
and returns a Pandas data frame."""
p = get_process(sas_code, wrds_id, fpath)
if wrds_id:
df = pd.read_csv(StringIO(p.read().decode('utf-8')))
else:
df = pd... | 50806526e1f44e58c227472ced3b5884d8b9f2d5 | 5,662 |
def _client_ip_address(request):
"""Return client ip address for flask `request`.
"""
if request.headers.getlist("X-PNG-Query-For"):
ip_addr = request.headers.getlist("X-PNG-Query-For")[0]
if ip_addr.startswith('::ffff:'):
ip_addr = ip_addr[7:]
elif request.headers.getlist("... | eb1b41ee707bac5aefaacdbb1958cd26a47fe288 | 5,664 |
def create_bb_points(vehicle):
"""
Extract the eight vertices of the bounding box from the vehicle.
Parameters
----------
vehicle : opencda object
Opencda ObstacleVehicle that has attributes.
Returns
-------
bbx : np.ndarray
3d bounding box, shape:(8, 4).
"""
b... | 2cf2e2b1e9d64a246369ff9b182199ed64fb71b9 | 5,665 |
def featuredrep_set_groups(sender, **kwargs):
"""Set permissions to groups."""
app_label = sender.label
if (isinstance(app_label, basestring) and app_label != 'featuredrep'):
return True
perms = {'can_edit_featured': ['Admin', 'Council', 'Peers'],
'can_delete_featured': ['Admin', '... | 354731d88ed6633d6cd62b73c6d1ea4cae97ca73 | 5,667 |
def download(loc, rem):
"""download rem to loc"""
# does the remote file exist
if not rem.exists():
return ReturnCode.NO_SOURCE
# does the local file exist
# if it doesnt, copy rem to loc, isLogged = False
if not loc.is_file():
return do_copy(rem, loc, False)
# is the local... | ff7421674f97a6923bbee6fa9be27d132d0095e3 | 5,668 |
from utils import publish_event
def read_dict (conf_dict = {}, filename = "SWIM_config"):
"""
Open and read a dictionary of key-value pairs from the file given by
filename. Use the read-in values to augment or update the dictionary passed
in, then return the new dictionary.
"""
try:
... | 655699cf8c0c007c8e66f15a75bf778686c7d8d9 | 5,669 |
def ordinals_to_ordinals(s):
""" Example:
'third' -> '3rd'
Up to 31st (intended for dates)
"""
for val in ordinals.keys():
s = s.replace(val, ordinals[val])
return s | 4d45a9cfa0171a42deaf99d2e34e41dd5be6c96c | 5,670 |
def create_dataframe_schema():
"""
Create dataframe schema
"""
return pd.DataFrame(columns=['Station_id', 'Name']) | 9f15aa5fb72716e0e398554caabafb972261e5ca | 5,671 |
import requests
def shutdown_check_handler():
"""This checks the AWS instance data URL to see if there's a pending
shutdown for the instance.
This is useful for AWS spot instances. If there is a pending shutdown posted
to the instance data URL, we'll use the result of this function break out of
t... | dd5a7c3b3ab856d72afe01a19b2389071c4e70f3 | 5,672 |
def cal_d(date=cal_date.today(), zf=True):
"""
Month, optionally left-padded with zeroes (default: pad)
"""
day_num = "d" if zf else "-d" # optionally zero fill
return date.strftime(f"%{day_num}") | c0501449035c10f3c4b05a8f9088b30d5789f662 | 5,673 |
from typing import Mapping
from typing import Sequence
from typing import Tuple
def get_max_total(map_of_maps: Mapping[Sequence[str], Mapping[Tuple, float]]) -> float:
"""
>>> df = get_sample_df()
>>> get_max_total(calculate_kls_for_attackers(df, [1]))
1.3861419037664793
>>> get_max_total(calculat... | 6480676c3960e36e434dd8b229ddbd840fbcaa7a | 5,674 |
import requests
def get_keeper_token(host: str, username: str, password: str) -> str:
"""Get a temporary auth token from LTD Keeper.
Parameters
----------
host : `str`
Hostname of the LTD Keeper API (e.g., ``'https://keeper.lsst.codes'``).
username : `str`
Username.
password :... | 4c1feb095b3409786c5bac62aed41939f31a1431 | 5,675 |
import json
def edit_comment(post_id, comment_id):
"""Edit a comment from a specific post"""
post = posts.get(post_id)
if not post:
return json.dumps({"error": "Post Not Found"}), 404
comments = post["comments"]
comment = comments.get(comment_id)
if not comment:
return json.d... | dba79ed0bbdbc48b804a5a9f446c289f47606a75 | 5,676 |
def update_transition_dirichlet(
pB, B, actions, qs, qs_prev, lr=1.0, return_numpy=True, factors="all"
):
"""
Update Dirichlet parameters that parameterize the transition model of the generative model
(describing the probabilistic mapping between hidden states over time).
Parameters
----------... | 3b41320f20abee2cec4cfa651d932a388c4595c2 | 5,677 |
def MRP2Euler231(q):
"""
MRP2Euler231(Q)
E = MRP2Euler231(Q) translates the MRP
vector Q into the (2-3-1) euler angle vector E.
"""
return EP2Euler231(MRP2EP(q)) | 09929b4858eb0f8a755b623fa86b6d77333e9f6b | 5,678 |
def get_entry_or_none(base: dict, target, var_type=None):
"""Helper function that returns an entry or None if key is missing.
:param base: dictionary to query.
:param target: target key.
:param var_type: Type of variable this is supposed to be (for casting).
:return: entry or None.
"""
if ... | b3855be0c7d2c3bdd42e57ae959bb97409abe828 | 5,681 |
def group_list(request):
"""
List all gourps, or create a new group.
"""
if request.method == 'GET':
tasks = Group.objects.all()
serializer = GroupSerializer(tasks, many=True)
return Response(serializer.data)
elif request.method == 'POST':
unique_name = request.data.... | 39e3d67aa88008541898aea2d21d5a811ec17699 | 5,682 |
def CreateBooleanSplit(meshesToSplit, meshSplitters, multiple=False):
"""
Splits a set of meshes with another set.
Args:
meshesToSplit (IEnumerable<Mesh>): A list, an array, or any enumerable set of meshes to be split. If this is null, None will be returned.
meshSplitters (IEnumerable<Mesh>... | 56f8956b9cce7bd9467ac23b80a7573a889c05bf | 5,683 |
def template14():
"""Simple ML workflow"""
script = """
## (Enter,datasets)
<< host = chemml
<< function = load_cep_homo
>> smiles 0
>> homo 4
## (Store,file)
<< host = chemml
... | d321d2016f0894d0a0538a09f6bc17f3f690317b | 5,684 |
def get_group_selector(*args):
"""
get_group_selector(grpsel) -> sel_t
Get common selector for a group of segments.
@param grpsel: selector of group segment (C++: sel_t)
@return: common selector of the group or 'grpsel' if no such group is
found
"""
return _ida_segment.get_group_selector(*... | 6b750702186d70f2b21b64c13145d8da7bfd0b9c | 5,685 |
import textwrap
def wrap(text=cert_text) -> str:
"""Wraps the given text using '\n' to fit the desired width."""
wrapped_text = textwrap.fill(text, fit_char())
return wrapped_text | a6e42a7ca8fa78e7be89e31a920e8b3baa95245e | 5,686 |
def encode(data):
"""calls simplejson's encoding stuff with our needs"""
return simplejson.dumps(
data,
cls=CahootsEncoder,
ensure_ascii=False,
encoding='utf8',
indent=4
) | d3577e87b830b17222614d978d78eaa8329843bd | 5,687 |
def SE_HRNet_W48_C(pretrained=False, use_ssld=False, **kwargs):
"""
SE_HRNet_W48_C
Args:
pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
If str, means the path of the pretrained model.
use_ssld: bool=False. Whether using distillatio... | 0204ff852a18e6319c0454c5fd81d748626fcf78 | 5,688 |
from typing import Union
from typing import Any
from typing import List
def manifest(argument: Union[Any, List[Any]], data: bytearray) -> Union[Any, List[Any]]:
"""
Returns the manifestation of a `refinery.lib.argformats.LazyEvaluation`
on the given data. This function can change the data.
"""
if ... | b8c5335494fda972c09a6d1937344783fb91ea80 | 5,689 |
def get_child_hwnd_by_class(hwnd: int, window_class: str) -> int:
"""Enumerates the child windows that belong to the specified parent window by passing the handle to
each child window.
:param hwnd: HWND in decimal
:param window_class: window class name
:return: window handle (HWND)
"""
def... | 0d6b7cb56b483c88305611520e9787ed4321b6ac | 5,690 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.