content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_service(hass, config, discovery_info=None):
"""Get the ClickSend notification service."""
if not _authenticate(config):
_LOGGER.error("You are not authorized to access ClickSend")
return None
return ClicksendNotificationService(config) | 4b3dd52d7ebcb37012bc847288d0ea38c4ca91f6 | 23,800 |
from faker import Faker
def mock_features_dtypes(num_rows=100):
"""Internal function that returns the default full dataset.
:param num_rows: The number of observations in the final dataset. Defaults to 100.
:type num_rows: int, optional
:return: The dataset with all columns included.
:rtype tuple... | c9d9bef26d908b2e47d4bc2e013f0c29e328b2b3 | 23,801 |
def random_bitstring(n, p, failcount=0):
"""
Constructs a random bitstring of length n with parity p
Parameters
----------
n : int
Number of bits.
p : int
Parity.
failcount : int, optional
Internal use only.
Returns
-------
numpy.ndarray
"""
bi... | 07637061e50bc1fe853aeb2eef19505ee1a6b612 | 23,802 |
import json
def serializer(message):
"""serializes the message as JSON"""
return json.dumps(message).encode('utf-8') | 7e8d9ae8e31653aad594a81e9f45170a915e291d | 23,803 |
def send_mail(request, format=None):
"""
Send mail to admin
"""
# serialize request data
serializer = MailSerializer(data=request.data)
if serializer.is_valid():
try:
# create data for mail
subject = settings.EMAIL_SUBJECT.format(
first_name=reque... | 02ac2d0f7bf76fcea0afcff0a2a690cf72836e08 | 23,804 |
def correct_name(name):
"""
Ensures that the name of object used to create paths in file system do not
contain characters that would be handled erroneously (e.g. \ or / that
normally separate file directories).
Parameters
----------
name : str
Name of object (course, file, folder, e... | b1df7a503324009a15f4f08e7641722d15a826b7 | 23,805 |
def runner(parallel, config):
"""Run functions, provided by string name, on multiple cores on the current machine.
"""
def run_parallel(fn_name, items):
items = [x for x in items if x is not None]
if len(items) == 0:
return []
items = diagnostics.track_parallel(items, fn_... | 66ba2c5cd57d4d2738d9dd3d57ca9d5daca2ec8d | 23,806 |
def hsv_to_hsl(hsv):
"""
HSV to HSL.
https://en.wikipedia.org/wiki/HSL_and_HSV#Interconversion
"""
h, s, v = hsv
s /= 100.0
v /= 100.0
l = v * (1.0 - s / 2.0)
return [
HSV._constrain_hue(h),
0.0 if (l == 0.0 or l == 1.0) else ((v - l) / min(l, 1.0 - l)) * 100,
... | 4fee4508f6db770265ef46e928cfed6dee094892 | 23,807 |
import os
def is_ci() -> bool:
"""Returns if current execution is running on CI
Returns:
`True` if current executions is on CI
"""
return os.getenv('CI', 'false') == 'true' | 84e746a9adec77139c88c4042fd31b08f2c6098a | 23,808 |
from .._mesh import Mesh
def reindex_faces(mesh, ordering):
"""
Reorder the faces of the given mesh, returning a new mesh.
Args:
mesh (lacecore.Mesh): The mesh on which to operate.
ordering (np.arraylike): An array specifying the order in which
the original faces should be arr... | 254cf3a036fa92253b105f3acd93dfe26d33a61c | 23,809 |
import re
def check_exact_match(line, expected_line):
"""
Uses regular expressions to find an exact (not partial) match for 'expected_line' in 'line', i.e.
in the example below it matches 'foo' and succeeds:
line value: '66118.999958 - INFO - [MainThread] - ly_test_tools.o3de.asset_processor - foo... | d01eaa13c40d66999e870d3b287ac869f64ae314 | 23,810 |
def rounding_filters(filters, w_multiplier):
""" Calculate and round number of filters based on width multiplier. """
if not w_multiplier:
return filters
divisor = 8
filters *= w_multiplier
new_filters = max(divisor, int(filters + divisor / 2) // divisor * divisor)
if new_filters < 0.9 *... | eb2938732792564fd324602fd74be41e6f88b265 | 23,811 |
def process(request, service, identifier):
"""
View that displays a detailed description for a WPS process.
"""
wps = get_wps_service_engine(service)
wps_process = wps.describeprocess(identifier)
context = {'process': wps_process,
'service': service,
'is_link': abs... | 0d9f5a0cdf7c15470547ff82ff3534cf6f624960 | 23,812 |
def update(pipeline_id, name, description):
"""Submits a request to CARROT's pipelines update mapping"""
# Create parameter list
params = [
("name", name),
("description", description),
]
return request_handler.update("pipelines", pipeline_id, params) | e808fb0fc313e8a5e51bb448d0aca68e389bfc30 | 23,813 |
from re import S
def symmetric_poly(n, *gens, **args):
"""Generates symmetric polynomial of order `n`. """
gens = _analyze_gens(gens)
if n < 0 or n > len(gens) or not gens:
raise ValueError("can't generate symmetric polynomial of order %s for %s" % (n, gens))
elif not n:
poly = S.One
... | 51177adf8873628669c1b75267c3c65821920044 | 23,814 |
from typing import Any
def load(name: str, *args, **kwargs) -> Any:
"""
Loads the unit specified by `name`, initialized with the given arguments
and keyword arguments.
"""
entry = get_entry_point(name)
return entry.assemble(*args, **kwargs) | e924dcebf082443fb9f36cd81302cb62ac53775d | 23,815 |
from typing import List
def get_gate_names_2qubit() -> List[str]:
"""Return the list of valid gate names of 2-qubit gates."""
names = []
names.append("cx")
names.append("cz")
names.append("swap")
names.append("zx90")
names.append("zz90")
return names | d3d7f20263805a186d9142ec087039eb53076346 | 23,816 |
def positive_leading_quat(quat):
"""Returns the positive leading version of the quaternion.
This function supports inputs with or without leading batch dimensions.
Args:
quat: A quaternion [w, i, j, k].
Returns:
The equivalent quaternion [w, i, j, k] with w > 0.
"""
# Ensure quat is an np.array ... | e0dce2e8fce42a15abdeeccc4bbf63c9e9241cf1 | 23,817 |
def comp_avg_silh_metric(data_input, cluster_indices, silh_max_samples, silh_distance):
"""
Given a input data matrix and an array of cluster indices, returns the
average silhouette metric for that clustering result (computed across all clusters).
Parameters
----------
data_input : ndarray
... | 0d2cb42b1f0b354f4776c9c2064d23ed4b8f0b75 | 23,818 |
def prepare_url(base_url, path, url_params=None):
"""Prepare url from path and params"""
if url_params is None:
url_params = {}
url = '{0}{1}'.format(base_url, path)
if not url.endswith('/'):
url += '/'
url_params_str = urlencode(url_params)
if url_params_str:
url += '?'... | 0a447d9f340a4ea9c99b98ca1e6f778f907d8a3d | 23,819 |
def extract_at_interval(da: xr.DataArray, interval) -> xr.DataArray:
"""Reduce size of an Error Grid by selecting data at a fixed interval along
both the number of high- and low-fidelity samples.
"""
return da.where(
da.n_high.isin(da.n_high[slice(None, None, interval)]) *
da.n_low.isin(... | cad3dce9850edbad9decadbc37e0372001b8ecc9 | 23,820 |
def compute_log_zT_var(log_rho_var, log_seebeck_sqr_var, log_kappa_var):
"""Compute the variance of the logarithmic thermoelectric figure
of merit zT.
"""
return log_rho_var + log_seebeck_sqr_var + log_kappa_var | 3528181796aeafb3df5eac09b06852afe028cb13 | 23,821 |
def main(global_config, **settings):
""" Very basic pyramid app """
config = Configurator(settings=settings)
config.include('pyramid_swagger')
config.add_route(
'sample_nonstring',
'/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}',
)
config.add_route('standard', '/sample/... | 677187e63b6b885f5dc27850039a54b7510ed9cf | 23,822 |
def get_name():
"""MUST HAVE FUNCTION! Returns plugin name."""
return "ASP.NET MVC" | 08a8b413ad1c86c270c79da245f0718aa22883a8 | 23,823 |
import os
def tag_images(
x_test,
test_case_images,
tag_list_file,
image_source,
clean=False
):
"""
Performs the tagging of abnormal images using RTEX@R
:param test_case_ids:
:param x_test:
:param x_test:
:param tag_list_file:
:param clean: if True t... | d8e3f0bc98c3b7fefb27b6d75cf650f0dddb3f47 | 23,824 |
def load_CIFAR(model_mode):
"""
Loads CIFAR-100 or CIFAR-10 dataset and maps it to Target Model and Shadow Model.
:param model_mode: one of "TargetModel" and "ShadowModel".
:param num_classes: one of 10 and 100 and the default value is 100
:return: Tuple of numpy arrays:'(x_train, y_train), (x_test,... | d47d5546c26b1a776b84acb407782837170da43d | 23,825 |
def _jbackslashreplace_error_handler(err):
"""
Encoding error handler which replaces invalid characters with Java-compliant Unicode escape sequences.
:param err: An `:exc:UnicodeEncodeError` instance.
:return: See https://docs.python.org/2/library/codecs.html?highlight=codecs#codecs.register_error
... | 2bec9e9563a7f4a4d206f630f7d8372fa7c56d89 | 23,826 |
import math
import sys
def calculate_spark_settings(instance_type, num_slaves, max_executor=192,
memory_overhead_coefficient=0.15,
num_partitions_factor=3):
"""
More info:
http://c2fo.io/c2fo/spark/aws/emr/2016/07/06/apache-spark-config-cheatsheet... | 618c038c969ce3d414063d07b6b6e11c403306dc | 23,827 |
from pathlib import Path
def run_on_host(con_info, command):
"""
Runs a command on a target pool of host defined in a hosts.yaml file.
"""
# Paramiko client configuration
paramiko.util.log_to_file(base + "prt_paramiko.log")
UseGSSAPI = (paramiko.GSS_AUTH_AVAILABLE)
DoGSSAPIKeyExchange = (p... | e3747daa1ea6e68ae4900bd596458bf756017c69 | 23,828 |
import colorsys
import hashlib
def uniqueColor(string):
"""
Returns a color from the string.
Same strings will return same colors, different strings will return different colors ('randomly' different)
Internal: string =md5(x)=> hex =x/maxhex=> float [0-1] =hsv_to_rgb(x,1,1)=> rgb =rgb_to_int=> int
... | 0c895612c3bf2dd5f594a15daf6f2aa5d778eeb0 | 23,829 |
def _quoteattr(data, entities={}):
""" Escape and quote an attribute value.
Escape &, <, and > in a string of data, then quote it for use as
an attribute value. The \" character will be escaped as well, if
necessary.
You can escape other strings of data by passing a dictionary as
... | 1f03a09e19d349458ec48b6041159e48ef93d97e | 23,830 |
import http
import urllib
def external_login_confirm_email_get(auth, uid, token):
"""
View for email confirmation links when user first login through external identity provider.
HTTP Method: GET
When users click the confirm link, they are expected not to be logged in. If not, they will be logged out ... | 18a92d289e63224b245e4e958efd6d5924495ce1 | 23,831 |
def date_since_epoch(date, unit='day'):
""" Get the date for the specified date in unit
:param date: the date in the specified unit
:type date: int
:param unit: one of 'year', 'month' 'week', 'day', 'hour', 'minute',
or 'second'
:return: the corresponding date
:rtype: ee.Date
"""
... | f787170869ba081a2d321d0198d27948dc44ffa6 | 23,832 |
def eval_assoc(param_list, meta):
"""
Evaluate the assoication score between a given text and
a list of categories or statements.
Param 1 - string, the text in question
Param 2 - list of strings, the list of categories to associate Param 1 to
"""
data = {
'op': 'eval_assoc',
... | f49d5080d0b5f6a526be11b487bbbf17782d7197 | 23,833 |
def quiver3d(*args, **kwargs):
"""Wraps `mayavi.mlab.quiver3d`
Args:
*args: passed to `mayavi.mlab.quiver3d`
**kwargs: Other Arguments are popped, then kwargs is passed to
`mayavi.mlab.quiver3d`
Keyword Arguments:
cmap (str, None, False): see :py:func:`apply_cmap`
... | 8cfd494f0b801490372d94f7ab842c0b5cd19099 | 23,834 |
def get_instance_types(self):
"""
Documentation:
---
Description:
Generate SSH pub
"""
instance_types = sorted([instance_type["InstanceType"] for instance_type in self.ec2_client.describe_instance_types()["InstanceTypes"]])
return instance_types | 583311de8b2f23a967e40c8be5d140f6ab28244c | 23,835 |
def ret_digraph_points(sed, digraph):
"""Finds the digraph points of the subject extracted data.
Parameters
----------
`sed` (object) "_subject","_track_code", "data": [{"digraph","points"}]
Returns
---------
(list) The points of the particular digraph found
"""
ret = [d['points'] fo... | 853dac3afdb542dbc2878340c8d75b8b4544c531 | 23,836 |
def _sizeof_fmt(num):
"""Format byte size to human-readable format.
https://web.archive.org/web/20111010015624/http://blogmag.net/blog/read/38/Print_human_readable_file_size
Args:
num (float): Number of bytes
"""
for x in ["bytes", "KB", "MB", "GB", "TB", "PB"]:
if num < 1024.0:
... | 97c700954248a455592b3da9b274bfda69a7370f | 23,837 |
from .. import sim
from typing import Dict
def gatherData(gatherLFP = True):
"""
Function for/to <short description of `netpyne.sim.gather.gatherData`>
Parameters
----------
gatherLFP : bool
<Short description of gatherLFP>
**Default:** ``True``
**Options:** ``<option>`` <... | a40b61088aaedbb8f866014f933671b2264a2031 | 23,838 |
def stations_by_distance(stations, p):
"""For a list of stations (MonitoringStation object) and
coordinate p (latitude, longitude), returns list of tuples
(station, distance) sorted by the distance from the given
coordinate p"""
# Create the list of (stations, distance) tuples
station_dist = []... | 098e692c2ec18b7c15cebf84043eaca768566075 | 23,839 |
from typing import TextIO
from typing import Optional
from typing import Dict
import csv
def process(fh: TextIO, headers: Optional[Dict[str, str]],
writer: csv.DictWriter, args: Args) -> int:
"""
Process the file into Mongo (client)
First 5 columns are: STREAM, DATE, STATION, REP, #GRIDS
... | 40a68091d65e1f9a56ca150703aaaa207ef438a2 | 23,840 |
def dipole_moment_programs():
""" Constructs a list of program modules implementing
static dipole moment output readers.
"""
return pm.program_modules_with_function(pm.Job.DIP_MOM) | a225997a445451411819ebfb8c7bf14629ee3742 | 23,841 |
def kappa(a, b, c, d):
""" GO term 2
| yes | no |
-------------------------------
GO | yes | a | b |
term1 | no | c | d |
kapa(GO_1, GO_2) = 1 - (1 - po) / (1 - pe)
po = (a + d) / (a + b + c + d)
marginal_a = ( (a + b) * ( a + c )) / (a + b + ... | 5884a6745f6a93b044eabb1bfe38834cb59366d4 | 23,842 |
import functools
import torch
def test_CreativeProject_integration_ask_tell_ask_works(covars, model_type, train_X, train_Y,
covars_proposed_iter, covars_sampled_iter,
response_sampled_it... | 98d665e85b19acf956026848614d9b49e204afb8 | 23,843 |
def ferret_init(id):
"""
Initialization for the stats_chisquare Ferret PyEF
"""
axes_values = [ pyferret.AXIS_DOES_NOT_EXIST ] * pyferret.MAX_FERRET_NDIM
axes_values[0] = pyferret.AXIS_CUSTOM
false_influences = [ False ] * pyferret.MAX_FERRET_NDIM
retdict = { "numargs": 3,
"d... | 5231fec470d8c968334d6f72766cc1d0ad9ae61c | 23,844 |
def has(key):
"""Checks if the current context contains the given key."""
return not not (key in Context.currentContext.values) | 0c6c46812e97c9d38d101dcc06346b329a3cd81a | 23,845 |
def VGG_16(weights_path=None):
"""
Creates a convolutional keras neural network, training it with data from ct scans from both datasets.
Using the VGG-16 architecture.
----
Returns the model
"""
X_train, Y_train = loadfromh5(1, 2, 19)
X_train1, Y_train1 = loadfromh5(2, 2, 19)
X_tr... | 640aa7480afac0c8c4b71f3045f702888672172f | 23,846 |
from scipy import optimize
def inv_fap_davies(p, fmax, t, y, dy, normalization='standard'):
"""Inverse of the davies upper-bound"""
args = (fmax, t, y, dy, normalization)
z0 = inv_fap_naive(p, *args)
func = lambda z, *args: fap_davies(z, *args) - p
res = optimize.root(func, z0, args=args, method='... | 9b6f8a82ca25235785d5fe83a5c671130ddd509b | 23,847 |
def public(request):
"""browse public repos. Login not required"""
username = request.user.get_username()
public_repos = DataHubManager.list_public_repos()
# This should really go through the api... like everything else
# in this file.
public_repos = serializers.serialize('json', public_repos)
... | 0d44053c6db872032b65b4786c5771dbecad946a | 23,848 |
def get_boundaries_old(im,su=5,sl=5,valley=5,cutoff_max=1.,plt_val=False):
"""Bintu et al 2018 candidate boundary calling"""
im_=np.array(im)
ratio,ration,center,centern=[],[],[],[]
for i in range(len(im)):
x_im_l,y_im_l = [],[]
x_im_r,y_im_r = [],[]
xn_im_l,yn_im_l = [],[]
... | 620fa37306f85a06d88b4f08fd84e9873866e011 | 23,849 |
def zfsr32(val, n):
"""zero fill shift right for 32 bit integers"""
return (val >> n) if val >= 0 else ((val + 4294967296) >> n) | 4b890caa0b7b086e923e7b229e5551fd66d24016 | 23,850 |
def n_optimize_fn(step: int) -> int:
"""`n_optimize` scheduling function."""
if step <= FLAGS.change_n_optimize_at:
return FLAGS.n_optimize_1
else:
return FLAGS.n_optimize_2 | 2d8b05a19c05a662119e51ace97817246c38ebe3 | 23,851 |
import torch
def compute_receptive_field(model, img_size=(1, 3, 3)):
"""Computes the receptive field for a model.
The receptive field is computed using the magnitude of the gradient of the
model's output with respect to the input.
Args:
model: Model for hich to compute the receptive field. A... | bdc3065e696bf221698d1abdb0717b7da957ca84 | 23,852 |
def flippv(pv, n):
"""Flips the meaning of an index partition vector.
Parameters
----------
pv : ndarray
The index partition to flip.
n : integer
The length of the dimension to partition.
Returns
-------
notpv : ndarray
The complement of pv.
Example:
>>... | 6c063169100eba098460cd12339f7a6266ea01f0 | 23,853 |
from typing import Union
from pathlib import Path
def is_dir(path: Union[str, Path]) -> bool:
"""Check if the given path is a directory
:param path: path to be checked
"""
if isinstance(path, str):
path = Path(path)
if path.exists():
return path.is_dir()
else:
return ... | 540cce7f5c6a25186427ba71b94aa090c2ab90a7 | 23,854 |
import os
import sys
def work(out_dir: str, in_coord: str, in_imd_path: str, in_topo_path: str, in_perttopo_path: str, in_disres_path: str,
nmpi: int = 1, nomp: int = 1, out_trg: bool = False,
gromos_bin: str = None, work_dir: str = None):
"""
Executed by repex_EDS_long_production_ru... | c2607e37fedd7e8a121d20585f23b1ea793fc9aa | 23,855 |
from itertools import cycle
def _replace_dendro_colours(
colours,
above_threshold_colour="C0",
non_cluster_colour="black",
colorscale=None
):
""" Returns colorscale used for dendrogram tree clusters.
Keyword arguments:
colorscale -- Colors to use for the plot in rgb format.
Should... | ce50b8c061bb908d8670b059261cde83e7dd62b1 | 23,856 |
import re
def document_to_vector(lemmatized_document, uniques):
"""
Converts a lemmatized document to a bow vector
representation.
1/0 for word exists/doesn't exist
"""
#print(uniques)
# tokenize
words = re.findall(r'\w+', lemmatized_document.lower())
# vector = {}
vector = ... | e4b108b8e99a827788d7eff5d4eabf71021d6e21 | 23,857 |
def ubcOcTree(FileName_Mesh, FileName_Model, pdo=None):
"""
Description
-----------
Wrapper to Read UBC GIF OcTree mesh and model file pairs. UBC OcTree models are defined using a 2-file format. The "mesh" file describes how the data is descritized. The "model" file lists the physical property values fo... | f9d71c7beebc8ca5f3c45fc24a4fd6ccae607634 | 23,858 |
def load_colormaps():
"""Return the provided colormaps."""
return load_builtin_data('colormaps') | 00b0d73e127cbbf11b76d5a2281493af95337008 | 23,859 |
def discriminator(hr_images, scope, dim):
"""
Discriminator
"""
conv_lrelu = partial(conv, activation_fn=lrelu)
def _combine(x, newdim, name, z=None):
x = conv_lrelu(x, newdim, 1, 1, name)
y = x if z is None else tf.concat([x, z], axis=-1)
return minibatch_stddev_layer(y)
... | 9af149750aed5febd17ab37b1e816356d2e27a40 | 23,860 |
def addchallenges(request) :
"""
管理员添加新的题目
"""
if request.user.is_superuser :
if request.method == 'POST' :
success = 0
form = forms.AddChallengeForm(request.POST, request.FILES)
if form.is_valid() :
success = 1
print(request.FILES)
if request.FILES :
i = models.Challenges(file=request.F... | e7aaa3a8418f66322f050dee74d74fd1d71bc0c9 | 23,861 |
def _decompose_ridge(Xtrain, alphas, n_alphas_batch=None, method="svd",
negative_eigenvalues="zeros"):
"""Precompute resolution matrices for ridge predictions.
To compute the prediction::
Ytest_hat = Xtest @ (XTX + alphas * Id)^-1 @ Xtrain^T @ Ytrain
where XTX = Xtrain^T ... | ba7d466546f4d417f9f455aee5fa0cccdaba968c | 23,862 |
import requests
def get_new_listing(old_listing):
"""Get the new listing."""
try:
fetched_listing = requests.get(cfg['api_url']).json()['product']
except requests.exceptions.RequestException:
return old_listing
else:
old_item_ids = {old_item['productId'] for old_item in old_lis... | f8aa02d1a804ef5cfbb1192da15091d8e8816d16 | 23,863 |
from typing import Union
import logging
def create_user(engine: create_engine, data: dict) -> Union[User, None]:
"""
Function for creating row in database
:param engine: sqlmodel's engine
:param data: dictionary with data that represents user
:return: Created user instance or nothing
"""
l... | bb1dff7aca37a8a1eab9104d0b6cd27cb55f78da | 23,864 |
def _densify_2D(a, fact=2):
"""Densify a 2D array using np.interp.
:fact - the factor to density the line segments by
:Notes
:-----
:original construction of c rather than the zero's approach
: c0 = c0.reshape(n, -1)
: c1 = c1.reshape(n, -1)
: c = np.concatenate((c0, c1), 1)
"""
... | e9a881f014c9ebcae6f3550c3b0c4d7beb576203 | 23,865 |
import os
def conf_paths(filename) -> list:
"""Get config paths"""
home = os.path.expanduser('~')
paths = [path.format(home=home, filename=filename) for path in
PATH_TEMPLATES]
return paths | a4864b0c3bf8f3a0fed1ec4d459852dea7aea577 | 23,866 |
from typing import Union
def get_neighbor_edge(
graph: srf.Alignment,
edge: tuple[int, int],
column: str = 'z',
direction: str = 'up',
window: Union[None, int] = None,
statistic: str = 'min'
) -> Union[None, tuple[int, int]]:
"""Return the neighboring edge having the lowest minimum value
... | df81a5480a673efbf66bda7951b634f99996ffcf | 23,867 |
def show_comparison(x_coordinates: np.ndarray, analytic_expression: callable, numeric_solution: [dict, np.ndarray],
numeric_label: str = "Numeric Solution", analytic_label: str = "Analytic Solution",
title: str = None, x_label: str = None, y_label: str = None, save_file_as: str =... | 10727c4db401469f88fa93db31a13e21037f8e63 | 23,868 |
def has_master(mc: MasterCoordinator) -> bool:
""" True if `mc` has a master. """
return bool(mc.sc and not mc.sc.master and mc.sc.master_url) | 314fc4a2aa4deed7291d4676230bc9dafbb142d8 | 23,869 |
import time
def sz_margin_details(date='', retry_count=3, pause=0.001):
"""
获取深市融资融券明细列表
Parameters
--------
date:string
明细数据日期 format:YYYY-MM-DD 默认为空''
retry_count : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题... | 115ef7ec68a08de065f086b53835c7bd05a34ff8 | 23,870 |
def delay_slot_insn(*args):
"""
delay_slot_insn(ea, bexec, fexec) -> bool
Helper function to get the delay slot instruction.
@param ea (C++: ea_t *)
@param bexec (C++: bool *)
@param fexec (C++: bool *)
"""
return _ida_idp.delay_slot_insn(*args) | 6b0316845c4cefa2a33a9e9f5e0c24c1f2920a52 | 23,871 |
def decode_argument(params, word_embeddings, argument_extractors):
"""
:type params: dict
:type word_embeddings: nlplingo.embeddings.WordEmbedding
:type argument_extractors: list[nlplingo.nn.extractor.Extractor] # argument extractors
"""
if len(argument_extractors) == 0:
raise RuntimeErr... | d0f4c819e0f8b29827bee28778a76ff4b0b2d8e7 | 23,872 |
import numpy
def pairwise_radial_basis(K: numpy.ndarray, B: numpy.ndarray) -> numpy.ndarray:
"""Compute the TPS radial basis function phi(r) between every row-pair of K
and B where r is the Euclidean distance.
Arguments
---------
K : numpy.array
n by d vector containing n d-dimens... | 5ce4ff200bf953d80b7aff30b84b4ae0a62a0445 | 23,873 |
def low_index_subgroups(G, N, Y=[]):
"""
Implements the Low Index Subgroups algorithm, i.e find all subgroups of
``G`` upto a given index ``N``. This implements the method described in
[Sim94]. This procedure involves a backtrack search over incomplete Coset
Tables, rather than over forced coinciden... | 03dc48ada37302ca6d4bc5054660aae60bca2ca5 | 23,874 |
def ifft_complex(fft_sig_complex) -> np.ndarray:
"""
Compute the one-dimensional inverse discrete Fourier Transform.
:param fft_sig_complex: input array, can be complex.
:return: the truncated or zero-padded input, transformed along the axis
"""
ifft_sig = np.fft.ifft(fft_sig_complex)
fft_p... | 101189d4116b0d968ee015534ab8b8fc0020a769 | 23,875 |
def merge_eopatches(*eopatches, features=..., time_dependent_op=None, timeless_op=None):
""" Merge features of given EOPatches into a new EOPatch
:param eopatches: Any number of EOPatches to be merged together
:type eopatches: EOPatch
:param features: A collection of features to be merged together. By ... | 6328528c6b6fc3013db6aa17f0153354230efd4b | 23,876 |
import argparse
def parse_args():
"""Parse cli arguments."""
parser = argparse.ArgumentParser(description="Java project package name changer.")
parser.add_argument("--directory", default=".", type=str, help="Working directory.")
parser.add_argument(
"--current",
required=True,
... | ceddd5028cd7aea1625e31f4c08bb22d112ea71a | 23,877 |
import math
def dispos(dra0, decd0, dra, decd):
"""
Source/credit: Skycat
dispos computes distance and position angle solving a spherical
triangle (no approximations)
INPUT :coords in decimal degrees
OUTPUT :dist in arcmin, returns phi in degrees (East of North)
AUTHOR ... | 5c1b7c79a82f59764fd43ba0d89a763955b09a04 | 23,878 |
import socket
def bind_port(sock, host=HOST):
"""Bind the socket to a free port and return the port number. Relies on
ephemeral ports in order to ensure we are using an unbound port. This is
important as many tests may be running simultaneously, especially in a
buildbot environment. This method rai... | a326581bea0f0873292028a5e39a710ea89fde4b | 23,879 |
from typing import Union
def node_to_html(node: Union[str, NodeElement, list]) -> str:
"""
Convert Nodes to HTML
:param node:
:return:
"""
if isinstance(node, str): # Text
return escape(node)
elif isinstance(node, list): # List of nodes
result = ''
for child_nod... | 0366dffc181f27ac10cbae8d9eae65b6822371c6 | 23,880 |
def cuda_reshape(a, shape):
""" Reshape a GPUArray.
Parameters:
a (gpu): GPUArray.
shape (tuple): Dimension of new reshaped GPUArray.
Returns:
gpu: Reshaped GPUArray.
Examples:
>>> a = cuda_reshape(cuda_give([[1, 2], [3, 4]]), (4, 1))
array([[ 1.],
... | 966cae8aeb88aeaeada28a11c284920746771f00 | 23,881 |
def test_ep_basic_equivalence(stateful, state_tuple, limits):
"""
Test that EpisodeRoller is equivalent to a
BasicRoller when run on a single environment.
"""
def env_fn():
return SimpleEnv(3, (4, 5), 'uint8')
env = env_fn()
model = SimpleModel(env.action_space.low.shape,
... | 4f9632bd088a0be806ca9c4f51e3c5bc55431513 | 23,882 |
def _find_crate_root_src(srcs, file_names=["lib.rs"]):
"""Finds the source file for the crate root."""
if len(srcs) == 1:
return srcs[0]
for src in srcs:
if src.basename in file_names:
return src
fail("No %s source file found." % " or ".join(file_names), "srcs") | dd3488b49dc6c315c3d35ead75a83008e7bcd962 | 23,883 |
def decode_check(string):
"""Returns the base58 decoded value, verifying the checksum.
:param string: The data to decode, as a string.
"""
number = b58decode(string)
# Converting to bytes in order to verify the checksum
payload = number.to_bytes(sizeof(number), 'big')
if payload and sha256d... | 716c0a92be68feb2a97cacfd57940e9e43fa07d9 | 23,884 |
import math
def rotate(origin, point, angle):
"""
Rotate a point counterclockwise by a given angle around a given origin.
The angle should be given in radians.
"""
ox, oy = origin
px, py = point
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(ang... | 9c542fd45b8b53bad61121429377298bd9d7fd08 | 23,885 |
def get_users_info(token, ids):
"""Return a response from vk api users.get
:param token: access token
:param ids: users ids
:return: dict with users info
"""
args = {
'user_ids': ids,
'fields': 'city,bdate,connections,photo_200',
'access_token': token,
'v': set... | 02246232df0f3eebc530e05e1734e10f6be5ed9e | 23,886 |
def create_consistencygroup(ctxt,
host='test_host@fakedrv#fakepool',
name='test_cg',
description='this is a test cg',
status='available',
availability_zone='fake_az',
... | a7548774690eccdc0c44231ae10dd345c9e84eb8 | 23,887 |
def ndigit(num):
"""Returns the number of digits in non-negative number num"""
with nowarn(): return np.int32(np.floor(np.maximum(1,np.log10(num))))+1 | ac83e0b31ce9213646e856aa47fa8bfba7d74a86 | 23,888 |
def data_store_folder_unzip_public(request, pk, pathname):
"""
Public version of data_store_folder_unzip, incorporating path variables
:param request:
:param pk:
:param pathname:
:return HttpResponse:
"""
return data_store_folder_unzip(request, res_id=pk, zip_with_rel_path=pathname) | 7866ed0539a00e16cbe0cbb2ab6902faebfd4434 | 23,889 |
def privateDataOffsetLengthTest10():
"""
Offset doesn't begin immediately after last table.
>>> doctestFunction1(testPrivateDataOffsetAndLength, privateDataOffsetLengthTest10())
(None, 'ERROR')
"""
header = defaultTestData(header=True)
header["privOffset"] = header["length"] + 4
header[... | 8744b97da80151a24c480ad29d2b1625f0c687f0 | 23,890 |
def meanncov(x, y=[], p=0, norm=True):
"""
Wrapper to multichannel case of new covariance *ncov*.
Args:
*x* : numpy.array
multidimensional data (channels, data points, trials).
*y* = [] : numpy.array
multidimensional data. If not given the autocovariance of *x*
will... | 926bc64a0b7e15822f40f705ac3e770a57bb2e11 | 23,891 |
def nasnet_6a4032(**kwargs):
"""
NASNet-A 6@4032 (NASNet-A-Large) model from 'Learning Transferable Architectures for Scalable Image Recognition,'
https://arxiv.org/abs/1707.07012.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
... | 78f8862a69c12e8de85dc441e6b45e364d9b3385 | 23,892 |
def get_character_card(character_id, preston, access_token):
"""Get all the info for the character card.
Args:
character_id (int): ID of the character.
preston (preston): Preston object to make scope-required ESI calls.
access_token (str): Access token for the scope-required ESI calls.
... | 23f201833537a8a596e42acc41061a583ebead38 | 23,893 |
def expand_ALL_constant(model, fieldnames):
"""Replaces the constant ``__all__`` with all concrete fields of the model"""
if "__all__" in fieldnames:
concrete_fields = []
for f in model._meta.get_fields():
if f.concrete:
if f.one_to_one or f.many_to_many:
... | 8c44c9b16fd93ca1c9a4efddd1ea85b44d34dba3 | 23,894 |
def server(user, password):
"""A shortcut to use MailServer.
SMTP:
server.send_mail([recipient,], mail)
POP3:
server.get_mail(which)
server.get_mails(subject, sender, after, before)
server.get_latest()
server.get_info()
server.stat()
Parse mail:
... | acd2e2b69b6fe22ac8ae40cbe1b9d51a750e4e46 | 23,895 |
import requests
import sys
def get_rackspace_token(username, apikey):
"""Get Rackspace Identity token.
Login to Rackspace with cloud account and api key from environment vars.
Returns dict of the token and tenant id.
"""
auth_params = {
"auth": {
"RAX-KSKEY:apiKeyCredentials":... | 35809def34199245e603ea9766dd03d9f7ff6578 | 23,896 |
def calculate_hessian(model, data, step_size):
"""
Computes the mixed derivative using finite differences mathod
:param model: The imported model module
:param data: The sampled data in structured form
:param step_size: The dx time step taken between each
:returns: mixed derivative
"""
hessian = pd.... | 44ebed355e5db7991080e55f786850fb6b0e8908 | 23,897 |
def get_quarterly_income_statements(symbol):
"""
Returns quarterly IS for the past 5 yrs.
"""
df = query_av(function="INCOME_STATEMENT", symbol=symbol, datatype='quarterlyReports')
return df | 2b9094da22782d02ff5c6e4f32930c0816d213a9 | 23,898 |
def BRepBlend_HCurve2dTool_IsPeriodic(*args):
"""
:param C:
:type C: Handle_Adaptor2d_HCurve2d &
:rtype: bool
"""
return _BRepBlend.BRepBlend_HCurve2dTool_IsPeriodic(*args) | 707895ece8aa032bcd6b747c5be0313102758957 | 23,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.