content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _zero_out_datetime(dt, unit):
"""To fix a super obnoxious issue where datetrunc (or SQLAlchemy) would
break up resulting values if provided a datetime with nonzero values more
granular than datetrunc expects. Ex. calling datetrunc('hour', ...) with
a datetime such as 2016-09-20 08:12:12.
Note t... | adac3a5c84b0b7def93c044488afb57074cf2d09 | 75,515 |
def fitness_score_distance(id1, id2, to_consider, distance):
"""A value to choose between two resources considering the distance"""
return max(distance(id1,to_consider), distance(to_consider, id2))/distance(id1,id2) | ab6dd14f0e3ac3ef5b26abe3136ff5a61c3b74a5 | 75,516 |
def build_rnn_inference_subgraph(features, reuse, params):
"""Builds the inference subgraph for the RNN.
Args:
features: ({str: Tensor}) The feature tensors provided by the input_fn.
reuse: (bool) Should the variables declared be reused?
params: (dict) Model configuration parameters.
Returns:
(Te... | 8076dd56245af9114fb97d6e5fd5999f6d173622 | 75,517 |
import six
def parse_fetch_response(text, normalise_times=True, uid_is_key=True):
"""Pull apart IMAP FETCH responses as returned by imaplib.
Returns a dictionary, keyed by message ID. Each value a dictionary
keyed by FETCH field type (eg."RFC822").
"""
if text == [None]:
return {}
res... | de36ff2384df4759aeca76ab9e7806cf225274bd | 75,518 |
def _ssh_template():
""" SSH command to log into remote server. """
ssh = Template("""
ssh -q -o ConnectTimeout=10 -o ServerAliveInterval=10 ${user}${server} \
'cd ${remote_dir}; batchgen ${command_file} ${config_file} || \
echo "Error: while executing batchgen."'
""")
return ssh | 2dfb954e10ce46b4ec7eaa3d8634410abafd228b | 75,519 |
from typing import List
from typing import Tuple
def rank_centrality(comparisons: List[Tuple[int, int]], n_objects: int) -> np.ndarray:
"""
Finds an ordering based on pairwise comparison using a random-walk interpretation over
a rank centrality graph.
:param comparisons: A list containing tuples repre... | 750d2e9fccbe6c6f6e0b6bbd70dcad9b202dffe3 | 75,520 |
import psutil
def get_user_processes(user):
"""Get all process for a specific user
Arguments:
user {str} -- username
Returns:
[list(int)] -- list of process pids for that user
"""
result = []
for process in psutil.process_iter():
if process.username() == user:
... | 7bdb2596dcd9452aa956fc57a7c7e0eade177709 | 75,521 |
def create_new_user(username,password):
"""
method to create new user with username and password
"""
new_user = User(username,password)
return new_user | e860a0303bb7065f5a4c859cbef928d10af423dd | 75,522 |
def vtk_output(obj):
""" Configure the input data for vtk pipeline object obj."""
if vtk_old():
return obj.output
return obj.get_output() | eecaa41794b081945ddd2f360176ddecd8158002 | 75,524 |
def is_cst_type(node_type):
"""Judge whether the type is const type."""
return node_type == NodeTypeEnum.CONST.value | 4a96885c1487031fbf52ccd31f59b0223140c6ce | 75,525 |
def visualise_mmd_curve(mmd_curve, loglog=True, ylims=[0.0, 1.0]):
"""Visualise the trace of the mmd score as a function of the size
Given a curve which has mmd_curve[t] = MMD(P, Q_t), visualise
both the normal plot and the log plot.
:param mmd_curve: (np.ndarraym,(stop_t,)) array of mmd scores
:p... | 4237ca54fdd185876fb37b2eda989d5f9c826866 | 75,526 |
def _get_total_seconds(td):
"""
Fixes the missing :meth:`datetime.timedelta.total_seconds()`
method in Python 2.6
"""
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6)\
/ 10**6 | 7c65b7901737a66ac7a66dd7496d2674b842ba5a | 75,527 |
def csv(draw, header=None, columns=None, lines=None, dialect="excel"):
"""
Strategy to produce a CSV string. Uses `data_rows` strategy to generate the values. Refer to the `data_rows`
strategy for more details about the `columns` and `lines` parameter.
:param draw:
:param header: if a list of strin... | f6c27909fada77f2dc3f604ad05f471f559400f6 | 75,528 |
def vroll(vel_1, vel_2):
"""
Calculate the rolling speed in a tribological contact based on contact body
velocities.
Parameters
----------
vel_1: ndarray, scalar
The contact velocity of body 1.
vel_2: ndarray, scalar
The contact velocity of body 2
Returns
-------
... | 27ad9280e7392732981d85c9e33d4a7906daf2fd | 75,529 |
import logging
def delete_entity_recognizer(entity_recognizer_arn: str):
"""[Deletes a Entity Recognizer on AWS]
Args:
entity_recognizer_arn (str): [Unique Identifier for Entity Recognizer]
Raises:
error: [description]
Returns:
[type]: [description]
"""
try:
... | 54c91447f9da59e0de22c663de367715c712b487 | 75,530 |
def pause(api, name):
"""Pause a container"""
path = "/containers/{}/pause".format(api.quote(name))
try:
response = api.post(path, headers={'content-type': 'application/json'})
response.read()
return response.status == HTTPStatus.NO_CONTENT
except errors.NotFoundError as e:
... | 2a469eb73ff4a8c9bcaf2cb710440d4f8abd3164 | 75,531 |
import pandas
def update_context(df_context) -> pandas.DataFrame:
"""replaces unspecified air and water flows for impact categories that
don't rely on sub-compartments for characterization factor selection."""
single_context = ['Freshwater acidification',
'Terrestrial acidification... | 5fb3420e5af4bfd10653b8246c370ab5ed5ec254 | 75,533 |
import math
def ln(x):
"""
x est un nombre strictement positif.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Retourne l'image du nombre x par la fonction logarithme népérien.
"""
return math.log(x) | 3612dce0120c6b8b3d4176f1883ee8fb1694d7f4 | 75,534 |
def expand(M, power):
"""
Applies expansion process to the matrix with the given power.
"""
return np.linalg.matrix_power(M, power) | cabfb0ac39f1a4a3c45bf7797ec8262cb05c5432 | 75,535 |
def OD_to_RGB(OD):
"""
Convert from optical density to RGB
:param OD:
:return:
"""
return (255 * np.exp(-1 * OD)).astype(np.uint8) | 5ba60aef61cb7d8af1713af511cba3731152b02e | 75,536 |
def page_not_found(error):
"""
Error 404 page
"""
doc = {
'title': 'Page not Found',
'header': 'Error: Page not Found',
'sub-head': "The Page requested cannot be found on the server.",
'content': 'This is a test!'
}
app.logger.error("Raising error 404 '%s'", err... | b6dcff6a6a1159d139d078fe98dfdb60b95d9922 | 75,537 |
def by_name(session: Session, instance: Instance, name: str) -> Dataset:
"""Get dataset by name
Fetches dataset from Tamr server
Args:
instance: Tamr instance containing this dataset
name: Dataset name
Raises:
dataset.NotFound: If no dataset could be found with that name.
... | c0c82b207985778649d4b4b0c9b6e4a92a9879f4 | 75,538 |
def read_data(path):
"""Load a sample file containing acquisition days and spectral values.
The first column is assumed to be the day number, subsequent columns
correspond to the day number. This improves readability of large datasets.
Args:
path: location of CSV containing test data
Retu... | 43e066beceddae044dda0d61aa1646a12866c02b | 75,539 |
def bundled_piface(request):
""" Provide an essentially minimal collection of PI config data. """
pipelines = request.getfixturevalue("basic_pipe_iface_data")
return {PROTOMAP_KEY: {"ATAC": "ATACSeq.py"}, PL_KEY: pipelines} | b3d59ea6d7dba03ae2a0449e368916d05b2bd022 | 75,540 |
import requests
import csv
def pred_crop(N,P,K,Ph,lat,long,NaiveBayes):
"""N = input("Enter the Nitrogen ")
P = input("Enter the phosphorous ")
K = input("Enter the potassium ")
Ph = input("Enter the PH value ")
lat = input('lat')
long = input('long')"""
BASE_URL = "https://api.openwea... | 165617cd9b3efddea8d0fabeb2c4b538f75dbd34 | 75,543 |
def asbool(s):
"""
Convert a string to its boolean value
"""
if s.lower() == 'true':
return True
elif s.lower() == 'false':
return False
elif s.isdigit():
return bool(int(s))
else:
raise ValueError('must be integer or boolean: %r' % s) | bbc245fb74648adb113d189ed43af003d40f7cfd | 75,544 |
def remove(S, rack):
"""removes only one instance of a letter in a rack"""
if rack == []:
return []
if S == rack[0]:
return rack[1:]
return [rack[0]] + remove(S, rack[1:]) | 28041197da6a7978dacbfe65d413d4e6fd9c3a03 | 75,545 |
from typing import Iterable
from typing import Any
from typing import Union
from typing import List
def remove_from_iterable(
the_iterable: Iterable[Any], items_to_remove: Iterable[Any]
) -> Union[Iterable[Any], None]:
"""
remove_from_iterable removes any items in items_to_remove from the_iterable.
:... | 9ac800fb69f46c8b65ed2ac73158678b4c0ae7d6 | 75,546 |
def register(func):
"""Register sdk client method as a plug-in"""
plugins[func.__name__] = func
return func | 044854d2425adcfe349461409faf386f00d4cde6 | 75,547 |
def downsampling(inputs, output_shape):
"""downsampling"""
scale_h, scale_w = [int(akg.tvm.truncdiv(inputs.shape[i], output_shape[i])) for i in range(1, 3)]
res = akg.tvm.compute(output_shape, lambda b, h, w, c: inputs[b, h * scale_h, w * scale_w, c], name="downsampling")
return res | f10c18dd1ecfb15290abc8c5cd3a103bb718595b | 75,549 |
def integer_matrix(a):
"""
returns an integer matrix from row vectors.
"""
found = True
b = np.zeros((3, 3))
a = np.array(a)
for i in range(3):
for j in range(1, 2000):
test_v = j * a[i]
if integer_array(test_v):
b[i] = test_v
b... | 0a861430cb2da74885740aa06617828129d6352c | 75,550 |
def import_data(filename):
""" Take data from txt file"""
dataset = list()
with open(filename) as f:
lines = f.readlines()
for line in lines:
dataset.append(line.split())
return dataset | d360506f2015f31b09dbac632427390eca10cf1b | 75,551 |
import string
def parse(description):
""" Parse an ingredient text and insert into measurement/ingredients tables """
measurements = {'teaspoons', 'tablespoons', 'cup', 'cups', 'pints', 'pint', \
'quarts', 'quart', 'ounce', 'ounces', 'dash', 'pinch', 'cube', 'cubes'}
# Remove funky as... | 81afc00cb0e97161b1c8b3dc211191160defe5b8 | 75,552 |
def _datacheck_peakdetect(x_axis, y_axis):
"""Used as part of "peakdetect" """
if x_axis is None:
x_axis = range(len(y_axis))
if len(y_axis) != len(x_axis):
raise ValueError("Input vectors y_axis and x_axis must have same length")
#needs to be a numpy array
y_axis = np.array(y_... | d29db942ab899f5db176fb59d4dec1d03f9f4031 | 75,553 |
def history(config, rev_range=None, verbose=False):
"""List changeset scripts in chronological order."""
script = ScriptDirectory.from_config(config)
if rev_range is not None:
if ":" not in rev_range:
raise util.CommandError(
"History range requires [start]:[end], "
... | 4a6379703768a6d8f8bfed56d985a8fec1352485 | 75,554 |
import re
def validate_seq(seq):
"""Check Dna object sequence property data. Enforce lowercase."""
if not isinstance(seq, str):
raise TypeError('seq must be str.')
if re.match(dna_re,seq) is None:
raise ValueError('seq must only consist only of '+alphabet+'.')
return seq.lower() | 2d7614ec61a778ca2614ec4349cd908f642a146b | 75,555 |
def from_3d_array_to_nested_df(data: np.ndarray,
columns_names: str = None,
cells_as_array: bool = True):
"""Convert Numpy ndarray with shape (nb_samples, series_length, nb_variables)
into nested pandas DataFrame (with time series as numpy array or p... | 3c62760f8c21091ca8ec81f6ee6de940822618b2 | 75,556 |
def to_bytes(data: str):
"""
将unicode字符串转换为bytes
"""
try:
bytes_data = data.encode("GBK")
return bytes_data
except AttributeError:
return data | 9a3777d5ec52daa0a063a089c42943abf4e5c8a9 | 75,557 |
def get_type_registered(type_code):
"""Get a boolean representing whether the type is registered
Parameters
----------
type_code: int
The type code
"""
return _api_internal._datatype_get_type_registered(type_code) | 76fe2dfda3416132d8e890e735f1a0c8212168f9 | 75,558 |
import torch
import csv
def pretrain(model, optimizer, batches):
"""Pretrains the model on a certain set of images.
params:
"""
#model.train()
device = model.device
loss_function = nn.CTCLoss(zero_infinity=True)
num_batches = len(batches)
epochs_since_improvement = 0
#best_... | 8e60012062f7b5ebd4717eedd648d253fa076371 | 75,559 |
from typing import Dict
from typing import Any
import logging
import json
def load_model_config_file(model_config_file: str) -> Dict[str, Any]:
"""Loads bert config json file or `encoders.EncoderConfig` in yaml file."""
if not model_config_file:
# model_config_file may be empty when using tf.hub.
return {... | e4338e9dc949b120b390b65cb5b4e1334befb5a0 | 75,560 |
def find_sensor_type_id(session, sensor_type):
"""
Function to find sensor type id by name.
Args:
session: sqlalchemy active seession object
sensor_type: sensor type name
Returns:
type_id: type id, -1 if not found
log: message if not found
"""
type_id = -1
... | c99711f3f82b1c85e6e1ba3c0a760e6677aa3df6 | 75,562 |
def read_conf(sitename):
"""read a config file; returns a dictionary of options
"""
try:
sett = dml.read_settings(sitename)
except FileNotFoundError:
return 'no_such_sett', None
else:
return '', sett | e93dc90bb77ede971f5502e13ff0e19877ad3061 | 75,563 |
import re
def find_config_file_line_number(path: str, section: str, setting_name: str) -> int:
"""Return the approximate location of setting_name within mypy config file.
Return -1 if can't determine the line unambiguously.
"""
in_desired_section = False
try:
results = []
with ope... | 03b1f77b051f260471653df6e7ddd7a599c8e100 | 75,564 |
def elina_abstract0_meet_lincons_array(man, destructive, a1, lincons_array):
"""
Meet of an ElinaAbstract0 with an ElinaLincons0Array.
Parameters
----------
man : ElinaManagerPtr
Pointer to the ElinaManager.
destructive : c_bool
Boolean flag.
a1 : ElinaAbstract0
Poin... | 52c5a73123a6d667c7a8232a3594c23ceb4edc48 | 75,565 |
def get_png(prediction_obj):
"""Processes value produced by producer, returns prediction with png image.
:param prediction_obj:
:return: original frame, predicted frame with bounding box or prediction written over it
"""
original_frame = np_from_json(prediction_obj, prefix_name=ORIGINAL_PREFIX)
... | 77e308cfdf9aa73f630e4cb696b3829f14a93cf6 | 75,568 |
def color565(r, g, b):
"""Convert red, green, blue components to a 16-bit 565 RGB value. Components
should be values 0 to 255.
"""
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3) | 213f3b5c8b4123a8327956f81105c5d2e7080d3e | 75,569 |
def gray_color_map(np_image: np.array, color_map="rainbow") -> np.array:
"""
Returns a color image from a gray image
Parameters:
np_image (np.ndarray): a gray image `(H,W)`
Returns:
np.ndarray `(4,H,W)`
"""
assert len(np_image.shape) == 2
min_value = np_image.min()
max_... | e74cc04210f8ea264d3429dd0f249cf3a8447971 | 75,570 |
import time
import pickle
def calculate_diagram(
smiles,
verbose=False,
quiet=True,
compute_aam=False,
save_path=None,
save_plot=None,
train_mode="transition_state",
seed=[],
no_props=False,
plot_only_branches=False,
temp_dir_img=None,
):
"""
Computes a Hasse diagra... | 499b99faa012ca17d59df0093bb95288c81e9832 | 75,571 |
def print_array(*args):
"""
print_array(int * x, int length)
Parameters:
x: int *
length: int
"""
return _snap.print_array(*args) | b06d02b1fed6739ada3ee25d9eb4ec919a900fd7 | 75,572 |
def separates(S, A, B, G):
"""Returns true if the set S separates A from B in G, i.e. if all
paths in G from nodes in A to nodes in B contain a node in
S. Exception is raised if S, A and B are not pairwise disjoint.
Parameters
----------
S: set of ints
a set of nodes in G
A: set of ... | 8451b4cfb28a327aba3148c6762b610ae010dbc9 | 75,573 |
def var(input, axis=None):
"""Compute the variance along the given axis of a tensor `input`.
:param axis: Compute the variance along this axis of the tensor.
None means all axes (like numpy).
:type axis: None or int or (list of int) (see `Sum`)
"""
input_ndim = input.type.ndim
... | 35da706349bfd15478bb22a357660f9164b2c209 | 75,574 |
import time
def get_role_arn_from_stack(cloudformation, stack_id):
"""
Uses the stack id to get the role arn from describe_stacks.
"""
if stack_id is None:
print("A stack id was not returned. Exiting")
return None
cloudformation_stack_description = cloudformation.describe_stacks(StackName=stack_id)
if "St... | 08fff5b0645c9a9e71289143b09de3ea89e2fb08 | 75,575 |
def flatten_nested_list(l):
"""Flattens a list and provides a mapping from elements in the list back
into the nested list.
Args:
l: A list of lists.
Returns:
A tuple (flattened, index_to_position):
flattened: The flattened list.
index_to_position: A list of pairs (r, c) such that
... | 14e20ef2a29dc338a4d706e0b2110a56447ae84e | 75,576 |
def object_validator(*, validator=None, value_type=None, strict_type=False,
allow_none=False):
"""Create a function that checks whether an object is valid.
>>> # validator for values of type str and length 5-10
>>> len_vf = length_validator(min_len=5, max_len=10)
>>> vf = object_va... | be3b3d0ab748831389a6e67dde6c749c04d97da5 | 75,577 |
def user():
"""Manage users.
.. versionadded:: 1.6.0
"""
res = dict(code=1, msg=None)
ak = rsp("accounts")
Action = request.args.get("Action")
if request.method == "GET":
#: 查询用户
sort = request.args.get("sort") or "desc"
page = request.args.get("page") or 1
l... | e1e6fb8fe522ecd522c2490751c52c826a1c1e69 | 75,578 |
def get_mock_response_relationship(status_code, content):
"""Mock function for implementing test responses from the server for get_relationship() function."""
test_mock = mock.Mock()
test_mock.status_code = status_code
test_mock.content = content
def mock_response(api_url, headers, params, timeout,... | d4c0dbcdb7f6668c17daccad661c120144b42ea2 | 75,579 |
def fvec(xvec):
"""Vector function for Q7."""
x, y = xvec
return np.array([
x**4 + y**4 - 1,
x**2 - y**2 + 1
]) | 4a7612c33bbe896b94e166a8ce43219b0b57cf44 | 75,580 |
def index(s, sub, i = 0, last=None):
"""index(s, sub [,start [,end]]) -> int
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Raise ValueError if not found.
"""
if last is None: la... | 5386fec36221f5039022aea01d12f85bda44bd62 | 75,581 |
def relstateT_set(Nmax):
"""
Returns a list of relative states up to Nmax for all possible S and T
"""
stateset=[]
for Nr in range(0,Nmax+1):
wr=SU3State(Nr,0)
for T in [0,1]:
for S in [0,1]:
if (Nr+T+S)%2!=1:
continue
state=U3SU4State(wr,S,T)
stateset=stateset+[state]
return stateset | ce722e80241631d71f99d4ea5f92e1a491a6bc11 | 75,583 |
def randomly_sample_sphere(ntosample, randomseed=12345):
"""
Generates a set of spherical coordinates uniformly distributed over the
sphere in a way that gives the same answer for the same seed. Also
generates a random distance vector on [0, 1] (no units)
This simply returns (lon, lat, r) instead ... | 08e7d7e03d0e0efb2c01e84d3ae93129105641ce | 75,584 |
import re
def check_task(content_dict={}):
"""
对用户提交的内容进行统一的识别,并给出相应的回复
:param content_dict:
:return:
"""
func_dict = {u'博客': get_bloglist, u'帮助': get_commandmenu,
u'听歌': get_music, u'song': get_music, u's': get_music, u't': get_similar_songs,
u'风格': get_simil... | 01ee84c1d41d1a743ebfa3877bf2e4e2888ac9d8 | 75,585 |
def nativeCalculateAngle(self, x1, y1, x2, y2):
"""
TOWRITE
:param `x1`: TOWRITE
:type `x1`: qreal
:param `y1`: TOWRITE
:type `y1`: qreal
:param `x2`: TOWRITE
:type `x2`: qreal
:param `y2`: TOWRITE
:type `y2`: qreal
:rtype: qreal
"""
return QLineF(x1, -y1, x2, -y2).a... | c2c1e47a2ceb1e5b29e51117d292bb9ea296726f | 75,586 |
def runPyGame(scenario, update_hook=None):
# Initialise PyGame.
"""
if visualize:
pygame.init()
# Set up the clock. This will tick every frame and thus maintain a relatively constant framerate. Hopefully.
fps = 60.0
fpsClock = pygame.time.Clock()
# Set up the window.... | 8996cd43101b28a6a14370bebd592787e52436db | 75,587 |
from datetime import datetime
def retrieve_historical_tweets(session, user_id, daterange, pages=30):
""" retrieves tweets for a specific timeframe """
start, end = daterange
start = coerce_date(start)
end = coerce_date(end)
tweets = []
timeline = walk_timeline(session, user_id, max_pages=pag... | 3dc4b92e69368f35c887fa4a16c0348955d6228c | 75,588 |
def get_messages():
"""Return a queryset with the message data"""
return BackendMessage.objects.filter(name=BACKEND_NAME) | ea35c73aa757e3f231aff76de3ec04ca33b52545 | 75,589 |
async def Mcu(request):
"""
YAP:
Node Mcu dan Gelen Bilgiler Burada Dinlenecek Veritabanına Kayıt Buradan Yapılacak
"""
print(request.body)
return response.text("Gelen Form Bilgisi: %s" % request.body) | 2d732f56dbb355124ef5ba4c51ad86d6af5fd5a4 | 75,590 |
def get_owner_email_from_domain(domain):
"""Look up the owner email address for a given domain.
Returning dummy addresses here - implement your own domain->email lookup here.
Returns:
str: email address
"""
email = {
'example-domain-a.example.com': 'owner-a@example.com',
'ex... | 2d3851c87c5ba3c19af4c989887bf750b66ffbe1 | 75,591 |
def show_vcs_rpc(self, api_timeout=''):
"""
This is an auto-generated method for the PySwitchLib.
**Supported Versions**:
* NOS: 6.0.2f, 7.2.0
* SLXOS: 17r.1.01a, 17r.2.00, 17s.1.02
:type api_timeout: long or tuple(long, long)
:param api_timeout: Timeout for connection and res... | 5db39909a422a5278a61ba6969e400016b6d0aa7 | 75,592 |
def masked_imaging_from_agg_obj(
agg_obj: af.PhaseOutput, settings_masked_imaging: al.SettingsMaskedImaging = None
) -> "al.MaskedImaging":
"""
Returns a `MaskImaging` object from an aggregator's *PhaseOutput* class, which we call an 'agg_obj' to describe
that it acts as the aggregator object for one r... | 03c87035eb39f530fcb19c5f6ca6fb8f96182b6d | 75,593 |
def intensity_scale_compute(intscale):
"""
Return the intensity scale matrix.
Parameters
----------
intscale: dict
The intensity-scale object initialized with
:py:func:`pysteps.verification.spatialscores.intensity_scale_init`
and accumulated with
:py:func:`pysteps.ve... | a4cdcb1615ffb8daaf24c3b7abaf736813b4200f | 75,594 |
def color_plot_slices(xvals, yvals, zvals, ax=None,
normalize=False, log=False,
save_name=None, **kw):
"""
Originally by Nathan
Display a color figure for something like a tracked DAC sweep.
xvals should be a single vector with values for the primary sweep.
... | a963ed193e25d3255748ad3c8dbb96aa05c04004 | 75,595 |
from datetime import datetime
def parse_date(dtstr):
"""
Attempts to parse a date with given formats first, then default formats
"""
# Handle empty string or None
if not dtstr: return None
try:
# Attempt to use the email utils parser first
dt = parsedate_tz(dtstr)
if d... | 751d4c571c7f8f1c440e7dd602c326b29b74c71a | 75,596 |
import six
def bitlify(value):
"""
Gets or create a Bittle object for the passed object. If unable to get
Bittle and/or create bit.ly, will just return the get_absolute_url value.
"""
try:
bittle = Bittle.objects.bitlify(value)
if bittle:
url = bittle.shortUrl
... | 26dbd6e5ad7c1d5040fa2b232ea4d5e6f8c67fa5 | 75,597 |
import calendar
def get_timestamp(record, start_byte=4):
"""
Convert the date and time from the record to a Unix timestamp
:param record: The record read from the file which contains the date and time
:param start_byte: optional input of starting byte, defaults to 4
:return: the Unix timestamp
... | 8008e7065d7f37a1fa7cd856bfb1dc4d163d5214 | 75,598 |
def filename_to_date(filename, iso=False):
""" """
if iso:
return filename_to_time(filename).datetime.isoformat().split("T")[0]
return filename.split("_ifu")[1].split("_")[0] | e7c92f6634f0703fa16ca5ef06178b21fcbd0bab | 75,600 |
def stringify_dict(d):
"""create a pretty version of arguments for printing"""
if 'self' in d:
del d['self']
s = 'Arguments:\n'
for k in d:
if not isinstance(d[k], str):
d[k] = str(d[k])
s = s + '%s: %s\n' % (k, d[k])
return(s) | e79220bf7d1d769f5408cd0532ea97390ad35541 | 75,601 |
def map_gender(raw_input):
"""Map gender from (M,F) or (HL7:M, HL7:F) to (male,female)"""
if utils.is_empty(raw_input):
return None
mapping = {
"M": Gender.MALE.value,
"F": Gender.FEMALE.value,
"HL7:M": Gender.MALE.value,
"HL7:F": Gender.FEMALE.value,
}
if ra... | 2ecd56354ffdb941b6811489e809b7d532d7db40 | 75,602 |
import librosa
def get_mixed_DLNC0_CENS(x, sr, hop_length, lam=0.1):
"""
Concatenate DLNC0 to CENS
Parameters
----------
x: ndarray(N)
Audio samples
sr: int
Sample rate
hop_length: int
Hop size between windows
lam: float
The coefficient in front of the ... | 2d6d89b84e09e1bde14ee3f84e5ab62efb892cdb | 75,603 |
def upload_path_exe(instance, filename):
"""
Create a directory to store the algorithm binary and other data.
:param instance:
:param filename:
:return:
"""
return 'app_{app_name}/{filename}'.format(app_name=slugify(instance.name, allow_unicode=False), filename=filename) | 1fdfc98b023ea7c16c346d169f57cfbf60ef6575 | 75,605 |
from pathlib import Path
def proc_ctd(fname):
"""
CTD processing.
"""
cast = DataFrame.from_cnv(fname, below_water=True).split()[0]
cast = cast[cast['pumps']]
cast = cast[~cast['flag']]
name = Path(fname).stem
# Removed unwanted columns.
keep = {'t090C', 't190C', 'longitude', 'lat... | 88ca3ec589aa739f6cb2ed9c993b6b83164480bd | 75,606 |
def rules(host, _args, _old_graph, graph, _started_time):
"""list all the rules"""
for rule_name in sorted(graph.rules):
host.print_out("%s %s" % (rule_name,
graph.rules[rule_name]['command']))
return 0 | c4d094a90634101b754debde637685b95fcde556 | 75,607 |
def sparkwebhook():
"""Processes incoming requests to the '/sparkwebhook' URI."""
if request.method == 'GET':
return ("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spark Bot served ... | e792d43f5c126728ba13d775aa2ba636269f08a9 | 75,608 |
def iterators_equivalent(left, right):
"""
Compare two iterators, return True if and only if equivalent
up to first Ellipsis (which means 'do not care')
"""
# construct a unique object that won't have existed anywhere else
end = object()
for l, r in zip_longest(left, right, fillvalue=end):... | cdfca49bac21dec18b3d2384f8a5440d3f4e7a34 | 75,609 |
import re
def files_present(url, fileglobs, _all=True):
"""Return true if any/all of the fileglobs are present in the url.
"""
any_present = False
all_present = True
fileglobsstr = ','.join(fileglobs)
if fileglobs:
cmd = (f'wget -r -l 10 -nd -np --spider --accept={fileglobsstr} {url}')... | 6be123a7b9d3c64a8c57cb3d9a7dbfaf36529a83 | 75,610 |
from pathlib import Path
import requests
def download_file(url, dir=None, fname=None, overwrite=False, verbose=True):
"""Download file from given `url` and put it into `dir`.
Current working directory is used as default. Missing directories are created.
File name from `url` is used as default.
Return ... | 866c1ff7f24d1f2ebef357912720346876989b45 | 75,612 |
def push_env(env=None):
"""Overload push_env to default to the new Environment class."""
if env is None:
env = EnvironmentLTL()
return pysmt_push_env(env=env) | a922ac86182c6e99818dec7da1d6cb6c67af655f | 75,613 |
def create_detections(boxes, confs):
"""
----------
detection_mat : ndarray
Matrix of detections. The first 10 columns of the detection matrix are
in the standard MOTChallenge detection format. In the remaining columns
store the feature vector associated with each detection.
fram... | dfd03781e6d409efd8138928723081937afc5fd7 | 75,614 |
import struct
def defmsg(name: str, **kwargs):
"""Define a protocol message."""
fmt: str = ">" + "".join(kwargs.values())
msg_type = namedtuple(name, kwargs.keys()) # type: ignore
class _MessageType:
@staticmethod
def decode(data: bytes, allow_excessive=False):
"""Decode ... | 7ac76780f23e521404ef857d3c93f4f7c9e42be1 | 75,615 |
import math
def FOV(pose, polys, angle, radius, nrRays=50):
"""
Field of view (FOV) around ego car
"""
l_alpha = np.linspace(-angle, angle, nrRays) + pose.yaw_rad
l_alpha = np.append(l_alpha, np.array([pose.yaw_rad]))
l_alpha.sort()
l1_1 = np.array([pose.x_m, pose.y_m])
l1_1 = l1_1 + ... | 2374d7ce745112a1d44298cee8eab515eb501007 | 75,616 |
from core.utility import sort_dictonary
def load_all_profiles(limit=-1):
"""
load all available profiles
Returns:
an array of all profile names
"""
all_modules_with_details = load_all_modules(limit=limit, full_details=True)
profiles = {}
if '...' in all_modules_with_details:
... | 2ea71e8f52ec657474735611200de8097671f2c3 | 75,617 |
import re
def find_next(lines, find_str, start_index):
"""
Find the next instance of find_str from lines starting from start_index.
:param lines: Lines to look through
:param find_str: String or Invert to look for
:param start_index: Index to start from
:return: (boolean, index, line)
"""... | d68d64fead264630c0b936aa0c6ed3aa3eae7a30 | 75,618 |
def test():
"""
Runs a test of a few standard Riak operations
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.test
"""
ret = {"comment": "", "success": False}
cmd = __execute_cmd("riak-admin", "test")
if cmd["retcode"] != 0:
ret["comme... | b715dbc93da20ce616f7a98a5272a5c813a08dc0 | 75,620 |
def from_path(path):
"""
:param path: filepath
:return:
"""
return dwim.from_path_impl(
path,
from_dict=from_cereal,
from_ext={'.npz': from_npz},
) | c256222ba0c1be2cdb3f1993f8436576ffa51354 | 75,621 |
def index():
"""Landing page."""
# if user is logged in, go straight to home, otherwise go to OAuth
if flask_login.current_user is not None and flask_login.current_user.is_authenticated:
auth_url = flask.url_for('.home')
else:
google = get_google_auth()
auth_url, state = google.... | a35f29bc88ef063a18068d9db0dd69c8886a71f1 | 75,622 |
import torch
def linear_regression(X, Y=None, order=None, X_test=None):
"""Closed form linear regression
"""
if X.dim() == 1:
X = X.unsqueeze(1)
if Y is None:
if order is None:
beta_left = torch.matmul(torch.matmul(X.t(), X).inverse(), X.t())
return beta_left
... | 07420512f176955b394aeaa67a0eb0add168b38d | 75,623 |
def extract_secondary_keys_from_form(form):
"""Extracts text (autocomplete capable) secondary keys list from Indexes form.
@param form: is a MUI secondary indexes form object (Django Form() object)"""
keys_list = []
for field_id, field in form.fields.iteritems():
if 'field_name' in field.__dict... | bf73217293f379257f7e8f0ab33b45d735b04edb | 75,624 |
import uuid
def fromTime(timestamp, hw_addr):
"""Generate a Time Based UUID object.
:param timestamp: The rospy.Time timestamp for UUID generation
:param hw_addr: A 48-bit long representing the network address
:returns: type 1 :class:`uuid.UUID` object
Different calls to this function at any tim... | 97af0be8427564837e0fd140413c39a3a875d871 | 75,625 |
def parse_as_folder_reference(dep):
""" See if a dependency reference refers to a folder path.
If it does, return the folder path (which parses and
resolves file:// urls in the process).
If it doesn't, return None.
"""
# Special case: pep508 urls
if dep.find("@") > 0 and (
... | baf746a0342ba5182135da230f3db9b69a38f946 | 75,626 |
from typing import List
from typing import Tuple
def _prepare_labels(
complete_pairs: List[Tuple],
ground_truth_pairs: List[Tuple],
retrieved_pairs: List[Tuple],
) -> Tuple[List, List]:
"""
Given all possible unique pairs, ground truth positive pairs and retrieved positive pairs, generate true and... | dada4a5a87f1728100841de40b53168d0c2ca042 | 75,627 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.