content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def getForegroundClassNameUnicode(hwnd=None):
"""
Returns a unicode string containing the class name of the specified
application window.
If hwnd parameter is None, frontmost window will be queried.
"""
if hwnd is None:
hwnd = win32gui.GetForegroundWindow()
# Maximum numb... | 2,600 |
def test_simple_cordex_recipe(tmp_path, patched_datafinder, config_user):
"""Test simple CORDEX recipe."""
content = dedent("""
diagnostics:
test:
additional_datasets:
- dataset: MOHC-HadGEM3-RA
project: CORDEX
product: output
... | 2,601 |
def read_mapping_from_csv(bind):
"""
Calls read_csv() and parses the loaded array into a dictionary. The dictionary is defined as follows:
{
"teams": {
*team-name*: {
"ldap": []
},
....
},
"folders: {
*folder-id*: {
"name": *folder-name*... | 2,602 |
def primal_update(
agent_id: int,
A: np.ndarray,
W: np.ndarray,
x: np.ndarray,
z: np.ndarray,
lam: np.ndarray,
prev_x: np.ndarray,
prev_z: np.ndarray,
objective_grad: np.ndarray,
feasible_set: CCS,
alpha: float,
tau: float,
nu: float,
others_agent_id: Sequence[int... | 2,603 |
def test_app_create_validation(admin_mc, admin_pc, custom_catalog,
remove_resource, restore_rancher_version):
"""Test create validation for apps. This test will set the rancher version
explicitly and attempt to create apps with rancher version requirements.
"""
# 1.6.0 use... | 2,604 |
def clean_instaces(image, min_area=20):
"""
Removes smal instances
:param image:
:return:
"""
ids, counts = np.unique(image, return_counts=True)
removables = [ids for i, ids in enumerate(ids) if counts[i] < min_area]
for r in range(0, len(removables)):
image[image == removables[r... | 2,605 |
def norm_cmap(values, cmap, normalize, cm, mn, mx):
""" Normalize and set colormap
Parameters
----------
values
Series or array to be normalized
cmap
matplotlib Colormap
normalize
matplotlib.colors.Normalize
cm
matplotl... | 2,606 |
def _cpx(odss_tuple, nterm, ncond):
"""
This function transforms the raw data for electric parameters (voltage, current...) in a suitable complex array
:param odss_tuple: tuple of nphases*2 floats (returned by odsswr as couples of real, imag components, for each phase
of each terminal)
:type od... | 2,607 |
def get_l2_distance_arad(X1, X2, Z1, Z2, \
width=0.2, cut_distance=6.0, r_width=1.0, c_width=0.5):
""" Calculates the Gaussian distance matrix D for atomic ARAD for two
sets of molecules
K is calculated using an OpenMP parallel Fortran routine.
Arguments:
==============
... | 2,608 |
def test_list_server(provider):
""" Checks whether any server is listed and has attributes"""
servers = provider.inventory.list_server()
for server in servers:
assert server.id
assert server.name
assert server.path
assert server.data
assert len(servers) > 0, "No server is... | 2,609 |
def _swap_endian(val, length):
"""
Swap the endianness of a number
"""
if length <= 8:
return val
if length <= 16:
return (val & 0xFF00) >> 8 | (val & 0xFF) << 8
if length <= 32:
return ((val & 0xFF000000) >> 24 |
(val & 0x00FF0000) >> 8 |
... | 2,610 |
def get_analysis(output, topology, traj):
"""
Calls analysis fixture with the right arguments depending on the trajectory type.
Parameters
-----------
output : str
Path to simulation 'output' folder.
topology : str
Path to the topology file.
traj : str
Trajectory typ... | 2,611 |
def check_tag_match(extended_result: bool = False):
"""
Determine the discrepancy between the declared tags
and those actually specified in the Definition
:param extended_result: If True, returns an expanded dataset instead of a boolean
:return: Boolean or tuple, depending on the extended_result var... | 2,612 |
def get_callback_class(module_name, subtype):
""" Can return None. If no class implementation exists for the given subtype, the module is
searched for a BASE_CALLBACKS_CLASS implemention which is used if found. """
module = _get_module_from_name(module_name)
if subtype is None:
return _get_c... | 2,613 |
def merge_sort(data, left=None, right=None):
"""Merge sort in place. Like selection_sort, this is a generator."""
if left is None:
left = 0
if right is None:
right = len(data)
if right <= left + 1:
return
mid = (left + right) // 2
yield 'subdivide', left, mid
yield f... | 2,614 |
def index():
"""Toon de metingen"""
return render_template('index.html', metingen=Meting.query.all()) | 2,615 |
def ensure_lambda_uninstall_permissions(session):
"""
Ensures that the current AWS session has the necessary permissions to uninstall the
New Relic AWS Lambda layer and log subscription.
:param session: A boto3 session
"""
needed_permissions = check_permissions(
session, actions=["lambd... | 2,616 |
def about(template):
"""
Attach a template to a step which can be used to generate
documentation about the step.
"""
def decorator(step_function):
step_function._about_template = template
return step_function
return decorator | 2,617 |
def _extend_batch_dim(t: torch.Tensor, new_batch_dim: int) -> torch.Tensor:
"""
Given a tensor `t` of shape [B x D1 x D2 x ...] we output the same tensor repeated
along the batch dimension ([new_batch_dim x D1 x D2 x ...]).
"""
num_non_batch_dims = len(t.shape[1:])
repeat_shape = (new_batch_dim,... | 2,618 |
def read_GTSRB_train(directory, shuffle = True):
"""
Read the training portion of GTSRB database.
Each class has an own index file.
"""
print('Reading trainset index...')
entries = []
for class_id in range(num_classes):
# each class is in a separate folder
print('\r%i%%'%(int... | 2,619 |
def get_client(config):
"""
get_client returns a feature client configured using data found in the
settings of the current application.
"""
storage = _features_from_settings(config.registry.settings)
return Client(storage) | 2,620 |
def upgrade(profile, validator, writeProfileToFileFunc):
""" Upgrade a profile in memory and validate it
If it is safe to do so, as defined by shouldWriteProfileToFile, the profile is written out.
"""
# when profile is none or empty we can still validate. It should at least have a version set.
_ensureVersionProper... | 2,621 |
def print_results(ibs, testres):
"""
Prints results from an experiment harness run.
Rows store different qaids (query annotation ids)
Cols store different configurations (algorithm parameters)
Args:
ibs (IBEISController): ibeis controller object
testres (test_result.TestResult):
... | 2,622 |
def fra_months(z): # Apologies, this function is verbose--function modeled after SSA regulations
"""A function that returns the number of months from date of birth to FRA based on SSA chart"""
# Declare global variable
global months_to_fra
# If date of birth is 1/1/1938 or earlier, full retirement age... | 2,623 |
def repo_ls(node, relative_path, color):
"""List files in the node repository folder."""
from aiida.cmdline.utils.repository import list_repository_contents
try:
list_repository_contents(node, relative_path, color)
except FileNotFoundError:
echo.echo_critical('the path `{}` does not exi... | 2,624 |
def parse_process(i, jobs_queue):
"""Pull tuples of raw page content, do CPU/regex-heavy fixup, push finished text
:param i: process id.
:param jobs_queue: where to get jobs.
"""
logging.info("enter %d-th parse_process pid:%d",i,os.getpid());
while True:
logging.info("parse_process pid:%... | 2,625 |
def set_global_format_spec(formats: SpecDict):
"""Set the global default format specifiers.
Parameters
----------
formats: dict[type, str]
Class-based format identifiers.
Returns
-------
old_spec : MultiFormatSpec
The previous globally-set formatters.
Example
-----... | 2,626 |
def gen_base_pass(length=15):
"""
Generate base password.
- A new password will be generated on each call.
:param length: <int> password length.
:return: <str> base password.
"""
generator = PassGen()
return generator.make_password(length=length) | 2,627 |
def split_component_chars(address_parts):
"""
:param address_parts: list of the form [(<address_part_1>, <address_part_1_label>), .... ]
returns [(<char_0>, <address_comp_for_char_0), (<char_1>, <address_comp_for_char_1),.., (<char_n-1>, <address_comp_for_char_n-1)]
"""
char_arr = []
for addres... | 2,628 |
def report_metrics(topic, message):
"""
将metric数据通过datamanage上报到存储中
:param topic: 需要上报的topic
:param message: 需要上报的打点数据
:return: 上报结果
"""
try:
res = DataManageApi.metrics.report({"kafka_topic": topic, MESSAGE: message, TAGS: [DEFAULT_GEOG_AREA_TAG]})
logger.info(f"report capac... | 2,629 |
def wg_completion_scripts_cb(data, completion_item, buffer, completion):
""" Complete with known script names, for command '/weeget'. """
global wg_scripts
wg_read_scripts(download_list=False)
if len(wg_scripts) > 0:
for id, script in wg_scripts.items():
weechat.hook_completion_list_... | 2,630 |
def getG(source):
""" Read the Graph from a textfile """
G = {}
Grev = {}
for i in range(1,N+1):
G[i] = []
Grev[i] = []
fin = open(source)
for line in fin:
v1 = int(line.split()[0])
v2 = int(line.split()[1])
G[v1].append(v2)
Grev[v2].append(v... | 2,631 |
def word_to_signed_int(x):
"""
returns a signed integer from the word (2-bytes)
:param x: two-bytes to convert to a signed number
"""
pass | 2,632 |
def remove_version(code):
""" Remove any version directive """
pattern = '\#\s*version[^\r\n]*\n'
regex = re.compile(pattern, re.MULTILINE|re.DOTALL)
return regex.sub('\n', code) | 2,633 |
def unlabeled_balls_in_labeled_boxes(balls, box_sizes):
"""
OVERVIEW
This function returns a generator that produces all distinct distributions of
indistinguishable balls among labeled boxes with specified box sizes
(capacities). This is a generalization of the most common formulation of the
problem,... | 2,634 |
def NortekVectorConvert(dat, vhd, csv, sample_Hz=2):
"""
Take a NortekVector output file set (.dat and .vhd files only) and convert
them into csv files with times and measurements
@inputs
dat - path to .dat file output by Nortek, containing PUV data
vhd - path to .vhd file output by... | 2,635 |
def beginning_next_non_empty_line(bdata, i):
""" doc
"""
while bdata[i] not in EOL:
i += 1
while bdata[i] in EOL:
i += 1
return i | 2,636 |
def initate_process(args_array, isse, **kwargs):
"""Function: initate_process
Description: Sets up the program log, opens a sftp connection, and
determines which option will be ran.
Arguments:
(input) args_array -> Dict of command line options and values.
(input) isse -> ISSE Gu... | 2,637 |
def VisualizeBoxes(image,
boxes,
classes,
scores,
class_id_to_name,
min_score_thresh=.25,
line_thickness=4,
groundtruth_box_visualization_color='black',
skip_scores=Fal... | 2,638 |
def tagDataskp(dList, start, end, name):
"""
Toma una posición para obtener de la lista dList.
"""
try:
#if end is not None:
if end:
#tagdata = ",".join(dList[start:end + 1])
tagdata = dList[start:end + 1]
else:
tagdata = dList[start]
... | 2,639 |
def cal_softplus(x):
"""Calculate softplus."""
return np.log(np.exp(x) + 1) | 2,640 |
def load_list_from_disk_with_pickle(path_to_list: str) -> list:
"""This function loads a list from disk
Args:
path_to_list (str): path to where the list is saved
Returns:
loaded_list (list): loaded list
Raises:
AssertionError: if list path does not exist
"""
assert os.pat... | 2,641 |
def test_app_config():
"""
Test app_init call using the 'test-fence-config.yaml'
This includes the check to verify underlying storage
"""
config_path = "test-fence-config.yaml"
root_dir = os.path.dirname(os.path.realpath(__file__))
# delete the record operation from the data blueprint, be... | 2,642 |
def prepare_spark_conversion(df: pd.DataFrame) -> pd.DataFrame:
"""Pandas does not distinguish NULL and NaN values. Everything null-like
is converted to NaN. However, spark does distinguish NULL and NaN for
example. To enable correct spark dataframe creation with NULL and NaN
values, the `PANDAS_NULL` c... | 2,643 |
def get_user_vk_id(id):
"""
:param id: Числовой ID пользователя VK
:return: Ссылка на пользователя
"""
response = requests.get('{}users.get?user_ids={}&fields=domain&access_token={}&v={}'
.format(api_address, id, token, api_version))
dict = get_dictionary(response)
... | 2,644 |
def controllable_staircase(
A,
B,
C,
D,
E,
tol=1e-9,
):
"""
Implementation of
COMPUTATION OF IRREDUCIBLE GENERALIZED STATE-SPACE REALIZATIONS ANDRAS VARGA
using givens rotations.
it is very slow, but numerically stable
TODO, add pivoting,
TODO, make it use the U-T... | 2,645 |
def loyalty():
"""Пересчитать индекс лояльности"""
articles = Article.objects.all()
if articles.count() == 0:
logger.info('Пока нет статей для пересчёта. Выходим...')
return False
logger.info('Начало пересчёта индекса лояльности')
logger.info(f'Количество материалов: {articles.count(... | 2,646 |
def user_info(request):
"""Returns a JSON object containing the logged-in student's information."""
student = request.user.student
return HttpResponse(json.dumps({
'academic_id': student.academic_id,
'current_semester': int(student.current_semester),
'name': student.name,
'us... | 2,647 |
def main():
"""
A function to bootstrap the application.
This function loads the config.json file anf runs the proxy server.
:return: None
"""
args = parse_args()
# Check if config file provided
if args.config_file:
# Get data from config file
config = load_config(args.co... | 2,648 |
def extract_brain_activation(brainimg, mask, roilabels, method='mean'):
"""
Extract brain activation from ROI.
Parameters
----------
brainimg : array
A 4D brain image array with the first dimension correspond to pictures and the rest 3D correspond to brain images
mask : array
... | 2,649 |
def list_goal():
"""List relative path pants targets."""
path = lib.rel_cwd()
pants_args = "list {0}:".format(path)
lib.pants_list(pants_args) | 2,650 |
def load_sensor_suite_from_json(manager: 'WASensorManager', filename: str):
"""Load a sensor suite from json
Each loaded sensor will be added to the manager
Args:
manager (WASensorManager): The sensor manager to store all created objects in
filename (str): The json specification file that ... | 2,651 |
def logit(x):
"""
Elementwise logit (inverse logistic sigmoid).
:param x: numpy array
:return: numpy array
"""
return np.log(x / (1.0 - x)) | 2,652 |
def _base58_decode(address: str) -> bool:
"""
SEE https://en.bitcoin.it/wiki/Base58Check_encoding
"""
try:
decoded_address = base58.b58decode(address).hex()
result, checksum = decoded_address[:-8], decoded_address[-8:]
except ValueError:
return False
else:
for _... | 2,653 |
def to_nbody(cluster, do_key_params=False, ro=8.0, vo=220.0):
"""Convert stellar positions/velocities, centre of mass, and orbital position and velocity to Nbody units
- requires that cluster.zmbar, cluster.rbar, cluster.vstar are set (defaults are 1)
Parameters
----------
cluster : class
... | 2,654 |
def get_average_matrix(shape, matrices):
""" Take the average matrix by a list of matrices of same shape """
return _ImageConvolution().get_average_matrix(shape, matrices) | 2,655 |
def pph_custom_pivot(n, t0):
"""
O algoritmo recebe uma lista n com pares de coordenadas (a, b) e retorna uma lista s, somente com as
coordenadas que juntas tenham uma razão máxima do tipo r = ((a0 + a1 + ... + an) / (b0 + b1 + ... + bn)).
Esse algoritmo tem complexidade de pior caso O(n^2) quando a ra... | 2,656 |
def train(
model,
data_loader,
optimizer,
scheduler,
checkpointer,
device,
checkpoint_arguments,
params,
tensorboard,
getter,
dataloader_val=None,
evaluator=None
):
"""
Model training engine.
:param model: model(data, targets) should return a loss diction... | 2,657 |
def make_csv(secret, site_id, path_to_csv=None, result_limit=1000, query_params=None):
"""
Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems.
:param secret: <string> Secret value for your JWPlatform API key
:param site_id: <string> ID of a JWPl... | 2,658 |
def music(hot_music_url, **kwargs):
"""
get hot music result
:return: HotMusic object
"""
result = fetch(hot_music_url, **kwargs)
# process json data
datetime = parse_datetime(result.get('active_time'))
# video_list = result.get('music_list', [])
musics = []
music_list = result.g... | 2,659 |
def parse_from_docstring(docstring, spec='operation'):
"""Returns path spec from docstring"""
# preprocess lines
lines = docstring.splitlines(True)
parser = _ParseFSM(FSM_MAP, lines, spec)
parser.run()
return parser.spec | 2,660 |
def collection_headings(commodities) -> CommodityCollection:
"""Returns a special collection of headings to test header and chapter
parenting rules."""
keys = ["9900_80_0", "9905_10_0", "9905_80_0", "9910_10_0", "9910_80_0"]
return create_collection(commodities, keys) | 2,661 |
def get_ssh_user():
"""Returns ssh username for connecting to cluster workers."""
return getpass.getuser() | 2,662 |
def tryf(body, *handlers, elsef=None, finallyf=None):
"""``try``/``except``/``finally`` as a function.
This allows lambdas to handle exceptions.
``body`` is a thunk (0-argument function) that represents
the body of the ``try`` block.
``handlers`` is ``(excspec, handler), ...``, where
... | 2,663 |
def obtain_sheet_music(score, most_frequent_dur):
"""
Returns unformated sheet music from score
"""
result = ""
octaves = [3 for i in range(12)]
accidentals = [False for i in range(7)]
for event in score:
for note_indx in range(len(event[0])):
data = notenum2string(event... | 2,664 |
def adjacency_matrix(edges):
"""
Convert a directed graph to an adjacency matrix.
Note: The distance from a node to itself is 0 and distance from a node to
an unconnected node is defined to be infinite.
Parameters
----------
edges : list of tuples
list of dependencies between n... | 2,665 |
def estimate_Cn(P=1013, T=273.15, Ct=1e-4):
"""Use Weng et al to estimate Cn from meteorological data.
Parameters
----------
P : `float`
atmospheric pressure in hPa
T : `float`
temperature in Kelvin
Ct : `float`
atmospheric struction constant of temperature, typically 10... | 2,666 |
def sg_get_scsi_status_str(scsi_status):
""" Fetch scsi status string. """
buff = _get_buffer(128)
libsgutils2.sg_get_scsi_status_str(scsi_status, 128, ctypes.byref(buff))
return buff.value.decode('utf-8') | 2,667 |
def numpy_grid(x, pad=0, nrow=None, uint8=True):
""" thin wrap to make_grid to return frames ready to save to file
args
pad (int [0]) same as utils.make_grid(padding)
nrow (int [None]) # defaults to horizonally biased rectangle closest to square
uint8 (bool [True]) convert to ... | 2,668 |
def test__dialect__ansi_specific_segment_not_parse(raw, err_locations, caplog):
"""Test queries do not parse, with parsing errors raised properly."""
lnt = Linter()
parsed = lnt.parse_string(raw)
assert len(parsed.violations) > 0
locs = [(v.line_no(), v.line_pos()) for v in parsed.violations]
as... | 2,669 |
def if_active(f):
"""decorator for callback methods so that they are only called when active"""
@functools.wraps(f)
def inner(self, loop, *args, **kwargs):
if self.active:
return f(self, loop, *args, **kwargs)
return inner | 2,670 |
def _offset(requests: int = 3) -> None:
"""
Finds offset
:param requests:
:return none:
"""
loop = asyncio.get_event_loop()
loop.run_until_complete(Offset(
requests=requests
).find()) | 2,671 |
def main() -> None:
""" Main function that runs when the Script is called from the Console """
parser = argparse.ArgumentParser(description='A Script to populate App '
'Database with the test Data.')
parser.add_argument('-d', '--drop', help='Drop Data from th... | 2,672 |
def test_helmholtz_single_layer_p0_p1(
default_parameters, helpers, precision, device_interface
):
"""Test dense assembler for the slp with disc. p0/p1 basis."""
from bempp.api.operators.boundary.helmholtz import single_layer
from bempp.api import function_space
grid = helpers.load_grid("sphere")
... | 2,673 |
def obs_all_node_target_pairs_one_hot(agent_id: int, factory: Factory) -> np.ndarray:
"""One-hot encoding (of length nodes) of the target location for each node. Size of nodes**2"""
num_nodes = len(factory.nodes)
node_pair_target = np.zeros(num_nodes ** 2)
for n in range(num_nodes):
core_target_... | 2,674 |
def repeat_each_position(shape: GuitarShape, length: int = None, repeats: int = 2, order: Callable = asc) -> List[
List[FretPosition]]:
"""
Play each fret in the sequence two or more times
"""
if length is not None:
div_length = math.ceil(length / repeats)
else:
div_length = leng... | 2,675 |
def verify_same_strand(tx_names, data):
"""Verify exons are on the same strand"""
strands = data['strand'].unique()
if len(strands) > 1:
raise ValueError(f"Multiple strands found in {tx_names}, skipping.") | 2,676 |
def gz_csv_read(file_path, use_pandas=False):
"""Read a gzipped csv file.
"""
import csv
import gzip
from StringIO import StringIO
with gzip.open(file_path, 'r') as infile:
if use_pandas:
import pandas
data = pandas.read_csv(StringIO(infile.read()))
else:
... | 2,677 |
def init_block(in_channels, out_channels, stride, activation=nn.PReLU):
"""Builds the first block of the MobileFaceNet"""
return nn.Sequential(
nn.BatchNorm2d(3),
nn.Conv2d(in_channels, out_channels, 3, stride, 1, bias=False),
nn.BatchNorm2d(out_channels),
make_activation(activat... | 2,678 |
def yield_in_except_throw_exc_type():
"""
>>> g = yield_in_except_throw_exc_type()
>>> next(g)
>>> g.throw(TypeError)
Traceback (most recent call last):
TypeError
>>> next(g)
Traceback (most recent call last):
StopIteration
"""
try:
raise ValueError
except ValueEr... | 2,679 |
def address_working(address, value=None):
"""
Find, insert or delete from database task address
:param address: website address example: https://www.youtube.com/
:param value: True: add , False: remove, default: find
:return:
"""
global db
if value is True:
db.tasks.insert_one({'... | 2,680 |
def merge_default_values(resource_list, default_values):
"""
Generate a new list where each item of original resource_list will be merged with the default_values.
Args:
resource_list: list with items to be merged
default_values: properties to be merged with each item list. If the item alrea... | 2,681 |
async def async_setup_entry_usb(hass, config_entry, async_add_entities):
"""Set up Plugwise sensor based on config_entry."""
api_stick = hass.data[DOMAIN][config_entry.entry_id][STICK]
async def async_add_sensors(mac: str):
"""Add plugwise sensors for device."""
entities = []
entiti... | 2,682 |
def paint_smi_matrixs(matrixs, index=0):
"""paint similarity matrix (TSM/ KQ) """
plt.clf()
b, c, w, h = matrixs.shape
for i in range(c):
matrix = matrixs[0, i, :, :].detach().cpu().numpy()
plt.imshow(matrix)
plt.colorbar()
dir = 'graph/matrixs{0}'.format(index)
i... | 2,683 |
def test_ap_wpa2_eap_tls_domain_match_cn(dev, apdev):
"""WPA2-Enterprise using EAP-TLS and domainmatch (CN)"""
check_domain_match(dev[0])
params = int_eap_server_params()
params["server_cert"] = "auth_serv/server-no-dnsname.pem"
params["private_key"] = "auth_serv/server-no-dnsname.key"
hostapd.a... | 2,684 |
def finish_scheduling(request, schedule_item=None, payload=None):
"""
Finalize the creation of a scheduled action. All required data is passed
through the payload.
:param request: Request object received
:param schedule_item: ScheduledAction item being processed. If None,
it has to be extracted... | 2,685 |
def handle_result(context, res):
"""Handle results (sink)"""
_, date_key, df = res
try:
df = df.join(context['cep'])
except TypeError:
context['cep'].index = context['cep'].index.tz_localize(df.index.tz)
df = df.join(context['cep'])
df.to_csv(os.path.join(DST_D... | 2,686 |
def analyze(results_file, base_path):
"""
Parse and print the results from gosec audit.
"""
# Load gosec json Results File
with open(results_file) as f:
issues = json.load(f)['Issues']
if not issues:
print("Security Check: No Issues Detected!")
return ([], [], [])
e... | 2,687 |
def _peaks(image,nr,minvar=0):
"""Divide image into nr quadrants and return peak value positions."""
n = np.ceil(np.sqrt(nr))
quadrants = _rects(image.shape,n,n)
peaks = []
for q in quadrants:
q_image = image[q.as_slice()]
q_argmax = q_image.argmax()
q_maxpos = np.unravel_ind... | 2,688 |
def send_init_analytics(opt_out: bool, config_path: str, executed_at: datetime) -> None:
"""
Create a new `AnalyticsClient` and send an `AnalyticsEvent` representing
the execution of `fidesctl init` by a user.
"""
if opt_out is not False:
return
analytics_id = get_config_from_file(conf... | 2,689 |
def adf_test(df: pd.Series):
"""
정상성(Stationary) 검증 방법 - Dicky-Fuller test
$HO$ (귀무가설) : 비정상이 아니다라고 할만한 근거가 없다.
$H1$ 대립가설 : 비정상이 아니다.
* p-value가 5% 이내면, 귀무가설 기각
* Adjusted Close를 통해 정상섬 검증
* p-value가 0.05보다 작지 않으므로, 귀무가설을 기각할 수 없다. 그래서 비정상이 아니라고 할만한 근거가 없기 때문에 비정상이라고 말할 수도 있다.
:par... | 2,690 |
def pprint(value):
"""A wrapper around pprint.pprint -- for debugging, really."""
try:
return pformat(value)
except Exception as e:
return "Error in formatting: %s: %s" % (e.__class__.__name__, e) | 2,691 |
def dev_populate_db():
"""Performs the initial database setup for the application
"""
current_app.logger.info("Initializing tables with dev data")
roles = {x.name: x for x in model.UserRole.query.all()}
db_session.add_all(
[
model.User(
"superuser", "SuperUser", ... | 2,692 |
def connection_type_validator(type):
"""
Property: ConnectionInput.ConnectionType
"""
valid_types = [
"CUSTOM",
"JDBC",
"KAFKA",
"MARKETPLACE",
"MONGODB",
"NETWORK",
"SFTP",
]
if type not in valid_types:
raise ValueError("% is not a... | 2,693 |
def plot_time_series(meter_data, temperature_data, **kwargs):
""" Plot meter and temperature data in dual-axes time series.
Parameters
----------
meter_data : :any:`pandas.DataFrame`
A :any:`pandas.DatetimeIndex`-indexed DataFrame of meter data with the column ``value``.
temperature_data : ... | 2,694 |
def render_pretty_time(jd):
"""Convert jd into a pretty string representation"""
year, month, day, hour_frac = sweph.revjul(jd)
_, hours, minutes, seconds = days_frac_to_dhms(hour_frac/24)
time_ = calendar.timegm((year,month,day,hours,minutes,seconds,0,0,0))
return time.strftime('%e %b %Y %H:%M UTC'... | 2,695 |
def jsonify(obj):
"""Dump an object to JSON and create a Response object from the dump.
Unlike Flask's native implementation, this works on lists.
"""
dump = json.dumps(obj)
return Response(dump, mimetype='application/json') | 2,696 |
def section(stree):
"""
Create sections in a :class:`ScheduleTree`. A section is a sub-tree with
the following properties: ::
* The root is a node of type :class:`NodeSection`;
* The immediate children of the root are nodes of type :class:`NodeIteration`
and have same parent.
... | 2,697 |
def was_csv_updated() -> bool:
""" This function compares the last modified time on the csv file to the
actions folder to check which was last modified.
1. check if csv or files have more actions.
2. if same number of actions, assume the update was made in the csv
"""
csv_actions = get_cas_from... | 2,698 |
def MakeBands(dR, numberOfBands, nearestInteger):
"""
Divide a range into bands
:param dR: [min, max] the range that is to be covered by the bands.
:param numberOfBands: the number of bands, a positive integer.
:param nearestInteger: if True then [floor(min), ceil(max)] is used.
:return: A List... | 2,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.