content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
import pytz
def string_to_datetime(datetime_string):
"""
Should be in the form:
2012-08-29T04:00:00+0000
This is the inverse of datetime_to_string
"""
log.debug("Converting string: %s to datetime", datetime_string)
dt = datetime.strptime(datetime_string, "%Y-... | 03e9682bddfaa3e2d8c8edcf05c8094b87ba4dff | 3,625,800 |
def _process_tce(tce):
"""Processes the light curve for a Kepler TCE and returns an Example proto.
Args:
tce: Row of the input TCE table.
Returns:
A tensorflow.train.Example proto containing TCE features.
"""
all_time, all_flux = preprocess.read_light_curve(tce.kepid,
... | 56fdd0ee3762093398a07d608277a46df9c5e0f9 | 3,625,801 |
def extract_img(size, in_tensor):
"""
Args:
size (int): size of crop
in_tensor (tensor): tensor to be cropped
"""
dim1, dim2 = in_tensor.size()[2:]
in_tensor = in_tensor[:, :, int((dim1-size)/2):int((dim1+size)/2), int((dim2-size)/2):int((dim2+size)/2)]
return in_tensor | 5c167c88aa7c65ca06f46d2795dbcd2af38db71e | 3,625,802 |
def generate_plot_filename(pair, ticker_interval) -> str:
"""
Generate filenames per pair/ticker_interval to be used for storing plots
"""
pair_name = pair.replace("/", "_")
file_name = 'freqtrade-plot-' + pair_name + '-' + ticker_interval + '.html'
logger.info('Generate plot file for %s', pair... | a964a90f441ab8c5a41f96a3e6b23f2e5ff4a535 | 3,625,803 |
def pdm_prepare_weights_vggs(nets, device="cpu"):
"""
Note that we only handle the FC parts and leave the conv layers as is
"""
weights = []
for net_i, net in enumerate(nets):
layer_i = 0
statedict = net.state_dict()
net_weights = []
for i, (k,v) in enumerate(stated... | 5452976b68fb006f154c762e8f29a7dc776b191a | 3,625,804 |
def fmod2p(x):
""" Floating point modulo 2 pi """
rval = fmod(x, twopi)
if(rval < 0):
rval += 2*pi
return(rval) | e482cc7bc38c7e73471fe71072bd1923cb6f634e | 3,625,805 |
import math
import copy
def plan_cartesian_path_lin(move_arm, wpose, length, alpha, z_start, cs):
"""
:type move_arm: class 'moveit_commander.move_group.MoveGroupCommander'
:type length: float
:type alpha: float
"""
move_arm.set_start_state(cs)
waypoints = []
wpose.position.x += length*math.cos(alpha... | e064ff6239fd7bb6b29d4c210ef94956219b5165 | 3,625,806 |
def channelRelease(BaRange_presence=0, GroupChannelDescription_presence=0,
GroupCipherKeyNumber_presence=0, GprsResumption_presence=0,
BaListPref_presence=0):
"""CHANNEL RELEASE Section 9.1.7"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0xD) # 00001101
c = RrCause(... | df61fa49197211af871a08ed93e9d5a5e99ff04b | 3,625,807 |
def gemm_quantized_impl(M, N, K, unroll, interleave, data_type="uint8"):
"""Assembly implementation of a blocked gemv. Given
a block a of shape (4, k) and a block b' of shape (4, k)
produces the output block c = a*b of shape (4,4)"""
stepA = min(4, M)
stepB = min(4, N)
assert data_type in ["uin... | f688886a9c7e70b2408376b5e00521ac3b8522ff | 3,625,808 |
def get_key(h5, songidx=0):
"""
Get key from a HDF5 song file, by default the first song in it
"""
return h5.root.analysis.songs.cols.key[songidx] | 94524a97ccd6013db5228a7d20bd2435b4e781b8 | 3,625,809 |
import typing
def get_driver_for_browser(
browser: str = "Chrome",
) -> typing.Union[webdriver.Firefox, webdriver.Chrome]:
"""get_driver_for_browser
Args:
browser: Browser Name required for Test. Support "Firefox" and "Chrome".
Defaults to Chrome.
Returns:
Based on user-provide... | 2bc12f2871174ab1a22b2c1523d628fb4676e72b | 3,625,810 |
import sys
def get_rapt_token(
request, client_id, client_secret, refresh_token, token_uri, scopes=None
):
"""Given an http request method and refresh_token, get rapt token.
Args:
request (google.auth.transport.Request): A callable used to make
HTTP requests.
client_id (str): ... | 42cd1667f56a6de98a4bce1620f4c8b0bb292653 | 3,625,811 |
import requests
import json
def get_dev_vlans(devId):
"""Function takes input of devID to issue RESTUL call to HP IMC
:param devId: requires devId as the only input parameter
:return: list dictionaries of existing vlans on the devices. Device must be supported in HP IMC platform VLAN manager module
""... | 6f05eb52c2ac5e272b2e1bc1227a110c57a83334 | 3,625,812 |
def read_create_database_object(path: str, filename: str, data_dict: dict):
"""
Returns a dataframe based on existing files or by creating a new one
:param path: str
:param filename: str
:param data_dict: dict
:return: df
"""
try:
# check if an excel file is available
df = pd.read_excel(path + ... | f867456b14f88621351339a774bb363feebad37e | 3,625,813 |
import torch
def reset_replicate(ridx, assign_obj, reg_out, max_steps=10, accept_tol=1e-3):
"""Re-initialize a given replicate by cooperative re-initialization (CoRe).
On each iteration, we first find the best candidate from the set of all rk
clusters to add to the current replicate. We then find the best of th... | a23b393f62b5dd3d95dcca2ca2ee450bb2f55075 | 3,625,814 |
import re
def get_vulnerability(vulnerability_name_file, logger=structlog.get_logger()):
"""
Parse name of threat from given parameter(file)
:param vulnerability_name_file: string to parse from
:param logger: logger for the method
:return: name of threat
"""
pattern = r'^\d{4}-\d{2}-\d{2}-... | 68bcc0fa5d56d5682413c6dfd8592063652cd40e | 3,625,815 |
def t2d(twt, data, td_depth, td_twt, target_depth):
"""
Convenience function for converting a well log from depth to time given
time-depth pairs. This function both converts from time to depth and
resamples the log data to a regular sampling rate in depth.
"""
f1 = interp1d(td_twt, td_depth, k... | 501f42408a517ba39e726dee893dac8e69252505 | 3,625,816 |
from numpy import asarray, mean
def r_precision(r):
"""Score is precision after all relevant documents have been retrieved
Relevance is binary (nonzero is relevant).
>>> r = [0, 0, 1]
>>> r_precision(r)
0.33333333333333331
>>> r = [0, 1, 0]
>>> r_precision(r)
0.5
>>> r = [1, 0, 0... | 37467e1e02284e16a82a3dad6e0e5c14a0afcad3 | 3,625,817 |
def vector_to_symmetric_mat_4(vec):
"""Builds a symmetric 4x4 matrix using the elements specified in a vector.
The elements are copied first to the first row, in order, then to the second
row, starting from the element on the diagonal, and so on.
"""
A = np.zeros((4, 4))
# Fill the top-right tr... | 8155c0a03617ce199f5de3148f9181592ed5f0ec | 3,625,818 |
def list_tags_containing(s):
"""return list of tag records wherein tag's name contains substring
s: str, substring to search for
"""
cue(records)
req("TAG", lambda tag: s in tag)
srt(CREATED)
return val() | 27dbb15ddedd145b181fd97327620dc0e4c5ad03 | 3,625,819 |
import tqdm
import torch
def eval(model : nn.Module, valset, truedicts, n, r, batch_size=16, hitsat=[1, 3, 10], filter_candidates=True, verbose=False, elbo=True):
"""
Evaluates a triple scoring model. Does the sorting in a single, GPU-accelerated operation.
:param model:
:param val_set:
:param all... | ecf764a5def00b24978b833160f35bc3b26e04b1 | 3,625,820 |
import functools
def accepts(*types):
"""
Checks argument types.
"""
def decorator(f):
assert len(types) == f.__code__.co_argcount
@functools.wraps(f)
def wrapper(*args, **kwds):
for (a, t) in zip(args, types):
assert isinstance(a, t), "The input arg... | 26dd256b466659400898972eea0a19391433be87 | 3,625,821 |
def is_void_pointer( type ):
"""returns True, if type represents C{void*}, False otherwise"""
return is_same( type, cpptypes.pointer_t( cpptypes.void_t() ) ) | 504b81728b7e99311fcce1dcd83f0f326bdc3850 | 3,625,822 |
def pass_down(L,L1,map):
"""map maps L into L1.Populate L1 with values in L"""
## print len(L),len(L1),len(map),max(map)
## print sumsize(L)
## print sumsize(L1)
for j in range(len(map)):
if L[j] == -1:
continue
assert L1[map[j]] == -1 or L1[map[j]] == L[j], 'L... | 6896de91a37a29d1f0e360f410d83065b7434fc7 | 3,625,823 |
def parse_correctness_stats(filename):
"""
Parse the results returned from get_Correctness.sh
"""
results = []
stats_file = open(filename, 'r')
line = stats_file.readline()
while not line.startswith('Reference:'):
line = stats_file.readline()
# Add Reference bases.
result... | 8ac0ff9307169726597bd6bce632560faaed6b3b | 3,625,824 |
def are_equal_pyxb(a_pyxb, b_pyxb):
"""Normalize and compare PyXB objects for equality.
Args:
a_pyxb: PyXB object
b_pyxb: PyXB object
PyXB objects to compare for equality.
Returns:
bool: ``True`` if the PyXB objects are semantically equivalent.
"""
return are_equal_xml(a... | 104bdf1e07aabfcf1e58c1c2c526a0868f501a62 | 3,625,825 |
def compute_misses(n_misses, n_subj):
""" This function computes descriptive statistics of missed trials
:param n_misses: Number of missed trials
:param n_subj: Number of participants
:return: n_misses_min: Minimum of misses
n_misses_max: Maximum of misses
n_misses_mean: Mean ... | ad342d4439486db27bbcc48f3f1dd9f601a23be6 | 3,625,826 |
def courses_():
"""
Render form to register a student to a course, then save the IDs of the student and course to StudentCourses table
:return: redirection to student homepage if successful, else html for course form
"""
return_403('lecturer_id')
form = CourseForm()
form.reg_num.data = Stude... | 922a48eb5283e1c855186f8210b3dbd43e685a14 | 3,625,827 |
def three_phase_to_ground(distgrid,node_name,Df=False, zc=0+0j):
"""
Calculates the three-phase-grounded short circuit
Parameters
----------
distgrid: mygrid.grid.DistGrid
node_name: str
The name of node fault
fs: str
Designates which phases participate in the short circuit
Options: 'Iab', 'Iac', 'Ibc' a... | e0d1bf58bbaa63e840610f5150b0181c3735559d | 3,625,828 |
def _get_sender(*sender_params, **kwargs):
"""
Utility function acting as a Sender factory - ensures senders don't get
created twice of more for the same target server
"""
notify_func = kwargs['notify_func']
with _sender_instances_lock:
existing_sender = _sender_instances.get(sender_para... | 2411e35ca0d0399446beb3cbc1033882b3fd99f6 | 3,625,829 |
import os
def _simple_execution(cmd):
"""
Shell simple execution
Return only exit status (0 : Good)
"""
return os.system(cmd) | 5024f01e82f5da218cc4c6ec4a3c2086b588939c | 3,625,830 |
def whereSubseq(conditionFunc, seq, length, overlap=False):
"""
>>> a = [1, 3, 2, 3, 2]
>>> b = [1, 2]
>>> whereSubseq(lambda seq: seq == b, a, 2)
[]
>>> c = [3, 2]
>>> whereSubseq(lambda seq: seq == c, a, 2)
[1, 3]
>>> whereSubseq(lambda seq: sum(seq) < 8, a, 3)
[0]
>>> whereSubseq(lambda seq: sum(seq) < 8,... | f25ded43f91b4ecc05fa28e81095996f4d036418 | 3,625,831 |
import math
def bearing(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""Calculate bearing from lat1/lon2 to lat2/lon2
Arguments:
lat1 {float} -- Start latitude
lon1 {float} -- Start longitude
lat2 {float} -- End latitude
lon2 {float} -- End longitude
Retu... | 9148bc2726247cedf8a7de7279dac47316f2864f | 3,625,832 |
import threading
def get_thread_uuid(thread=None):
"""
Assigns and returns a UUID to our thread, since thread.ident can be recycled.
The UUID is used in mapping child threads to their parent threads.
"""
if not thread:
thread = threading.current_thread()
ident = thread.ident
try:
... | 5d488dffab783fd42512ea0861efd14c8d47f20f | 3,625,833 |
from s3 import S3LocationSelector, S3SQLCustomForm#, S3SQLInlineComponent
from s3 import S3DateFilter, \
from s3 import S3LocationSelector, S3SQLCustomForm#, S3SQLInlineComponent
from s3 import S3DateFilter, \
from s3 import S3SQLCustomForm, S3SQLInlineComponent
def config(settings):
"""
Template settings... | 7f0475d4e52ec7f2f591d456be02556a99a0975a | 3,625,834 |
def juggle_axes(xs, ys, zs, zdir):
"""
Reorder coordinates so that 2D xs, ys can be plotted in the plane
orthogonal to zdir. zdir is normally x, y or z. However, if zdir
starts with a '-' it is interpreted as a compensation for rotate_axes.
"""
if zdir == 'x':
return zs, xs, ys
elif ... | 5ca9cbc3557f8ceea92524d5ddc76da86e4da0eb | 3,625,835 |
import torch
def compute_loss_function(pz, z, pys, ys, ldj, args):
"""
Computes the cross entropy loss function while summing over batch dimension, not averaged!
:param x_logit: shape: (batch_size, num_classes * num_channels, pixel_width, pixel_height), real valued logits
:param x: shape (batchsize, n... | b310306c69051fc9b2f6664fd227f42fd39c9462 | 3,625,836 |
import re
def _filterargs(source):
"""Juice from a source file the four args needed by decoder."""
argsregex = (r"}\('(.*)', *(\d+), *(\d+), *'(.*)'\."
r"split\('\|'\), *(\d+), *(.*)\)\)")
args = re.search(argsregex, source).groups()
try:
return args[0], args[3].split('|'), in... | 9b719e156a7740ebce7683489d4182f937ca2de8 | 3,625,837 |
def get_title(reg_doc):
""" Extract the title of the regulation. """
parent = reg_doc.xpath('//PART/HD')[0]
title = parent.text
return title | 744759addf0cea3ba6cc3dadad05d535b66b20d6 | 3,625,838 |
import requests
import json
def requires_auth(permission=None):
"""
Decorator which checks if the user is logged in and has the requested permission, and give the user to the function
"""
# Define the decorator
def decorator(f):
# Define the decorated function
def decorated():
... | cd53c09c537920538737a8ab956ca08746e9f0e8 | 3,625,839 |
from pathlib import Path
import re
def load_dataset(img_path, txt_path, img_shape=(64, 64, 3), split_rate=0.1):
"""
Function: load_dataset
Input: img_path: image directory path,
txt_path: caption directory path,
img_shape: image shape array
Output: NumPy array
"""
print('Acquiring images & labels...'... | c16376d4b9bbef5a7daedb42e2ec4519ea7168c6 | 3,625,840 |
import random
import requests
def get_rising_submissions(subreddit):
"""Connects to the Reddit API and queries the top rising submission
from the specified subreddit.
Parameters
----------
subreddit : str
The name of the subreddit without forward slashes.
Returns
-------
... | 115edc8986acdefbb232218d237bcba7320db9a0 | 3,625,841 |
def print_last_rows():
"""
Get the last rows from the sheet.
Return the last row in the worksheet which contains data.
"""
global last_row_index
global worksheet
last_row = None
count=int(config['INTERFACE']['DisplayRows'])
row_index_from = last_row_index - count if (last_row_inde... | d1288b9b33e300ce15620c05f9db3b841ef6c01a | 3,625,842 |
def _OpenFileInSplitIfNeeded( filepath ):
"""Ensure that the supplied filepath is open in a visible window, opening a
new split if required. Returns the buffer number of the file and an indication
of whether or not a new split was opened.
If the supplied filename is already open in a visible window, return jus... | 4e6b842bb629679dfed73154c64c52346f26b071 | 3,625,843 |
from re import DEBUG
import re
def blockstack_tor_resolve( name ):
"""
Given the name (a blockchain ID), resolve it to a .onion address.
The blockchain ID's zone file must have a TXT record called 'tor',
and its text data should be a .onion address. There should be exactly
one 'tor' name.
Re... | 47544b9c170e2b101f9b9e7b307b649757ba1ab4 | 3,625,844 |
import uuid
def sqlalchemy_instance_model_extra(sqlalchemy_session_factory):
"""
Create session-wide database.
"""
sqlalchemy_session = sqlalchemy_session_factory()
# Instances
instance_1 = InstanceModel(id=str(uuid.uuid4()),
class_path='tests.unit_tests.agents.... | b99f65a36e7c87a765cd5533e0e940779d4794c3 | 3,625,845 |
from re import A
from typing import Optional
def index(_linked_list : LinkedList[A], idx : int) -> Optional[A]:
""" The element at index idx """
assert idx >= 0
if _linked_list.content is None:
return None
head = _linked_list.content[0]
tail = _linked_list.content[1]
if idx == 0:
... | 13090340b0e9a2dc64a80041546cffd4cfd397b5 | 3,625,846 |
def fetch(input_file: str):
"""Simulates a real API call."""
with open(input_file, 'r') as f:
json = f.read()
pb = json_format.Parse(json, gtfs_realtime_pb2.FeedMessage())
return pb.SerializeToString() | 8270cacb189335dea805b1c6087dfa7b0b36bde0 | 3,625,847 |
def read_surface(filepath):
"""Load in a Freesurfer surface mesh in triangular format."""
with open(filepath, "rb") as fobj:
magic = _fread3(fobj)
if magic == 16777215: # Quad file
nvert = _fread3(fobj)
nquad = _fread3(fobj)
coords = np.fromfile(fobj, ">i2", ... | 9fc791409bb23e01b52cd7283edeb53e011a372a | 3,625,848 |
def E_float2(y, _):
"""Numerically stable implementation of Muller's recurrence."""
return 8 - 15/y | 4e8801465994afcb554e048897ec1ff903385bbe | 3,625,849 |
import os
def get_auth_password():
"""Get from script or backward compatibility"""
password = os.environ.get('HUE_AUTH_PASSWORD')
if password is not None:
return password
password = AUTH_PASSWORD_SCRIPT.get()
if password:
return password
password = os.environ.get('HUE_LDAP_PASSWORD')
if passw... | 325a204a23df9f239ed0ceee47e1678ae3f4dc26 | 3,625,850 |
import copy
def perturbate_single(init_dict, label, value=None):
"""Perturbate a single parameter and fix all other parameters for estimation.
We also set the bounds for the perturbed parameter to its default bounds.
This increases the scope for perturbations.
"""
old_dict = copy.deepcopy(init_di... | 3b181f60af23a63733edab539732820682b0592e | 3,625,851 |
def compute_packet_csum(pkt):
"""Computes the checksum for the given GDB packet"""
csum = 0
for x in pkt:
csum += x
csum = csum & 0xFF
return csum | 29eef2afd1b33ab80013ce7fcd46c3b11c9f639b | 3,625,852 |
def new_headers() -> list:
"""Return list of new headers with clean names."""
return [
"date",
"Rohs FB1",
"Rohs FB2",
"Rohs gesamt",
"TS Rohschlamm",
"Rohs TS Fracht",
"Rohs oTS Fracht",
"Faulschlamm Menge FB1",
"Faulschlamm Menge FB2",
... | c81c38e8521f159f0bbf29b3a32adeaa13d4c38f | 3,625,853 |
def state_to_dictionary(state_tuple):
"""Flatten model state into a dictionary with string keys."""
flattened = {}
for state_number, state_value in enumerate(nest.flatten(state_tuple)):
prefixed_state_name = "{}_{:02d}".format(feature_keys.State.STATE_PREFIX,
state... | 120625257d2f504d1b91e2a8e323a015d406ab4a | 3,625,854 |
import torch
def add_decomposed_rel_pos(attn, q, rel_pos_h, rel_pos_w, q_size, k_size):
"""
Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950
Args:
... | bba5d66dd346108dae992745447e9995335a875e | 3,625,855 |
import copy
def gcc(rdg, tau_threshold=2, **kwargs):
"""Surface detection from relative time delay obtained through generalized
cross-correlation of each contiguous range lines
Parameters
----------
rdg: 2d-array
radargram
Return
------
"""
#---------------
# ... | ecaf1f234f64e71113c6ab0f0a7596d164e543a0 | 3,625,856 |
import hashlib
import io
def calc_file_md5(filepath, chunk_size=None):
"""
Calculate a file's md5 checksum. Use the specified chunk_size for IO or the
default 256KB
:param filepath:
:param chunk_size:
:return:
"""
if chunk_size is None:
chunk_size = 256 * 1024
md5sum = has... | 8f391ade85a5b69ca63d8adb3eff6ff6af7a08e3 | 3,625,857 |
def poll(client, container_name):
"""
poll checks if the jupyterhub-singleuser program is running.
"""
try:
container = client.containers.get(container_name)
except pylxd.exceptions.NotFound:
return 0 # No container => process not running.
if container.status != 'Running':
... | a8a79fb1d78e0bcf669c74c9a111c65e31f10618 | 3,625,858 |
def calculate_pct_poi_msgs(series):
"""calculates the percentage of a potential POI's
total messages that are to or from a POI
Args:
series (pandas.core.series.Series): data series associated with a single POI
Returns:
[pandas.core.series.Series]: data series with the added POI mess... | 857e23204e6eab5db36f23d583613dd19bc7ffd4 | 3,625,859 |
import os
def clear_cache(location):
"""
Remove selected cached data, please run malaya_speech.print_cache() to get path.
Parameters
----------
location : str
Returns
-------
result : boolean
"""
if not isinstance(location, str):
raise ValueError('location must be a ... | 5153594d72bf85933dabb0d0ff9df570a17d9dd7 | 3,625,860 |
import re
def version():
"""
Get the Vagrant version.
"""
with settings(hide('running', 'warnings'), warn_only=True):
res = local('vagrant --version', capture=True)
if res.failed:
return None
line = res.splitlines()[-1]
version = re.match(r'Vagrant (?:v(?:ersion )?)?(.*)', ... | 1167d80b5bf1839c7e156596b6d11b3a6c85a93b | 3,625,861 |
def aggrmem(mems):
"""Aggregates memory information returned from keymem().
If mems is a dict, uses its values() only.
If mems is a list, uses it directly.
Returns a single memory structure, formatted just like keymem():
- keys: list of key names
- types: list of types, corresponding to ... | 687f276c459f1ab5dc29cdc4af6efa698aed9a72 | 3,625,862 |
def create_ir():
"""
Read out the ir to compare it before and after adding a flag from the pass
to the sequence or work with its returnings.
"""
complete_ir = mktemp("-p", local.cwd)
complete_ir = complete_ir.rstrip('\n')
return complete_ir | 572f2db3033f5db58d7b738615bffbf34b15d25d | 3,625,863 |
def _dist_obs_oracle(oracle, query, trn_list):
"""A helper function calculating distances between a feature and frames in oracle."""
a = np.subtract(query, [oracle.f_array[t] for t in trn_list])
return (a * a).sum(axis=1) | affd188fccdaef543521c209386cda1da147347d | 3,625,864 |
import requests
from datetime import datetime
def bond_zh_hs_cov_daily(symbol: str = "sz123111") -> pd.DataFrame:
"""
新浪财经-债券-沪深可转债的历史行情数据, 大量抓取容易封 IP
http://vip.stock.finance.sina.com.cn/mkt/#hskzz_z
:param symbol: 沪深可转债代码; e.g., sh010107
:type symbol: str
:return: 指定沪深可转债代码的日 K 线数据
:rtyp... | 288113406d9d564ebaf68a75f4c46bb88ad9e3db | 3,625,865 |
def predict_m(m, f, g, c0, alpha, B, pv, e, mu, R, eta):
"""
Calculate a predicted m given an input m. The idea is that we can iterate until they match.
Inputs:
parameters, m
Outputs:
predicted m
predicted establishment fraction
predicted mutation rate
predicted mean time ... | 234b153984f8a4cd6b03fa61c48bdab16411eca3 | 3,625,866 |
def msg_encoder( encoding=None ):
""" 返回一个 with a pair of functions to encode/decode 消息 的命名元组。
如果 encoding 为None , 将返回 a pass through function 。 """
Codec = namedtuple( 'Codec', ['enc','dec'] )
if encoding in (None,False):
l = lambda x : unicode(x)
return Codec(l,l)
else:
... | 45b9351b6961aaaa035a3152c3ea1fc8d3e99a80 | 3,625,867 |
def is_dataframe_column_numeric(dataset : pd.DataFrame, column : str) -> bool:
"""
Return True if column in dataset is float or int (numeric), otherwise False
Parameters
----------
dataset : pandas.DataFrame
the dataframe that contains at least the column "column"
column : str
n... | 86555bcc4245a8d02f8c89fbb487296e15e07b27 | 3,625,868 |
import struct
def dylan_string(value):
"""Assuming value is a Dylan string, return it as a Python str"""
if dylan_is_byte_string(value):
return dylan_byte_string_data(value).decode('utf-8')
elif dylan_is_unicode_string(value):
data = dylan_unicode_string_data(value)
(int_size, data_format) = target_... | 1d4de456907245a34f4bd081aacbdb4a2bc7daed | 3,625,869 |
def read_CUB(train_list_file, test_list_file):
""" Reads and parses examples from CUB dataset """
img_height = 227
img_width = 227
num_val_img = 500 # you can change the number of validation images here
train_img = []
train_label = []
test_img = []
test_label = []
train_img, tra... | 06caf4b58ca108b29f87031c0b62072962009639 | 3,625,870 |
def mediatailor_configuration_ddb_items(region):
"""
Retrieve and format MediaTailor configuration for cache storage.
"""
items = []
for config in mediatailor_configurations(region):
arn = config["PlaybackConfigurationArn"]
service = "mediatailor-configuration"
items.append(n... | cce7cf86ff04a811f7afd8500cc97f9d22146264 | 3,625,871 |
def parse_user_input(req):
"""Helper function to parse the information received by spark."""
http_method = None
if req.method == "GET":
fake_json = {
"roomType": "direct",
"created": "2016-12-02T23:27:30.199Z",
"personId": "Y2lzY29zcGFyazovL3VzL1BFT1BMRS82NmVjMDkyNi0zO... | cb71c846e17045f955ba19ef2b64b458626af163 | 3,625,872 |
def validate(ticket):
"""
Will attempt to validate the ticket. If validation fails, then False
is returned. If validation is successful, then True is returned
and the validated username is saved in the session under the
key `CAS_USERNAME_SESSION_KEY` while tha validated attributes dictionary
is ... | 8b6c1f0b23eaa9004973e0b7be102e088b02dba5 | 3,625,873 |
from typing import Tuple
def network_to_bandwidth_range(network_type: NetworkType, network_speed: NetworkSpeed) -> Tuple[int, int]:
""" Returns the (low, high) bandwidth range in kbps for the given network type """
network_bandwidth_map = {
NetworkType.WIRED: {NetworkSpeed.FAST: (48000, 96000), Networ... | 156e30f435f14fcd06e23d873fb3b2d338f72db7 | 3,625,874 |
import os
import sys
def open_session(file_location=None, base_url=DEFAULT_BASE_URL):
"""Open Session File or URL.
Open a session file or URL. This will clear all networks, tables and styles associated with current
session. Be sure to ``saveSession`` first.
Args:
file_location (str): File pa... | 2ee962a0a7df3f47a975d8bc34e50fd4d6737641 | 3,625,875 |
def hex_to_uint(hex_string: str) -> Uint:
"""
Convert hex string to Uint.
Parameters
----------
hex_string :
The hexadecimal string to be converted to Uint.
Returns
-------
converted : `Uint`
The unsigned integer obtained from the given hexadecimal string.
"""
r... | d9c66d44cc420678c5db90bdeb79e29c0077abe0 | 3,625,876 |
import struct
def _read_int(f, b):
"""
Read an integer of a specified number of bytes from the filestream f
"""
if b == 1:
return struct.unpack('<B', f.read(b))[0]
elif b == 2:
return struct.unpack('<H', f.read(b))[0]
elif b == 4:
return struct.unpack('<I', f.read(b))[0... | 36bcc2ccd4edd61fd9c6a438c3a069e699b7b17a | 3,625,877 |
def order_auditable_fields_at_end(field):
"""
Sort Condition for Auditable Fields
:param field:
:return:
"""
if field in AUDITABLE_FIELDS:
return 2 if field == LAST_FIELD else 1
return 0 | 2f08b0b62081fd3ba323fe8a0e6a70aea832b534 | 3,625,878 |
def led_pwm_handler(frequency=None, duty_cycle=None):
"""
Change PWM frequency and/or duty cycle for LED.
Optional arguments:
- frequency (float): Change to frequency in Hz.
- duty_cycle (float): Change to duty cycle in percent.
"""
ret = {}
if frequency != None:
led_pwm.C... | 6bd092b38b34a587a1809b23223e9d21f20d8037 | 3,625,879 |
def get_module_list(username, bk_biz_id, kwargs=None):
"""
@summary: 查询模块
@param kwargs:
@param username: 执行用户名
@param bk_biz_id: 业务id
@return: [{'bk_module_id':'', 'bk_module_name':''}...]
"""
client = get_client_by_user(username)
params = {
"bk_biz_id": bk_biz_id,
}
... | a7653de4f8bdb30c725962d0c57d7fa06300b480 | 3,625,880 |
def _visualize_feature_correlations(feature_correlations, figsize=(16,12), cmap="coolwarm", annot=True,
fmt=".2f", linewidths=.05):
"""
Visualizes the feature correlations of a training dataset or feature group in the featurestore
Args:
:feature_correlations: th... | 3a2a6c8783c543363bbfb13ddc4945c60654cf24 | 3,625,881 |
from typing import Optional
def get_level(env_level: Optional[str]) -> Optional[int]:
"""
Convert user-entered log level to a numeric one to send to the logger
module.
:param env_level: either log level number or log level name
:return: the associated log level number
"""
if env_level is ... | 00960b6bcb9738a97b3bd06af74e95a539da663f | 3,625,882 |
def select_modality():
"""
modalityを選択する
Returns:
[str]]: selected_modality[0] ["CT", "XR", "ANGIO","PT"]のいずれかひとつ
"""
root = tk.Tk()
root.title("Modalityを選択")
root.geometry("400x300")
M = tk.Label(text='')
label1 = tk.Label(text="Modalityを選択")
label1.pack(padx=5, pady=... | dcc00aea5fe23c34b9c2d9e02bb612eb7de37a79 | 3,625,883 |
import os
import inspect
def make_env(env_fn, env_kwargs, index_col_worker, index_grad_worker, index_env, log_dir=None, info_keywords=(), mode="train"):
"""
Returns a function that handles the creating of a single environment, so it
can be executed in an independent thread.
Parameters
----------
... | f1ed25819af81bf91772d896da9c00e3c5f824da | 3,625,884 |
def getMenuOption():
"""Return the user's option"""
return menu_option | d5af14bded520c180262e4381f05c506b376292b | 3,625,885 |
def calc_transform(src, dst_crs=None, resolution=None, dimensions=None,
src_bounds=None, dst_bounds=None, target_aligned_pixels=False):
"""Output dimensions and transform for a reprojection.
Parameters
------------
src: rasterio.io.DatasetReader
Data source.
dst_crs: rast... | 205615cef142c7d80d323e0ce5673d04506c247e | 3,625,886 |
def usearch_dereplicate_exact_seqs(
fasta_filepath,
output_filepath=None,
minlen=64,
w=64,
slots=16769023,
sizeout=True,
maxrejects=64,
log_name = "derep.log",
usersort=False,
HALT_EXEC=False,
save_intermediate_files=False,
... | 4661c4cdca9f741ae71ca6915706ed7d13b02e4d | 3,625,887 |
def get(remote_path, local_path=None):
"""
Download one or more files from a remote host.
`~fabric.operations.get` returns an iterable containing the absolute paths
to all files downloaded, which will be empty if ``local_path`` was a
StringIO object (see below for more on using StringIO). This obje... | acd00ce91cb32a819767c9cc031106cd40e47f1e | 3,625,888 |
def compare_equality(col_1, col_2):
"""
This function compare the equality of two columns
and output an accuracy percentage
"""
return float(col_1.eq(col_2.values).mean()) | adf6e6bb26988c7ee0211669881b2cd8331838da | 3,625,889 |
def run_SEIR(E0, I0, R0, ds):
"""
Simulate SEIR model using forward euler integration. All states are defined as
fractions of a population. All rates are discrete rates at the timescale of a
signle simulation timestep.
Parameters
----------
E0, I0, R0 : float
Initial condition... | 34b9775b31cc43604b593829251b210359e5676a | 3,625,890 |
def segment_min(data, segment_ids, name=None):
"""
Segment min operator.
This operator calculate the minimum elements of input `data` which with
the same index in `segment_ids`.
It computes a tensor such that $out_i = \\min_{j} data_{j}$
where min is over j such that `segment_ids[j] == i`.
... | 4993d472fbf498c86126d3b5742a6029e3c1f691 | 3,625,891 |
def standardize(df, feature_list, exclude_list):
"""Fit and save StandardScaler and PCA
"""
# Exclude unnecessary columns
df.drop(columns=exclude_list, inplace=True)
# Fit and save standardizer
standard_scaler = StandardScaler()
# standard_scaler.fit(songs_df[feature_list])
standard_fea... | df3252f08df5167c94f9afc0288d28c7007c0426 | 3,625,892 |
import os
import yaml
def plumbing(fn: str) -> Plumbing:
"""
Create a new plumbing instance by parsing yaml from the filename.
:param fn: A filename containing the pipeline.
:return: A plumbing object
This uses the resource framework to locate the yaml file which means that pipelines can be ship... | 004205df3a771d844789619813d462f8b3e41917 | 3,625,893 |
def upgrade(options, version=None, repo_path=None):
"""Upgrade the database's current migration level.
:param options: options dict
:param version: version to upgrade (defaults to latest)
:retval version number
"""
db_version(options, repo_path) # Ensure db is under migration control
repo... | 8cf0f27d884169ff44c2c90ba92d1fdaf6bc6650 | 3,625,894 |
def saveForwardState(old_s_tree, new_s_tree, s):
"""Saving the s_current as well as all its successors in the old_s_tree into the new_s_tree.
Parameters
----------
old_s_tree : dict
The old tree.
new_s_tree : dict
The new tree.
s_current : :py:class:`ast_toolbox.mcts.AdaptiveStr... | 1cf8aeac314c2f224a76d9c91c3bf1a8d54fd9df | 3,625,895 |
def display_volume_group():
"""
this function display the available physical volume
:return: output variable that contains exit code and output string in tuple datatype
"""
cmd = "vgdisplay"
output = sp.getstatusoutput(cmd)
return output | 6b26157369accffb02b9eb4d2944153384433214 | 3,625,896 |
def get_keyable_attributes(object_name=""):
"""
return an array of keyable attributes.
:param object_name:
:return: <list> keyable attributes found for this object.
"""
cnst_attr = Attributes(object_name, keyable=True)
return cnst_attr.keyable.keys() | 2fcc712f72836ba26cf6edf9f81204fec141d172 | 3,625,897 |
def find_pangrams(word_set, depth_max=6, current_words=None):
"""
Find minimal pangrams out of a set of words.
Call with any iterable of words, and it returns a list of pangrams,
if any, sorted by increasing letter count. You can set depth_max to control
search depth if your word set calls for it.
... | 1808f7e84136777d81f3dc0c18084e09efa520c1 | 3,625,898 |
import argparse
def parse_cli():
"""Parse the command line arguments.
"""
parser = argparse.ArgumentParser(
'CLI options take precedence over settings in the yaml file'
'empty arguments are replaced by settings in the default yaml file')
parser.add_argument('-s',
dest='setti... | 46ab879f3b5edd67ecd6ed112256dd85a60723bd | 3,625,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.