content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def concat(*streams, **kwargs):
"""Concatenate audio and video streams, joining them together one after the other.
The filter works on segments of synchronized video and audio streams. All segments
must have the same number of streams of each type, and that will also be the number
of streams at output.... | a6fe1278191f85c0496ae133c4f36ccf814d6ed6 | 3,628,943 |
def proj(ax,s,ds,
axis='z',title='',vmin=1e0,vmax=1e3,dat=xr.Dataset(),**kwargs):
"""Draw projection plot at given snapshot number
Args:
ax: axes to draw.
s: LoadSim object.
ds: AthenaDataSet object.
axis: axis to project (default:'z').
title: axes title (defaul... | 0b329c8d0173944d4f037795d3b1c5a008c83c44 | 3,628,944 |
from typing import Dict
import aiohttp
from datetime import datetime
import logging
import json
import asyncio
async def fetch_network_node_health(
network_name: str,
time_s: int,
interval_s: int,
node_stats: Dict,
session: aiohttp.ClientSession,
) -> None:
"""Fetch health metric for all nodes... | 4fe082f36bf6c403357268a54a01310cc249ad53 | 3,628,945 |
def get_ingress_address(endpoint_name):
"""Returns an ingress-address belonging to the named endpoint, if
available. Falls back to private-address if necessary."""
return get_ingress_addresses(endpoint_name)[0] | 1b584e20a8b281c2739df1dd24a3c5cc9409a1e0 | 3,628,946 |
import torch
def evaluate_sfp(logits_cls, labels, flag):
""" evaluate same family prediction """
result = {}
result["n"] = len(logits_cls)
result["avg_loss"] = F.binary_cross_entropy_with_logits(logits_cls, labels.float())
if flag["acc"]:
samefamily_hat = logits_cls > 0.5
result[... | b244f57d3d6c74b468d3608d6d2972dab4ee408f | 3,628,947 |
def round(x):
"""Round tensor to nearest integer. Rounds half to even. """
return np.round(x) | c022ac98db8345ec1fe544772746d501c837cb7a | 3,628,948 |
from typing import Any
def regnet_y_8gf(
pretrained: bool = False, progress: bool = True, **kwargs: Any
) -> RegNet:
"""
Constructs a RegNetY-8GF architecture from
`"Designing Network Design Spaces" <https://arxiv.org/abs/2003.13678>`_.
Args:
pretrained (bool): If True, returns a mode... | 83c84bb2706d33c54cce4a9ce0c23eed3fc0f0e6 | 3,628,949 |
def fit_single_univariate_sample(samples):
""" Fit a univariate gaussian model based on the samples given """
gaussian = UnivariateGaussian()
return gaussian.fit(samples) | ab18a34972146d4cd506aaf59014cee0b3d8c4ae | 3,628,950 |
def get_durations_from_alignment(batch_alignments, mels, phonemes, weighted=False, binary=False, fill_gaps=False,
fix_jumps=False, fill_mode='max'):
"""
:param batch_alignments: attention weights from autoregressive model.
:param mels: mel spectrograms.
:param phone... | 192155b6968a276c308290c250f1487a4be5c1e7 | 3,628,951 |
import functools
def argparser_course_required_wrapper(with_argparser):
"""
When applied to a do_x function in the Clanvas class that takes in argparser opts,
will convert/replace course attribute with a corresponding course object either
using the course string as a query or the current (cc'd) course... | b1862167e95480eda5fe746dcd739f31292aebde | 3,628,952 |
from pathlib import Path
from typing import Optional
def read_csv_and_filter_prediction_target(csv: Path, prediction_target: str,
crossval_split_index: Optional[int] = None,
data_split: Optional[ModelExecutionMode] = None,
... | b2034440fc8c198001054edb69edcb9067cae861 | 3,628,953 |
def compare(Target, Population):
"""
This function takes in two picture objects and compares them.
:param Target: target image
:type Target: Picture object
:param Population: The population of the current generations
:type Population: A list of picture objects
:return: Two best members of... | 4456141d1c980c5ca008d614ced05e1ec2efc062 | 3,628,954 |
def normalize_AE_state(states, noSOC=True): # return normalized states for AE (no pred, soc)
"""
:param states: (9, seq, 27)
:return: (9, seq, 19)
"""
state_list = np.split(states, SPLIT_IDX, -1)
result_list = []
for state, func in zip(state_list, func_callbacks):
result_list.append... | 53d0f3d9f23bbc22ab4a3a978a6893b8f1a2238c | 3,628,955 |
def load(image_file):
"""Load the image from file path."""
image = tf.io.read_file(image_file)
image = tf.image.decode_jpeg(image)
width = tf.shape(image)[1]
width = width // 2
real_image = image[:, :width, :]
input_image = image[:, width:, :]
input_image = tf.cast(input_image, tf.flo... | c64f19c3779703dff0b08fc22740cf04ec0561b9 | 3,628,956 |
def get_corpus_directory():
"""Return path of Data/Corpus directory"""
data_directory = get_data_directory()
corpus_directory = data_directory / "Corpus"
return corpus_directory | ecb42b88390a09eb3994034b4982164fa07fc037 | 3,628,957 |
from typing import Optional
from typing import Sequence
from typing import Union
def multilateral_methods(
df: pd.DataFrame,
price_col: str = 'price',
quantity_col: str = 'quantity',
date_col: str='month',
product_id_col: str='id',
characteristics: Optional[Sequence[str]] = None,
groups: O... | 30448b0e9b0f6bff0cfd7042c154cb63d091ee9d | 3,628,959 |
import torch
def causal_fftconv(
signal: torch.Tensor,
kernel: torch.Tensor,
bias: torch.Tensor = None,
) -> torch.Tensor:
"""
Args:
signal: (Tensor) Input tensor to be convolved with the kernel.
kernel: (Tensor) Convolution kernel.
bias: (Optional, Tensor) Bias tensor to a... | 3a9cb98ee6edb00a0bf5523fa1e1e580d5a99523 | 3,628,960 |
def sell_at_loss_switch(value, exchange):
"""enable/disable buy size amount"""
tg_wrapper.helper.config[exchange]["config"].update({"sellatloss": 0})
if "sellatloss" in value:
tg_wrapper.helper.config[exchange]["config"].update({"sellatloss": 1})
return False, False
return True, True | 64ebde92f24f583f18a2a686db4956d29f4f9d64 | 3,628,961 |
def strify(iterable_struct, delimiter=','):
""" Convert an iterable structure to comma separated string.
:param iterable_struct: an iterable structure
:param delimiter: separated character, default comma
:return: a string with delimiter separated
"""
return delimiter.join(map(str, iterable_struc... | 3c8337691c9008449a86e1805fe703d6da73a523 | 3,628,962 |
import copy
def load_shifting_multiple_tech(
fueltypes,
enduse_techs,
technologies,
fuel_yh,
param_lf_improved_cy
):
"""Shift demand in case of multiple technologiesself.
Check how much of each technology is shifted in peak hours.
Calculate the absolute and rel... | 76d57269697ba4b2b7734ede87f9abe019f02243 | 3,628,963 |
def configure_node(
cluster,
node,
certnkey,
dataset_backend_configuration,
provider,
logging_config=None
):
"""
Configure flocker-dataset-agent on a node,
so that it could join an existing Flocker cluster.
:param Cluster cluster: Description of the cluster.
:param Node node... | cdff328b042b6b3a9b8afbad6e103e838735a976 | 3,628,964 |
import torch
def unsubdivide(P, T, iter=1):
"""
Unsubdivides the given mesh n times
In order to work, the mesh is intended subdivided using the method 'subdivide'.
Parameters
----------
P : Tensor
the input points set
T : LongTensor
the topology tensor
iter : int (opt... | 304d98376075925fbac549b2ab042b9e75dc9d98 | 3,628,965 |
def table2sparse(data, shape, order, m_type=lil_matrix):
"""Constructs a 2D sparse matrix from an Orange.data.Table
Note:
This methods sort the columns (=> [rows, cols])
Args:
data: Orange.data.Table
shape: (int, int)
Tuple of integers with the s... | c84309cb330eb3aab2160feb5a525e2147afcfcd | 3,628,966 |
from typing import OrderedDict
def get_s_bi_status(c: analyze.CZSC) -> OrderedDict:
"""倒数第1笔的表里关系信号
:param c: CZSC 对象
:return: 信号字典
"""
freq: Freq = c.freq
s = OrderedDict()
v = Signal(k1=str(freq.value), k2="倒1笔", k3="表里关系", v1="其他", v2='其他', v3='其他')
s[v.key] = v.value
if c.bi_... | 2cb9f416e346a0b4b8bc64081b2049f6f280ff2d | 3,628,967 |
def shuffle_code_book(encode_book):
"""
shuffle the code book
:param encode_book: code book
:return: shuffled code book
"""
codbok = np.array(list(encode_book.items()))
ids0 = np.random.permutation(codbok.shape[0])
ids1 = np.random.permutation(codbok.shape[0])
cod = codbok[ids0, 0]
... | d9f84db17179fd68daa9e5882624267d4e67a9a7 | 3,628,968 |
def default_handler(data: pd.Series, *args, **kwargs) -> pd.Series:
"""Processes given data and indicates if the data matches requirements.
Parameters
----------
data: pd.Series
The data to process.
Returns
-------
pd.Series: The logical list indicating if the data matches requirem... | c0913be67440e41a08788558e20464ef5b02caae | 3,628,969 |
def load_original_data(data, load_dirty=False):
"""
Loads the original dataframe. Missing values are replaced with
np.nan. If load_dirty is set to True, the dirty dataset of a
cleaning experiment is loaded. Otherwise, the default clean dataset
is loaded.
"""
if load_dirty:
df = pd.re... | 15fd528c49d46ea83479f2b35de99c91f5bfe46d | 3,628,970 |
def mapped_col_index_nb(mapped_arr, col_arr, n_cols):
"""Identical to `record_col_index_nb`, but for mapped arrays."""
col_index = np.full((n_cols, 2), -1, dtype=np.int_)
prev_col = -1
for r in range(mapped_arr.shape[0]):
col = col_arr[r]
if col < prev_col:
raise ValueError("... | e640da21bce2a570c0d96f588de1739f90a9bc70 | 3,628,974 |
from typing import Set
from typing import Dict
from typing import OrderedDict
def get_greedy_advanced(data: OrderedDictType[_T1, Set[_T2]], unit_counts: Dict[_T1, int], mode: SelectionMode) -> OrderedSet[_T1]:
"""The parameter ngrams needs to be ordered to be able to produce reproductable results."""
assert isins... | 8820dca332cc3c1e833195170327c1bcd49c84c8 | 3,628,975 |
def generate_pattern_eq_ipv4(value):
"""
makes a pattern to check an ip address
"""
return "ipv4-addr:value = '" + value + "'" | 36b4a09363512709c3bdf8046ea52f8ba14aa8e7 | 3,628,976 |
def get_pub_velocity_cmd_vel(**kvargs):
"""
Returns publisher for :setpoint_velocity: plugin, :cmd_vel: topic
"""
return rospy.Publisher(mavros.get_topic('setpoint_velocity', 'cmd_vel'), TwistStamped, **kvargs) | 00f0a8331950791a5a072549e13014d32cfbef37 | 3,628,979 |
def get_point_information(form):
"""
Функция для формирования json с полигоном для отрисовки аналитики по точке
:param form: форма из POST запроса с координатами точки и 6 основными фильтрами
:return: json с полигоном с необходимой информацией
"""
point_info = generate_point_information(form)
... | 4e1ec811b1c790aa4940bf2b9a178e6d3ba78d8d | 3,628,980 |
def __kspack(ks):
"""takes a kset and returns an 8-bit number"""
bits = 0
_ks = __make_ks()
for i in range(8):
if _ks[i] in ks:
bits += 2**i
return bits | 44c1a99c1c91c8c2d7991968af5b607eeccf8834 | 3,628,981 |
import warnings
def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', r2postfix='2'):
"""
Join record arrays *r1* and *r2* on *key*; *key* is a tuple of
field names -- if *key* is a string it is assumed to be a single
attribute name. If *r1* and *r2* have equal values on all the ke... | c77fb9520edd02817c806930a91058da62a91d12 | 3,628,982 |
from typing import OrderedDict
def cf(data):
"""AFF Community Facts"""
# AFF linked to Community Facts by place name
# CEDSCI links to Community Profiles by GEOID, but we can get around
# that by using search instead
raw_data = OrderedDict(zip(aff_cf, data))
if raw_data["geo_type"] == "zip":
... | 6dbbd1ff5e8d8a2a98950b9a3e7f31bc6a84db12 | 3,628,983 |
def bytes_string(text, encode="utf-8"):
"""Return a bytes object on Python 3 and a str object on Python 2"""
if not PY3:
if isinstance(text, unicode): # pylint: disable=undefined-variable
result = text.encode(encode)
else:
result... | cb8592910081330645d71906f24743736152afc7 | 3,628,986 |
def log_gaussian_prior(map_data, sigma, ps_map):
""" Gaussian prior on the power spectrum of the map
"""
data_ft = jnp.fft.fft2(map_data) / map_data.shape[0]
return -0.5*jnp.sum(jnp.real(data_ft*jnp.conj(data_ft)) / (ps_map+sigma**2)) | ad02d9225a77e476f24c244d426ad29ffc2603c5 | 3,628,987 |
def calculate_cdf(data):
"""Calculate CDF given data points
Parameters
----------
data : array-like
Input values
Returns
-------
cdf : series
Cumulative distribution funvtion calculated at indexed points
"""
data = pd.Series(data)
data = data.fillna(0)
tota... | 2d1f29f2c3f18f6a832553c3a945b027328c327b | 3,628,988 |
def sanitize_df(df, d_round=2, **options):
"""All dataframe cleaning and standardizing logic goes here."""
for c in df.columns[df.dtypes == float]:
df[c] = df[c].round(d_round)
return df | cb411b0019112155311a926ec145becc0f8c4ce9 | 3,628,990 |
from typing import Any
from typing import Dict
def bind_args(func: FunctionType, *args: Any, **kwargs: Any) -> Dict[str, Any]:
"""Bind values from `args` and `kwargs` to corresponding arguments of `func`
:param func: function to be inspected
:param args: positional arguments to be bound
:param kwargs... | dc2495b1c53bd93f4ada168abe901e831d8682ac | 3,628,991 |
def register_user(request):
"""
---REGISTER USER---
:param request:
"""
registered = False
if request.method == 'POST':
# Using forms to collect new user data
user_form = UserForm(request.POST)
if user_form.is_valid():
neighborhood = Neighborhood.objects.get(division_title=request.POST['neighborhood_text... | 89773e85a900e93198830c3ceb61591c337f8366 | 3,628,992 |
def trans_quarter(string):
"""Transform from (not lexicographic friendly) {quarter}Q{year} to a datetime object.
>>> trans_quarter('4Q2019')
datetime.datetime(2019, 10, 1, 0, 0)
"""
quarter, year = qy_parser.str_to_tuple(string)
return dt(year=year, month=month_of_quarter[quarter], day=1) | 7e3d12b000ec752a939d8f1cdc92e33ad6804628 | 3,628,993 |
def edit_post(post_id):
"""EDIT-POST page helps in editing of blog post."""
post = Post.query.get(post_id)
if post:
form = PostForm(obj=post)
if form.validate_on_submit():
post.title = form.data.get("title")
post.body = form.data.get("body")
db.session.ad... | eff5144db6eb646350b2a92ba661b0b1d50fb82b | 3,628,994 |
def shutdown(at_time=None):
"""
Shutdown a running system
at_time
The wait time in minutes before the system will be shutdown.
CLI Example:
.. code-block:: bash
salt '*' system.shutdown 5
"""
if (
salt.utils.platform.is_freebsd()
or salt.utils.platform.is_... | 17367da0e3308709347f2853daa5f2c0ed5afdf3 | 3,628,995 |
def list_products(website, category, search):
"""
There are 3 ways to list the products, 1 by category, 2 by the search bar, 3 by accessing the homepage.
"""
if search:
return Products.objects.filter(websites=website, is_available=True,
title__icontains=se... | 23fa03aebafeef8ff84077df932a0e07ba2ee4b2 | 3,628,997 |
def get_feature_columns(num_hash_buckets, embedding_dimension):
"""Creates sequential input columns to `RNNEstimator`.
Args:
num_hash_buckets: `int`, number of embedding vectors to use.
embedding_dimension: `int`, size of embedding vectors.
Returns:
List of `tf.feature_column` ojects.
"""
id_co... | ab4c60333a556839b9835d405a6c39762f1df2a3 | 3,628,998 |
def afsluitmiddel_soort(damo_gdf=None, obj=None):
""""
Zet naam van SOORTAFSLUITMIDDEL om naar attribuutwaarde
"""
data = [_afsluitmiddel_soort(name) for name in damo_gdf['SOORTAFSLUITMIDDEL']]
df = pd.Series(data=data, index=damo_gdf.index)
return df | 337eadf2bbb8b42fcdc3f4060b5a34bfdd5db13d | 3,628,999 |
def d2tf(ndp, days):
"""
Wrapper for ERFA function ``eraD2tf``.
Parameters
----------
ndp : int array
days : double array
Returns
-------
sign : char array
ihmsf : int array
Notes
-----
The ERFA documentation is below.
- - - - - - - -
e r a D 2 t f
- ... | 5577e48bf50304cbda71947e673e06ab09d18ea7 | 3,629,000 |
def libxl_init_members(ty, nesting = 0):
"""Returns a list of members of ty which require a separate init"""
if isinstance(ty, idl.Aggregate):
return [f for f in ty.fields if not f.const and isinstance(f.type,idl.KeyedUnion)]
else:
return [] | fae1eb0e3962ee59df83209ba605473f893cb2ea | 3,629,001 |
from operator import concat
def make_weekly_data(con, ticker_id, begin_date, today):
"""
INPUTS:
con (mysql) - pymysql database connection
ticker_id (int) - Ticker id number from symbols table
begin_date (str) - Last price date in series. Iso8601 standard format
today (str) - T... | 8cb9f4baca363df8f081ccf8a6eae5dc90ecd5d3 | 3,629,004 |
import zmq
def kill_service(ctrl_addr):
"""kill the LLH service running at `ctrl_addr`"""
with zmq.Context.instance().socket(zmq.REQ) as sock:
sock.setsockopt(zmq.LINGER, 0)
sock.setsockopt(zmq.RCVTIMEO, 1000)
sock.connect(ctrl_addr)
sock.send_string("die")
return soc... | 8ffdb8fda4e8ed6c9b82a70fa70adbe6fcdc7f29 | 3,629,005 |
def dmp_grounds(c, n, u):
"""
Return a list of multivariate constants.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.densebasic import dmp_grounds
>>> dmp_grounds(ZZ(4), 3, 2)
[[[[4]]], [[[4]]], [[[4]]]]
>>> dmp_grounds(ZZ(4), 3, -1)
[4, 4, 4]
... | 32f2e60bce921f525336fd8288c4736ee7677129 | 3,629,006 |
def has_attrs(inst, *args):
"""
checks if the instance has all attributes
as specified in *args and if they not falsy
:param inst: obj instance
:param args: attribute names of the object
"""
for a in args:
try:
if not getattr(inst, a, None)
return False
... | 297911bd61824cf171946afa26014ffcd0ee6be1 | 3,629,007 |
def get_related_offers(order):
"""
Search related offers to order from parameter
:param order: client order
:return: string with related offers to order from parameter or empty string
"""
related_offers = ""
if OrdersOffers.objects.filter(order=order).count() > 0:
order_offers = Orde... | d55c3d58b4e88161fbeaa3226d4d9ee636b53de4 | 3,629,008 |
import torch
def undo_imagenet_preprocess(image):
""" Undo imagenet preprocessing
Input:
- image (pytorch tensor): image after imagenet preprocessing in CPU, shape = (3, 224, 224)
Output:
- undo_image (pytorch tensor): pixel values in [0, 1]
"""
mean = torch.Tensor([0.485, 0.456, 0.406]).v... | 57d4cfc365c4e6c2dcfd37c8a2c500465daa421a | 3,629,009 |
def ob_mol_from_file(fname, ftype="xyz", add_hydrogen=True):
"""
Import a molecule from a file using OpenBabel
fname: the path string to the file to be opened
ftype: the file format
add_hydrogen: whether or not to insert hydrogens automatically
openbabel does not always add ... | 6dbbff4dc176637274af53799143e3bc862d403a | 3,629,010 |
def collapse(html):
"""Remove any indentation and newlines from the html."""
return ''.join([line.strip() for line in html.split('\n')]).strip() | a5a55691f2f51401dbd8b933562266cbed90c63d | 3,629,011 |
import torch
def multiclass_cross_entropy(phat, y, N_classes, weights, EPS = 1e-30) :
""" Per instance weighted cross entropy loss
(negative log-likelihood)
"""
y = F.one_hot(y, N_classes)
# Protection
loss = - y*torch.log(phat + EPS) * weights
loss = loss.sum() / y.shape[0]
ret... | 782e230c49314e8426a8a78cc78709929dadcf67 | 3,629,012 |
def get_arc_polygon(resolution,size=[1,1],arc=[0,1]):
"""resolution is the quantity of polygon points
horizontal and vertical size are requested
arc give the starting and ending angles"""
polygon=[]
for increment in range(resolution+1):
inc= arc[1]*(increment/resolution)
angl=(arc[0]+inc)*pi*2
polygon.append... | 7688bd90c093fb3db4a822af8e4ddd317d55cd62 | 3,629,013 |
def load(filename):
"""
Loads data line by line from a .wbp file, initiates a WellPlan object
and populates it with data.
Parameters
----------
filename: string
The location and filename of the .wbp file to load.
Returns
-------
A welleng.exchange.wbp.WellPlan o... | d0606514ffe89e9e3f09b76c8becd65db94e0bd9 | 3,629,014 |
def get_input_fn(data_dir, is_training, num_epochs, batch_size, shuffle, normalize=True):
"""
This will return input_fn from which batches of data can be obtained.
Parameters
----------
data_dir: str
Path to where the mnist data resides
is_training: bool
Whether to read the trai... | 4f41ff8939df638749efaf4a29106cc363a6737e | 3,629,015 |
def get_pagination_request_params():
"""
Pagination request params for a @doc decorator in API view.
"""
return {
"page": "Page",
"per_page": "Items per page",
} | 8ceb2f8ead3d9285017b595671f02817d098bc40 | 3,629,017 |
def access_bit(data, num):
""" from bytes array to bits by num position
"""
base = int(num // 8)
shift = 7 - int(num % 8)
return (data[base] & (1 << shift)) >> shift | fed874d0d7703c9e697da86c5a5832d20b46ebe5 | 3,629,018 |
def _any_isclose(left, right):
"""Short circuit any isclose for ndarray."""
return _any(np.isclose, left, right) | 8732c8db0b3e574a220c534ae7336acd89dbe753 | 3,629,019 |
def push(src, dest):
"""
Push object from host to target
:param src: string path to source object on host
:param dest: string destination path on target
:return: result of _exec_command() execution
"""
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_PUSH, src, dest]
return _exec_comm... | 926964ac7aa8b6c9e83c2049128bee138c5157ba | 3,629,020 |
def merge_set_if_true(set_1, set_2):
"""
Merges two sets if True
:return: New Set
"""
if set_1 and set_2:
return set_1.from_merge(set_1, set_2)
elif set_1 and not set_2:
return set_1
elif set_2 and not set_1:
return set_2
else:
return None | 833e6925ef2b3f70160238cdc32516be2482082d | 3,629,021 |
import pytz
def localtime(utc_dt, tz_str):
"""
Convert utc datetime to local timezone datetime
:param utc_dt: datetime, utc
:param tz_str: str, pytz e.g. 'US/Eastern'
:return: datetime, in timezone of tz
"""
tz = pytz.timezone(tz_str)
local_dt = tz.normalize(utc_dt.astimezone(tz))
... | f48844c72895813fdcd3913cfe7de0e6f6d0ac3c | 3,629,022 |
from typing import List
import torch
def _flatten_tensor_optim_state(
state_name: str,
pos_dim_tensors: List[torch.Tensor],
unflat_param_names: List[str],
unflat_param_shapes: List[torch.Size],
flat_param: FlatParameter,
) -> torch.Tensor:
"""
Flattens the positive-dimension tensor optimiz... | 1b8ebbbe99cc5d0ce6f48ef9f321c8ea4fd0b7ee | 3,629,023 |
def get_mysql_entitySets(username, databaseName):
""" View all the enity sets in the databaseName """
password = get_password(username)
try:
cnx = connectSQLServerDB(username, password, username + "_" + databaseName)
mycursor = cnx.cursor()
sql = "USE " + username + "_" + databaseNam... | 3eac962c936422258a2740e5ef429a72a440da92 | 3,629,025 |
def check_dbconnect_success(sess, system):
"""
測試資料庫是否成功連上(若連上且查詢成功代表資料庫存在)
Args:
sess: database connect session
system: 使用之系統名稱
Returns:
[0]: status(狀態,True/False)
[1]: err_msg(返回訊息)
"""
try:
if not sess.execute("select 1 as is_alive"): raise Exception
... | 28a4bfc0ac1a71ba9d7d13f62cea1f4bb9cec385 | 3,629,026 |
def split(filename, size=10.):
"""split the figure into color bands"""
arr, aspect = _load_array(filename)
fig = Figure(figsize=(size, size*aspect))
cmaps = ['Reds_r', 'Greens_r', 'Blues_r', 'gray_r']
for i, band in enumerate(arr):
ax = fig.add_axes([(i % 2) * .5, (1 - i // 2) * .5, .5, .5... | 4e64ed73c2054aef1f729674f13c059010466c0a | 3,629,027 |
def _compute_common_args(mapping):
"""Compute the list of arguments for dialog common options.
Compute a list of the command-line arguments to pass to dialog
from a keyword arguments dictionary for options listed as "common
options" in the manual page for dialog. These are the options
that are not ... | 3e3dff995864d64452e8ef091ec949b281899455 | 3,629,029 |
def is_url(url):
"""URL書式チェック"""
return url.startswith("https://") or url.startswith("http://") | bc8f59d2e96e0a625317e86216b9b93077bbf8e2 | 3,629,030 |
import re
def _preclean(Q):
"""
Clean before annotation.
"""
Q = re.sub('#([0-9])', r'# \1', Q)
Q = Q.replace('€', ' €').replace('\'', ' ').replace(',', '').replace('?', '').replace('\"', '').replace('(s)', '').replace(' ', ' ').replace(u'\xa0', u' ')
return Q.lower() | 115828037b884108b9e3324337874c6b23dc066c | 3,629,031 |
import aiohttp
async def job_info(request):
"""Get job info."""
conn_manager = request.app[common.KEY_CONN_MANAGER]
conn_uid = request.match_info[ROUTE_VARIABLE_CONNECTION_UID]
job_uid = request.match_info[ROUTE_VARIABLE_JOB_UID]
connection = conn_manager.connection(conn_uid)
info = await conn... | 29ad0a6fb10d1ce0b982743443889d0771940d7d | 3,629,032 |
from typing import Dict
from typing import Callable
def load_dataset_map() -> Dict[str, Callable]:
"""
Get a map of datasets.
Returns:
Dict[str, Callable]: Key: Dataset name, Value: loader function which returns (X, y).
"""
dss = {
"iris-2d": load_iris_2d,
"wine-2d": load_... | 9ecb35ba59ef1c15f0d0d609d269c2c8a54aed3b | 3,629,033 |
def m2fs_pixel_flat(flatfname, fiberconfig, Npixcut):
"""
Use the flat to find pixel variations.
DON'T USE THIS. It doesn't work.
"""
R, eR, header = read_fits_two(flatfname)
#shape = R.shape
#X, Y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing="ij")
tracefn = m2fs... | 07a82fe106f38e9da70c02d1195e596606c9d835 | 3,629,034 |
def HTTP405(environ, start_response):
"""
HTTP 405 Response
"""
start_response('405 METHOD NOT ALLOWED', [('Content-Type', 'text/plain')])
return [''] | f07522ac904ec5ab1367ef42eb5afe8a2f0d1fce | 3,629,035 |
from datetime import datetime
from typing import Iterable
def get_all_trips(*, date_from: datetime, date_to: datetime, departure_station: BusStation, arrival_station: BusStation) \
-> Iterable[Trip]:
"""
[Step1] filter trips with departure time between `date_form` and `date_to`
[Step2] filter trip... | be58f578740bde35b45435d1f82a4d5e82b4dc6d | 3,629,038 |
from typing import Callable
from typing import Optional
from datetime import datetime
import httpx
import time
def get_coinbase_api_response(
get_api_url: Callable,
base_url: str,
timestamp_from: Optional[datetime] = None,
pagination_id: Optional[str] = None,
retry=30,
):
"""Get Coinbase API r... | bc34ab3980f782403321d65214f0dad27e92e800 | 3,629,039 |
def intersect(A, B, C, D):
""" Finds the intersection of two lines represented by four points.
@parameter A: point #1, belongs to line #1
@parameter B: point #2, belongs to line #1
@parameter C: point #3, belongs to line #2
@parameter D: point #4, belongs to line #2
@returns: None if lines are... | 54bb9fc4c826de00d144120edea55463699214ac | 3,629,040 |
def detect(inputs, anchors, n_classes, img_size, scope='detection'):
"""Detect layer
"""
with tf.name_scope(scope, 'detection',[inputs]):
n_anchors = len(anchors)
bbox_attrs = 5+n_classes
predictions = inputs
grid_size = predictions.get_shape().as_list()[1:3]
n_dims = grid_size[0] * grid_size... | 4751db9980137cf3f5acaee9a900653d5f31e90e | 3,629,041 |
def get_scenario_data():
"""Return sample scenario_data
"""
return [
{
'population_count': 100,
'county': 'oxford',
'season': 'cold_month',
'timestep': 2017
},
{
'population_count': 150,
'county': 'oxford',
... | b66ba716e6bd33e1a0ff80735acb64041663ed99 | 3,629,042 |
def user_not_found(error):
"""Custom error handler.
More info: http://flask.pocoo.org/docs/1.0/patterns/apierrors/#registering-an-error-handler
"""
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response | 3b63876308d616d4d206b3eaa4742a77490f4c50 | 3,629,043 |
from typing import Dict
from typing import Any
def get_do_pass_with_amendments_by_committee(
biennium: str, agency: str, committee_name: str
) -> Dict[str, Any]:
"""See: http://wslwebservices.leg.wa.gov/committeeactionservice.asmx?op=GetDoPassWithAmendmentsByCommittee"""
argdict: Dict[str, Any] = dict(bie... | f27622c2840b3375181f42e373ad96c569d2edc6 | 3,629,044 |
def petrosian_fd(x):
"""Petrosian fractal dimension.
Parameters
----------
x : list or np.array
One dimensional time series
Returns
-------
pfd : float
Petrosian fractal dimension
Notes
-----
The Petrosian algorithm can be used to provide a fast computation of
... | 775d0e27d305d0111d20a001282d369f78f7d48e | 3,629,045 |
def lemma(word):
"""
Transforms a given word to its lemmatized form, checking a lemma dictionary. If the word is
not included in the dictionary, the same word is returned.
:param word: string containing a single word
:type: string
:return: the word's lemma
:type: string
"""
return le... | 04f434d7a86ceeadc16a2d2a4eb329f7b814e61a | 3,629,046 |
def is_style_file(filename):
"""Return True if the filename looks like a style file."""
return STYLE_FILE_PATTERN.match(filename) is not None | 18a85b21d898b27e65d8debcda408507ba5ca5d9 | 3,629,047 |
def add_subnet():
"""add subnet.
Must fields: ['subnet']
Optional fields: ['name']
"""
data = _get_request_data()
return utils.make_json_response(
200,
network_api.add_subnet(user=current_user, **data)
) | 82db191d2b678cbf873ac80878138708a10371c7 | 3,629,048 |
def V_beta(gamma, pi):
""" Defining function for the expected utility for insured agent,
where we know the coverage ratio gamma and x is drawn from beta
distribution.
Args:
pi(float): insurance premium
gamma(float): coverage ratio
Returns:
Expected utility for agent.
... | bf21816d5c80f34e8bc8c8883de14b739520a0da | 3,629,049 |
def counted(fn):
"""
count number of times a subroutine is called
:param fn:
:return:
"""
def wrapper(*args, **kwargs):
wrapper.called+= 1
return fn(*args, **kwargs)
wrapper.called= 0
wrapper.__name__= fn.__name__
return wrapper | 5c1ad20af39ed745718726045fa9f23938d7e479 | 3,629,050 |
def removeneg(im, key=0):
"""
remove NAN and INF in an image
"""
im2 = np.copy(im)
arr = im2 < 0
im2[arr] = key
return im2 | 572aa73d2f50f48b7940e476ba4cd885f93151d4 | 3,629,051 |
def mape(df, w):
"""Mean absolute percent error
Parameters
----------
df: Cross-validation results dataframe.
w: Aggregation window size.
Returns
-------
Dataframe with columns horizon and mape.
"""
ape = np.abs((df['y'] - df['yhat']) / df['y'])
if w < 0:
return pd.... | c42c1fd32d71f0f2a2c2224fc88e1f9ecc467c39 | 3,629,052 |
def p3p(pts_2d, pts_3d, K, q_ref=None, allow_imag_roots=False):
"""An implementation of the ... problem from "A Stable Algebraic Camera
Pose Estimation for Minimal Configurations of 2D/3D Point and Line Correspondences",
from Zhou et al. at ACCV 2018.
3 points
pts_2d - pixels in 2d. Each pixel is ... | a042a9adb9f4c8d705fe8fdc54c4e100c083db50 | 3,629,053 |
def status() -> tuple:
"""Health check endpoint."""
return xmlify('<status>ok</status>'), HTTP_200_OK | 0479c7f3a18b30680f8878c3f439ff9c8a18538b | 3,629,054 |
from typing import Dict
from typing import Any
from typing import Sequence
def nested_keys(nested_dict: Dict[Text, Any],
delimiter: Text = '/',
prefix: Text = '') -> Sequence[Text]:
"""Returns a flattend list of nested key strings of a nested dict.
Args:
nested_dict: Nested di... | 7403321634986897e3ab9b974ba91dc81a2b0941 | 3,629,055 |
def has_id(sxpr, id):
"""Test if an s-expression has a given id.
"""
return attribute(sxpr, 'id') == id | a7e7ce73c8c99af003dfff9954b351bb0e02cd41 | 3,629,057 |
def gf_gcdex(f, g, p, K):
"""Extended Euclidean Algorithm in `GF(p)[x]`.
Given polynomials `f` and `g` in `GF(p)[x]`, computes polynomials
`s`, `t` and `h`, such that `h = gcd(f, g)` and `s*f + t*g = h`. The
typical application of EEA is solving polynomial diophantine equations.
Consid... | e40ceccf34173d4b6349ea2c77147e2a81ff09e4 | 3,629,058 |
from datetime import datetime
def _filetime_from_timestamp(timestamp):
""" See filetimes.py for details """
# Timezones are hard, sorry
moment = datetime.fromtimestamp(timestamp)
delta_from_utc = moment - datetime.utcfromtimestamp(timestamp)
return dt_to_filetime(moment, delta_from_utc) | 81122e093c78004392e3eee7819c52bc62d8d60b | 3,629,059 |
from typing import Callable
from typing import Optional
from typing import Union
from typing import Type
from typing import Sequence
from typing import Any
from typing import get_type_hints
def optimize(
func: Callable[[np.ndarray], float],
x: ArrayLike,
trials: int = 3,
iterations: Optional[int] = 15... | ccef3d67669e0420e88b119d9c180fb35a0a98f8 | 3,629,060 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.