max_stars_repo_path
stringlengths 4
245
| max_stars_repo_name
stringlengths 7
115
| max_stars_count
int64 101
368k
| id
stringlengths 2
8
| content
stringlengths 6
1.03M
|
---|---|---|---|---|
Z - Tool Box/LaZagne/Windows/lazagne/softwares/games/turba.py | dfirpaul/Active-Directory-Exploitation-Cheat-Sheet-1 | 1,290 | 11087686 | # -*- coding: utf-8 -*-
import os
try:
import _winreg as winreg
except ImportError:
import winreg
import lazagne.config.winstructure as win
from lazagne.config.module_info import ModuleInfo
from lazagne.config.winstructure import string_to_unicode
class Turba(ModuleInfo):
def __init__(self):
ModuleInfo.__init__(self, 'turba', 'games', registry_used=True)
def run(self):
creds = []
results = None
# Find the location of steam - to make it easier we're going to use a try block
# 'cos I'm lazy
try:
with win.OpenKey(win.HKEY_CURRENT_USER, 'Software\Valve\Steam') as key:
results = winreg.QueryValueEx(key, 'SteamPath')
except Exception:
pass
if results:
steampath = string_to_unicode(results[0])
steamapps = os.path.join(steampath, u'SteamApps\common')
# Check that we have a SteamApps directory
if not os.path.exists(steamapps):
self.error(u'Steam doesn\'t have a SteamApps directory.')
return
filepath = os.path.join(steamapps, u'Turba\\Assets\\Settings.bin')
if not os.path.exists(filepath):
self.debug(u'Turba doesn\'t appear to be installed.')
return
# If we're here we should have a valid config file file
with open(filepath, mode='rb') as filepath:
# We've found a config file, now extract the creds
data = filepath.read()
chunk = data[0x1b:].split('\x0a')
creds.append({
'Login': chunk[0],
'Password': chunk[1]
})
return creds
|
scripts/controllers/controller.py | MPC-Berkeley/genesis_path_follower | 101 | 11087689 | import abc
class Controller:
""" Abstract Base Class for control implementation. """
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def solve(self):
""" Returns a dictionary sol_dict with control input to apply,
as well as other useful information (e.g. MPC solution).
In particular, sol_dict must have a key "u_control" such that
sol_dict["u_control"][0] = acceleration input to apply
sol_dict["u_control"][1] = steering input to apply
"""
raise NotImplementedError
@abc.abstractmethod
def update(self, update_dict):
""" Updates the state of the controller with feedback info contained in update_dict. """
raise NotImplementedError
|
ML/Projects/Exploring_MNIST/utils/utils.py | xuyannus/Machine-Learning-Collection | 3,094 | 11087703 | <reponame>xuyannus/Machine-Learning-Collection
import torch
import visdom
import os
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float32
def save_checkpoint(filename, model, optimizer, train_acc, epoch):
save_state = {
"state_dict": model.state_dict(),
"acc": train_acc,
"epoch": epoch + 1,
"optimizer": optimizer.state_dict(),
}
print()
print("Saving current parameters")
print("___________________________________________________________")
torch.save(save_state, filename)
def check_accuracy(loader, model):
if loader.dataset.train:
print("Checking accuracy on training or validation set")
else:
print("Checking accuracy on test set")
num_correct = 0
num_samples = 0
# model.eval() # set model to evaluation mode
with torch.no_grad():
for x, y in loader:
x = x.to(device=device, dtype=dtype) # move to device, e.g. GPU
y = y.to(device=device, dtype=torch.long)
scores = model(x)
_, preds = scores.max(1)
num_correct += (preds == y).sum()
num_samples += preds.size(0)
acc = (float(num_correct) / num_samples) * 100.0
print("Got %d / %d correct (%.2f)" % (num_correct, num_samples, acc))
return acc
def load_model(args, model, optimizer):
if args.resume:
model.eval()
if os.path.isfile(args.resume):
print("=> loading checkpoint '{}'".format(args.resume))
checkpoint = torch.load(args.resume)
start_epoch = checkpoint["epoch"]
best_acc = checkpoint["acc"]
model.load_state_dict(checkpoint["state_dict"])
optimizer.load_state_dict(checkpoint["optimizer"])
print(
"=> loaded checkpoint '{}' (epoch {})".format(
args.resume, checkpoint["epoch"]
)
)
return model, optimizer, checkpoint, start_epoch, best_acc
else:
print("=> no checkpoint found at '{}'".format(args.resume))
else:
print("No pretrained model. Starting from scratch!")
class visdom_plotting(object):
def __init__(self):
self.viz = visdom.Visdom()
self.cur_batch_win = None
self.cur_batch_win_opts = {
"title": "Epoch Loss Trace",
"xlabel": "Batch Number",
"ylabel": "Loss",
"width": 600,
"height": 400,
}
self.cur_validation_acc = None
self.cur_validation_acc_opts = {
"title": "Validation accuracy",
"xlabel": "Epochs",
"ylabel": "Validation Accuracy",
"width": 600,
"height": 400,
}
self.cur_training_acc = None
self.cur_training_acc_opts = {
"title": "Training accuracy",
"xlabel": "Epochs",
"ylabel": "Train Accuracy",
"width": 600,
"height": 400,
}
def create_plot(
self, loss_list, batch_list, validation_acc_list, epoch_list, training_acc_list
):
if self.viz.check_connection():
self.cur_batch_win = self.viz.line(
torch.FloatTensor(loss_list),
torch.FloatTensor(batch_list),
win=self.cur_batch_win,
name="current_batch_loss",
update=(None if self.cur_batch_win is None else "replace"),
opts=self.cur_batch_win_opts,
)
self.cur_validation_acc = self.viz.line(
torch.FloatTensor(validation_acc_list),
torch.FloatTensor(epoch_list),
win=self.cur_validation_acc,
name="current_validation_accuracy",
update=(None if self.cur_validation_acc is None else "replace"),
opts=self.cur_validation_acc_opts,
)
self.cur_training_acc = self.viz.line(
torch.FloatTensor(training_acc_list),
torch.FloatTensor(epoch_list),
win=self.cur_validation_acc,
name="current_training_accuracy",
update=(None if self.cur_training_acc is None else "replace"),
opts=self.cur_training_acc_opts,
)
#
|
src/olympia/addons/signals.py | shashwatsingh/addons-server | 843 | 11087723 | <filename>src/olympia/addons/signals.py
import django.dispatch
version_changed = django.dispatch.Signal()
|
scripts/mell/core/trainer.py | zhenhua32/EasyTransfer | 806 | 11087728 | <filename>scripts/mell/core/trainer.py
# coding=utf-8
# Copyright (c) 2020 Alibaba PAI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import time
import torch
from torch.utils.data import DataLoader, RandomSampler
from torch.utils.data.distributed import DistributedSampler
try:
from torch.utils.tensorboard import SummaryWriter
except:
from tensorboardX import SummaryWriter
from evaluator import Evaluator
from optimizers import get_optimizer
from layers.base import WEIGHTS_NAME, CONFIG_NAME
from utils import exporter, io, get_dir_name
from utils.logger import logger
from utils.statistics import Statistics
class Trainer(object):
def __init__(self, model, train_dataset, valid_dataset, cfg, evaluator=None):
self.cfg = cfg
self._model = None
self._optimizer = None
self._train_loader = None
self._valied_loader = None
self._start_epoch = 0
self._start_global_step = 0
self._start_time = time.time()
self._current_loss = 0.
self._eval_scores = None
self._best_valid_score = float('-inf')
self._current_epoch = self._start_epoch
self.set_evaluator(evaluator, valid_dataset.eval_metrics)
self.set_data_loader(train_dataset, valid_dataset, cfg)
self.set_model_and_optimizer(model, cfg)
self.resume_from_ckpt(self.model_module, cfg)
self.set_tensorboard()
self._global_step = self._start_epoch * len(self._train_loader)
@property
def model_module(self):
if self._model is None:
return self._model
# space left for apex/deepspeed
return self._model.module if hasattr(self._model, 'module') else self._model
@property
def learning_rate(self):
return self._optimizer.get_current_lr()
def set_model_and_optimizer(self, model, cfg):
self._model = model.to(self.cfg.local_rank)
if self.cfg.n_gpu > 1:
self._model = torch.nn.parallel.DistributedDataParallel(
self._model, device_ids=[self.cfg.local_rank],
output_device=self.cfg.local_rank,
find_unused_parameters=True)
# Build Optimizer
self._optimizer = get_optimizer(optimizer_type="adam",
learning_rate=cfg.learning_rate,
warmup_proportion=cfg.warmup_proportion,
max_grad_norm=cfg.max_grad_norm,
named_parameters=list(self.model_module.named_parameters()),
gradient_accumulation_steps=cfg.gradient_accumulation_steps,
num_steps_per_epoch=len(self._train_loader),
epoch_num=cfg.epoch_num)
# space left for apex/deepspeed
def resume_from_ckpt(self, model_module, cfg):
if cfg.resume_from_checkpoint is None:
return
meta_file = cfg.resume_from_checkpoint + ".meta.bin"
model_file = cfg.resume_from_checkpoint + ".bin"
if "oss::" in cfg.resume_from_checkpoint:
local_file = "easytexminer_resume_pytorch_model.meta.bin"
io.download(model_file, local_file)
meta_file = local_file
local_file = "easytexminer_resume_pytorch_model.bin"
io.download(model_file, local_file)
model_file = local_file
with io.open(meta_file, "rb") as f:
meta_data = torch.load(f, map_location='cpu')
self._start_epoch = meta_data["epoch"]
self._start_global_step = meta_data["global_step"] + 1
self._optimizer.load_state_dict(meta_data['optimizer'])
logger.info("Resume from checkpoint {}".format(cfg.resume_from_checkpoint))
logger.info("Start epoch {}".format(self._start_epoch))
logger.info("Start step {}".format(self._start_global_step))
logger.info("Start learning rate {:.6f}".format(self._optimizer.get_current_lr()))
with io.open(model_file, "rb") as f:
model_module.load_state_dict(torch.load(f, map_location='cpu'))
logger.info("Resume checkpoint Done".format(cfg.resume_from_checkpoint))
def set_tensorboard(self):
cfg = self.cfg
if not cfg.is_master_node:
return
logger.info("=" * 10 + " Initializing Tensorboard " + "=" * 10)
if "oss://" in cfg.checkpoint_dir:
self.tensorboard = SummaryWriter(log_dir=os.path.join("./easytexminer_tensorboard"))
else:
self.tensorboard = SummaryWriter(log_dir=os.path.join(cfg.checkpoint_dir, "log"))
self.tensorboard.add_text(tag="config/training", text_string=str(self.cfg), global_step=0)
self.tensorboard.add_text(tag="config/model_arch",
text_string=self.model_module.arch, global_step=0)
def set_evaluator(self, evaluator=None, eval_metrics=None):
if evaluator is None:
self.evaluator = Evaluator(metrics=eval_metrics)
else:
self.evaluator = evaluator
def set_data_loader(self, train_dataset, valid_dataset, cfg):
if cfg.read_odps:
train_sampler = None
else:
train_sampler = RandomSampler if cfg.n_gpu <= 1 else DistributedSampler
self._train_loader = DataLoader(train_dataset,
sampler=train_sampler(train_dataset) if train_sampler else None,
batch_size=cfg.train_batch_size,
collate_fn=train_dataset.batch_fn)
self._valid_loader = DataLoader(valid_dataset,
batch_size=cfg.eval_batch_size,
shuffle=False,
collate_fn=valid_dataset.batch_fn)
def log_train_infos(self):
cfg = self.cfg
logger.info("=" * 10 + " Training Start " + "=" * 10 + "\n")
logger.info(" Num of GPUs = %d", cfg.n_gpu)
n_tr_samples = len(self._train_loader.dataset) * cfg.n_gpu if cfg.read_odps else len(self._train_loader.dataset)
logger.info(" Num training examples = %d", n_tr_samples)
logger.info(" Num validation examples = %d", len(self._valid_loader.dataset))
logger.info(" Training batch size = %d",
cfg.train_batch_size * cfg.n_gpu * cfg.gradient_accumulation_steps)
logger.info(" Evaluation batch size = %d", cfg.eval_batch_size)
total_training_steps = self._optimizer.total_training_steps
logger.info(" Total training steps = %d", total_training_steps)
logger.info(" Saving steps = %s", str(cfg.save_checkpoint_steps))
model_num_params = sum([p.nelement() for n, p in self.model_module.named_parameters()])
trainable_num_params = sum([p.nelement() for n, p in self.model_module.named_parameters() if p.requires_grad])
logger.info(" num model parameters = %s" % format(model_num_params, ","))
logger.info(" num trainable parameters = %s" % format(trainable_num_params, ","))
logger.info("\n")
logger.info("=" * 10 + " Model Arch " + "=" * 10)
logger.info(self.model_module.arch)
def before_epoch(self, _epoch):
cfg = self.cfg
self._current_epoch = _epoch
if cfg.n_gpu > 1:
torch.distributed.barrier()
self._model.train()
self._epoch_tr_loss = 0.0
self._epoch_n_tr_steps = 0.0
if cfg.is_master_node:
self._epoch_stats = Statistics(epoch_num=int(cfg.epoch_num),
total_training_steps=self._optimizer.total_training_steps)
def after_epoch(self):
pass
def before_iter(self):
pass
def optimizer_step(self):
self._optimizer.step()
self._optimizer.zero_grad()
def after_iter(self, _step, _epoch, loss_dict):
cfg = self.cfg
self.pred_loss = loss_dict["loss"].item()
self._epoch_tr_loss += self.pred_loss
self._epoch_n_tr_steps += 1
if (_step + 1) % cfg.gradient_accumulation_steps == 0:
self.optimizer_step()
self._global_step += 1
if not cfg.is_master_node:
return
self._epoch_stats.update(loss_dict)
if self._global_step == 0 or (self._global_step + 1) % cfg.logging_steps == 0:
self._epoch_stats.output(self._global_step + 1, _epoch, self.learning_rate)
self._epoch_stats.log_tensorboard(writer=self.tensorboard,
learning_rate=self.learning_rate,
current_loss=self.pred_loss,
global_step=self._global_step,
output_dir=os.path.join(cfg.checkpoint_dir, "log"))
if cfg.save_checkpoint_steps and (self._global_step + 1) % cfg.save_checkpoint_steps == 0:
print()
if cfg.save_all_checkpoints:
self.save_checkpoint()
self._eval_scores = self.evaluator.evaluate(
model=self._model, valid_loader=self._valid_loader)
if self._eval_scores[0][1] > self._best_valid_score:
logger.info("Saving best model to %s..." % os.path.join(cfg.checkpoint_dir, WEIGHTS_NAME))
self.save_checkpoint(save_best=True)
self._best_valid_score = self._eval_scores[0][1]
logger.info("Best score: {}".format(self._best_valid_score))
logger.info("Learning rate: {:.8f}".format(self._optimizer.get_current_lr()))
logger.info("")
self._epoch_stats.log_tensorboard(writer=self.tensorboard,
learning_rate=self.learning_rate,
eval_scores=self._eval_scores,
global_step=self._global_step,
is_training=False,
output_dir=os.path.join(cfg.checkpoint_dir, "log"))
def after_train(self):
cfg = self.cfg
# Save last checkpoint if needed
if not cfg.is_master_node:
return
if cfg.save_checkpoint_steps is None:
logger.info("Saving best model to %s..." % os.path.join(cfg.checkpoint_dir, WEIGHTS_NAME))
self.save_checkpoint(save_best=True)
else:
self._eval_scores = self.evaluator.evaluate(
model=self._model, valid_loader=self._valid_loader)
if self._eval_scores[0][1] > self._best_valid_score:
logger.info("Saving best model to %s..." % os.path.join(cfg.checkpoint_dir, WEIGHTS_NAME))
self.save_checkpoint(save_best=True)
self._best_valid_score = self._eval_scores[0][1]
logger.info("Best score: {}".format(self._best_valid_score))
self.tensorboard.close()
logger.info("Training Time: {}".format(time.time() - self._start_time))
def save_checkpoint(self, save_best=False):
if not self.cfg.is_master_node:
return
# Save config.json
output_config_file = os.path.join(self.cfg.checkpoint_dir, CONFIG_NAME)
with io.open(output_config_file, "w") as f:
f.write(self.model_module.arch)
# Save vocab.txt
if self.cfg.pretrain_model_name_or_path is not None:
io.copy(os.path.join(get_dir_name(self.cfg.pretrain_model_name_or_path), "vocab.txt"),
os.path.join(get_dir_name(self.cfg.checkpoint_dir), "vocab.txt"))
# Save the model
model_to_save_prefix = "pytorch_model" if save_best else "pytorch_model_step_%d" % (self._global_step + 1)
with io.open(os.path.join(self.cfg.checkpoint_dir, model_to_save_prefix + ".bin"), "wb") \
as output_model_file:
torch.save(self.model_module.state_dict(), output_model_file)
meta_data = {
"epoch": self._current_epoch,
"global_step": self._global_step,
"optimizer": self._optimizer.state_dict()
}
with io.open(os.path.join(self.cfg.checkpoint_dir, model_to_save_prefix + ".meta.bin"), "wb") \
as output_model_file:
torch.save(meta_data, output_model_file)
if not save_best:
return
if hasattr(self.model_module, "model_name"):
# If the student is pre-defined EasyTransfer AppZoo model
# Save train_config.json, model.ckpt.* for EasyTransfer
logger.info("Export tensorflow checkpoint (%s format) to %s" % (
self.cfg.export_tf_checkpoint_type,
os.path.join(get_dir_name(self.cfg.checkpoint_dir), "model.ckpt")))
exporter.export_easytransfer_train_config(
saved_path=os.path.join(self.cfg.checkpoint_dir, "train_config.json"),
vocab_dir=get_dir_name(self.cfg.checkpoint_dir),
label_enumerate_values=self._valid_loader.dataset.label_enumerate_values,
sequence_length=self.cfg.sequence_length,
model_name=self.model_module.model_name,
extra_model_params=self.model_module.extra_model_params)
if self.cfg.export_tf_checkpoint_type == "easytransfer":
exporter.export_pytorch_checkpoint_to_tf(
model=self.model_module,
ckpt_dir=get_dir_name(self.cfg.checkpoint_dir),
bert_output_prefix="bert_pre_trained_model",
appended_val_map=(("classifier", "app/ez_dense"),),
appended_tensors_to_transpose=("classifier.weight",))
elif self.cfg.export_tf_checkpoint_type == "google":
exporter.export_pytorch_checkpoint_to_tf(
model=self.model_module,
ckpt_dir=get_dir_name(self.cfg.checkpoint_dir),
bert_output_prefix="",
appended_val_map=(("classifier.weight", "output_weights"),
("classifier.bias", "output_bias")),
appended_tensors_to_transpose=())
else:
raise RuntimeError("Invalid export_tf_checkpoint_type %s" % self.cfg.export_tf_checkpoint_type)
# This is a hack
torch.cuda.set_device(self.cfg.local_rank)
def train(self):
self.log_train_infos()
cfg = self.cfg
for _epoch in range(self._start_epoch, int(cfg.epoch_num)):
self.before_epoch(_epoch)
for _step, batch in enumerate(self._train_loader):
print('running step: {}'.format(_step))
if self._global_step + 1 < self._start_global_step:
if (_step + 1) % cfg.gradient_accumulation_steps == 0:
self._global_step += 1
continue
self.before_iter()
batch = {key: val.to(cfg.local_rank) if isinstance(val, torch.Tensor) else val
for key, val in batch.items()}
# model output logis
model_outputs = self._model(batch)
loss_dict = self.model_module.compute_loss(model_outputs, batch)
_loss = loss_dict["loss"]
if cfg.n_gpu > 1:
_loss = _loss.mean()
if cfg.gradient_accumulation_steps > 1:
_loss = _loss / cfg.gradient_accumulation_steps
_loss.backward()
self.after_iter(_step, _epoch, loss_dict)
self.after_epoch()
print('running to here!!!!')
self.after_train()
class DistillTrainer(Trainer):
def __init__(self,
teacher_model,
student_model,
distiller,
train_dataset,
valid_dataset,
cfg,
evaluator=None):
self.cfg = cfg
self.teacher = teacher_model
self.teacher = self.teacher.to(cfg.local_rank) if self.teacher else None
student_model.init_from_teacher(self.teacher, cfg.student_init_strategy)
self.distiller = distiller
self.need_teacher_in_eval = "last_layer_mse" in train_dataset.eval_metrics
super(DistillTrainer, self).__init__(student_model, train_dataset, valid_dataset,
cfg, evaluator=evaluator)
if cfg.is_master_node:
if self.teacher is not None:
self.tensorboard.add_text(tag="config/teacher_arch",
text_string=str(self.teacher.module.arch
if hasattr(self.teacher, "module")
else self.teacher.arch), global_step=0)
self.tensorboard.add_text(tag="config/kd_map",
text_string=json.dumps(self.distiller.kd_map, indent=4), global_step=0)
def log_train_infos(self):
super(DistillTrainer, self).log_train_infos()
if self.teacher is not None:
logger.info("=" * 10 + " Teacher Arch " + "=" * 10)
logger.info(self.teacher.module.arch if hasattr(self.teacher, "module") else self.teacher.arch)
logger.info("=" * 10 + " Distiller KD Map " + "=" * 10)
logger.info(json.dumps(self.distiller.kd_map, indent=4))
def train(self):
self.log_train_infos()
cfg = self.cfg
for _epoch in range(self._start_epoch, int(cfg.epoch_num)):
self.before_epoch(_epoch)
for _step, batch in enumerate(self._train_loader):
if self._global_step + 1 < self._start_global_step:
if (_step + 1) % cfg.gradient_accumulation_steps == 0:
self._global_step += 1
continue
self.before_iter()
batch = {key: val.to(cfg.local_rank) if isinstance(val, torch.Tensor) else val
for key, val in batch.items()}
if self.teacher is not None:
with torch.no_grad():
teacher_outputs = self.teacher(batch)
elif "teacher_logits" in batch:
teacher_outputs = {
"logits": batch["teacher_logits"]
}
else:
teacher_outputs = {}
student_outputs = self._model(batch)
label_ids = batch["label_ids"] if "label_ids" in batch else None
attention_mask = batch["input_mask"] if "input_mask" in batch else None
kd_loss, kd_loss_dict = self.distiller(
teacher_outputs, student_outputs, label_ids, attention_mask)
kd_loss_dict["loss"] = kd_loss
if cfg.n_gpu > 1:
kd_loss = kd_loss.mean()
if cfg.gradient_accumulation_steps > 1:
kd_loss = kd_loss / cfg.gradient_accumulation_steps
kd_loss.backward()
self.after_iter(_step, _epoch, kd_loss_dict)
self.after_epoch()
self.after_train()
|
data_utils/utils.py | Pelhans/ZASR_tensorflow | 115 | 11087732 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
import os
from collections import Counter
import numpy as np
import scipy.io.wavfile as wav
from python_speech_features import mfcc
from data_utils.audio_featurizer import AudioFeaturizer
from data_utils.speech import SpeechSegment
from data_utils.normalizer import FeatureNormalizer
from conf.hyparam import Config
'''
To help creat train set and get batch from data
'''
def next_batch(start_idx=0,
batch_size=1,
n_input=None,
n_context=None,
labels=None,
wav_files=None,
word_num_map=None,
specgram_type='mfcc'):
""" Get data batch for training
:param start_idx:
:param batch_size:
:param n_input:
:param n_context:
:param labels:
:param wav_files:
:param word_num_map:
:param specgram_type
:return:
"""
filesize = len(labels)
end_idx = min(filesize, start_idx + batch_size)
idx_list = range(start_idx, end_idx)
txt_labels = [labels[i] for i in idx_list]
wav_files = [wav_files[i] for i in idx_list]
audio_features, audio_features_len, text_vector, text_vector_len = get_audio_mfcc_features(None,
wav_files,
n_input,
n_context,
word_num_map,
txt_labels,
specgram_type)
start_idx += batch_size
# confirm start_idx
if start_idx >= filesize:
start_idx = -1
# use 0 padding when serveral inputs
audio_features, audio_features_len = pad_sequences(audio_features)
sparse_labels = sparse_tuple_from(text_vector)
return start_idx, audio_features, audio_features_len, sparse_labels, wav_files
def get_audio_mfcc_features(txt_files, wav_files, n_input,
n_context, word_num_map, txt_labels=None,
specgram_type='mfcc', mean_std_filepath='data/aishell/mean_std.npz'):
""" Get MFCC/linear specgram features. The dim of MFCC is 39, contains 13 mfcc + 13 delta1 + 13 delta2.
Linear specgram contains 161 features in different frequency section.
:param txt_files:
:param wav_files:
:param n_input:
:param n_context:
:param word_num_map:
:param txt_labels:
:return:
"""
audio_features = []
audio_features_len = []
text_vector = []
text_vector_len = []
if txt_files != None:
txt_labels = txt_files
get_feature = AudioFeaturizer(specgram_type)
normalizer = FeatureNormalizer(mean_std_filepath)
for txt_obj, wav_file in zip(txt_labels, wav_files):
# Turn inputs into features
if specgram_type == 'mfcc':
audio_data = audiofile_to_input_vector(wav_file, n_input, n_context) # get mfcc feature ( ???, 741 )
elif specgram_type == 'linear':
speech_segment = SpeechSegment.from_file(wav_file, "")
specgram = get_feature.featurize(speech_segment)
audio_data = normalizer.apply(specgram)
audio_data = np.transpose(audio_data) # get linear specgram feature, (?, 161)
audio_data = audio_data.astype('float32')
audio_features.append(audio_data)
audio_features_len.append(np.int32(len(audio_data)))
target = []
if txt_files != None: # txt_obj是文件
target = trans_text_ch_to_vector(txt_obj, word_num_map)
else:
target = trans_text_ch_to_vector(None, word_num_map, txt_obj) # txt_obj是labels
text_vector.append(target)
text_vector_len.append(len(target))
audio_features = np.asarray(audio_features)
audio_features_len = np.asarray(audio_features_len)
text_vector = np.asarray(text_vector)
text_vector_len = np.asarray(text_vector_len)
return audio_features, audio_features_len, text_vector, text_vector_len
def sparse_tuple_from(sequences, dtype=np.int32):
""" Turn dense matrix to sparse matrix
:param sequences:
:param dtype:
:return:
"""
indices = []
values = []
for n, seq in enumerate(sequences):
indices.extend(zip([n] * len(seq), range(len(seq))))
values.extend(seq)
indices = np.asarray(indices, dtype=np.int64)
values = np.asarray(values, dtype=dtype)
shape = np.asarray([len(sequences), indices.max(0)[1] + 1], dtype=np.int64)
return indices, values, shape
def trans_text_ch_to_vector(txt_file, word_num_map, txt_label=None):
""" Trans chinese chars to vector
:param txt_file:
:param word_num_map:
:param txt_label:
:return:
"""
words_size = len(word_num_map)
to_num = lambda word: word_num_map.get(word.encode('utf-8'), words_size)
if txt_file != None:
txt_label = get_ch_lable(txt_file)
labels_vector = list(map(to_num, txt_label))
return labels_vector
def get_ch_lable(txt_file):
labels = ""
with open(txt_file, 'rb') as f:
for label in f:
labels = labels + label.decode('gb2312')
return labels
def trans_tuple_to_texts_ch(tuple, words):
""" Trans vector to chars
:param tuple:
:param words:
:return:
"""
indices = tuple[0]
values = tuple[1]
results = [''] * tuple[2][0]
for i in range(len(indices)):
index = indices[i][0]
c = values[i]
c = ' ' if c == 0 else words[c] # chr(c + FIRST_INDEX)
results[index] = results[index] + c
return results
def trans_array_to_text_ch(value, words):
results = ''
for i in range(len(value)):
results += words[value[i]] # chr(value[i] + FIRST_INDEX)
return results.replace('`', ' ')
def audiofile_to_input_vector(audio_filename, n_input, n_context):
""" Compute MFCC features with n_context
:param audio_filename:
:param n_input:
:param n_context:
:return:
"""
fs, audio = wav.read(audio_filename)
# get mfcc features with dim 39
get_feature = AudioFeaturizer("mfcc")
speech_segment = SpeechSegment.from_file(audio_filename, "")
orig_inputs = get_feature.featurize(speech_segment) # (39, ?)
orig_inputs = np.transpose(orig_inputs) # trans to time major (?, 39)
train_inputs = np.zeros((orig_inputs.shape[0], n_input + 2 * n_input * n_context)) #(***/2, 195)
empty_mfcc = np.zeros((n_input))
# Prepare input data, consist of three parts,
# output is (past hyparam.n_context * 39 + current + future hyparam.n_context * 39)
time_slices = range(train_inputs.shape[0])
context_past_min = time_slices[0] + n_context
context_future_max = time_slices[-1] - n_context
for time_slice in time_slices:
# padding with 0 for the first of 9,mfcc features
need_empty_past = max(0, (context_past_min - time_slice))
empty_source_past = list(empty_mfcc for empty_slots in range(need_empty_past))
data_source_past = orig_inputs[ max(0, time_slice - n_context):time_slice]
# padding with 0 for the last of 9,mfcc features
need_empty_future = max(0, (time_slice - context_future_max))
empty_source_future = list(empty_mfcc for empty_slots in range(need_empty_future))
data_source_future = orig_inputs[time_slice + 1:time_slice + n_context + 1]
if need_empty_past:
past = np.concatenate((empty_source_past, data_source_past))
else:
past = data_source_past
if need_empty_future:
future = np.concatenate((data_source_future, empty_source_future))
else:
future = data_source_future
past = np.reshape(past, n_context * 39)
now = orig_inputs[time_slice]
future = np.reshape(future, n_context * n_input)
train_inputs[time_slice] = np.concatenate((past, now, future))
# Tran data to Norm distribution, minus mean value then over the varr
train_inputs = (train_inputs - np.mean(train_inputs)) / np.std(train_inputs)
# shape of train_inputs: (shape(orig_inputs)/2, n_context * 2 * 39 + 39)
return train_inputs
def pad_sequences(sequences, maxlen=None, dtype=np.float32,
padding='post', truncating='post', value=0.):
""" Padding data with 0
:param sequences:
:param maxlen:
:param dtype:
:param padding:
:param truncating:
:param value:
:return:
"""
sequences_each_len = np.asarray([len(s) for s in sequences], dtype=np.int64)
nb_samples = len(sequences)
if maxlen is None:
maxlen = np.max(sequences_each_len)
sample_shape = tuple()
for s in sequences:
if len(s) > 0:
sample_shape = np.asarray(s).shape[1:]
break
x = (np.ones((nb_samples, maxlen) + sample_shape) * value).astype(dtype)
for idx, s in enumerate(sequences):
if len(s) == 0:
continue
if truncating == 'pre':
trunc = s[-maxlen:]
elif truncating == 'post':
trunc = s[:maxlen]
else:
raise ValueError('Truncating type "%s" not understood' % truncating)
# check `trunc` has expected shape
trunc = np.asarray(trunc, dtype=dtype)
if trunc.shape[1:] != sample_shape:
raise ValueError('Shape of sample %s of sequence at position %s is different from expected shape %s' %
(trunc.shape[1:], idx, sample_shape))
if padding == 'post':
x[idx, :len(trunc)] = trunc
elif padding == 'pre':
x[idx, -len(trunc):] = trunc
else:
raise ValueError('Padding type "%s" not understood' % padding)
return x, sequences_each_len
if __name__ == "__main__":
print("")
|
src/prefect/tasks/asana/asana_task.py | concreted/prefect | 8,633 | 11087741 | <filename>src/prefect/tasks/asana/asana_task.py
from prefect import Task
from typing import Any
from prefect.utilities.tasks import defaults_from_attrs
try:
import asana
except ImportError:
pass
class OpenAsanaToDo(Task):
"""
Task for opening / creating new Asana tasks using the Asana REST API.
Args:
- project (str; , required): The GID of the project the task will be posted to;
can also be provided to the `run` method
- name (str, optional): the name of the task to create; can also be provided to the
`run` method
- notes (str, optional): the contents of the task; can also be provided to the `run` method
- token (str): an Asana Personal Access Token
- **kwargs (Any, optional): additional keyword arguments to pass to the standard Task
init method
"""
def __init__(
self,
name: str = None,
notes: str = None,
project: str = None,
token: str = None,
**kwargs: Any
):
self.name = name
self.notes = notes
self.project = project
self.token = token
super().__init__(**kwargs)
@defaults_from_attrs("name", "notes", "project", "token")
def run(
self,
name: str = None,
notes: str = None,
project: str = None,
token: str = None,
) -> None:
"""
Run method for this Task. Invoked by calling this Task after initialization within a
Flow context, or by using `Task.bind`.
Args:
- name (str, optional): the name of the task to create; can also be provided at initialization
- project (str; , required): The GID of the project the task will be posted to;
can also be provided at initialization
- notes (str, optional): the contents of the task; can also be provided at initialization
- token (str): an ASANA Personal Access Token
Raises:
- ValueError: if no project is provided
- ValueError: if no access token is provided
- ValueError: if no result is returned
Returns:
- The result object with details of the new asana task
"""
if project is None:
raise ValueError("An Asana project must be provided.")
if token is None:
raise ValueError("An Asana access token must be provided.")
client = asana.Client.access_token(token)
result = client.tasks.create_task(
{"name": name, "notes": notes, "projects": [project]}
)
if not result:
raise ValueError("Creating Asana Task failed")
return result
|
open_spiel/python/algorithms/discounted_cfr_test.py | texasmichelle/open_spiel | 3,167 | 11087774 | <filename>open_spiel/python/algorithms/discounted_cfr_test.py<gh_stars>1000+
# Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Tests for open_spiel.python.algorithms.discounted_cfr."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
import numpy as np
from open_spiel.python.algorithms import discounted_cfr
from open_spiel.python.algorithms import expected_game_score
import pyspiel
class DiscountedCfrTest(absltest.TestCase):
def test_discounted_cfr_on_kuhn(self):
game = pyspiel.load_game("kuhn_poker")
solver = discounted_cfr.DCFRSolver(game)
for _ in range(300):
solver.evaluate_and_update_policy()
average_policy = solver.average_policy()
average_policy_values = expected_game_score.policy_value(
game.new_initial_state(), [average_policy] * 2)
# 1/18 is the Nash value. See https://en.wikipedia.org/wiki/Kuhn_poker
np.testing.assert_allclose(
average_policy_values, [-1 / 18, 1 / 18], atol=1e-3)
def test_discounted_cfr_runs_against_leduc(self):
game = pyspiel.load_game("leduc_poker")
solver = discounted_cfr.DCFRSolver(game)
for _ in range(10):
solver.evaluate_and_update_policy()
solver.average_policy()
if __name__ == "__main__":
absltest.main()
|
var/spack/repos/builtin/packages/py-planar/package.py | kkauder/spack | 2,360 | 11087802 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyPlanar(PythonPackage):
"""2D planar geometry library for Python."""
homepage = "https://bitbucket.org/caseman/planar/src/default/"
pypi = "planar/planar-0.4.zip"
version('0.4', sha256='cbfb9cbae8b0e296e6e7e3552b7d685c7ed5cae295b7a61f2b2b096b231dad76')
|
Contents/Libraries/Shared/subliminal/utils.py | jippo015/Sub-Zero.bundle | 1,553 | 11087806 | <gh_stars>1000+
# -*- coding: utf-8 -*-
from datetime import datetime
import hashlib
import os
import re
import struct
def hash_opensubtitles(video_path):
"""Compute a hash using OpenSubtitles' algorithm.
:param str video_path: path of the video.
:return: the hash.
:rtype: str
"""
bytesize = struct.calcsize(b'<q')
with open(video_path, 'rb') as f:
filesize = os.path.getsize(video_path)
filehash = filesize
if filesize < 65536 * 2:
return
for _ in range(65536 // bytesize):
filebuffer = f.read(bytesize)
(l_value,) = struct.unpack(b'<q', filebuffer)
filehash += l_value
filehash &= 0xFFFFFFFFFFFFFFFF # to remain as 64bit number
f.seek(max(0, filesize - 65536), 0)
for _ in range(65536 // bytesize):
filebuffer = f.read(bytesize)
(l_value,) = struct.unpack(b'<q', filebuffer)
filehash += l_value
filehash &= 0xFFFFFFFFFFFFFFFF
returnedhash = '%016x' % filehash
return returnedhash
def hash_thesubdb(video_path):
"""Compute a hash using TheSubDB's algorithm.
:param str video_path: path of the video.
:return: the hash.
:rtype: str
"""
readsize = 64 * 1024
if os.path.getsize(video_path) < readsize:
return
with open(video_path, 'rb') as f:
data = f.read(readsize)
f.seek(-readsize, os.SEEK_END)
data += f.read(readsize)
return hashlib.md5(data).hexdigest()
def hash_napiprojekt(video_path):
"""Compute a hash using NapiProjekt's algorithm.
:param str video_path: path of the video.
:return: the hash.
:rtype: str
"""
readsize = 1024 * 1024 * 10
with open(video_path, 'rb') as f:
data = f.read(readsize)
return hashlib.md5(data).hexdigest()
def hash_shooter(video_path):
"""Compute a hash using Shooter's algorithm
:param string video_path: path of the video
:return: the hash
:rtype: string
"""
filesize = os.path.getsize(video_path)
readsize = 4096
if os.path.getsize(video_path) < readsize * 2:
return None
offsets = (readsize, filesize // 3 * 2, filesize // 3, filesize - readsize * 2)
filehash = []
with open(video_path, 'rb') as f:
for offset in offsets:
f.seek(offset)
filehash.append(hashlib.md5(f.read(readsize)).hexdigest())
return ';'.join(filehash)
def sanitize(string, ignore_characters=None):
"""Sanitize a string to strip special characters.
:param str string: the string to sanitize.
:param set ignore_characters: characters to ignore.
:return: the sanitized string.
:rtype: str
"""
# only deal with strings
if string is None:
return
ignore_characters = ignore_characters or set()
# replace some characters with one space
characters = {'-', ':', '(', ')', '.'} - ignore_characters
if characters:
string = re.sub(r'[%s]' % re.escape(''.join(characters)), ' ', string)
# remove some characters
characters = {'\''} - ignore_characters
if characters:
string = re.sub(r'[%s]' % re.escape(''.join(characters)), '', string)
# replace multiple spaces with one
string = re.sub(r'\s+', ' ', string)
# strip and lower case
return string.strip().lower()
def sanitize_release_group(string):
"""Sanitize a `release_group` string to remove content in square brackets.
:param str string: the release group to sanitize.
:return: the sanitized release group.
:rtype: str
"""
# only deal with strings
if string is None:
return
# remove content in square brackets
string = re.sub(r'\[\w+\]', '', string)
# strip and upper case
return string.strip().upper()
def timestamp(date):
"""Get the timestamp of the `date`, python2/3 compatible
:param datetime.datetime date: the utc date.
:return: the timestamp of the date.
:rtype: float
"""
return (date - datetime(1970, 1, 1)).total_seconds()
|
omni_anomaly/model.py | hyydrra/OmniAnomaly | 344 | 11087831 | # -*- coding: utf-8 -*-
from functools import partial
import tensorflow as tf
import tfsnippet as spt
from tensorflow.python.ops.linalg.linear_operator_identity import LinearOperatorIdentity
from tensorflow_probability.python.distributions import LinearGaussianStateSpaceModel, MultivariateNormalDiag
from tfsnippet.distributions import Normal
from tfsnippet.utils import VarScopeObject, reopen_variable_scope
from tfsnippet.variational import VariationalInference
from omni_anomaly.recurrent_distribution import RecurrentDistribution
from omni_anomaly.vae import Lambda, VAE
from omni_anomaly.wrapper import TfpDistribution, softplus_std, rnn, wrap_params_net
class OmniAnomaly(VarScopeObject):
def __init__(self, config, name=None, scope=None):
self.config = config
super(OmniAnomaly, self).__init__(name=name, scope=scope)
with reopen_variable_scope(self.variable_scope):
if config.posterior_flow_type == 'nf':
self._posterior_flow = spt.layers.planar_normalizing_flows(
config.nf_layers, name='posterior_flow')
else:
self._posterior_flow = None
self._window_length = config.window_length
self._x_dims = config.x_dim
self._z_dims = config.z_dim
self._vae = VAE(
p_z=TfpDistribution(
LinearGaussianStateSpaceModel(
num_timesteps=config.window_length,
transition_matrix=LinearOperatorIdentity(config.z_dim),
transition_noise=MultivariateNormalDiag(
scale_diag=tf.ones([config.z_dim])),
observation_matrix=LinearOperatorIdentity(config.z_dim),
observation_noise=MultivariateNormalDiag(
scale_diag=tf.ones([config.z_dim])),
initial_state_prior=MultivariateNormalDiag(
scale_diag=tf.ones([config.z_dim]))
)
) if config.use_connected_z_p else Normal(mean=tf.zeros([config.z_dim]), std=tf.ones([config.z_dim])),
p_x_given_z=Normal,
q_z_given_x=partial(RecurrentDistribution,
mean_q_mlp=partial(tf.layers.dense, units=config.z_dim, name='z_mean', reuse=tf.AUTO_REUSE),
std_q_mlp=partial(softplus_std, units=config.z_dim, epsilon=config.std_epsilon,
name='z_std'),
z_dim=config.z_dim, window_length=config.window_length) if config.use_connected_z_q else Normal,
h_for_p_x=Lambda(
partial(
wrap_params_net,
h_for_dist=lambda x: rnn(x=x,
window_length=config.window_length,
rnn_num_hidden=config.rnn_num_hidden,
hidden_dense=2,
dense_dim=config.dense_dim,
name='rnn_p_x'),
mean_layer=partial(
tf.layers.dense, units=config.x_dim, name='x_mean', reuse=tf.AUTO_REUSE
),
std_layer=partial(
softplus_std, units=config.x_dim, epsilon=config.std_epsilon,
name='x_std'
)
),
name='p_x_given_z'
),
h_for_q_z=Lambda(
lambda x: {'input_q': rnn(x=x,
window_length=config.window_length,
rnn_num_hidden=config.rnn_num_hidden,
hidden_dense=2,
dense_dim=config.dense_dim,
name="rnn_q_z")},
name='q_z_given_x'
) if config.use_connected_z_q else Lambda(
partial(
wrap_params_net,
h_for_dist=lambda x: rnn(x=x,
window_length=config.window_length,
rnn_num_hidden=config.rnn_num_hidden,
hidden_dense=2,
dense_dim=config.dense_dim,
name="rnn_q_z"),
mean_layer=partial(
tf.layers.dense, units=config.z_dim, name='z_mean', reuse=tf.AUTO_REUSE
),
std_layer=partial(
softplus_std, units=config.z_dim, epsilon=config.std_epsilon,
name='z_std'
)
),
name='q_z_given_x'
)
)
@property
def x_dims(self):
"""Get the number of `x` dimensions."""
return self._x_dims
@property
def z_dims(self):
"""Get the number of `z` dimensions."""
return self._z_dims
@property
def vae(self):
"""
Get the VAE object of this :class:`OmniAnomaly` model.
Returns:
VAE: The VAE object of this model.
"""
return self._vae
@property
def window_length(self):
return self._window_length
def get_training_loss(self, x, n_z=None):
"""
Get the training loss for `x`.
Args:
x (tf.Tensor): 2-D `float32` :class:`tf.Tensor`, the windows of
KPI observations in a mini-batch.
n_z (int or None): Number of `z` samples to take for each `x`.
(default :obj:`None`, one sample without explicit sampling
dimension)
Returns:
tf.Tensor: 0-d tensor, the training loss, which can be optimized
by gradient descent algorithms.
"""
with tf.name_scope('training_loss'):
chain = self.vae.chain(x, n_z=n_z, posterior_flow=self._posterior_flow)
x_log_prob = chain.model['x'].log_prob(group_ndims=0)
log_joint = tf.reduce_sum(x_log_prob, -1)
chain.vi.training.sgvb()
vi = VariationalInference(
log_joint=log_joint,
latent_log_probs=chain.vi.latent_log_probs,
axis=chain.vi.axis
)
loss = tf.reduce_mean(vi.training.sgvb())
return loss
def get_score(self, x, n_z=None,
last_point_only=True):
"""
Get the reconstruction probability for `x`.
The larger `reconstruction probability`, the less likely a point
is anomaly. You may take the negative of the score, if you want
something to directly indicate the severity of anomaly.
Args:
x (tf.Tensor): 2-D `float32` :class:`tf.Tensor`, the windows of
KPI observations in a mini-batch.
n_z (int or None): Number of `z` samples to take for each `x`.
(default :obj:`None`, one sample without explicit sampling
dimension)
last_point_only (bool): Whether to obtain the reconstruction
probability of only the last point in each window?
(default :obj:`True`)
Returns:
tf.Tensor: The reconstruction probability, with the shape
``(len(x) - self.x_dims + 1,)`` if `last_point_only` is
:obj:`True`, or ``(len(x) - self.x_dims + 1, self.x_dims)``
if `last_point_only` is :obj:`False`. This is because the
first ``self.x_dims - 1`` points are not the last point of
any window.
"""
with tf.name_scope('get_score'):
x_r = x
# get the reconstruction probability
print('-' * 30, 'testing', '-' * 30)
q_net = self.vae.variational(x=x_r, n_z=n_z, posterior_flow=self._posterior_flow) # notice: x=x_r
p_net = self.vae.model(z=q_net['z'], x=x, n_z=n_z) # notice: x=x
z_samples = q_net['z'].tensor
z_mean = tf.reduce_mean(z_samples, axis=0) if n_z is not None else z_samples
z_std = tf.sqrt(tf.reduce_sum(tf.square(z_samples - z_mean), axis=0) / (n_z - 1)) \
if n_z is not None and n_z > 1 else tf.zeros_like(z_mean)
z = tf.concat((z_mean, z_std), axis=-1)
r_prob = p_net['x'].log_prob(group_ndims=int(not self.config.get_score_on_dim))
if last_point_only:
r_prob = r_prob[:, -1]
return r_prob, z
|
textworld/thirdparty/glulx/Git-Glulx/user_agent.py | JohnnySun8/TextWorld | 307 | 11087834 | <filename>textworld/thirdparty/glulx/Git-Glulx/user_agent.py<gh_stars>100-1000
def evaluate(words):
return ('n', False)
|
packaging/setup/plugins/ovirt-engine-setup/ovirt-engine-common/dialog/titles.py | hbraha/ovirt-engine | 347 | 11087836 | #
# ovirt-engine-setup -- ovirt engine setup
#
# Copyright oVirt Authors
# SPDX-License-Identifier: Apache-2.0
#
#
"""Titles plugin."""
import gettext
from otopi import plugin
from otopi import util
from ovirt_engine_setup import constants as osetupcons
from ovirt_engine_setup import util as osetuputil
from ovirt_engine_setup.engine_common import constants as oengcommcons
def _(m):
return gettext.dgettext(message=m, domain='ovirt-engine-setup')
@util.export
class Plugin(plugin.PluginBase):
"""Titles plugin."""
def _title(self, text):
self.dialog.note(
text='\n--== %s ==--\n\n' % text,
)
def __init__(self, context):
super(Plugin, self).__init__(context=context)
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=osetupcons.Stages.DIALOG_TITLES_S_PACKAGES,
after=(
osetupcons.Stages.DIALOG_TITLES_E_PRODUCT_OPTIONS,
),
condition=lambda self: (
osetuputil.is_ovirt_packaging_supported_distro()
),
)
def _title_s_packages(self):
self._title(
text=_('PACKAGES'),
)
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=osetupcons.Stages.DIALOG_TITLES_E_PACKAGES,
after=(
osetupcons.Stages.DIALOG_TITLES_S_PACKAGES,
),
)
def _title_e_packages(self):
pass
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=osetupcons.Stages.DIALOG_TITLES_S_NETWORK,
after=(
osetupcons.Stages.DIALOG_TITLES_E_PACKAGES,
),
)
def _title_s_network(self):
self._title(
text=_('NETWORK CONFIGURATION'),
)
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.NETWORK_OWNERS_CONFIG_CUSTOMIZED,
before=(
osetupcons.Stages.DIALOG_TITLES_E_NETWORK,
),
after=(
osetupcons.Stages.DIALOG_TITLES_S_NETWORK,
),
)
def _network_owners_config_customized(self):
pass
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=osetupcons.Stages.DIALOG_TITLES_E_NETWORK,
after=(
osetupcons.Stages.DIALOG_TITLES_S_NETWORK,
),
)
def _title_e_network(self):
pass
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.DIALOG_TITLES_S_DATABASE,
after=(
osetupcons.Stages.DIALOG_TITLES_E_NETWORK,
),
)
def _title_s_database(self):
self._title(
text=_('DATABASE CONFIGURATION'),
)
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.DB_OWNERS_CONNECTIONS_CUSTOMIZED,
before=(
oengcommcons.Stages.DIALOG_TITLES_E_DATABASE,
),
after=(
oengcommcons.Stages.DIALOG_TITLES_S_DATABASE,
),
)
def _db_owners_connections_customized(self):
pass
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.DIALOG_TITLES_E_DATABASE,
after=(
oengcommcons.Stages.DIALOG_TITLES_S_DATABASE,
),
)
def _title_e_database(self):
pass
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.DIALOG_TITLES_S_ENGINE,
after=(
oengcommcons.Stages.DIALOG_TITLES_E_DATABASE,
),
)
def _title_s_engine(self):
self._title(
text=_('OVIRT ENGINE CONFIGURATION'),
)
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.DIALOG_TITLES_E_ENGINE,
after=(
oengcommcons.Stages.DIALOG_TITLES_S_ENGINE,
),
)
def _title_e_engine(self):
pass
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.DIALOG_TITLES_S_STORAGE,
after=(
oengcommcons.Stages.DIALOG_TITLES_E_ENGINE,
),
)
def _title_s_storage(self):
self._title(
text=_('STORAGE CONFIGURATION'),
)
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.DIALOG_TITLES_E_STORAGE,
after=(
oengcommcons.Stages.DIALOG_TITLES_S_STORAGE,
),
)
def _title_e_storage(self):
pass
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.DIALOG_TITLES_S_PKI,
after=(
oengcommcons.Stages.DIALOG_TITLES_E_STORAGE,
),
)
def _title_s_pki(self):
self._title(
text=_('PKI CONFIGURATION'),
)
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.DIALOG_TITLES_E_PKI,
after=(
oengcommcons.Stages.DIALOG_TITLES_S_PKI,
),
)
def _title_e_pki(self):
pass
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.DIALOG_TITLES_S_APACHE,
after=(
oengcommcons.Stages.DIALOG_TITLES_E_PKI,
),
)
def _title_s_apache(self):
self._title(
text=_('APACHE CONFIGURATION'),
)
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=oengcommcons.Stages.DIALOG_TITLES_E_APACHE,
after=(
oengcommcons.Stages.DIALOG_TITLES_S_APACHE,
),
)
def _title_e_apache(self):
pass
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=osetupcons.Stages.DIALOG_TITLES_S_SYSTEM,
after=(
oengcommcons.Stages.DIALOG_TITLES_E_APACHE,
),
)
def _title_s_system(self):
self._title(
text=_('SYSTEM CONFIGURATION'),
)
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=osetupcons.Stages.DIALOG_TITLES_E_SYSTEM,
after=(
osetupcons.Stages.DIALOG_TITLES_S_SYSTEM,
),
)
def _title_e_system(self):
pass
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=osetupcons.Stages.DIALOG_TITLES_S_MISC,
after=(
osetupcons.Stages.DIALOG_TITLES_E_SYSTEM,
),
)
def _title_s_misc(self):
self._title(
text=_('MISC CONFIGURATION'),
)
@plugin.event(
stage=plugin.Stages.STAGE_CUSTOMIZATION,
name=osetupcons.Stages.DIALOG_TITLES_E_MISC,
after=(
osetupcons.Stages.DIALOG_TITLES_S_MISC,
),
)
def _title_e_misc(self):
self._title(
text=_('END OF CONFIGURATION'),
)
# vim: expandtab tabstop=4 shiftwidth=4
|
thumbor/handler_lists/upload.py | bear8421/thumbor | 6,837 | 11087838 | <filename>thumbor/handler_lists/upload.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com <EMAIL>
from typing import Any, cast
from thumbor.handler_lists import HandlerList
from thumbor.handlers.image_resource import ImageResourceHandler
from thumbor.handlers.upload import ImageUploadHandler
def get_handlers(context: Any) -> HandlerList:
is_upload_enabled = cast(bool, context.config.UPLOAD_ENABLED)
if not is_upload_enabled:
return []
return [
(r"/image", ImageUploadHandler, {"context": context}),
(r"/image/(.*)", ImageResourceHandler, {"context": context}),
]
|
tests/test_stacks.py | coltonfischer/pydfs-lineup-optimizer | 326 | 11087854 | from __future__ import absolute_import, division
import unittest
from collections import Counter, defaultdict
from parameterized import parameterized
from pydfs_lineup_optimizer import get_optimizer
from pydfs_lineup_optimizer.constants import Site, Sport
from pydfs_lineup_optimizer.player import Player, GameInfo
from pydfs_lineup_optimizer.exceptions import LineupOptimizerException
from pydfs_lineup_optimizer.utils import list_intersection
from pydfs_lineup_optimizer.stacks import GameStack, TeamStack, PositionsStack
from tests.utils import load_players
class StacksRuleTestCase(unittest.TestCase):
def setUp(self):
self.players = load_players()
self.optimizer = get_optimizer(Site.DRAFTKINGS, Sport.BASKETBALL)
self.optimizer.settings.max_from_one_team = 4
self.test_team = 'TEST'
self.spacing_players = [
Player('1', '1', '1', ['PG'], self.test_team, 100, 4, roster_order=1),
Player('2', '2', '2', ['SG'], self.test_team, 100, 3, roster_order=2),
Player('3', '3', '3', ['SG'], self.test_team, 100, 3, roster_order=2),
Player('4', '4', '4', ['SF'], self.test_team, 100, 5, roster_order=3),
Player('5', '5', '5', ['PF'], self.test_team, 100, 1, roster_order=4),
]
self.optimizer.player_pool.load_players(self.players + self.spacing_players)
def test_stacks_correctness(self):
stacks = [4, 2]
for stack in stacks:
self.optimizer.add_stack(TeamStack(stack))
lineup = next(self.optimizer.optimize(n=1))
teams = Counter([player.team for player in lineup])
self.assertListEqual(stacks, [stack[1] for stack in Counter(teams).most_common(len(stacks))])
def test_stack_greater_than_max_from_one_team(self):
with self.assertRaises(LineupOptimizerException):
self.optimizer.add_stack(TeamStack(5))
def test_stacks_for_positions(self):
position = 'PG'
self.optimizer.add_stack(TeamStack(4, for_positions=[position]))
lineup = next(self.optimizer.optimize(n=1))
all_position_players_teams = [player.team for player in lineup if position in player.positions]
self.assertEqual(len(set(all_position_players_teams)), 1)
@parameterized.expand([
(3, [1, 3]),
(2, [2, 3]),
(1, [2, 2]),
])
def test_stacks_with_spacing(self, spacing, expected):
self.optimizer.add_stack(TeamStack(2, spacing=spacing))
lineup = next(self.optimizer.optimize(n=1))
spacings = [player.roster_order for player in lineup if player in self.spacing_players]
spacings.sort()
self.assertEqual(spacings, expected)
class TestPositionsFromSameTeamTestCase(unittest.TestCase):
def setUp(self):
self.optimizer = get_optimizer(Site.YAHOO, Sport.BASKETBALL)
self.first_team = 'TEST'
self.second_team = 'TEST2'
self.players = [
Player('1', 'p1', 'p1', ['PG'], self.first_team, 10, 200),
Player('2', 'p2', 'p2', ['SG'], 'team2', 10, 200),
Player('3', 'p3', 'p3', ['SF'], 'team3', 10, 200),
Player('4', 'p4', 'p4', ['PF'], 'team4', 10, 200),
Player('5', 'p5', 'p5', ['C'], 'team5', 10, 200),
Player('6', 'p6', 'p6', ['PG', 'SG'], 'team6', 10, 200),
Player('7', 'p7', 'p7', ['SF', 'PF'], 'team7', 10, 200),
Player('8', 'p8', 'p8', ['SF', 'PF'], self.second_team, 10, 2),
Player('9', 'p9', 'p9', ['PG', 'SG', 'SF'], self.second_team, 10, 2),
Player('10', 'p10', 'p10', ['C'], self.first_team, 10, 2),
Player('11', 'p11', 'p11', ['SF'], self.first_team, 10, 2),
Player('12', 'p12', 'p12', ['PF', 'C'], self.first_team, 10, 2),
]
self.optimizer.player_pool.load_players(self.players)
@parameterized.expand([
(['PG', 'C'], ),
(['PG', 'SF', 'C'], ),
(['PG', 'SF', 'C', 'C'], ),
])
def test_positions_from_same_team(self, combination):
self.optimizer.stacks = []
self.optimizer.add_stack(PositionsStack(combination))
lineup = next(self.optimizer.optimize(1))
self.assertEqual(len([p for p in lineup.lineup if p.team == self.first_team]), len(combination))
def test_multiple_positions_from_same_team(self):
from_same_team = (['PG', 'C'], ['SG', 'SF'])
for position_stack in from_same_team:
self.optimizer.add_stack(PositionsStack(position_stack))
lineup = next(self.optimizer.optimize(1))
self.assertEqual(len([p for p in lineup.lineup if p.team == self.first_team]), len(from_same_team[0]))
self.assertEqual(len([p for p in lineup.lineup if p.team == self.second_team]), len(from_same_team[1]))
def test_positions_stack_greater_than_max_from_one_team(self):
with self.assertRaises(LineupOptimizerException):
self.optimizer.add_stack(PositionsStack(['PG', 'PG', 'SG', 'SG', 'SF', 'PF', 'C']))
def test_incorrect_position_names(self):
with self.assertRaises(LineupOptimizerException):
self.optimizer.add_stack(PositionsStack(['G']))
def test_empty_positions_stacks_tuple(self):
with self.assertRaises(LineupOptimizerException):
self.optimizer.add_stack(PositionsStack([]))
def test_positions_from_same_team_with_combo_position(self):
self.optimizer.add_stack(PositionsStack(['PG', ('SF', 'C')]))
lineups = list(self.optimizer.optimize(2))
stack = ('PG', 'SF', 'C')
players_in_stack = max([
len([p for p in lineup if p.team == self.first_team and list_intersection(p.positions, stack)])
for lineup in lineups
])
self.assertEqual(players_in_stack, 2)
class GameStackRuleTestCase(unittest.TestCase):
def setUp(self):
self.players = load_players()
self.optimizer = get_optimizer(Site.DRAFTKINGS, Sport.BASKETBALL)
self.optimizer.settings.max_from_one_team = 4
self.home_team = 'Home'
self.away_team = 'Away'
self.game_info = GameInfo(
home_team=self.home_team,
away_team=self.away_team,
starts_at=None,
)
self.game_players = [
Player('1', '1', '1', ['PG'], self.home_team, 1000, 3, game_info=self.game_info),
Player('2', '2', '2', ['SG'], self.home_team, 1000, 3, game_info=self.game_info),
Player('3', '3', '3', ['C'], self.home_team, 1000, 3, game_info=self.game_info),
Player('4', '4', '4', ['SG'], self.away_team, 1000, 1, game_info=self.game_info),
Player('5', '5', '5', ['SF'], self.away_team, 1000, 1, game_info=self.game_info),
Player('6', '6', '6', ['PF'], self.away_team, 1000, 1, game_info=self.game_info),
]
self.optimizer.player_pool.load_players(self.players + self.game_players)
@parameterized.expand([(i, ) for i in (range(2, 7))])
def test_stacks_correctness(self, size):
self.optimizer.add_stack(GameStack(size))
lineup = next(self.optimizer.optimize(n=1))
players_from_game = len([player for player in self.game_players if player in lineup])
self.assertEqual(players_from_game, size)
def test_stacks_correctness_min_from_team(self):
self.optimizer.add_stack(GameStack(4, min_from_team=2))
lineup = next(self.optimizer.optimize(n=1))
players_by_team = defaultdict(int)
for player in lineup:
players_by_team[player.team] += 1
self.assertEqual(players_by_team[self.home_team], 2)
self.assertEqual(players_by_team[self.away_team], 2)
def test_stacks_incorrect_params(self):
with self.assertRaises(LineupOptimizerException):
self.optimizer.add_stack(GameStack(4, min_from_team=3))
|
plugin/gogo/protobuf/variants.bzl | heartless-clown/rules_proto | 249 | 11087878 | <gh_stars>100-1000
"""variants.bzl
"""
GOGO_VARIANTS = [
"combo",
"gogo",
"gogofast",
"gogofaster",
"gogoslick",
"gogotypes",
"gostring",
]
|
t/unit/test_sasl.py | scottp-dpaw/py-amqp | 253 | 11087881 | import contextlib
import socket
import sys
from io import BytesIO
from unittest.mock import Mock, call, patch
import pytest
from amqp import sasl
from amqp.serialization import _write_table
class test_SASL:
def test_sasl_notimplemented(self):
mech = sasl.SASL()
with pytest.raises(NotImplementedError):
mech.mechanism
with pytest.raises(NotImplementedError):
mech.start(None)
def test_plain(self):
username, password = '<PASSWORD>', 'bar'
mech = sasl.PLAIN(username, password)
response = mech.start(None)
assert isinstance(response, bytes)
assert response.split(b'\0') == \
[b'', username.encode('utf-8'), password.encode('utf-8')]
def test_plain_no_password(self):
username, password = '<PASSWORD>', None
mech = sasl.PLAIN(username, password)
response = mech.start(None)
assert response == NotImplemented
def test_amqplain(self):
username, password = '<PASSWORD>', 'bar'
mech = sasl.AMQPLAIN(username, password)
response = mech.start(None)
assert isinstance(response, bytes)
login_response = BytesIO()
_write_table({b'LOGIN': username, b'PASSWORD': password},
login_response.write, [])
expected_response = login_response.getvalue()[4:]
assert response == expected_response
def test_amqplain_no_password(self):
username, password = '<PASSWORD>', None
mech = sasl.AMQPLAIN(username, password)
response = mech.start(None)
assert response == NotImplemented
def test_gssapi_missing(self):
gssapi = sys.modules.pop('gssapi', None)
GSSAPI = sasl._get_gssapi_mechanism()
with pytest.raises(NotImplementedError):
GSSAPI()
if gssapi is not None:
sys.modules['gssapi'] = gssapi
@contextlib.contextmanager
def fake_gssapi(self):
orig_gssapi = sys.modules.pop('gssapi', None)
orig_gssapi_raw = sys.modules.pop('gssapi.raw', None)
orig_gssapi_raw_misc = sys.modules.pop('gssapi.raw.misc', None)
gssapi = sys.modules['gssapi'] = Mock()
sys.modules['gssapi.raw'] = gssapi.raw
sys.modules['gssapi.raw.misc'] = gssapi.raw.misc
class GSSError(Exception):
pass
gssapi.raw.misc.GSSError = GSSError
try:
yield gssapi
finally:
if orig_gssapi is None:
del sys.modules['gssapi']
else:
sys.modules['gssapi'] = orig_gssapi
if orig_gssapi_raw is None:
del sys.modules['gssapi.raw']
else:
sys.modules['gssapi.raw'] = orig_gssapi_raw
if orig_gssapi_raw_misc is None:
del sys.modules['gssapi.raw.misc']
else:
sys.modules['gssapi.raw.misc'] = orig_gssapi_raw_misc
def test_gssapi_rdns(self):
with self.fake_gssapi() as gssapi, \
patch('socket.gethostbyaddr') as gethostbyaddr:
connection = Mock()
connection.transport.sock.getpeername.return_value = ('192.0.2.0',
5672)
connection.transport.sock.family = socket.AF_INET
gethostbyaddr.return_value = ('broker.example.org', (), ())
GSSAPI = sasl._get_gssapi_mechanism()
mech = GSSAPI(rdns=True)
mech.start(connection)
connection.transport.sock.getpeername.assert_called_with()
gethostbyaddr.assert_called_with('192.0.2.0')
gssapi.Name.assert_called_with(b'<EMAIL>',
gssapi.NameType.hostbased_service)
def test_gssapi_no_rdns(self):
with self.fake_gssapi() as gssapi:
connection = Mock()
connection.transport.host = 'broker.example.org'
GSSAPI = sasl._get_gssapi_mechanism()
mech = GSSAPI()
mech.start(connection)
gssapi.Name.assert_called_with(b'<EMAIL>',
gssapi.NameType.hostbased_service)
def test_gssapi_step_without_client_name(self):
with self.fake_gssapi() as gssapi:
context = Mock()
context.step.return_value = b'secrets'
name = Mock()
gssapi.SecurityContext.return_value = context
gssapi.Name.return_value = name
connection = Mock()
connection.transport.host = 'broker.example.org'
GSSAPI = sasl._get_gssapi_mechanism()
mech = GSSAPI()
response = mech.start(connection)
gssapi.SecurityContext.assert_called_with(name=name, creds=None)
context.step.assert_called_with(None)
assert response == b'secrets'
def test_gssapi_step_with_client_name(self):
with self.fake_gssapi() as gssapi:
context = Mock()
context.step.return_value = b'secrets'
client_name, service_name, credentials = Mock(), Mock(), Mock()
gssapi.SecurityContext.return_value = context
gssapi.Credentials.return_value = credentials
gssapi.Name.side_effect = [client_name, service_name]
connection = Mock()
connection.transport.host = 'broker.example.org'
GSSAPI = sasl._get_gssapi_mechanism()
mech = GSSAPI(client_name='amqp-client/client.example.org')
response = mech.start(connection)
gssapi.Name.assert_has_calls([
call(b'amqp-client/client.example.org'),
call(b'<EMAIL>',
gssapi.NameType.hostbased_service)])
gssapi.Credentials.assert_called_with(name=client_name)
gssapi.SecurityContext.assert_called_with(name=service_name,
creds=credentials)
context.step.assert_called_with(None)
assert response == b'secrets'
def test_external(self):
mech = sasl.EXTERNAL()
response = mech.start(None)
assert isinstance(response, bytes)
assert response == b''
|
tests/admin_scripts/management/commands/label_command.py | webjunkie/django | 790 | 11087937 | <filename>tests/admin_scripts/management/commands/label_command.py
from django.core.management.base import LabelCommand
class Command(LabelCommand):
help = "Test Label-based commands"
requires_model_validation = False
args = '<label>'
def handle_label(self, label, **options):
print('EXECUTE:LabelCommand label=%s, options=%s' % (label, sorted(options.items())))
|
iceoryx_integrationtest/iceoryx_integrationtest/test_ice_access_control_example.py | sloretz/iceoryx | 560 | 11087939 | # Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
import os
import unittest
import launch
from launch_ros.substitutions import ExecutableInPackage
import launch_testing
import launch_testing.actions
from launch_testing.asserts import assertSequentialStdout
import pytest
# @brief Test goal: "Integrationtest for the ice_access_control example of iceoryx"
# @pre setup ROS2 launch executable for RouDi (debug mode) the example processes
# @post check if all applications return exitcode 0 (success) after test run
@pytest.mark.launch_test
def generate_test_description():
proc_env = os.environ.copy()
colcon_prefix_path = os.environ.get('COLCON_PREFIX_PATH', '')
# Configure users and groups necessary to run this integration test
subprocess.call(['sh', '$(git rev-parse --show-toplevel)/iceoryx_examples/ice_access_control/config_and_run_ice_access_control.sh config'])
executable_list = ['iox-cpp-display', 'iox-cpp-radar', 'iox-cpp-cheeky']
user_list = ['infotainment', 'perception', 'notallowed']
for exec, user in zip(executable_list, user_list):
tmp_exec = os.path.join(
colcon_prefix_path,
'example_waitset/bin/',
exec)
tmp_process = launch.actions.ExecuteProcess(
cmd=['sudo -u ', user, ' -g iceoryx --', tmp_exec],
env=proc_env, output='screen')
process_list.append(tmp_process)
print("Process list:", process_list)
roudi_executable = os.path.join(
colcon_prefix_path,
'iceoryx_ice_access_control/bin/',
'iox-cpp-roudi-static-segments'
)
roudi_process = launch.actions.ExecuteProcess(
cmd=[roudi_executable, '-l', 'debug'],
env=proc_env, output='screen',
sigterm_timeout='20')
return launch.LaunchDescription([
roudi_process,
process_list[0],
process_list[1],
process_list[2],
launch_testing.actions.ReadyToTest()
]), {'iox-cpp-radar': process_list[0], 'iox-cpp-display': process_list[1], 'iox-cpp-cheeky': process_list[2]}
class TestIceAccessControlExample(unittest.TestCase):
def test_roudi_ready(self, proc_output):
proc_output.assertWaitFor(
'RouDi is ready for clients', timeout=45, stream='stdout')
def test_ice_access_control_radar(self, proc_output):
proc_output.assertWaitFor(
'iox-cpp-radar sent value: 10', timeout=45, stream='stdout')
def test_ice_access_control_display(self, proc_output):
proc_output.assertWaitFor(
'iox-cpp-display sending value: 10', timeout=45, stream='stdout')
def test_ice_access_control_cheeky(self, proc_output):
proc_output.assertWaitFor(
'RouDi did not find a writable shared memory segment for the current user.', timeout=45, stream='stdout')
@ launch_testing.post_shutdown_test()
class Testice_access_controlSetExampleExitCodes(unittest.TestCase):
def test_exit_code(self, proc_info):
launch_testing.asserts.assertExitCodes(proc_info)
|
refinery/refinery/__init__.py | csa0001/Refinery | 103 | 11087944 | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from celery import Celery
print "Opening a Refinery"
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
def make_celery(app):
celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
app.config.update(
CELERY_BROKER_URL='redis://localhost:6379',
CELERY_RESULT_BACKEND='redis://localhost:6379',
CELERY_IMPORTS=['refinery.webapp.topicmodel','refinery.webapp.main_menu'],
CELERY_REDIS_MAX_CONNECTIONS=4
)
celery = make_celery(app)
|
systrace/systrace/tracing_agents/walt_agent_unittest.py | tingshao/catapult | 311 | 11087945 | #!/usr/bin/env python
# Copyright (c) 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import unittest
from systrace import decorators
from systrace import run_systrace
from systrace.tracing_agents import walt_agent
class WaltAgentTest(unittest.TestCase):
"""
The WALT agent pulls the trace log from the Android phone, and does not
communicate with the WALT device directly. This makes the agent similar
to atrace. Since the host only connects to the Android phone, more exhaustive
testing would require mocking DeviceUtils.
"""
@decorators.HostOnlyTest
def test_construct_walt_args(self):
options, _ = run_systrace.parse_options(['./run_systrace.py',
'--walt'])
self.assertTrue(walt_agent.get_config(options).is_walt_enabled)
options, _ = run_systrace.parse_options(['./run_systrace.py'])
self.assertFalse(walt_agent.get_config(options).is_walt_enabled)
@decorators.HostOnlyTest
def test_format_clock_sync_marker(self):
actual_marker = walt_agent.format_clock_sync_marker(
'some_sync_id', 12345678901234)
expected_marker = ('<0>-0 (-----) [001] ...1 12345.6789012: ' +
'tracing_mark_write: trace_event_clock_sync: ' +
'name=some_sync_id\n')
self.assertEqual(actual_marker, expected_marker)
@decorators.HostOnlyTest
def test_get_results_string(self):
agent = walt_agent.WaltAgent()
agent._trace_contents = '<trace contents here>\n'
agent._clock_sync_marker = '<clock sync marker here>\n'
result = agent._get_trace_result()
self.assertEquals(result, '# tracer: \n# clock_type=LINUX_CLOCK_MONOTONIC\n'
'<trace contents here>\n<clock sync marker here>\n')
if __name__ == "__main__":
logging.getLogger().setLevel(logging.DEBUG)
unittest.main(verbosity=2)
|
build/lib.linux-x86_64-3.7/detectron2/modeling/roi_heads/mutil_path_fuse_module.py | muchwater/TextFuseNet_EfficientNet | 348 | 11087961 | import torch
from torch import nn
from detectron2.structures import Boxes
def get_selfarea_and_interarea(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:
"""
Given two lists of boxes of size N and M,
compute self_area and inter_area
between __all__ N x M pairs of boxes.
The box order must be (xmin, ymin, xmax, ymax).
Args:
boxes1,boxes2 (Boxes): two `Boxes`. Contains N & N boxes, respectively.
Returns:
self_area: proposal_boxes_area, sized [N]
inter_area: inter_area, sized [N,N].
"""
self_area = boxes1.area()
boxes1, boxes2 = boxes1.tensor, boxes2.tensor
lt = torch.max(boxes1[:, None, :2], boxes2[:, :2])
rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:])
wh = (rb - lt).clamp(min=0)
inter_area = wh[:, :, 0] * wh[:, :, 1]
return self_area, inter_area
class Mutil_Path_Fuse_Module(nn.Module):
"""
Mutil path fuse module. given features of word-level texts, character-level texts,
global context, and get the richer fused features.
Args:
x (Tensor): mask roi features of word-level and character-level text instances, sized [N,256,14,14]
global context (Tensor): seg roi features of global context, sized [N,256,14,14]
proposals (list[Instances]): selected positive proposals
Returns:
feature_fuse (Tensor): richer fused features
"""
def __init__(self, cfg):
super(Mutil_Path_Fuse_Module, self).__init__()
self.channels = cfg.MODEL.TEXTFUSENET_SEG_HEAD.CHANNELS
self.char_conv3x3 = nn.Conv2d(self.channels, self.channels, kernel_size=3, stride=1,
padding=1, bias=False)
self.char_conv1x1 = nn.Conv2d(self.channels, self.channels, kernel_size=1, stride=1,
padding=0, bias=False)
self.text_conv3x3 = nn.Conv2d(self.channels, self.channels, kernel_size=3, stride=1,
padding=1, bias=False)
self.text_conv1x1 = nn.Conv2d(self.channels, self.channels, kernel_size=1, stride=1,
padding=0, bias=False)
self.conv3x3 = nn.Conv2d(self.channels, self.channels, kernel_size=3, stride=1,
padding=1, bias=False)
self.conv1x1 = nn.Conv2d(self.channels, self.channels, kernel_size=1, stride=1,
padding=0, bias=False)
self.bn = nn.BatchNorm2d(self.channels)
self.relu = nn.ReLU(inplace=False)
def forward(self, x, global_context, proposals):
result = []
if self.training:
proposal_boxes = proposals[0].proposal_boxes
classes = proposals[0].gt_classes
else:
proposal_boxes = proposals[0].pred_boxes
classes = proposals[0].pred_classes
if len(proposal_boxes) == 0:
return x
self_area, inter_area = get_selfarea_and_interarea(proposal_boxes, proposal_boxes)
self_area = self_area.reshape(1, self_area.shape[0])
self_area = self_area.repeat(len(proposal_boxes), 1)
inter_percent = inter_area / self_area
char_pos = inter_percent > 0.9
for i in range(len(proposal_boxes)):
if classes[i] != 0:
char = x[i]
char = char.reshape([1, char.shape[0], char.shape[1], char.shape[2]])
char = self.char_conv3x3(char)
char = self.char_conv1x1(char)
result.append(char)
else:
if torch.sum(char_pos[i]) > 1:
text = x[char_pos[i]]
text = torch.sum(text,dim=0)/(text.shape[0])
text = text.reshape([1, text.shape[0], text.shape[1], text.shape[2]])
text = self.text_conv3x3(text)
text = self.text_conv1x1(text)
result.append(text)
else:
text = x[i]
text = text.reshape([1, text.shape[0], text.shape[1], text.shape[2]])
text = self.text_conv3x3(text)
text = self.text_conv1x1(text)
result.append(text)
char_context = torch.stack(result)
char_context = char_context.squeeze(1)
feature_fuse = char_context + x + global_context
feature_fuse = self.conv3x3(feature_fuse)
feature_fuse = self.conv1x1(feature_fuse)
feature_fuse = self.bn(feature_fuse)
feature_fuse = self.relu(feature_fuse)
return feature_fuse
def build_mutil_path_fuse_module(cfg):
return Mutil_Path_Fuse_Module(cfg)
|
mpf/platforms/pkone/pkone_switch.py | haggispinball/mpf_fathom_fast | 163 | 11087962 | <filename>mpf/platforms/pkone/pkone_switch.py
"""A switch input on a PKONE Extension board."""
import logging
from collections import namedtuple
from mpf.core.platform import SwitchConfig
from mpf.platforms.interfaces.switch_platform_interface import SwitchPlatformInterface
MYPY = False
if MYPY: # pragma: no cover
from mpf.platforms.pkone.pkone import PKONEHardwarePlatform # pylint: disable-msg=cyclic-import,unused-import
PKONESwitchNumber = namedtuple("PKONESwitchNumber", ["board_address_id", "switch_number"])
# pylint: disable-msg=too-few-public-methods
class PKONESwitch(SwitchPlatformInterface):
"""An PKONE input on a PKONE Extension board."""
__slots__ = ["log"]
def __init__(self, config: SwitchConfig, number: PKONESwitchNumber, platform: "PKONEHardwarePlatform") -> None:
"""Initialise switch."""
super().__init__(config, number, platform)
self.log = logging.getLogger('PKONESwitch')
def get_board_name(self):
"""Return PKONE Extension addr."""
if self.number.board_address_id not in self.platform.pkone_extensions.keys():
return "PKONE Unknown Board"
return "PKONE Extension Board {}".format(self.number.board_address_id)
|
OpenAttack/victim/classifiers/methods.py | e-tornike/OpenAttack | 444 | 11087976 | <filename>OpenAttack/victim/classifiers/methods.py
from ..method import VictimMethod
from ...attack_assist.word_embedding import WordEmbedding
class GetPredict(VictimMethod):
def before_call(self, input_):
if not isinstance(input_, list):
raise TypeError( "get_pred: `input` must be a list of sentences, but got %s" % type(input_) )
if len(input_) == 0:
raise ValueError("empty `input` list")
for i, it in enumerate(input_):
if not isinstance(it, str):
raise TypeError( "get_pred: `input[%d]` must be a list of sentences, but got %s" % (i, type(it)) )
def invoke_count(self, input_):
return len(input_)
class GetProbability(VictimMethod):
def before_call(self, input_):
if not isinstance(input_, list):
raise TypeError( "get_prob: `input` must be a list of sentences, but got %s" % type(input_) )
if len(input_) == 0:
raise ValueError("empty `input` list")
for i, it in enumerate(input_):
if not isinstance(it, str):
raise TypeError( "get_prob: `input[%d]` must be a sentence, but got %s" % (i, type(it)) )
def invoke_count(self, input_):
return len(input_)
class GetGradient(VictimMethod):
def before_call(self, input_, labels):
if not isinstance(input_, list):
raise TypeError( "get_grad: `input` must be a list of token lists, but got %s" % type(input_) )
if len(input_) == 0:
raise ValueError("empty `input` list")
for i, it in enumerate(input_):
if not isinstance(it, list):
raise TypeError( "get_grad: `input[%d]` must be a token list, but got %s" % (i, type(it)) )
for j, token in enumerate(it):
if not isinstance(token, str):
raise TypeError( "get_grad: `input[%d][%d]` must be a token, but got %s" % (i, j, type(it)) )
if len(input_) != len(labels):
raise ValueError("`input_` and `labels` must be the same length. (%d != %d)" % (len(input_), len(labels)))
def invoke_count(self, input_, labels):
return len(input_)
class GetEmbedding(VictimMethod):
def after_call(self, ret):
if not isinstance(ret, WordEmbedding):
raise TypeError("`get_embedding`: must return a `WordEmbedding` object") |
third_party/py/abseil/absl/command_name.py | jobechoi/bazel | 38,667 | 11087980 | <reponame>jobechoi/bazel<gh_stars>1000+
# Copyright 2017 The Abseil Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A tiny stand alone library to change the kernel process name on Linux."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
# This library must be kept small and stand alone. It is used by small things
# that require no extension modules.
def make_process_name_useful():
"""Sets the process name to something better than 'python' if possible."""
set_kernel_process_name(os.path.basename(sys.argv[0]))
def set_kernel_process_name(name):
"""Changes the Kernel's /proc/self/status process name on Linux.
The kernel name is NOT what will be shown by the ps or top command.
It is a 15 character string stored in the kernel's process table that
is included in the kernel log when a process is OOM killed.
The first 15 bytes of name are used. Non-ASCII unicode is replaced with '?'.
Does nothing if /proc/self/comm cannot be written or prctl() fails.
Args:
name: bytes|unicode, the Linux kernel's command name to set.
"""
if not isinstance(name, bytes):
name = name.encode('ascii', 'replace')
try:
# This is preferred to using ctypes to try and call prctl() when possible.
with open('/proc/self/comm', 'wb') as proc_comm:
proc_comm.write(name[:15])
except EnvironmentError:
try:
import ctypes
except ImportError:
return # No ctypes.
try:
libc = ctypes.CDLL('libc.so.6')
except EnvironmentError:
return # No libc.so.6.
pr_set_name = ctypes.c_ulong(15) # linux/prctl.h PR_SET_NAME value.
zero = ctypes.c_ulong(0)
try:
libc.prctl(pr_set_name, name, zero, zero, zero)
# Ignore the prctl return value. Nothing we can do if it errored.
except AttributeError:
return # No prctl.
|
pylearn2/scripts/icml_2013_wrepl/multimodal/extract_kmeans_features.py | ikervazquezlopez/Pylearn2 | 2,045 | 11088010 | <reponame>ikervazquezlopez/Pylearn2
from __future__ import print_function
import numpy as np
import os
import sys
from pylearn2.utils import serial
from pylearn2.utils.string_utils import preprocess
def usage():
print("""
Run
python extract_kmeans_features.py public_test
to extract features for the ICML 2013 multimodal learning contest's public test images.
or
python extract_kmeans_features.py private_test
to extract features for the ICML 2013 multimodal learning contest's private test images
(which will be released 72 hours before the contest ends)
""")
if len(sys.argv) != 2:
usage()
print('(You used the wrong number of arguments)')
quit(-1)
_, arg = sys.argv
if arg == 'public_test':
base = preprocess('${PYLEARN2_DATA_PATH}/icml_2013_multimodal/public_test_lcn')
expected_num_images = 500
elif arg == 'private_test':
base = preprocess('${PYLEARN2_DATA_PATH}/icml_2013_multimodal/private_test_lcn')
expected_num_images = 500
else:
usage()
print('Unrecognized argument value:',arg)
print('Recognized values are: public_test, private_test')
outdir = base[:-3] + 'layer_1_features'
serial.mkdir(outdir)
paths = os.listdir(base)
if len(paths) != expected_num_images:
raise AssertionError("Something is wrong with your " + base \
+ "directory. It should contain " + str(expected_num_images) + \
" lcn-preprocessed image files, but contains " + str(len(paths)))
means = np.load('lcn_means.npy')
norms = 1e-7 + np.sqrt(np.square(means).sum(axis=3).sum(axis=2).sum(axis=1))
means = np.transpose(np.transpose(means, (1, 2, 3, 0)) / norms, (3, 0, 1, 2))
from pylearn2.utils import sharedX
kernels = sharedX(np.transpose(means, (0, 3, 1, 2)))
import theano.tensor as T
X = T.TensorType(broadcastable=(False, False, False), dtype=kernels.dtype)()
bc01 = X.dimshuffle('x', 2, 0, 1)
Z = T.nnet.conv2d(input=bc01, filters=kernels, subsample = (means.shape[1] / 2, means.shape[2] /2),
filter_shape = kernels.get_value().shape)
F = T.signal.pool.pool_2d(Z, (2, 2))
F = T.clip(F - .5, 0., 10.)
from theano import function
f = function([X], F)
for i, path in enumerate(paths):
print(i)
try:
X = np.load(base + '/' + path)
assert X.ndim == 3
F = f(X)
np.save(outdir + '/' + path, F)
except Exception as e:
raise
|
src/genie/libs/parser/utils/tests/test_add_parser.py | balmasea/genieparser | 204 | 11088018 | import logging
import unittest
from unittest.mock import Mock
from genie.libs.parser.utils import common
from genie.libs.parser.utils.entry_points import add_parser
class TestAddParser(unittest.TestCase):
def setUp(self):
try:
del common.parser_data
except AttributeError as err:
logging.warning(err)
def test_add_parser_command_string(self):
cli_command = 'show test_add_parser_single_command_string'
mock_parser = Mock()
mock_parser.MockParser = Mock(cli_command=cli_command)
mock_parser.MockParser.__name__ = 'asa.MockParser'
mock_parser.MockParser.__package__ = 'asa'
with self.assertRaises(AttributeError):
getattr(common.parser_data)
add_parser(parser=mock_parser.MockParser, os_name='asa')
self.assertIn(cli_command, common.parser_data)
def test_add_parser_command_iterable(self):
cli_command = ['show test_add_parser_single_command_iterable1',
'show test_add_parser_single_command_iterable2']
mock_parser = Mock()
mock_parser.MockParser = Mock(cli_command=cli_command)
mock_parser.MockParser.__name__ = 'asa.MockParser'
mock_parser.MockParser.__package__ = 'asa'
with self.assertRaises(AttributeError):
getattr(common.parser_data)
add_parser(parser=mock_parser.MockParser, os_name='asa')
for cmd in cli_command:
self.assertIn(cmd, common.parser_data)
if __name__ == '__main__':
unittest.main()
|
5]. Projects/Machine Learning & Data Science (ML-DS)/Python/Deep Learning Projects/Computer Vision/011]. Traffic Light Classification/Traffic_Light_Classification.py | Utqrsh04/The-Complete-FAANG-Preparation | 6,969 | 11088019 | import cv2
import numpy as np
from scipy.stats import itemfreq
def get_dominant_color(image, n_colors):
pixels = np.float32(image).reshape((-1, 3))
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1)
flags = cv2.KMEANS_RANDOM_CENTERS
flags, labels, centroids = cv2.kmeans(
pixels, n_colors, None, criteria, 10, flags)
palette = np.uint8(centroids)
return palette[np.argmax(itemfreq(labels)[:, -1])]
clicked = False
def onMouse(event, x, y, flags, param):
global clicked
if event == cv2.EVENT_LBUTTONUP:
clicked = True
cameraCapture = cv2.VideoCapture(0)
cv2.namedWindow('camera')
cv2.setMouseCallback('camera', onMouse)
# Read and process frames in loop
success, frame = cameraCapture.read()
while success and not clicked:
cv2.waitKey(1)
success, frame = cameraCapture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
img = cv2.medianBlur(gray, 37)
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT,
1, 50, param1=120, param2=40)
if not circles is None:
circles = np.uint16(np.around(circles))
max_r, max_i = 0, 0
for i in range(len(circles[:, :, 2][0])):
if circles[:, :, 2][0][i] > 50 and circles[:, :, 2][0][i] > max_r:
max_i = i
max_r = circles[:, :, 2][0][i]
x, y, r = circles[:, :, :][0][max_i]
if y > r and x > r:
square = frame[y-r:y+r, x-r:x+r]
dominant_color = get_dominant_color(square, 2)
if dominant_color[2] > 100:
print("STOP")
elif dominant_color[0] > 80:
zone_0 = square[square.shape[0]*3//8:square.shape[0]
* 5//8, square.shape[1]*1//8:square.shape[1]*3//8]
cv2.imshow('Zone0', zone_0)
zone_0_color = get_dominant_color(zone_0, 1)
zone_1 = square[square.shape[0]*1//8:square.shape[0]
* 3//8, square.shape[1]*3//8:square.shape[1]*5//8]
cv2.imshow('Zone1', zone_1)
zone_1_color = get_dominant_color(zone_1, 1)
zone_2 = square[square.shape[0]*3//8:square.shape[0]
* 5//8, square.shape[1]*5//8:square.shape[1]*7//8]
cv2.imshow('Zone2', zone_2)
zone_2_color = get_dominant_color(zone_2, 1)
if zone_1_color[2] < 60:
if sum(zone_0_color) > sum(zone_2_color):
print("LEFT")
else:
print("RIGHT")
else:
if sum(zone_1_color) > sum(zone_0_color) and sum(zone_1_color) > sum(zone_2_color):
print("FORWARD")
elif sum(zone_0_color) > sum(zone_2_color):
print("FORWARD AND LEFT")
else:
print("FORWARD AND RIGHT")
else:
print("N/A")
for i in circles[0, :]:
cv2.circle(frame, (i[0], i[1]), i[2], (0, 255, 0), 2)
cv2.circle(frame, (i[0], i[1]), 2, (0, 0, 255), 3)
cv2.imshow('camera', frame)
cv2.destroyAllWindows()
cameraCapture.release() |
examples/03-exceptions/example.py | tavaresrodrigo/kopf | 855 | 11088020 | <filename>examples/03-exceptions/example.py
import kopf
class MyException(Exception):
pass
@kopf.on.create('kopfexamples')
def instant_failure_with_only_a_message(**kwargs):
raise kopf.PermanentError("Fail once and for all.")
@kopf.on.create('kopfexamples')
def eventual_success_with_few_messages(retry, **kwargs):
if retry < 3: # 0, 1, 2, 3
raise kopf.TemporaryError("Expected recoverable error.", delay=1.0)
@kopf.on.create('kopfexamples', retries=3, backoff=1.0)
def eventual_failure_with_tracebacks(**kwargs):
raise MyException("An error that is supposed to be recoverable.")
@kopf.on.create('kopfexamples', errors=kopf.ErrorsMode.PERMANENT, backoff=1.0)
def instant_failure_with_traceback(**kwargs):
raise MyException("An error that is supposed to be recoverable.")
# Marks for the e2e tests (see tests/e2e/test_examples.py):
E2E_ALLOW_TRACEBACKS = True
E2E_CREATION_STOP_WORDS = ['Something has changed,']
E2E_SUCCESS_COUNTS = {'eventual_success_with_few_messages': 1}
E2E_FAILURE_COUNTS = {'eventual_failure_with_tracebacks': 1,
'instant_failure_with_traceback': 1,
'instant_failure_with_only_a_message': 1}
|
qa/rpc-tests/test_framework/connectrum/__init__.py | MONIMAKER365/BitcoinUnlimited | 535 | 11088044 |
from .exc import ElectrumErrorResponse
__version__ = '0.7.4'
|
solt/constants/__init__.py | MIPT-Oulu/solt | 263 | 11088126 | <reponame>MIPT-Oulu/solt
"""
Constants module
.. data:: ALLOWED_BLURS
Defines the blur modes. Can be ``'g'`` - gaussian or ``'m'`` - median.
.. data:: ALLOWED_TYPES
Defines the allowed types to be stored in a DataCantainer. Can be
``'I'`` - image, ``'M'`` - mask, ``'L'`` - labels, ``'P'`` - Keypoints.
.. data:: ALLOWED_CROPS
Defines the allowed crops. Can be ``'r'`` - random crop or ``'c'`` - center crop.
.. data:: ALLOWED_PADDINGS
Defines the allowed crops. Can be ``'z'`` - zero padding or ``'r'`` - reflective padding.
.. data:: ALLOWED_INTERPOLATIONS
Defines the allowed interpolation modes. Can be ``'bilinear'``, ``'nearest'`` or ``'bicubic'``.
.. data:: DTYPES_MAX
Defines the maximums for different data types. Can be ``numpy.uint8`` or ``numpy.uint16``.
.. data:: ALLOWED_COLOR_CONVERSIONS
Defines the allowed color conversion modes. Can be ``'gs2rgb'``, ``'rgb2gs'`` or ``'none'``.
"""
from ._constants import (
ALLOWED_BLURS,
ALLOWED_TYPES,
ALLOWED_CROPS,
ALLOWED_PADDINGS,
ALLOWED_INTERPOLATIONS,
DTYPES_MAX,
ALLOWED_COLOR_CONVERSIONS,
ALLOWED_GRIDMASK_MODES,
)
__all__ = [
"ALLOWED_BLURS",
"ALLOWED_TYPES",
"ALLOWED_CROPS",
"ALLOWED_PADDINGS",
"ALLOWED_INTERPOLATIONS",
"DTYPES_MAX",
"ALLOWED_COLOR_CONVERSIONS",
"ALLOWED_GRIDMASK_MODES",
]
|
astroML/datasets/sdss_filters.py | astroML/astroML | 735 | 11088140 | <gh_stars>100-1000
import os
import numpy as np
from urllib.request import urlopen
from astroML.datasets import get_data_home
# Info on vega spectrum: http://www.stsci.edu/hst/observatory/cdbs/calspec.html
VEGA_URL = ('https://github.com/astroML/astroML-data/raw/main/datasets/'
'1732526_nic_002.ascii')
FILTER_URL = 'http://classic.sdss.org/dr7/instruments/imager/filters/%s.dat'
def fetch_sdss_filter(fname, data_home=None, download_if_missing=True):
"""Loader for SDSS Filter profiles
Parameters
----------
fname : str
filter name: must be one of 'ugriz'
data_home : optional, default=None
Specify another download and cache folder for the datasets. By default
all data is stored in '~/astroML_data'.
download_if_missing : optional, default=True
If False, raise a IOError if the data is not locally available
instead of trying to download the data from the source site.
Returns
-------
data : ndarray
data is an array of shape (5, Nlam)
first row: wavelength in angstroms
second row: sensitivity to point source, airmass 1.3
third row: sensitivity to extended source, airmass 1.3
fourth row: sensitivity to extended source, airmass 0.0
fifth row: assumed atmospheric extinction, airmass 1.0
"""
if fname not in 'ugriz':
raise ValueError("Unrecognized filter name '%s'" % fname)
url = FILTER_URL % fname
data_home = get_data_home(data_home)
archive_file = os.path.join(data_home, '%s.dat' % fname)
if not os.path.exists(archive_file):
if not download_if_missing:
raise IOError('data not present on disk. '
'set download_if_missing=True to download')
print("downloading from %s" % url)
F = urlopen(url)
open(archive_file, 'wb').write(F.read())
F = open(archive_file)
return np.loadtxt(F, unpack=True)
def fetch_vega_spectrum(data_home=None, download_if_missing=True):
"""Loader for Vega reference spectrum
Parameters
----------
fname : str
filter name: must be one of 'ugriz'
data_home : optional, default=None
Specify another download and cache folder for the datasets. By default
all astroML data is stored in '~/astroML_data'.
download_if_missing : optional, default=True
If False, raise a IOError if the data is not locally available
instead of trying to download the data from the source site.
Returns
-------
data : ndarray
data[0] is the array of wavelength in angstroms
data[1] is the array of fluxes in Jy (F_nu, not F_lambda)
"""
data_home = get_data_home(data_home)
archive_name = os.path.join(data_home, VEGA_URL.split('/')[-1])
if not os.path.exists(archive_name):
if not download_if_missing:
raise IOError('data not present on disk. '
'set download_if_missing=True to download')
print("downnloading from %s" % VEGA_URL)
F = urlopen(VEGA_URL)
open(archive_name, 'wb').write(F.read())
F = open(archive_name, 'r')
return np.loadtxt(F, unpack=True)
|
zentral/contrib/santa/migrations/0010_auto_20190603_1543.py | arubdesu/zentral | 634 | 11088146 | <filename>zentral/contrib/santa/migrations/0010_auto_20190603_1543.py
# Generated by Django 2.2.1 on 2019-06-03 15:43
from django.db import migrations
def update_santa_releases(apps, schema_editor):
Enrollment = apps.get_model("santa", "Enrollment")
for enrollment in Enrollment.objects.filter(santa_release__gt=""):
enrollment.santa_release = enrollment.santa_release.replace("santa-", "").replace(".dmg", "")
enrollment.save()
class Migration(migrations.Migration):
dependencies = [
('santa', '0009_configuration_file_changes_prefix_filters'),
]
operations = [
migrations.RunPython(update_santa_releases),
]
|
blogs/hparam/trainer/flow.py | laurenzberger/training-data-analyst | 6,140 | 11088167 | <reponame>laurenzberger/training-data-analyst
import argparse
import hypertune
import logging
# Problem from GINO program (Liebman, Lasdon, Schrage, and Waren 1986)
# as quoted in SAS manual Version 8 on p340
# See: http://www.math.wpi.edu/saspdf/iml/chap11.pdf
# Reformulated slightly to meet boxed constrained optimization
def compute_delay(flow, x12, x32):
# traffic on other roads, assuming all traffic that arrives
# at an intersection has to leave it
x13 = flow - x12
x24 = x12 + x32
x34 = x13 - x32
# travel time on each road segment
t12 = 5 + .1 * x12 / (1. - x12 / 10.);
t13 = x13 / (1. - x13 / 30.);
t32 = 1. + x32 / (1. - x32 / 10.);
t24 = x24 / (1. - x24 / 30.);
t34 = 5 + .1 * x34 / (1. - x34 / 10.);
# total delay
f = t12*x12 + t13*x13 + t32*x32 + t24*x24 + t34*x34;
return(f);
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--x12', type=float, required=True)
parser.add_argument('--x32', type=float, required=True)
parser.add_argument('--flow', type=float, default=5.0)
parser.add_argument('--job-dir', default='ignored') # output directory to save artifacts. we have none
# get args and invoke model
args = parser.parse_args()
delay = compute_delay(args.flow, args.x12, args.x32)
logging.info('{} Resulting delay: {}'.format(args.__dict__, delay))
print('{} Resulting delay: {}'.format(args.__dict__, delay))
# write out the metric so that the executable can be
# invoked again with next set of metrics
hpt = hypertune.HyperTune()
hpt.report_hyperparameter_tuning_metric(
hyperparameter_metric_tag='delay',
metric_value=delay,
global_step=1)
|
examples/issues/issue387.py | tgolsson/appJar | 666 | 11088177 | import sys
sys.path.append('../../')
from appJar import gui
def press():
app.changeOptionBox('opt', ['aaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbb'])
with gui() as app:
with app.labelFrame("test"):
app.setSticky('ew')
app.option('opt', ['a','b','c','d','e'])
app.button('press', press)
|
airflow_code_editor/code_editor_view.py | dolfinus/airflow-code-editor | 194 | 11088216 | <reponame>dolfinus/airflow-code-editor
#!/usr/bin/env python
#
# Copyright 2019 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the Licens
#
import os
import os.path
import logging
import mimetypes
from flask import abort, request, send_file
from flask_wtf.csrf import generate_csrf
from airflow.version import version
from airflow_code_editor.commons import HTTP_404_NOT_FOUND
from airflow_code_editor.tree import get_tree
from airflow_code_editor.utils import (
get_plugin_boolean_config,
get_plugin_int_config,
git_absolute_path,
execute_git_command,
error_message,
normalize_path,
prepare_api_response,
)
__all__ = ["AbstractCodeEditorView"]
AIRFLOW_MAJOR_VERSION = int(version.split(".")[0])
class AbstractCodeEditorView(object):
airflow_major_version = AIRFLOW_MAJOR_VERSION
def _index(self):
return self._render("index")
def _save(self, path=None):
try:
fullpath = git_absolute_path(path)
mime_type = request.headers.get("Content-Type", "text/plain")
is_text = mime_type.startswith("text/")
if is_text:
data = request.get_data(as_text=True)
# Newline fix (remove cr)
data = data.replace("\r", "").rstrip()
os.makedirs(os.path.dirname(fullpath), exist_ok=True)
with open(fullpath, "w") as f:
f.write(data)
f.write("\n")
else: # Binary file
data = request.get_data()
os.makedirs(os.path.dirname(fullpath), exist_ok=True)
with open(fullpath, "wb") as f:
f.write(data)
return prepare_api_response(path=normalize_path(path))
except Exception as ex:
logging.error(ex)
return prepare_api_response(
path=normalize_path(path),
error_message="Error saving {path}: {message}".format(
path=path, message=error_message(ex)
),
)
def _git_repo(self, path):
if request.method == "POST":
return self._git_repo_post(path)
else:
return self._git_repo_get(path)
def _git_repo_get(self, path):
" Get a file from GIT (invoked by the HTTP GET method) "
return execute_git_command(["cat-file", "-p", path])
def _git_repo_post(self, path):
" Execute a GIT command (invoked by the HTTP POST method) "
git_args = request.json.get('args', [])
return execute_git_command(git_args)
def _load(self, path):
" Send the contents of a file to the client "
try:
path = normalize_path(path)
if path.startswith("~git/"):
# Download git blob - path = '~git/<hash>/<name>'
_, path, filename = path.split("/", 3)
response = execute_git_command(["cat-file", "-p", path])
response.headers["Content-Disposition"] = (
'attachment; filename="%s"' % filename
)
try:
content_type = mimetypes.guess_type(filename)[0]
if content_type:
response.headers["Content-Type"] = content_type
except Exception:
pass
return response
else:
# Download file
fullpath = git_absolute_path(path)
return send_file(fullpath, as_attachment=True)
except Exception as ex:
logging.error(ex)
abort(HTTP_404_NOT_FOUND)
def _format(self):
" Format code "
try:
import black
data = request.get_data(as_text=True)
# Newline fix (remove cr)
data = data.replace("\r", "").rstrip()
mode = black.Mode(
string_normalization=get_plugin_boolean_config("string_normalization"),
line_length=get_plugin_int_config("line_length"),
)
data = black.format_str(src_contents=data, mode=mode)
return prepare_api_response(data=data)
except ImportError:
return prepare_api_response(
error_message="black dependency is not installed: to install black `pip install black`"
)
except Exception as ex:
logging.error(ex)
return prepare_api_response(
error_message="Error formatting: {message}".format(
message=error_message(ex)
)
)
def _tree(self, path, args = {}):
return {'value': get_tree(path, args)}
def _ping(self):
return {'value': generate_csrf()}
|
examples/manage/plot_failed_fits.py | varman-m/eeg_notebooks_doc | 154 | 11088217 | <filename>examples/manage/plot_failed_fits.py<gh_stars>100-1000
"""
Failed Model Fits
=================
Example of model fit failures and how to debug them.
"""
###################################################################################################
# Import the FOOOFGroup object
from fooof import FOOOFGroup
# Import simulation code to create test power spectra
from fooof.sim.gen import gen_group_power_spectra
# Import FitError, which we will use to help debug model fit errors
from fooof.core.errors import FitError
###################################################################################################
# Model Fit Failures
# ------------------
#
# The power spectrum model is not guaranteed to fit - sometimes the fit procedure can fail.
#
# Model fit failures are rare, and they typically only happen on spectra that are
# particular noisy, and/or are some kind of outlier for which the fitting procedure
# fails to find a good model solution.
#
# In general, model fit failures should lead to a clean exit, meaning that
# a failed model fit does not lead to a code error. The failed fit will be encoded in
# the results as a null model, and the code can continue onwards.
#
# In this example, we will look through what it looks like when model fits fail.
#
###################################################################################################
# Simulate some example power spectra to use for the example
freqs, powers = gen_group_power_spectra(25, [1, 50], [1, 1], [10, 0.25, 3],
nlvs=0.1, freq_res=0.25)
###################################################################################################
# Initialize a FOOOFGroup object, with some desired settings
fg = FOOOFGroup(min_peak_height=0.1, max_n_peaks=6)
###################################################################################################
# Fit power spectra
fg.fit(freqs, powers)
###################################################################################################
#
# If there are failed fits, these are stored as null models.
#
# Let's check if there were any null models, from model failures, in the models
# that we have fit so far. To do so, the :class:`~fooof.FOOOFGroup` object has some
# attributes that provide information on any null model fits.
#
# These attributes are:
#
# - ``n_null_`` : the number of model results that are null
# - ``null_inds_`` : the indices of any null model results
#
###################################################################################################
# Check for failed model fits
print('Number of Null models : \t', fg.n_null_)
print('Indices of Null models : \t', fg.null_inds_)
###################################################################################################
# Inducing Model Fit Failures
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# So far, we have no model failures (as is typical).
#
# For this example, to induce some model fits, we will use a trick to change the number of
# iterations the model uses to fit parameters (`_maxfev`), making it much more likely to fail.
#
# Note that in normal usage, you would likely never want to change the value of `_maxfev`,
# and this here is a 'hack' of the code in order to induce reproducible failure modes
# in simulated data.
#
###################################################################################################
# Hack the object to induce model failures
fg._maxfev = 50
###################################################################################################
# Try fitting again
fg.fit(freqs, powers)
###################################################################################################
#
# As we can see, there are now some model fit failures! Note that, as above, it will
# be printed out if there is as model fit failure when in verbose mode.
#
###################################################################################################
# Check how many model fit failures we have failed model fits
print('Number of Null models : \t', fg.n_null_)
print('Indices of Null models : \t', fg.null_inds_)
###################################################################################################
# Debug Mode
# ----------
#
# There are multiple possible reasons why a model fit failure can occur, or at least
# multiple possible steps in the algorithm at which the fit failure can occur.
#
# If you have a small number of fit failures, you can likely just exclude them.
#
# However, if you have multiple fit failures, and/or you want to investigate why the
# model is failing, you can use the debug mode to get a bit more information about
# where the model is failing.
#
# The debug mode will stop the FOOOF object catching and continuing any model
# fit errors, allowing you to see where the error is happening, and get more
# information about where it is failing.
#
# Note that here we will run the fitting in a try / except to catch the error and
# print it out, without the error actually being raised (for website purposes).
# If you just want to see the error, you can run the fit call without the try/except.
#
###################################################################################################
# Set FOOOFGroup into debug mode
fg.set_debug_mode(True)
###################################################################################################
# Refit in debug mode, in which failed fits will raise an error
try:
fg.fit(freqs, powers)
except FitError as fooof_error:
print(fooof_error)
###################################################################################################
# Debugging Model Fit Errors
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# This debug mode should indicate in which step the model is failing, which might indicate
# what aspects of the data to look into, and/or which settings to try and tweak.
#
# Also, all known model fit failures should be caught by the object, and not raise an
# error (when not in debug mode). If you are finding examples in which the model is failing
# to fit, and raising an error (outside of debug mode), then this might be an unanticipated
# issue with the model fit.
#
# If you are unsure about why or how the model is failing to fit, consider
# opening an `issue <https://github.com/fooof-tools/fooof/issues>`_ on the project
# repository, and we will try to look into what seems to be happening.
#
|
qt4i/driver/instruments/internal/_command.py | beijixing0202/QT4i | 209 | 11088240 | # coding: UTF-8
#
# Tencent is pleased to support the open source community by making QTA available.
# Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the BSD 3-Clause License (the "License"); you may not use this
# file except in compliance with the License. You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
#
'''命令'''
# -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*-
from __future__ import absolute_import, print_function
import time, threading
from qt4i.driver.tools import logger
# -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*-
log = logger.get_logger("instruments")
class __DeviceCommandId__(threading.Thread):
Id = 0
Lock = threading.Lock()
def __init__(self):
threading.Thread.__init__(self)
self._id = None
def get_id(self):
return self._id
def run(self):
__DeviceCommandId__.Lock.acquire()
__DeviceCommandId__.Id += 1
self._id = __DeviceCommandId__.Id
__DeviceCommandId__.Lock.release()
@classmethod
def create_id(cls):
obj = cls()
obj.start()
obj.join()
return obj.get_id()
# -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*-
class __DeviceCommand__(threading.Thread):
StandbyStatus = 0
ExecuteStatus = 1
ExecutedStatus = 2
DiscardStatus = 3
TimeoutStatus = 4
FinishedStatus = 5
def __init__(self, _udid, _command, _standby_timeout, _execute_timeout, _print=False):
'''@desc: 构造函数
# -*- -*- -*- -*- -*- -*-
# ---> _command = { "id": <int>(内部自动维护id), "method": <str>, "params": [<base-object>,...] }
# <--- _result = { "id": <int>(命令的id), "result": <base-object>, "error" : <None>|<str> }
# -*- -*- -*- -*- -*- -*-
@param _udid : 命令关联的设备
@type _udid : <str>
@param _command : 命令的实体数据(Python的dict对象)
@type _command : <dict>
@param _standby_timeout : 命令等待执行超时值
@type _standby_timeout : <int>|<float>
@param _execute_timeout : 命令执行超时值
@type _execute_timeout : <int>|<float>
@param _print : 内部是否跟踪打印命令交互的信息(用于调试)
@type _print : <bool>
'''
if False == isinstance(_command, dict) : raise Exception("__DeviceCommand__.__init__(..., _command, ...): The _command is not an instance of the <dict>.")
if None == _command.get('method', None) : raise Exception("__DeviceCommand__.__init__(..., _command, ...): The _command hasn't [method].")
threading.Thread.__init__(self)
self._execute_event = threading.Event()
self._executed_event = threading.Event()
_command['id'] = __DeviceCommandId__.create_id()
self._command_id = _command['id']
self._udid = _udid
self._command = _command
self._standby_timeout = _standby_timeout
self._execute_timeout = _execute_timeout
self._print = _print
self._result = None
self._standby_timestamp = time.time()
self._execute_timestamp = None
self._executed_timestamp = None
self._discard_timestamp = None
self._timeout_timestamp = None
self._finished_timestamp = None
self._status = self.StandbyStatus
def __get_result_struct__(self, _result=None, _error=None):
return {"id": self._command_id, "result": _result, "error": _error}
@property
def standby_timestamp(self):
return self._standby_timestamp
@property
def finished_timestamp(self):
return self._finished_timestamp
@property
def udid(self):
return self._udid
@property
def command_id(self):
return self._command_id
@property
def status(self):
return self._status
@property
def command(self):
self._execute_timestamp = time.time()
self._status = self.ExecuteStatus
self._execute_event.set()
if True == self._print : log.info('DeviceCommand-%s: Execute - Standby = %ss' % (self._command_id, round(self._execute_timestamp - self._standby_timestamp, 3)))
return self._command
@property
def result(self):
if self._status != self.FinishedStatus:
self._finished_timestamp = time.time()
self._status = self.FinishedStatus
if True == self._print : log.info('DeviceCommand-%s: Finished - Standby = %ss' % (self._command_id, round(self._finished_timestamp - self._standby_timestamp, 3)))
return self._result
@result.setter
def result(self, _result={}):
if False == isinstance(_result, dict) : raise Exception("__DeviceCommand__.result = _result: The _result is not an instance of the <dict>.")
self._executed_timestamp = time.time()
self._status = self.ExecutedStatus
self._result = self.__get_result_struct__()
self._result.update(_result)
self._executed_event.set()
if True == self._print : log.info('DeviceCommand-%s: Executed - Execute = %ss' % (self._command_id, round(self._executed_timestamp - self._execute_timestamp, 3)))
def discard(self, _error='CommandDiscard'):
self._discard_timestamp = time.time()
self._status = self.DiscardStatus
self._result = self.__get_result_struct__(_error=_error)
self._executed_event.set()
if True == self._print : log.info('DeviceCommand-%s: Discarded - Standby = %ss' % (self._command_id, round(self._discard_timestamp - self._standby_timestamp, 3)))
def run(self):
if True == self._print :
log.info('DeviceCommand-%s: %s' % (self._command_id, '-' * 60))
log.info('DeviceCommand-%s: Command = %s' % (self._command_id, self._command))
if self._standby_timeout > 0 : self._execute_event.wait(self._standby_timeout)
if self._execute_timeout > 0 : self._executed_event.wait(self._execute_timeout)
if self._execute_timeout > 0 and self._status not in [self.ExecutedStatus, self.DiscardStatus, self.FinishedStatus]:
self._timeout_timestamp = time.time()
self._status = self.TimeoutStatus
self._result = self.__get_result_struct__(_error="CommandTimeout")
if self._status == self.ExecutedStatus:
self._finished_timestamp = time.time()
self._status = self.FinishedStatus
if True == self._print :
log.info('DeviceCommand-%s: Result = %s' % (self._command_id, self._result))
log.info('DeviceCommand-%s: Duration = %ss' % (self._command_id, time.time() - self._standby_timestamp))
# -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*-
class __NewDeviceCommandEvent__(threading.Thread):
def __init__(self, _udid, _timeout):
threading.Thread.__init__(self)
self._udid = _udid
self._timeout = _timeout
self._standby_timestamp = time.time()
self._finished_timestamp = None
self._event = threading.Event()
@property
def udid(self):
return self._udid
@property
def timeout(self):
return self._timeout
@property
def standby_timestamp(self):
return self._standby_timestamp
@property
def finished_timestamp(self):
return self._finished_timestamp
def notify(self):
self._event.set()
def run(self):
self._event.wait(self._timeout)
self._finished_timestamp = time.time()
# -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*-
class __NewDeviceCommandEventDelegator__(threading.Thread):
def __init__(self, _events_buffer_time=1, _events_clean_buffer_interval=0.3):
threading.Thread.__init__(self)
self._events = list()
self._events_lock = threading.Lock()
self._events_buffer_time = _events_buffer_time
self._events_clean_buffer_interval = _events_clean_buffer_interval
self.setDaemon(True)
self.start()
def create_event_and_waiting(self, _udid, _timeout):
self._events_lock.acquire()
_event = __NewDeviceCommandEvent__(_udid, _timeout)
self._events.append(_event)
_event.start()
self._events_lock.release()
_event.join()
def notify_event(self, _udid):
self._events_lock.acquire()
for _event in self._events:
if _event.is_alive() and _event.udid == _udid:
_event.notify()
self._events.remove(_event)
break
self._events_lock.release()
def run(self):
while True:
time.sleep(self._events_clean_buffer_interval)
self._events_lock.acquire()
for _event in self._events:
if _event.is_alive() == False and _event.finished_timestamp != None and time.time() - _event.finished_timestamp >= self._events_buffer_time:
self._events.remove(_event)
self._events_lock.release()
# -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*-
class DeviceCommandDelegator(threading.Thread):
Timeout = 30
def __init__(self, _command_buffer_time=3, _command_clean_buffer_interval=0.5):
threading.Thread.__init__(self)
self._command_list = list()
self._new_command_lock = threading.Lock()
self._get_next_command_lock = threading.Lock()
self._new_command_event_delegator = __NewDeviceCommandEventDelegator__(_command_buffer_time, _command_clean_buffer_interval)
self._last_get_next_command_id = 0
self._command_buffer_time = _command_buffer_time
self._command_clean_buffer_interval = _command_clean_buffer_interval
self.setDaemon(True)
self.start()
def run(self):
while True:
time.sleep(self._command_clean_buffer_interval)
self._new_command_lock.acquire()
for _command in self._command_list:
if _command.is_alive() == False and _command.finished_timestamp != None and time.time() - _command.finished_timestamp >= self._command_buffer_time:
self._command_list.remove(_command)
self._new_command_lock.release()
def __exec_command__(self, _udid, _command, _standby_timeout=Timeout, _execute_timeout=Timeout, _print=False):
'''@desc: 执行命令
@param _udid : 命令关联的设备
@type _udid : <str>
@param _command : 命令体: {"method": <str>, "params": <list>}
@type _command : <dict>
@param _standby_timeout : 命令等待执行超时值(秒,默认为30秒)
@type _standby_timeout : <int>|<float>
@param _execute_timeout : 命令执行超时值(秒,默认为30秒)
@type _execute_timeout : <int>|<float>
@param _print : 是否print命令的过程信息(默认为False)
@type _print : <bool>
@return : <dict> : {"id": <int>, "result": <object>, "error": "error"}
'''
self._new_command_lock.acquire()
_command = __DeviceCommand__(_udid, _command, _standby_timeout, _execute_timeout, _print)
self._command_list.append(_command)
_command.start()
self._new_command_event_delegator.notify_event(_udid)
self._new_command_lock.release()
_command.join()
return _command.result
def exec_command(self, _udid, _command, _timeout=Timeout, _print=False):
'''@desc: 执行命令(阻塞至命令执行完毕或超时)'''
return self.__exec_command__(_udid, _command, 0, _timeout, _print)
def send_command(self, _udid, _command, _timeout=Timeout, _print=False):
'''@desc: 执行命令(阻塞至设备接收命令,不需要返回值。如超时未被接收则被抛弃)'''
self.__exec_command__(_udid, _command, _timeout, 0, _print)
def __get_next_command__(self, _udid):
self._get_next_command_lock.acquire()
_next_command = None
for _command in self._command_list:
if _command.udid == _udid and _command.status == _command.StandbyStatus and _command.command_id > self._last_get_next_command_id:
_next_command = _command.command
self._last_get_next_command_id = _command.command_id
break
self._get_next_command_lock.release()
return _next_command
def get_next_command(self, _udid, _timeout=Timeout):
'''@desc: 获取某设备的下一条待执行的命令
@param _udid : 设备的UUID(iOS、Android、Windows、Mac、Server自己)
@type _udid : <str> - 理论上不局限类型
@param _timeout : 超时(秒) - 当一定时间后,没有对应的命令时则超时
@type _timeout : <int> or <float>
@return : <dict> : {"id": <int>, "method": <str>, "params": <list>}
'''
_start_timestamp = time.time()
_next_command = self.__get_next_command__(_udid)
if _next_command == None and _timeout > 0:
self._new_command_event_delegator.create_event_and_waiting(_udid, (_timeout - (time.time() - _start_timestamp)))
return self.get_next_command(_udid, (_timeout - (time.time() - _start_timestamp)))
return _next_command
def set_command_result(self, _udid, _result):
'''@desc: 返回结果给指定的命令
@param _udid : 设备的UUID(iOS、Android、Windows、Mac、Server自己)
@type _udid : <str> - 理论上不局限类型
@param _result : 命令的结果
@type _result : <dict> : {"id": <int>, "result": <object>, "error": "error"}
'''
for _command in self._command_list:
if _udid == _command.udid and _result.get('id') == _command.command_id:
_command.result = _result
return
def clean_all(self, _udid, _error):
'''@desc: 清除所有命令,统一设置结果(例如Crash了取消所有命令)
@param _udid: 设备的UUID(iOS、Android、Windows、Mac、Server自己)
@type _udid: <str> - 理论上不局限类型
@param _error: 命令的结果,主要含清除命令的原因(命令不能无故清除,导致上层无法定位问题)
@type _error: <dict> = <JSONRPC-Result>
'''
for _command in self._command_list:
if _command.is_alive() and _command.udid == _udid and _command.status not in [_command.ExecutedStatus, _command.DiscardStatus, _command.TimeoutStatus, _command.FinishedStatus]:
_command.discard(_error)
# -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*-
if __name__ == '__main__':
cmds = 2000
udid = 'iPhone'
deviceCommandDelegator = DeviceCommandDelegator()
class Driver(threading.Thread):
def __init__(self, _cmds=cmds):
threading.Thread.__init__(self)
self._cmds = _cmds
self.start()
def exec_command(self, i):
_cmd = deviceCommandDelegator.get_next_command(udid)
if _cmd:
log.info('Driver - %s <<< cmd : %s' % (i, _cmd))
_rst = {"id": _cmd['id'], "result": "%s" % _cmd['method'], "error": _cmd['method']}
deviceCommandDelegator.set_command_result(udid, _rst)
log.info('Driver - %s >>> rst : %s' % (i, _rst))
else:
import sys
sys.stderr.write('%s\n' % '无命令')
def run(self):
for i in range(self._cmds):
self.exec_command(i)
class Case(threading.Thread):
def __init__(self, _cmds=cmds):
threading.Thread.__init__(self)
self._cmds = _cmds
self.start()
def run(self):
_exec_command_times = list()
for i in range(self._cmds):
_cmd = {"method": "%s" % i, "params": ["%s" % i]}
log.info('-' * 60)
log.info('Case - %s cmd --> : %s' % (i, _cmd))
_start_timestamp = time.time()
_rst = deviceCommandDelegator.exec_command(udid, _cmd)
_exec_command_times.append(time.time() - _start_timestamp)
log.info('Case - %s rst <-- : %s' % (i, _rst))
log.info('-' * 60)
_all_exec_command_time = 0
for item in _exec_command_times:
_all_exec_command_time += item
log.info('执行命令开销: %s\n' % (_all_exec_command_time / len(_exec_command_times)))
for i in range(6):
case1 = Case()
driver1 = Driver()
driver2 = Driver()
case2 = Case()
while threading.active_count() > 3:
time.sleep(1)
log.info('Waitting... [count: %s]' % threading.active_count())
for item in threading.enumerate():
log.info(item)
while len(deviceCommandDelegator._command_list) > 0:
log.info('命令队列残留: %s' % len(deviceCommandDelegator._command_list))
time.sleep(1)
log.info('命令队列残留: %s' % len(deviceCommandDelegator._command_list))
log.info('Finished...')
|
test/test_query.py | dongsc1994/sql-metadata | 313 | 11088259 | from sql_metadata.parser import Parser
def test_get_query_tokens():
assert Parser("").tokens == []
tokens = Parser("SELECT * FROM foo").tokens
assert len(tokens) == 4
assert str(tokens[0]) == "SELECT"
assert tokens[1].is_wildcard
assert tokens[2].is_keyword
assert str(tokens[2]) == "FROM"
def test_preprocessing():
# normalize database selector
assert Parser("SELECT foo FROM `db`.`test`").query == "SELECT foo FROM `db`.`test`"
assert Parser('SELECT foo FROM "db"."test"').query == "SELECT foo FROM `db`.`test`"
assert (
Parser(
"SELECT r1.wiki_id AS id FROM report_wiki_recent_pageviews AS r1 "
"INNER JOIN dimension_wikis AS d ON r.wiki_id = d.wiki_id"
).query
== "SELECT r1.wiki_id AS id FROM report_wiki_recent_pageviews AS r1 "
"INNER JOIN dimension_wikis AS d ON r.wiki_id = d.wiki_id"
)
# comments are kept
assert (
Parser("SELECT /*my random comment*/ foo, id FROM `db`.`test`").query
== "SELECT /*my random comment*/ foo, id FROM `db`.`test`"
)
# check " in strings are kept
assert (
Parser("SELECT * from aa where name = 'test name with \" in string'").query
== "SELECT * from aa where name = 'test name with \" in string'"
)
assert (
Parser("SELECT * from aa where name = 'test name with \"aa\" in string'").query
== "SELECT * from aa where name = 'test name with \"aa\" in string'"
)
assert (
Parser("SELECT * from aa where name = 'test name with \"aa\" in string'").query
== "SELECT * from aa where name = 'test name with \"aa\" in string'"
)
assert (
Parser(
"SELECT * from aa where name = 'test name with \"aa\" in string' "
"and aa =' as \"aa.oo\" '"
).query
== "SELECT * from aa where name = 'test name with \"aa\" in string' "
"and aa =' as \"aa.oo\" '"
)
def test_case_insensitive():
# case-insensitive handling
# https://github.com/macbre/sql-metadata/issues/71
assert ["abc.foo", "foo", "bar"] == Parser(
"CREATE table abc.foo as SELECT pqr.foo1 , ab.foo2 FROM foo pqr, bar ab"
).tables
assert ["abc.foo", "foo", "bar"] == Parser(
"CREATE table abc.foo as SELECT pqr.foo1 , ab.foo2 FROM foo pqr, bar ab"
).tables
assert ["foo.foo1", "bar.foo2"] == Parser(
"CREATE table abc.foo as SELECT pqr.foo1 , ab.foo2 FROM foo pqr, bar ab"
).columns
assert ["foo.foo1", "bar.foo2"] == Parser(
"CREATE table abc.foo as SELECT pqr.foo1 , ab.foo2 FROM foo pqr, bar ab"
).columns
def test_handle_force_index():
query = (
"SELECT page_title,page_namespace FROM `page` FORCE INDEX (page_random) "
"JOIN `categorylinks` ON ((page_id=cl_from)) WHERE page_is_redirect = '0' "
"AND (page_random >= 0.197372293871) AND cl_to = 'Muppet_Characters' "
"ORDER BY page_random LIMIT 1"
)
parser = Parser(query)
assert parser.tables == ["page", "categorylinks"]
assert parser.columns == [
"page_title",
"page_namespace",
"page_id",
"cl_from",
"page_is_redirect",
"page_random",
"cl_to",
]
assert parser.columns_dict == {
"select": ["page_title", "page_namespace"],
"join": ["page_id", "cl_from"],
"where": ["page_is_redirect", "page_random", "cl_to"],
"order_by": ["page_random"],
}
def test_insert_into_select():
# https://dev.mysql.com/doc/refman/5.7/en/insert-select.html
query = "INSERT INTO foo SELECT * FROM bar"
assert Parser(query).tables == ["foo", "bar"]
assert Parser(query).columns == ["*"]
query = "INSERT INTO foo SELECT id, price FROM bar"
assert Parser(query).tables == ["foo", "bar"]
assert Parser(query).columns == ["id", "price"]
query = "INSERT INTO foo SELECT id, price FROM bar WHERE qty > 200"
assert Parser(query).tables == ["foo", "bar"]
assert Parser(query).columns == ["id", "price", "qty"]
assert Parser(query).columns_dict == {"select": ["id", "price"], "where": ["qty"]}
def test_case_syntax():
# https://dev.mysql.com/doc/refman/8.0/en/case.html
assert Parser(
"SELECT case when p > 0 then 1 else 0 end as cs from c where g > f"
).columns == ["p", "g", "f"]
assert Parser(
"SELECT case when p > 0 then 1 else 0 end as cs from c where g > f"
).tables == ["c"]
|
release/stubs.min/System/Windows/Forms/__init___parts/DataGridView.py | htlcnn/ironpython-stubs | 182 | 11088267 | class DataGridView(Control,IComponent,IDisposable,IOleControl,IOleObject,IOleInPlaceObject,IOleInPlaceActiveObject,IOleWindow,IViewObject,IViewObject2,IPersist,IPersistStreamInit,IPersistPropertyBag,IPersistStorage,IQuickActivate,ISupportOleDropSource,IDropTarget,ISynchronizeInvoke,IWin32Window,IArrangedElement,IBindableComponent,ISupportInitialize):
"""
Displays data in a customizable grid.
DataGridView()
"""
def AccessibilityNotifyClients(self,*args):
"""
AccessibilityNotifyClients(self: Control,accEvent: AccessibleEvents,objectID: int,childID: int)
Notifies the accessibility client applications of the specified
System.Windows.Forms.AccessibleEvents for the specified child control .
accEvent: The System.Windows.Forms.AccessibleEvents to notify the accessibility client applications of.
objectID: The identifier of the System.Windows.Forms.AccessibleObject.
childID: The child System.Windows.Forms.Control to notify of the accessible event.
AccessibilityNotifyClients(self: Control,accEvent: AccessibleEvents,childID: int)
Notifies the accessibility client applications of the specified
System.Windows.Forms.AccessibleEvents for the specified child control.
accEvent: The System.Windows.Forms.AccessibleEvents to notify the accessibility client applications of.
childID: The child System.Windows.Forms.Control to notify of the accessible event.
"""
pass
def AccessibilityNotifyCurrentCellChanged(self,*args):
"""
AccessibilityNotifyCurrentCellChanged(self: DataGridView,cellAddress: Point)
Notifies the accessible client applications when a new cell becomes the current cell.
cellAddress: A System.Drawing.Point indicating the row and column indexes of the new current cell.
"""
pass
def AdjustColumnHeaderBorderStyle(self,dataGridViewAdvancedBorderStyleInput,dataGridViewAdvancedBorderStylePlaceholder,isFirstDisplayedColumn,isLastVisibleColumn):
"""
AdjustColumnHeaderBorderStyle(self: DataGridView,dataGridViewAdvancedBorderStyleInput: DataGridViewAdvancedBorderStyle,dataGridViewAdvancedBorderStylePlaceholder: DataGridViewAdvancedBorderStyle,isFirstDisplayedColumn: bool,isLastVisibleColumn: bool) -> DataGridViewAdvancedBorderStyle
Adjusts the System.Windows.Forms.DataGridViewAdvancedBorderStyle for a column header cell of a
System.Windows.Forms.DataGridView that is currently being painted.
dataGridViewAdvancedBorderStyleInput: A System.Windows.Forms.DataGridViewAdvancedBorderStyle that that represents the column header
border style to modify.
dataGridViewAdvancedBorderStylePlaceholder: A System.Windows.Forms.DataGridViewAdvancedBorderStyle that is used to store intermediate
changes to the column header border style.
isFirstDisplayedColumn: true to indicate that the System.Windows.Forms.DataGridViewCell that is currently being painted
is in the first column displayed on the System.Windows.Forms.DataGridView; otherwise,false.
isLastVisibleColumn: true to indicate that the System.Windows.Forms.DataGridViewCell that is currently being painted
is in the last column in the System.Windows.Forms.DataGridView that has the
System.Windows.Forms.DataGridViewColumn.Visible property set to true; otherwise,false.
Returns: A System.Windows.Forms.DataGridViewAdvancedBorderStyle that represents the border style for the
current column header.
"""
pass
def AreAllCellsSelected(self,includeInvisibleCells):
"""
AreAllCellsSelected(self: DataGridView,includeInvisibleCells: bool) -> bool
Returns a value indicating whether all the System.Windows.Forms.DataGridView cells are currently
selected.
includeInvisibleCells: true to include the rows and columns with System.Windows.Forms.DataGridViewBand.Visible property
values of false; otherwise,false.
Returns: true if all cells (or all visible cells) are selected or if there are no cells (or no visible
cells); otherwise,false.
"""
pass
def AutoResizeColumn(self,columnIndex,autoSizeColumnMode=None):
"""
AutoResizeColumn(self: DataGridView,columnIndex: int,autoSizeColumnMode: DataGridViewAutoSizeColumnMode)
Adjusts the width of the specified column using the specified size mode.
columnIndex: The index of the column to resize.
autoSizeColumnMode: One of the System.Windows.Forms.DataGridViewAutoSizeColumnMode values.
AutoResizeColumn(self: DataGridView,columnIndex: int)
Adjusts the width of the specified column to fit the contents of all its cells,including the
header cell.
columnIndex: The index of the column to resize.
"""
pass
def AutoResizeColumnHeadersHeight(self,columnIndex=None):
"""
AutoResizeColumnHeadersHeight(self: DataGridView,columnIndex: int)
Adjusts the height of the column headers based on changes to the contents of the header in the
specified column.
columnIndex: The index of the column containing the header with the changed content.
AutoResizeColumnHeadersHeight(self: DataGridView)
Adjusts the height of the column headers to fit the contents of the largest column header.
"""
pass
def AutoResizeColumns(self,autoSizeColumnsMode=None):
"""
AutoResizeColumns(self: DataGridView,autoSizeColumnsMode: DataGridViewAutoSizeColumnsMode)
Adjusts the width of all columns using the specified size mode.
autoSizeColumnsMode: One of the System.Windows.Forms.DataGridViewAutoSizeColumnsMode values.
AutoResizeColumns(self: DataGridView)
Adjusts the width of all columns to fit the contents of all their cells,including the header
cells.
"""
pass
def AutoResizeRow(self,rowIndex,autoSizeRowMode=None):
"""
AutoResizeRow(self: DataGridView,rowIndex: int,autoSizeRowMode: DataGridViewAutoSizeRowMode)
Adjusts the height of the specified row using the specified size mode.
rowIndex: The index of the row to resize.
autoSizeRowMode: One of the System.Windows.Forms.DataGridViewAutoSizeRowMode values.
AutoResizeRow(self: DataGridView,rowIndex: int)
Adjusts the height of the specified row to fit the contents of all its cells including the
header cell.
rowIndex: The index of the row to resize.
"""
pass
def AutoResizeRowHeadersWidth(self,*__args):
"""
AutoResizeRowHeadersWidth(self: DataGridView,rowIndex: int,rowHeadersWidthSizeMode: DataGridViewRowHeadersWidthSizeMode)
Adjusts the width of the row headers based on changes to the contents of the header in the
specified row and using the specified size mode.
rowIndex: The index of the row header with the changed content.
rowHeadersWidthSizeMode: One of the System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode values.
AutoResizeRowHeadersWidth(self: DataGridView,rowHeadersWidthSizeMode: DataGridViewRowHeadersWidthSizeMode)
Adjusts the width of the row headers using the specified size mode.
rowHeadersWidthSizeMode: One of the System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode values.
"""
pass
def AutoResizeRows(self,autoSizeRowsMode=None):
"""
AutoResizeRows(self: DataGridView,autoSizeRowsMode: DataGridViewAutoSizeRowsMode)
Adjusts the heights of the rows using the specified size mode value.
autoSizeRowsMode: One of the System.Windows.Forms.DataGridViewAutoSizeRowsMode values.
AutoResizeRows(self: DataGridView)
Adjusts the heights of all rows to fit the contents of all their cells,including the header
cells.
"""
pass
def BeginEdit(self,selectAll):
"""
BeginEdit(self: DataGridView,selectAll: bool) -> bool
Puts the current cell in edit mode.
selectAll: true to select all the cell's contents; false to not select any contents.
Returns: true if the current cell is already in edit mode or successfully enters edit mode; otherwise,
false.
"""
pass
def CancelEdit(self):
"""
CancelEdit(self: DataGridView) -> bool
Cancels edit mode for the currently selected cell and discards any changes.
Returns: true if the cancel was successful; otherwise,false.
"""
pass
def ClearSelection(self):
"""
ClearSelection(self: DataGridView)
Clears the current selection by unselecting all selected cells.
"""
pass
def CommitEdit(self,context):
"""
CommitEdit(self: DataGridView,context: DataGridViewDataErrorContexts) -> bool
Commits changes in the current cell to the data cache without ending edit mode.
context: A bitwise combination of System.Windows.Forms.DataGridViewDataErrorContexts values that
specifies the context in which an error can occur.
Returns: true if the changes were committed; otherwise false.
"""
pass
def CreateAccessibilityInstance(self,*args):
"""
CreateAccessibilityInstance(self: DataGridView) -> AccessibleObject
Creates a new accessible object for the System.Windows.Forms.DataGridView.
Returns: A new System.Windows.Forms.DataGridView.DataGridViewAccessibleObject for the
System.Windows.Forms.DataGridView.
"""
pass
def CreateColumnsInstance(self,*args):
"""
CreateColumnsInstance(self: DataGridView) -> DataGridViewColumnCollection
Creates and returns a new System.Windows.Forms.DataGridViewColumnCollection.
Returns: An empty System.Windows.Forms.DataGridViewColumnCollection.
"""
pass
def CreateControlsInstance(self,*args):
"""
CreateControlsInstance(self: DataGridView) -> ControlCollection
Creates and returns a new System.Windows.Forms.Control.ControlCollection that can be cast to
type System.Windows.Forms.DataGridView.DataGridViewControlCollection.
Returns: An empty System.Windows.Forms.Control.ControlCollection.
"""
pass
def CreateHandle(self,*args):
"""
CreateHandle(self: Control)
Creates a handle for the control.
"""
pass
def CreateRowsInstance(self,*args):
"""
CreateRowsInstance(self: DataGridView) -> DataGridViewRowCollection
Creates and returns a new System.Windows.Forms.DataGridViewRowCollection.
Returns: An empty System.Windows.Forms.DataGridViewRowCollection.
"""
pass
def DefWndProc(self,*args):
"""
DefWndProc(self: Control,m: Message) -> Message
Sends the specified message to the default window procedure.
m: The Windows System.Windows.Forms.Message to process.
"""
pass
def DestroyHandle(self,*args):
"""
DestroyHandle(self: Control)
Destroys the handle associated with the control.
"""
pass
def DisplayedColumnCount(self,includePartialColumns):
"""
DisplayedColumnCount(self: DataGridView,includePartialColumns: bool) -> int
Returns the number of columns displayed to the user.
includePartialColumns: true to include partial columns in the displayed column count; otherwise,false.
Returns: The number of columns displayed to the user.
"""
pass
def DisplayedRowCount(self,includePartialRow):
"""
DisplayedRowCount(self: DataGridView,includePartialRow: bool) -> int
Returns the number of rows displayed to the user.
includePartialRow: true to include partial rows in the displayed row count; otherwise,false.
Returns: The number of rows displayed to the user.
"""
pass
def Dispose(self):
"""
Dispose(self: DataGridView,disposing: bool)
disposing: true to release both managed and unmanaged resources; false to release only unmanaged resources.
"""
pass
def EndEdit(self,context=None):
"""
EndEdit(self: DataGridView,context: DataGridViewDataErrorContexts) -> bool
Commits and ends the edit operation on the current cell using the specified error context.
context: A bitwise combination of System.Windows.Forms.DataGridViewDataErrorContexts values that
specifies the context in which an error can occur.
Returns: true if the edit operation is committed and ended; otherwise,false.
EndEdit(self: DataGridView) -> bool
Commits and ends the edit operation on the current cell using the default error context.
Returns: true if the edit operation is committed and ended; otherwise,false.
"""
pass
def GetAccessibilityObjectById(self,*args):
"""
GetAccessibilityObjectById(self: DataGridView,objectId: int) -> AccessibleObject
objectId: An Int32 that identifies the System.Windows.Forms.AccessibleObject to retrieve.
Returns: An System.Windows.Forms.AccessibleObject.
"""
pass
def GetAutoSizeMode(self,*args):
"""
GetAutoSizeMode(self: Control) -> AutoSizeMode
Retrieves a value indicating how a control will behave when its
System.Windows.Forms.Control.AutoSize property is enabled.
Returns: One of the System.Windows.Forms.AutoSizeMode values.
"""
pass
def GetCellCount(self,includeFilter):
"""
GetCellCount(self: DataGridView,includeFilter: DataGridViewElementStates) -> int
Gets the number of cells that satisfy the provided filter.
includeFilter: A bitwise combination of the System.Windows.Forms.DataGridViewElementStates values specifying
the cells to count.
Returns: The number of cells that match the includeFilter parameter.
"""
pass
def GetCellDisplayRectangle(self,columnIndex,rowIndex,cutOverflow):
"""
GetCellDisplayRectangle(self: DataGridView,columnIndex: int,rowIndex: int,cutOverflow: bool) -> Rectangle
Returns the rectangle that represents the display area for a cell.
columnIndex: The column index for the desired cell.
rowIndex: The row index for the desired cell.
cutOverflow: true to return the displayed portion of the cell only; false to return the entire cell bounds.
Returns: The System.Drawing.Rectangle that represents the display rectangle of the cell.
"""
pass
def GetClipboardContent(self):
"""
GetClipboardContent(self: DataGridView) -> DataObject
Retrieves the formatted values that represent the contents of the selected cells for copying to
the System.Windows.Forms.Clipboard.
Returns: A System.Windows.Forms.DataObject that represents the contents of the selected cells.
"""
pass
def GetColumnDisplayRectangle(self,columnIndex,cutOverflow):
"""
GetColumnDisplayRectangle(self: DataGridView,columnIndex: int,cutOverflow: bool) -> Rectangle
Returns the rectangle that represents the display area for a column,as determined by the column
index.
columnIndex: The column index for the desired cell.
cutOverflow: true to return the column rectangle visible in the System.Windows.Forms.DataGridView bounds;
false to return the entire column rectangle.
Returns: The System.Drawing.Rectangle that represents the display rectangle of the column.
"""
pass
def GetRowDisplayRectangle(self,rowIndex,cutOverflow):
"""
GetRowDisplayRectangle(self: DataGridView,rowIndex: int,cutOverflow: bool) -> Rectangle
Returns the rectangle that represents the display area for a row,as determined by the row index.
rowIndex: The row index for the desired cell.
cutOverflow: true to return the row rectangle visible in the System.Windows.Forms.DataGridView bounds; false
to return the entire row rectangle.
Returns: The System.Drawing.Rectangle that represents the display rectangle of the row.
"""
pass
def GetScaledBounds(self,*args):
"""
GetScaledBounds(self: Control,bounds: Rectangle,factor: SizeF,specified: BoundsSpecified) -> Rectangle
Retrieves the bounds within which the control is scaled.
bounds: A System.Drawing.Rectangle that specifies the area for which to retrieve the display bounds.
factor: The height and width of the control's bounds.
specified: One of the values of System.Windows.Forms.BoundsSpecified that specifies the bounds of the
control to use when defining its size and position.
Returns: A System.Drawing.Rectangle representing the bounds within which the control is scaled.
"""
pass
def GetService(self,*args):
"""
GetService(self: Component,service: Type) -> object
Returns an object that represents a service provided by the System.ComponentModel.Component or
by its System.ComponentModel.Container.
service: A service provided by the System.ComponentModel.Component.
Returns: An System.Object that represents a service provided by the System.ComponentModel.Component,or
null if the System.ComponentModel.Component does not provide the specified service.
"""
pass
def GetStyle(self,*args):
"""
GetStyle(self: Control,flag: ControlStyles) -> bool
Retrieves the value of the specified control style bit for the control.
flag: The System.Windows.Forms.ControlStyles bit to return the value from.
Returns: true if the specified control style bit is set to true; otherwise,false.
"""
pass
def GetTopLevel(self,*args):
"""
GetTopLevel(self: Control) -> bool
Determines if the control is a top-level control.
Returns: true if the control is a top-level control; otherwise,false.
"""
pass
def HitTest(self,x,y):
"""
HitTest(self: DataGridView,x: int,y: int) -> HitTestInfo
Returns location information,such as row and column indices,given x- and y-coordinates.
x: The x-coordinate.
y: The y-coordinate.
Returns: A System.Windows.Forms.DataGridView.HitTestInfo that contains the location information.
"""
pass
def InitLayout(self,*args):
"""
InitLayout(self: Control)
Called after the control has been added to another container.
"""
pass
def InvalidateCell(self,*__args):
"""
InvalidateCell(self: DataGridView,columnIndex: int,rowIndex: int)
Invalidates the cell with the specified row and column indexes,forcing it to be repainted.
columnIndex: The column index of the cell to invalidate.
rowIndex: The row index of the cell to invalidate.
InvalidateCell(self: DataGridView,dataGridViewCell: DataGridViewCell)
Invalidates the specified cell of the System.Windows.Forms.DataGridView,forcing it to be
repainted.
dataGridViewCell: The System.Windows.Forms.DataGridViewCell to invalidate.
"""
pass
def InvalidateColumn(self,columnIndex):
"""
InvalidateColumn(self: DataGridView,columnIndex: int)
Invalidates the specified column of the System.Windows.Forms.DataGridView,forcing it to be
repainted.
columnIndex: The index of the column to invalidate.
"""
pass
def InvalidateRow(self,rowIndex):
"""
InvalidateRow(self: DataGridView,rowIndex: int)
Invalidates the specified row of the System.Windows.Forms.DataGridView,forcing it to be
repainted.
rowIndex: The index of the row to invalidate.
"""
pass
def InvokeGotFocus(self,*args):
"""
InvokeGotFocus(self: Control,toInvoke: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.GotFocus event for the specified control.
toInvoke: The System.Windows.Forms.Control to assign the event to.
e: An System.EventArgs that contains the event data.
"""
pass
def InvokeLostFocus(self,*args):
"""
InvokeLostFocus(self: Control,toInvoke: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.LostFocus event for the specified control.
toInvoke: The System.Windows.Forms.Control to assign the event to.
e: An System.EventArgs that contains the event data.
"""
pass
def InvokeOnClick(self,*args):
"""
InvokeOnClick(self: Control,toInvoke: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.Click event for the specified control.
toInvoke: The System.Windows.Forms.Control to assign the System.Windows.Forms.Control.Click event to.
e: An System.EventArgs that contains the event data.
"""
pass
def InvokePaint(self,*args):
"""
InvokePaint(self: Control,c: Control,e: PaintEventArgs)
Raises the System.Windows.Forms.Control.Paint event for the specified control.
c: The System.Windows.Forms.Control to assign the System.Windows.Forms.Control.Paint event to.
e: An System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def InvokePaintBackground(self,*args):
"""
InvokePaintBackground(self: Control,c: Control,e: PaintEventArgs)
Raises the PaintBackground event for the specified control.
c: The System.Windows.Forms.Control to assign the System.Windows.Forms.Control.Paint event to.
e: An System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def IsInputChar(self,*args):
"""
IsInputChar(self: DataGridView,charCode: Char) -> bool
Determines whether a character is an input character that the System.Windows.Forms.DataGridView
recognizes.
charCode: The character to test.
Returns: true if the character is recognized as an input character; otherwise,false.
"""
pass
def IsInputKey(self,*args):
"""
IsInputKey(self: DataGridView,keyData: Keys) -> bool
keyData: One of the System.Windows.Forms.Keys values.
Returns: true if the specified key is a regular input key; otherwise,false.
"""
pass
def MemberwiseClone(self,*args):
"""
MemberwiseClone(self: MarshalByRefObject,cloneIdentity: bool) -> MarshalByRefObject
Creates a shallow copy of the current System.MarshalByRefObject object.
cloneIdentity: false to delete the current System.MarshalByRefObject object's identity,which will cause the
object to be assigned a new identity when it is marshaled across a remoting boundary. A value of
false is usually appropriate. true to copy the current System.MarshalByRefObject object's
identity to its clone,which will cause remoting client calls to be routed to the remote server
object.
Returns: A shallow copy of the current System.MarshalByRefObject object.
MemberwiseClone(self: object) -> object
Creates a shallow copy of the current System.Object.
Returns: A shallow copy of the current System.Object.
"""
pass
def NotifyCurrentCellDirty(self,dirty):
"""
NotifyCurrentCellDirty(self: DataGridView,dirty: bool)
Notifies the System.Windows.Forms.DataGridView that the current cell has uncommitted changes.
dirty: true to indicate the cell has uncommitted changes; otherwise,false.
"""
pass
def NotifyInvalidate(self,*args):
"""
NotifyInvalidate(self: Control,invalidatedArea: Rectangle)
Raises the System.Windows.Forms.Control.Invalidated event with a specified region of the control
to invalidate.
invalidatedArea: A System.Drawing.Rectangle representing the area to invalidate.
"""
pass
def OnAllowUserToAddRowsChanged(self,*args):
"""
OnAllowUserToAddRowsChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.AllowUserToAddRowsChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnAllowUserToDeleteRowsChanged(self,*args):
"""
OnAllowUserToDeleteRowsChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.AllowUserToDeleteRowsChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnAllowUserToOrderColumnsChanged(self,*args):
"""
OnAllowUserToOrderColumnsChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.AllowUserToOrderColumnsChanged event.
e: A System.EventArgs that contains the event data.
"""
pass
def OnAllowUserToResizeColumnsChanged(self,*args):
"""
OnAllowUserToResizeColumnsChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.AllowUserToResizeColumnsChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnAllowUserToResizeRowsChanged(self,*args):
"""
OnAllowUserToResizeRowsChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.AllowUserToResizeRowsChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnAlternatingRowsDefaultCellStyleChanged(self,*args):
"""
OnAlternatingRowsDefaultCellStyleChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.AlternatingRowsDefaultCellStyleChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnAutoGenerateColumnsChanged(self,*args):
"""
OnAutoGenerateColumnsChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.AutoGenerateColumnsChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnAutoSizeChanged(self,*args):
"""
OnAutoSizeChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.AutoSizeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnAutoSizeColumnModeChanged(self,*args):
"""
OnAutoSizeColumnModeChanged(self: DataGridView,e: DataGridViewAutoSizeColumnModeEventArgs)
Raises the System.Windows.Forms.DataGridView.AutoSizeColumnModeChanged event.
e: A System.Windows.Forms.DataGridViewAutoSizeColumnModeEventArgs that contains the event data.
"""
pass
def OnAutoSizeColumnsModeChanged(self,*args):
"""
OnAutoSizeColumnsModeChanged(self: DataGridView,e: DataGridViewAutoSizeColumnsModeEventArgs)
Raises the System.Windows.Forms.DataGridView.AutoSizeColumnsModeChanged event.
e: A System.Windows.Forms.DataGridViewAutoSizeColumnsModeEventArgs that contains the event data.
"""
pass
def OnAutoSizeRowsModeChanged(self,*args):
"""
OnAutoSizeRowsModeChanged(self: DataGridView,e: DataGridViewAutoSizeModeEventArgs)
Raises the System.Windows.Forms.DataGridView.AutoSizeRowsModeChanged event.
e: A System.Windows.Forms.DataGridViewAutoSizeModeEventArgs that contains the event data.
"""
pass
def OnBackColorChanged(self,*args):
"""
OnBackColorChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BackColorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBackgroundColorChanged(self,*args):
"""
OnBackgroundColorChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.BackgroundColorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBackgroundImageChanged(self,*args):
"""
OnBackgroundImageChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BackgroundImageChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBackgroundImageLayoutChanged(self,*args):
"""
OnBackgroundImageLayoutChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BackgroundImageLayoutChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBindingContextChanged(self,*args):
"""
OnBindingContextChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.Control.BindingContextChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBorderStyleChanged(self,*args):
"""
OnBorderStyleChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.BorderStyleChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnCancelRowEdit(self,*args):
"""
OnCancelRowEdit(self: DataGridView,e: QuestionEventArgs)
Raises the System.Windows.Forms.DataGridView.CancelRowEdit event.
e: A System.Windows.Forms.QuestionEventArgs that contains the event data.
"""
pass
def OnCausesValidationChanged(self,*args):
"""
OnCausesValidationChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.CausesValidationChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnCellBeginEdit(self,*args):
"""
OnCellBeginEdit(self: DataGridView,e: DataGridViewCellCancelEventArgs)
Raises the System.Windows.Forms.DataGridView.CellBeginEdit event.
e: A System.Windows.Forms.DataGridViewCellCancelEventArgs that contains the event data.
"""
pass
def OnCellBorderStyleChanged(self,*args):
"""
OnCellBorderStyleChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.CellBorderStyleChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnCellClick(self,*args):
"""
OnCellClick(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellClick event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellContentClick(self,*args):
"""
OnCellContentClick(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellContentClick event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains information regarding the cell
whose content was clicked.
"""
pass
def OnCellContentDoubleClick(self,*args):
"""
OnCellContentDoubleClick(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellContentDoubleClick event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellContextMenuStripChanged(self,*args):
"""
OnCellContextMenuStripChanged(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellContextMenuStripChanged event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellContextMenuStripNeeded(self,*args):
"""
OnCellContextMenuStripNeeded(self: DataGridView,e: DataGridViewCellContextMenuStripNeededEventArgs)
Raises the System.Windows.Forms.DataGridView.CellContextMenuStripNeeded event.
e: A System.Windows.Forms.DataGridViewCellContextMenuStripNeededEventArgs that contains the event
data.
"""
pass
def OnCellDoubleClick(self,*args):
"""
OnCellDoubleClick(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellDoubleClick event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellEndEdit(self,*args):
"""
OnCellEndEdit(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellEndEdit event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellEnter(self,*args):
"""
OnCellEnter(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellEnter event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellErrorTextChanged(self,*args):
"""
OnCellErrorTextChanged(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellErrorTextChanged event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellErrorTextNeeded(self,*args):
"""
OnCellErrorTextNeeded(self: DataGridView,e: DataGridViewCellErrorTextNeededEventArgs)
Raises the System.Windows.Forms.DataGridView.CellErrorTextNeeded event.
e: A System.Windows.Forms.DataGridViewCellErrorTextNeededEventArgs that contains the event data.
"""
pass
def OnCellFormatting(self,*args):
"""
OnCellFormatting(self: DataGridView,e: DataGridViewCellFormattingEventArgs)
Raises the System.Windows.Forms.DataGridView.CellFormatting event.
e: A System.Windows.Forms.DataGridViewCellFormattingEventArgs that contains the event data.
"""
pass
def OnCellLeave(self,*args):
"""
OnCellLeave(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellLeave event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellMouseClick(self,*args):
"""
OnCellMouseClick(self: DataGridView,e: DataGridViewCellMouseEventArgs)
Raises the System.Windows.Forms.DataGridView.CellMouseClick event.
e: A System.Windows.Forms.DataGridViewCellMouseEventArgs that contains the event data.
"""
pass
def OnCellMouseDoubleClick(self,*args):
"""
OnCellMouseDoubleClick(self: DataGridView,e: DataGridViewCellMouseEventArgs)
Raises the System.Windows.Forms.DataGridView.CellMouseDoubleClick event.
e: A System.Windows.Forms.DataGridViewCellMouseEventArgs that contains the event data.
"""
pass
def OnCellMouseDown(self,*args):
"""
OnCellMouseDown(self: DataGridView,e: DataGridViewCellMouseEventArgs)
Raises the System.Windows.Forms.DataGridView.CellMouseDown event.
e: A System.Windows.Forms.DataGridViewCellMouseEventArgs that contains the event data.
"""
pass
def OnCellMouseEnter(self,*args):
"""
OnCellMouseEnter(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellMouseEnter event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellMouseLeave(self,*args):
"""
OnCellMouseLeave(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellMouseLeave event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellMouseMove(self,*args):
"""
OnCellMouseMove(self: DataGridView,e: DataGridViewCellMouseEventArgs)
Raises the System.Windows.Forms.DataGridView.CellMouseMove event.
e: A System.Windows.Forms.DataGridViewCellMouseEventArgs that contains the event data.
"""
pass
def OnCellMouseUp(self,*args):
"""
OnCellMouseUp(self: DataGridView,e: DataGridViewCellMouseEventArgs)
Raises the System.Windows.Forms.DataGridView.CellMouseUp event.
e: A System.Windows.Forms.DataGridViewCellMouseEventArgs that contains the event data.
"""
pass
def OnCellPainting(self,*args):
"""
OnCellPainting(self: DataGridView,e: DataGridViewCellPaintingEventArgs)
Raises the System.Windows.Forms.DataGridView.CellPainting event.
e: A System.Windows.Forms.DataGridViewCellPaintingEventArgs that contains the event data.
"""
pass
def OnCellParsing(self,*args):
"""
OnCellParsing(self: DataGridView,e: DataGridViewCellParsingEventArgs)
Raises the System.Windows.Forms.DataGridView.CellParsing event.
e: A System.Windows.Forms.DataGridViewCellParsingEventArgs that contains the event data.
"""
pass
def OnCellStateChanged(self,*args):
"""
OnCellStateChanged(self: DataGridView,e: DataGridViewCellStateChangedEventArgs)
Raises the System.Windows.Forms.DataGridView.CellStateChanged event.
e: A System.Windows.Forms.DataGridViewCellStateChangedEventArgs that contains the event data.
"""
pass
def OnCellStyleChanged(self,*args):
"""
OnCellStyleChanged(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellStyleChanged event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellStyleContentChanged(self,*args):
"""
OnCellStyleContentChanged(self: DataGridView,e: DataGridViewCellStyleContentChangedEventArgs)
Raises the System.Windows.Forms.DataGridView.CellStyleContentChanged event.
e: A System.Windows.Forms.DataGridViewCellStyleContentChangedEventArgs that contains the event data.
"""
pass
def OnCellToolTipTextChanged(self,*args):
"""
OnCellToolTipTextChanged(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellToolTipTextChanged event.
e: An System.Windows.Forms.DataGridViewCellEventArgs that contains information about the cell.
"""
pass
def OnCellToolTipTextNeeded(self,*args):
"""
OnCellToolTipTextNeeded(self: DataGridView,e: DataGridViewCellToolTipTextNeededEventArgs)
Raises the System.Windows.Forms.DataGridView.CellToolTipTextNeeded event.
e: A System.Windows.Forms.DataGridViewCellToolTipTextNeededEventArgs that contains the event data.
"""
pass
def OnCellValidated(self,*args):
"""
OnCellValidated(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellValidated event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellValidating(self,*args):
"""
OnCellValidating(self: DataGridView,e: DataGridViewCellValidatingEventArgs)
Raises the System.Windows.Forms.DataGridView.CellValidating event.
e: A System.Windows.Forms.DataGridViewCellValidatingEventArgs that contains the event data.
"""
pass
def OnCellValueChanged(self,*args):
"""
OnCellValueChanged(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellValueChanged event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnCellValueNeeded(self,*args):
"""
OnCellValueNeeded(self: DataGridView,e: DataGridViewCellValueEventArgs)
Raises the System.Windows.Forms.DataGridView.CellValueNeeded event.
e: A System.Windows.Forms.DataGridViewCellValueEventArgs that contains the event data.
"""
pass
def OnCellValuePushed(self,*args):
"""
OnCellValuePushed(self: DataGridView,e: DataGridViewCellValueEventArgs)
Raises the System.Windows.Forms.DataGridView.CellValuePushed event.
e: A System.Windows.Forms.DataGridViewCellValueEventArgs that contains the event data.
"""
pass
def OnChangeUICues(self,*args):
"""
OnChangeUICues(self: Control,e: UICuesEventArgs)
Raises the System.Windows.Forms.Control.ChangeUICues event.
e: A System.Windows.Forms.UICuesEventArgs that contains the event data.
"""
pass
def OnClick(self,*args):
"""
OnClick(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.Click event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnClientSizeChanged(self,*args):
"""
OnClientSizeChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ClientSizeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnColumnAdded(self,*args):
"""
OnColumnAdded(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnAdded event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnColumnContextMenuStripChanged(self,*args):
"""
OnColumnContextMenuStripChanged(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnContextMenuStripChanged event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnColumnDataPropertyNameChanged(self,*args):
"""
OnColumnDataPropertyNameChanged(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnDataPropertyNameChanged event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnColumnDefaultCellStyleChanged(self,*args):
"""
OnColumnDefaultCellStyleChanged(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnDefaultCellStyleChanged event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnColumnDisplayIndexChanged(self,*args):
"""
OnColumnDisplayIndexChanged(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnDisplayIndexChanged event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnColumnDividerDoubleClick(self,*args):
"""
OnColumnDividerDoubleClick(self: DataGridView,e: DataGridViewColumnDividerDoubleClickEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnDividerDoubleClick event.
e: A System.Windows.Forms.DataGridViewColumnDividerDoubleClickEventArgs that contains the event
data.
"""
pass
def OnColumnDividerWidthChanged(self,*args):
"""
OnColumnDividerWidthChanged(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnDividerWidthChanged event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnColumnHeaderCellChanged(self,*args):
"""
OnColumnHeaderCellChanged(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnHeaderCellChanged event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnColumnHeaderMouseClick(self,*args):
"""
OnColumnHeaderMouseClick(self: DataGridView,e: DataGridViewCellMouseEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnHeaderMouseClick event.
e: A System.Windows.Forms.DataGridViewCellMouseEventArgs that contains the event data.
"""
pass
def OnColumnHeaderMouseDoubleClick(self,*args):
"""
OnColumnHeaderMouseDoubleClick(self: DataGridView,e: DataGridViewCellMouseEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnHeaderMouseDoubleClick event.
e: A System.Windows.Forms.DataGridViewCellMouseEventArgs that contains information about the cell
and the position of the mouse pointer.
"""
pass
def OnColumnHeadersBorderStyleChanged(self,*args):
"""
OnColumnHeadersBorderStyleChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnHeadersBorderStyleChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnColumnHeadersDefaultCellStyleChanged(self,*args):
"""
OnColumnHeadersDefaultCellStyleChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnHeadersDefaultCellStyleChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnColumnHeadersHeightChanged(self,*args):
"""
OnColumnHeadersHeightChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnHeadersHeightChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnColumnHeadersHeightSizeModeChanged(self,*args):
"""
OnColumnHeadersHeightSizeModeChanged(self: DataGridView,e: DataGridViewAutoSizeModeEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnHeadersHeightSizeModeChanged event.
e: A System.Windows.Forms.DataGridViewAutoSizeModeEventArgs that contains the event data.
"""
pass
def OnColumnMinimumWidthChanged(self,*args):
"""
OnColumnMinimumWidthChanged(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnMinimumWidthChanged event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnColumnNameChanged(self,*args):
"""
OnColumnNameChanged(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnNameChanged event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnColumnRemoved(self,*args):
"""
OnColumnRemoved(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnRemoved event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnColumnSortModeChanged(self,*args):
"""
OnColumnSortModeChanged(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnSortModeChanged event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnColumnStateChanged(self,*args):
"""
OnColumnStateChanged(self: DataGridView,e: DataGridViewColumnStateChangedEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnStateChanged event.
e: A System.Windows.Forms.DataGridViewColumnStateChangedEventArgs that contains the event data.
"""
pass
def OnColumnToolTipTextChanged(self,*args):
"""
OnColumnToolTipTextChanged(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnToolTipTextChanged event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains information about the column.
"""
pass
def OnColumnWidthChanged(self,*args):
"""
OnColumnWidthChanged(self: DataGridView,e: DataGridViewColumnEventArgs)
Raises the System.Windows.Forms.DataGridView.ColumnWidthChanged event.
e: A System.Windows.Forms.DataGridViewColumnEventArgs that contains the event data.
"""
pass
def OnContextMenuChanged(self,*args):
"""
OnContextMenuChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ContextMenuChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnContextMenuStripChanged(self,*args):
"""
OnContextMenuStripChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ContextMenuStripChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnControlAdded(self,*args):
"""
OnControlAdded(self: Control,e: ControlEventArgs)
Raises the System.Windows.Forms.Control.ControlAdded event.
e: A System.Windows.Forms.ControlEventArgs that contains the event data.
"""
pass
def OnControlRemoved(self,*args):
"""
OnControlRemoved(self: Control,e: ControlEventArgs)
Raises the System.Windows.Forms.Control.ControlRemoved event.
e: A System.Windows.Forms.ControlEventArgs that contains the event data.
"""
pass
def OnCreateControl(self,*args):
"""
OnCreateControl(self: Control)
Raises the System.Windows.Forms.Control.CreateControl method.
"""
pass
def OnCurrentCellChanged(self,*args):
"""
OnCurrentCellChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.CurrentCellChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnCurrentCellDirtyStateChanged(self,*args):
"""
OnCurrentCellDirtyStateChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.CurrentCellDirtyStateChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnCursorChanged(self,*args):
"""
OnCursorChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.Control.CursorChanged event and updates the
System.Windows.Forms.DataGridView.UserSetCursor property if the cursor was changed in user code.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDataBindingComplete(self,*args):
"""
OnDataBindingComplete(self: DataGridView,e: DataGridViewBindingCompleteEventArgs)
Raises the System.Windows.Forms.DataGridView.DataBindingComplete event.
e: A System.Windows.Forms.DataGridViewBindingCompleteEventArgs that contains the event data.
"""
pass
def OnDataError(self,*args):
"""
OnDataError(self: DataGridView,displayErrorDialogIfNoHandler: bool,e: DataGridViewDataErrorEventArgs)
Raises the System.Windows.Forms.DataGridView.DataError event.
displayErrorDialogIfNoHandler: true to display an error dialog box if there is no handler for the
System.Windows.Forms.DataGridView.DataError event.
e: A System.Windows.Forms.DataGridViewDataErrorEventArgs that contains the event data.
"""
pass
def OnDataMemberChanged(self,*args):
"""
OnDataMemberChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.DataMemberChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDataSourceChanged(self,*args):
"""
OnDataSourceChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.DataSourceChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDefaultCellStyleChanged(self,*args):
"""
OnDefaultCellStyleChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.DefaultCellStyleChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDefaultValuesNeeded(self,*args):
"""
OnDefaultValuesNeeded(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.DefaultValuesNeeded event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnDockChanged(self,*args):
"""
OnDockChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.DockChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDoubleClick(self,*args):
"""
OnDoubleClick(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.Control.DoubleClick event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDpiChangedAfterParent(self,*args):
""" OnDpiChangedAfterParent(self: Control,e: EventArgs) """
pass
def OnDpiChangedBeforeParent(self,*args):
""" OnDpiChangedBeforeParent(self: Control,e: EventArgs) """
pass
def OnDragDrop(self,*args):
"""
OnDragDrop(self: Control,drgevent: DragEventArgs)
Raises the System.Windows.Forms.Control.DragDrop event.
drgevent: A System.Windows.Forms.DragEventArgs that contains the event data.
"""
pass
def OnDragEnter(self,*args):
"""
OnDragEnter(self: Control,drgevent: DragEventArgs)
Raises the System.Windows.Forms.Control.DragEnter event.
drgevent: A System.Windows.Forms.DragEventArgs that contains the event data.
"""
pass
def OnDragLeave(self,*args):
"""
OnDragLeave(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.DragLeave event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDragOver(self,*args):
"""
OnDragOver(self: Control,drgevent: DragEventArgs)
Raises the System.Windows.Forms.Control.DragOver event.
drgevent: A System.Windows.Forms.DragEventArgs that contains the event data.
"""
pass
def OnEditingControlShowing(self,*args):
"""
OnEditingControlShowing(self: DataGridView,e: DataGridViewEditingControlShowingEventArgs)
Raises the System.Windows.Forms.DataGridView.EditingControlShowing event.
e: A System.Windows.Forms.DataGridViewEditingControlShowingEventArgs that contains information
about the editing control.
"""
pass
def OnEditModeChanged(self,*args):
"""
OnEditModeChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.EditModeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnEnabledChanged(self,*args):
"""
OnEnabledChanged(self: DataGridView,e: EventArgs)
e: An System.EventArgs that contains the event data.
"""
pass
def OnEnter(self,*args):
"""
OnEnter(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.Control.Enter event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnFontChanged(self,*args):
"""
OnFontChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.FontChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnForeColorChanged(self,*args):
"""
OnForeColorChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.ForeColorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnGiveFeedback(self,*args):
"""
OnGiveFeedback(self: Control,gfbevent: GiveFeedbackEventArgs)
Raises the System.Windows.Forms.Control.GiveFeedback event.
gfbevent: A System.Windows.Forms.GiveFeedbackEventArgs that contains the event data.
"""
pass
def OnGotFocus(self,*args):
"""
OnGotFocus(self: DataGridView,e: EventArgs)
e: An System.EventArgs that contains the event data.
"""
pass
def OnGridColorChanged(self,*args):
"""
OnGridColorChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.GridColorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnHandleCreated(self,*args):
"""
OnHandleCreated(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.Control.HandleCreated event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnHandleDestroyed(self,*args):
"""
OnHandleDestroyed(self: DataGridView,e: EventArgs)
e: An System.EventArgs that contains the event data.
"""
pass
def OnHelpRequested(self,*args):
"""
OnHelpRequested(self: Control,hevent: HelpEventArgs)
Raises the System.Windows.Forms.Control.HelpRequested event.
hevent: A System.Windows.Forms.HelpEventArgs that contains the event data.
"""
pass
def OnImeModeChanged(self,*args):
"""
OnImeModeChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ImeModeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnInvalidated(self,*args):
"""
OnInvalidated(self: Control,e: InvalidateEventArgs)
Raises the System.Windows.Forms.Control.Invalidated event.
e: An System.Windows.Forms.InvalidateEventArgs that contains the event data.
"""
pass
def OnKeyDown(self,*args):
"""
OnKeyDown(self: DataGridView,e: KeyEventArgs)
Raises the System.Windows.Forms.Control.KeyDown event.
e: A System.Windows.Forms.KeyEventArgs that contains the event data.
"""
pass
def OnKeyPress(self,*args):
"""
OnKeyPress(self: DataGridView,e: KeyPressEventArgs)
Raises the System.Windows.Forms.Control.KeyPress event.
e: A System.Windows.Forms.KeyPressEventArgs that contains the event data.
"""
pass
def OnKeyUp(self,*args):
"""
OnKeyUp(self: DataGridView,e: KeyEventArgs)
Raises the System.Windows.Forms.Control.KeyUp event.
e: A System.Windows.Forms.KeyEventArgs that contains the event data.
"""
pass
def OnLayout(self,*args):
"""
OnLayout(self: DataGridView,e: LayoutEventArgs)
Raises the System.Windows.Forms.Control.Layout event.
e: A System.Windows.Forms.LayoutEventArgs that contains the event data.
"""
pass
def OnLeave(self,*args):
"""
OnLeave(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.Control.Leave event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnLocationChanged(self,*args):
"""
OnLocationChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.LocationChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnLostFocus(self,*args):
"""
OnLostFocus(self: DataGridView,e: EventArgs)
e: An System.EventArgs that contains the event data.
"""
pass
def OnMarginChanged(self,*args):
"""
OnMarginChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.MarginChanged event.
e: A System.EventArgs that contains the event data.
"""
pass
def OnMouseCaptureChanged(self,*args):
"""
OnMouseCaptureChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.MouseCaptureChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnMouseClick(self,*args):
"""
OnMouseClick(self: DataGridView,e: MouseEventArgs)
Raises the System.Windows.Forms.Control.MouseClick event.
e: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMouseDoubleClick(self,*args):
"""
OnMouseDoubleClick(self: DataGridView,e: MouseEventArgs)
e: An System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMouseDown(self,*args):
"""
OnMouseDown(self: DataGridView,e: MouseEventArgs)
Raises the System.Windows.Forms.Control.MouseDown event.
e: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMouseEnter(self,*args):
"""
OnMouseEnter(self: DataGridView,e: EventArgs)
e: An System.EventArgs that contains the event data.
"""
pass
def OnMouseHover(self,*args):
"""
OnMouseHover(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.MouseHover event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnMouseLeave(self,*args):
"""
OnMouseLeave(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.Control.MouseLeave event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnMouseMove(self,*args):
"""
OnMouseMove(self: DataGridView,e: MouseEventArgs)
Raises the System.Windows.Forms.Control.MouseMove event.
e: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMouseUp(self,*args):
"""
OnMouseUp(self: DataGridView,e: MouseEventArgs)
Raises the System.Windows.Forms.Control.MouseUp event.
e: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMouseWheel(self,*args):
"""
OnMouseWheel(self: DataGridView,e: MouseEventArgs)
e: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMove(self,*args):
"""
OnMove(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.Move event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnMultiSelectChanged(self,*args):
"""
OnMultiSelectChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.MultiSelectChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnNewRowNeeded(self,*args):
"""
OnNewRowNeeded(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.NewRowNeeded event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnNotifyMessage(self,*args):
"""
OnNotifyMessage(self: Control,m: Message)
Notifies the control of Windows messages.
m: A System.Windows.Forms.Message that represents the Windows message.
"""
pass
def OnPaddingChanged(self,*args):
"""
OnPaddingChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.PaddingChanged event.
e: A System.EventArgs that contains the event data.
"""
pass
def OnPaint(self,*args):
"""
OnPaint(self: DataGridView,e: PaintEventArgs)
Raises the System.Windows.Forms.Control.Paint event.
e: A System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def OnPaintBackground(self,*args):
"""
OnPaintBackground(self: Control,pevent: PaintEventArgs)
Paints the background of the control.
pevent: A System.Windows.Forms.PaintEventArgs that contains information about the control to paint.
"""
pass
def OnParentBackColorChanged(self,*args):
"""
OnParentBackColorChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BackColorChanged event when the
System.Windows.Forms.Control.BackColor property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentBackgroundImageChanged(self,*args):
"""
OnParentBackgroundImageChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BackgroundImageChanged event when the
System.Windows.Forms.Control.BackgroundImage property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentBindingContextChanged(self,*args):
"""
OnParentBindingContextChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BindingContextChanged event when the
System.Windows.Forms.Control.BindingContext property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentChanged(self,*args):
"""
OnParentChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ParentChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentCursorChanged(self,*args):
"""
OnParentCursorChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.CursorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentEnabledChanged(self,*args):
"""
OnParentEnabledChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.EnabledChanged event when the
System.Windows.Forms.Control.Enabled property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentFontChanged(self,*args):
"""
OnParentFontChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.FontChanged event when the
System.Windows.Forms.Control.Font property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentForeColorChanged(self,*args):
"""
OnParentForeColorChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ForeColorChanged event when the
System.Windows.Forms.Control.ForeColor property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentRightToLeftChanged(self,*args):
"""
OnParentRightToLeftChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.RightToLeftChanged event when the
System.Windows.Forms.Control.RightToLeft property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentVisibleChanged(self,*args):
"""
OnParentVisibleChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.VisibleChanged event when the
System.Windows.Forms.Control.Visible property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnPreviewKeyDown(self,*args):
"""
OnPreviewKeyDown(self: Control,e: PreviewKeyDownEventArgs)
Raises the System.Windows.Forms.Control.PreviewKeyDown event.
e: A System.Windows.Forms.PreviewKeyDownEventArgs that contains the event data.
"""
pass
def OnPrint(self,*args):
"""
OnPrint(self: Control,e: PaintEventArgs)
Raises the System.Windows.Forms.Control.Paint event.
e: A System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def OnQueryContinueDrag(self,*args):
"""
OnQueryContinueDrag(self: Control,qcdevent: QueryContinueDragEventArgs)
Raises the System.Windows.Forms.Control.QueryContinueDrag event.
qcdevent: A System.Windows.Forms.QueryContinueDragEventArgs that contains the event data.
"""
pass
def OnReadOnlyChanged(self,*args):
"""
OnReadOnlyChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.ReadOnlyChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnRegionChanged(self,*args):
"""
OnRegionChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.RegionChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnResize(self,*args):
"""
OnResize(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.Control.Resize event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnRightToLeftChanged(self,*args):
"""
OnRightToLeftChanged(self: DataGridView,e: EventArgs)
e: An System.EventArgs that contains the event data.
"""
pass
def OnRowContextMenuStripChanged(self,*args):
"""
OnRowContextMenuStripChanged(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.RowContextMenuStripChanged event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnRowContextMenuStripNeeded(self,*args):
"""
OnRowContextMenuStripNeeded(self: DataGridView,e: DataGridViewRowContextMenuStripNeededEventArgs)
Raises the System.Windows.Forms.DataGridView.RowContextMenuStripNeeded event.
e: A System.Windows.Forms.DataGridViewRowContextMenuStripNeededEventArgs that contains the event
data.
"""
pass
def OnRowDefaultCellStyleChanged(self,*args):
"""
OnRowDefaultCellStyleChanged(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.RowDefaultCellStyleChanged event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnRowDirtyStateNeeded(self,*args):
"""
OnRowDirtyStateNeeded(self: DataGridView,e: QuestionEventArgs)
Raises the System.Windows.Forms.DataGridView.RowDirtyStateNeeded event.
e: A System.Windows.Forms.QuestionEventArgs that contains the event data.
"""
pass
def OnRowDividerDoubleClick(self,*args):
"""
OnRowDividerDoubleClick(self: DataGridView,e: DataGridViewRowDividerDoubleClickEventArgs)
Raises the System.Windows.Forms.DataGridView.RowDividerDoubleClick event.
e: A System.Windows.Forms.DataGridViewRowDividerDoubleClickEventArgs that contains the event data.
"""
pass
def OnRowDividerHeightChanged(self,*args):
"""
OnRowDividerHeightChanged(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.RowDividerHeightChanged event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnRowEnter(self,*args):
"""
OnRowEnter(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.RowEnter event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnRowErrorTextChanged(self,*args):
"""
OnRowErrorTextChanged(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.RowErrorTextChanged event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnRowErrorTextNeeded(self,*args):
"""
OnRowErrorTextNeeded(self: DataGridView,e: DataGridViewRowErrorTextNeededEventArgs)
Raises the System.Windows.Forms.DataGridView.RowErrorTextNeeded event.
e: A System.Windows.Forms.DataGridViewRowErrorTextNeededEventArgs that contains the event data.
"""
pass
def OnRowHeaderCellChanged(self,*args):
"""
OnRowHeaderCellChanged(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.RowHeaderCellChanged event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnRowHeaderMouseClick(self,*args):
"""
OnRowHeaderMouseClick(self: DataGridView,e: DataGridViewCellMouseEventArgs)
Raises the System.Windows.Forms.DataGridView.RowHeaderMouseClick event.
e: A System.Windows.Forms.DataGridViewCellMouseEventArgs that contains information about the mouse
and the header cell that was clicked.
"""
pass
def OnRowHeaderMouseDoubleClick(self,*args):
"""
OnRowHeaderMouseDoubleClick(self: DataGridView,e: DataGridViewCellMouseEventArgs)
Raises the System.Windows.Forms.DataGridView.RowHeaderMouseDoubleClick event.
e: A System.Windows.Forms.DataGridViewCellMouseEventArgs that contains information about the mouse
and the header cell that was double-clicked.
"""
pass
def OnRowHeadersBorderStyleChanged(self,*args):
"""
OnRowHeadersBorderStyleChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.RowHeadersBorderStyleChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnRowHeadersDefaultCellStyleChanged(self,*args):
"""
OnRowHeadersDefaultCellStyleChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.RowHeadersDefaultCellStyleChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnRowHeadersWidthChanged(self,*args):
"""
OnRowHeadersWidthChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.RowHeadersWidthChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnRowHeadersWidthSizeModeChanged(self,*args):
"""
OnRowHeadersWidthSizeModeChanged(self: DataGridView,e: DataGridViewAutoSizeModeEventArgs)
Raises the System.Windows.Forms.DataGridView.RowHeadersWidthSizeModeChanged event.
e: A System.Windows.Forms.DataGridViewAutoSizeModeEventArgs that contains the event data.
"""
pass
def OnRowHeightChanged(self,*args):
"""
OnRowHeightChanged(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.RowHeightChanged event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnRowHeightInfoNeeded(self,*args):
"""
OnRowHeightInfoNeeded(self: DataGridView,e: DataGridViewRowHeightInfoNeededEventArgs)
Raises the System.Windows.Forms.DataGridView.RowHeightInfoNeeded event.
e: A System.Windows.Forms.DataGridViewRowHeightInfoNeededEventArgs that contains the event data.
"""
pass
def OnRowHeightInfoPushed(self,*args):
"""
OnRowHeightInfoPushed(self: DataGridView,e: DataGridViewRowHeightInfoPushedEventArgs)
Raises the System.Windows.Forms.DataGridView.RowHeightInfoPushed event.
e: A System.Windows.Forms.DataGridViewRowHeightInfoPushedEventArgs that contains the event data.
"""
pass
def OnRowLeave(self,*args):
"""
OnRowLeave(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.RowLeave event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnRowMinimumHeightChanged(self,*args):
"""
OnRowMinimumHeightChanged(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.RowMinimumHeightChanged event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnRowPostPaint(self,*args):
"""
OnRowPostPaint(self: DataGridView,e: DataGridViewRowPostPaintEventArgs)
Raises the System.Windows.Forms.DataGridView.RowPostPaint event.
e: A System.Windows.Forms.DataGridViewRowPostPaintEventArgs that contains the event data.
"""
pass
def OnRowPrePaint(self,*args):
"""
OnRowPrePaint(self: DataGridView,e: DataGridViewRowPrePaintEventArgs)
Raises the System.Windows.Forms.DataGridView.RowPrePaint event.
e: A System.Windows.Forms.DataGridViewRowPrePaintEventArgs that contains the event data.
"""
pass
def OnRowsAdded(self,*args):
"""
OnRowsAdded(self: DataGridView,e: DataGridViewRowsAddedEventArgs)
Raises the System.Windows.Forms.DataGridView.RowsAdded event.
e: A System.Windows.Forms.DataGridViewRowsAddedEventArgs that contains information about the added
rows.
"""
pass
def OnRowsDefaultCellStyleChanged(self,*args):
"""
OnRowsDefaultCellStyleChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.RowsDefaultCellStyleChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnRowsRemoved(self,*args):
"""
OnRowsRemoved(self: DataGridView,e: DataGridViewRowsRemovedEventArgs)
Raises the System.Windows.Forms.DataGridView.RowsRemoved event.
e: A System.Windows.Forms.DataGridViewRowsRemovedEventArgs that contains information about the
deleted rows.
"""
pass
def OnRowStateChanged(self,*args):
"""
OnRowStateChanged(self: DataGridView,rowIndex: int,e: DataGridViewRowStateChangedEventArgs)
Raises the System.Windows.Forms.DataGridView.RowStateChanged event.
rowIndex: The index of the row that is changing state.
e: A System.Windows.Forms.DataGridViewRowStateChangedEventArgs that contains the event data.
"""
pass
def OnRowUnshared(self,*args):
"""
OnRowUnshared(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.RowUnshared event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnRowValidated(self,*args):
"""
OnRowValidated(self: DataGridView,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.RowValidated event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def OnRowValidating(self,*args):
"""
OnRowValidating(self: DataGridView,e: DataGridViewCellCancelEventArgs)
Raises the System.Windows.Forms.DataGridView.RowValidating event.
e: A System.Windows.Forms.DataGridViewCellCancelEventArgs that contains the event data.
"""
pass
def OnScroll(self,*args):
"""
OnScroll(self: DataGridView,e: ScrollEventArgs)
Raises the System.Windows.Forms.DataGridView.Scroll event.
e: A System.Windows.Forms.ScrollEventArgs that contains the event data.
"""
pass
def OnSelectionChanged(self,*args):
"""
OnSelectionChanged(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.SelectionChanged event.
e: An System.EventArgs that contains information about the event.
"""
pass
def OnSizeChanged(self,*args):
"""
OnSizeChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.SizeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnSortCompare(self,*args):
"""
OnSortCompare(self: DataGridView,e: DataGridViewSortCompareEventArgs)
Raises the System.Windows.Forms.DataGridView.SortCompare event.
e: A System.Windows.Forms.DataGridViewSortCompareEventArgs that contains the event data.
"""
pass
def OnSorted(self,*args):
"""
OnSorted(self: DataGridView,e: EventArgs)
Raises the System.Windows.Forms.DataGridView.Sorted event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnStyleChanged(self,*args):
"""
OnStyleChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.StyleChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnSystemColorsChanged(self,*args):
"""
OnSystemColorsChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.SystemColorsChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnTabIndexChanged(self,*args):
"""
OnTabIndexChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.TabIndexChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnTabStopChanged(self,*args):
"""
OnTabStopChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.TabStopChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnTextChanged(self,*args):
"""
OnTextChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.TextChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnUserAddedRow(self,*args):
"""
OnUserAddedRow(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.UserAddedRow event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnUserDeletedRow(self,*args):
"""
OnUserDeletedRow(self: DataGridView,e: DataGridViewRowEventArgs)
Raises the System.Windows.Forms.DataGridView.UserDeletedRow event.
e: A System.Windows.Forms.DataGridViewRowEventArgs that contains the event data.
"""
pass
def OnUserDeletingRow(self,*args):
"""
OnUserDeletingRow(self: DataGridView,e: DataGridViewRowCancelEventArgs)
Raises the System.Windows.Forms.DataGridView.UserDeletingRow event.
e: A System.Windows.Forms.DataGridViewRowCancelEventArgs that contains the event data.
"""
pass
def OnValidated(self,*args):
"""
OnValidated(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.Validated event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnValidating(self,*args):
"""
OnValidating(self: DataGridView,e: CancelEventArgs)
Raises the System.Windows.Forms.Control.Validating event.
e: A System.ComponentModel.CancelEventArgs that contains the event data.
"""
pass
def OnVisibleChanged(self,*args):
"""
OnVisibleChanged(self: DataGridView,e: EventArgs)
e: An System.EventArgs that contains the event data.
"""
pass
def PaintBackground(self,*args):
"""
PaintBackground(self: DataGridView,graphics: Graphics,clipBounds: Rectangle,gridBounds: Rectangle)
Paints the background of the System.Windows.Forms.DataGridView.
graphics: The System.Drawing.Graphics used to paint the background.
clipBounds: A System.Drawing.Rectangle that represents the area of the System.Windows.Forms.DataGridView
that needs to be painted.
gridBounds: A System.Drawing.Rectangle that represents the area in which cells are drawn.
"""
pass
def ProcessAKey(self,*args):
"""
ProcessAKey(self: DataGridView,keyData: Keys) -> bool
Processes the A key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessCmdKey(self,*args):
"""
ProcessCmdKey(self: Control,msg: Message,keyData: Keys) -> (bool,Message)
Processes a command key.
msg: A System.Windows.Forms.Message,passed by reference,that represents the window message to
process.
keyData: One of the System.Windows.Forms.Keys values that represents the key to process.
Returns: true if the character was processed by the control; otherwise,false.
"""
pass
def ProcessDataGridViewKey(self,*args):
"""
ProcessDataGridViewKey(self: DataGridView,e: KeyEventArgs) -> bool
Processes keys used for navigating in the System.Windows.Forms.DataGridView.
e: Contains information about the key that was pressed.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessDeleteKey(self,*args):
"""
ProcessDeleteKey(self: DataGridView,keyData: Keys) -> bool
Processes the DELETE key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessDialogChar(self,*args):
"""
ProcessDialogChar(self: Control,charCode: Char) -> bool
Processes a dialog character.
charCode: The character to process.
Returns: true if the character was processed by the control; otherwise,false.
"""
pass
def ProcessDialogKey(self,*args):
"""
ProcessDialogKey(self: DataGridView,keyData: Keys) -> bool
Processes keys,such as the TAB,ESCAPE,ENTER,and ARROW keys,used to control dialog boxes.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessDownKey(self,*args):
"""
ProcessDownKey(self: DataGridView,keyData: Keys) -> bool
Processes the DOWN ARROW key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessEndKey(self,*args):
"""
ProcessEndKey(self: DataGridView,keyData: Keys) -> bool
Processes the END key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessEnterKey(self,*args):
"""
ProcessEnterKey(self: DataGridView,keyData: Keys) -> bool
Processes the ENTER key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessEscapeKey(self,*args):
"""
ProcessEscapeKey(self: DataGridView,keyData: Keys) -> bool
Processes the ESC key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessF2Key(self,*args):
"""
ProcessF2Key(self: DataGridView,keyData: Keys) -> bool
Processes the F2 key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessHomeKey(self,*args):
"""
ProcessHomeKey(self: DataGridView,keyData: Keys) -> bool
Processes the HOME key.
keyData: The key that was pressed.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessInsertKey(self,*args):
"""
ProcessInsertKey(self: DataGridView,keyData: Keys) -> bool
Processes the INSERT key.
keyData: One of the System.Windows.Forms.Keys values that represents the key to process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessKeyEventArgs(self,*args):
"""
ProcessKeyEventArgs(self: DataGridView,m: Message) -> (bool,Message)
Processes a key message and generates the appropriate control events.
m: A System.Windows.Forms.Message,passed by reference,that represents the window message to
process.
Returns: true if the message was processed; otherwise,false.
"""
pass
def ProcessKeyMessage(self,*args):
"""
ProcessKeyMessage(self: Control,m: Message) -> (bool,Message)
Processes a keyboard message.
m: A System.Windows.Forms.Message,passed by reference,that represents the window message to
process.
Returns: true if the message was processed by the control; otherwise,false.
"""
pass
def ProcessKeyPreview(self,*args):
"""
ProcessKeyPreview(self: DataGridView,m: Message) -> (bool,Message)
Previews a keyboard message.
m: A System.Windows.Forms.Message,passed by reference,that represents the window message to
process.
Returns: true if the message was processed; otherwise,false.
"""
pass
def ProcessLeftKey(self,*args):
"""
ProcessLeftKey(self: DataGridView,keyData: Keys) -> bool
Processes the LEFT ARROW key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessMnemonic(self,*args):
"""
ProcessMnemonic(self: Control,charCode: Char) -> bool
Processes a mnemonic character.
charCode: The character to process.
Returns: true if the character was processed as a mnemonic by the control; otherwise,false.
"""
pass
def ProcessNextKey(self,*args):
"""
ProcessNextKey(self: DataGridView,keyData: Keys) -> bool
Processes the PAGE DOWN key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessPriorKey(self,*args):
"""
ProcessPriorKey(self: DataGridView,keyData: Keys) -> bool
Processes the PAGE UP key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessRightKey(self,*args):
"""
ProcessRightKey(self: DataGridView,keyData: Keys) -> bool
Processes the RIGHT ARROW key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessSpaceKey(self,*args):
"""
ProcessSpaceKey(self: DataGridView,keyData: Keys) -> bool
Processes the SPACEBAR.
keyData: One of the System.Windows.Forms.Keys values that represents the key to process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessTabKey(self,*args):
"""
ProcessTabKey(self: DataGridView,keyData: Keys) -> bool
Processes the TAB key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessUpKey(self,*args):
"""
ProcessUpKey(self: DataGridView,keyData: Keys) -> bool
Processes the UP ARROW key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def ProcessZeroKey(self,*args):
"""
ProcessZeroKey(self: DataGridView,keyData: Keys) -> bool
Processes the 0 key.
keyData: A bitwise combination of System.Windows.Forms.Keys values that represents the key or keys to
process.
Returns: true if the key was processed; otherwise,false.
"""
pass
def RaiseDragEvent(self,*args):
"""
RaiseDragEvent(self: Control,key: object,e: DragEventArgs)
Raises the appropriate drag event.
key: The event to raise.
e: A System.Windows.Forms.DragEventArgs that contains the event data.
"""
pass
def RaiseKeyEvent(self,*args):
"""
RaiseKeyEvent(self: Control,key: object,e: KeyEventArgs)
Raises the appropriate key event.
key: The event to raise.
e: A System.Windows.Forms.KeyEventArgs that contains the event data.
"""
pass
def RaiseMouseEvent(self,*args):
"""
RaiseMouseEvent(self: Control,key: object,e: MouseEventArgs)
Raises the appropriate mouse event.
key: The event to raise.
e: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def RaisePaintEvent(self,*args):
"""
RaisePaintEvent(self: Control,key: object,e: PaintEventArgs)
Raises the appropriate paint event.
key: The event to raise.
e: A System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def RecreateHandle(self,*args):
"""
RecreateHandle(self: Control)
Forces the re-creation of the handle for the control.
"""
pass
def RefreshEdit(self):
"""
RefreshEdit(self: DataGridView) -> bool
Refreshes the value of the current cell with the underlying cell value when the cell is in edit
mode,discarding any previous value.
Returns: true if successful; false if a System.Windows.Forms.DataGridView.DataError event occurred.
"""
pass
def RescaleConstantsForDpi(self,*args):
""" RescaleConstantsForDpi(self: Control,deviceDpiOld: int,deviceDpiNew: int) """
pass
def ResetMouseEventArgs(self,*args):
"""
ResetMouseEventArgs(self: Control)
Resets the control to handle the System.Windows.Forms.Control.MouseLeave event.
"""
pass
def ResetText(self):
"""
ResetText(self: DataGridView)
Resets the System.Windows.Forms.DataGridView.Text property to its default value.
"""
pass
def RtlTranslateAlignment(self,*args):
"""
RtlTranslateAlignment(self: Control,align: ContentAlignment) -> ContentAlignment
Converts the specified System.Drawing.ContentAlignment to the appropriate
System.Drawing.ContentAlignment to support right-to-left text.
align: One of the System.Drawing.ContentAlignment values.
Returns: One of the System.Drawing.ContentAlignment values.
RtlTranslateAlignment(self: Control,align: LeftRightAlignment) -> LeftRightAlignment
Converts the specified System.Windows.Forms.LeftRightAlignment to the appropriate
System.Windows.Forms.LeftRightAlignment to support right-to-left text.
align: One of the System.Windows.Forms.LeftRightAlignment values.
Returns: One of the System.Windows.Forms.LeftRightAlignment values.
RtlTranslateAlignment(self: Control,align: HorizontalAlignment) -> HorizontalAlignment
Converts the specified System.Windows.Forms.HorizontalAlignment to the appropriate
System.Windows.Forms.HorizontalAlignment to support right-to-left text.
align: One of the System.Windows.Forms.HorizontalAlignment values.
Returns: One of the System.Windows.Forms.HorizontalAlignment values.
"""
pass
def RtlTranslateContent(self,*args):
"""
RtlTranslateContent(self: Control,align: ContentAlignment) -> ContentAlignment
Converts the specified System.Drawing.ContentAlignment to the appropriate
System.Drawing.ContentAlignment to support right-to-left text.
align: One of the System.Drawing.ContentAlignment values.
Returns: One of the System.Drawing.ContentAlignment values.
"""
pass
def RtlTranslateHorizontal(self,*args):
"""
RtlTranslateHorizontal(self: Control,align: HorizontalAlignment) -> HorizontalAlignment
Converts the specified System.Windows.Forms.HorizontalAlignment to the appropriate
System.Windows.Forms.HorizontalAlignment to support right-to-left text.
align: One of the System.Windows.Forms.HorizontalAlignment values.
Returns: One of the System.Windows.Forms.HorizontalAlignment values.
"""
pass
def RtlTranslateLeftRight(self,*args):
"""
RtlTranslateLeftRight(self: Control,align: LeftRightAlignment) -> LeftRightAlignment
Converts the specified System.Windows.Forms.LeftRightAlignment to the appropriate
System.Windows.Forms.LeftRightAlignment to support right-to-left text.
align: One of the System.Windows.Forms.LeftRightAlignment values.
Returns: One of the System.Windows.Forms.LeftRightAlignment values.
"""
pass
def ScaleControl(self,*args):
"""
ScaleControl(self: Control,factor: SizeF,specified: BoundsSpecified)
Scales a control's location,size,padding and margin.
factor: The factor by which the height and width of the control will be scaled.
specified: A System.Windows.Forms.BoundsSpecified value that specifies the bounds of the control to use
when defining its size and position.
"""
pass
def ScaleCore(self,*args):
"""
ScaleCore(self: Control,dx: Single,dy: Single)
This method is not relevant for this class.
dx: The horizontal scaling factor.
dy: The vertical scaling factor.
"""
pass
def Select(self):
"""
Select(self: Control,directed: bool,forward: bool)
Activates a child control. Optionally specifies the direction in the tab order to select the
control from.
directed: true to specify the direction of the control to select; otherwise,false.
forward: true to move forward in the tab order; false to move backward in the tab order.
"""
pass
def SelectAll(self):
"""
SelectAll(self: DataGridView)
Selects all the cells in the System.Windows.Forms.DataGridView.
"""
pass
def SetAutoSizeMode(self,*args):
"""
SetAutoSizeMode(self: Control,mode: AutoSizeMode)
Sets a value indicating how a control will behave when its System.Windows.Forms.Control.AutoSize
property is enabled.
mode: One of the System.Windows.Forms.AutoSizeMode values.
"""
pass
def SetBoundsCore(self,*args):
"""
SetBoundsCore(self: DataGridView,x: int,y: int,width: int,height: int,specified: BoundsSpecified)
This member overrides
System.Windows.Forms.Control.SetBoundsCore(System.Int32,System.Int32,System.Int32,System.Int32,Sy
stem.Windows.Forms.BoundsSpecified).
x: The new System.Windows.Forms.Control.Left property value of the control.
y: The new System.Windows.Forms.Control.Top property value of the control.
width: The new System.Windows.Forms.Control.Width property value of the control.
height: The new System.Windows.Forms.Control.Height property value of the control.
specified: A bitwise combination of the System.Windows.Forms.BoundsSpecified values.
"""
pass
def SetClientSizeCore(self,*args):
"""
SetClientSizeCore(self: Control,x: int,y: int)
Sets the size of the client area of the control.
x: The client area width,in pixels.
y: The client area height,in pixels.
"""
pass
def SetCurrentCellAddressCore(self,*args):
"""
SetCurrentCellAddressCore(self: DataGridView,columnIndex: int,rowIndex: int,setAnchorCellAddress: bool,validateCurrentCell: bool,throughMouseClick: bool) -> bool
Sets the currently active cell.
columnIndex: The index of the column containing the cell.
rowIndex: The index of the row containing the cell.
setAnchorCellAddress: true to make the new current cell the anchor cell for a subsequent multicell selection using the
SHIFT key; otherwise,false.
validateCurrentCell: true to validate the value in the old current cell and cancel the change if validation fails;
otherwise,false.
throughMouseClick: true if the current cell is being set as a result of a mouse click; otherwise,false.
Returns: true if the current cell was successfully set; otherwise,false.
"""
pass
def SetSelectedCellCore(self,*args):
"""
SetSelectedCellCore(self: DataGridView,columnIndex: int,rowIndex: int,selected: bool)
Changes the selection state of the cell with the specified row and column indexes.
columnIndex: The index of the column containing the cell.
rowIndex: The index of the row containing the cell.
selected: true to select the cell; false to cancel the selection of the cell.
"""
pass
def SetSelectedColumnCore(self,*args):
"""
SetSelectedColumnCore(self: DataGridView,columnIndex: int,selected: bool)
Changes the selection state of the column with the specified index.
columnIndex: The index of the column.
selected: true to select the column; false to cancel the selection of the column.
"""
pass
def SetSelectedRowCore(self,*args):
"""
SetSelectedRowCore(self: DataGridView,rowIndex: int,selected: bool)
Changes the selection state of the row with the specified index.
rowIndex: The index of the row.
selected: true to select the row; false to cancel the selection of the row.
"""
pass
def SetStyle(self,*args):
"""
SetStyle(self: Control,flag: ControlStyles,value: bool)
Sets a specified System.Windows.Forms.ControlStyles flag to either true or false.
flag: The System.Windows.Forms.ControlStyles bit to set.
value: true to apply the specified style to the control; otherwise,false.
"""
pass
def SetTopLevel(self,*args):
"""
SetTopLevel(self: Control,value: bool)
Sets the control as the top-level control.
value: true to set the control as the top-level control; otherwise,false.
"""
pass
def SetVisibleCore(self,*args):
"""
SetVisibleCore(self: Control,value: bool)
Sets the control to the specified visible state.
value: true to make the control visible; otherwise,false.
"""
pass
def SizeFromClientSize(self,*args):
"""
SizeFromClientSize(self: Control,clientSize: Size) -> Size
Determines the size of the entire control from the height and width of its client area.
clientSize: A System.Drawing.Size value representing the height and width of the control's client area.
Returns: A System.Drawing.Size value representing the height and width of the entire control.
"""
pass
def Sort(self,*__args):
"""
Sort(self: DataGridView,comparer: IComparer)
Sorts the contents of the System.Windows.Forms.DataGridView control using an implementation of
the System.Collections.IComparer interface.
comparer: An implementation of System.Collections.IComparer that performs the custom sorting operation.
Sort(self: DataGridView,dataGridViewColumn: DataGridViewColumn,direction: ListSortDirection)
Sorts the contents of the System.Windows.Forms.DataGridView control in ascending or descending
order based on the contents of the specified column.
dataGridViewColumn: The column by which to sort the contents of the System.Windows.Forms.DataGridView.
direction: One of the System.ComponentModel.ListSortDirection values.
"""
pass
def UpdateBounds(self,*args):
"""
UpdateBounds(self: Control,x: int,y: int,width: int,height: int,clientWidth: int,clientHeight: int)
Updates the bounds of the control with the specified size,location,and client size.
x: The System.Drawing.Point.X coordinate of the control.
y: The System.Drawing.Point.Y coordinate of the control.
width: The System.Drawing.Size.Width of the control.
height: The System.Drawing.Size.Height of the control.
clientWidth: The client System.Drawing.Size.Width of the control.
clientHeight: The client System.Drawing.Size.Height of the control.
UpdateBounds(self: Control,x: int,y: int,width: int,height: int)
Updates the bounds of the control with the specified size and location.
x: The System.Drawing.Point.X coordinate of the control.
y: The System.Drawing.Point.Y coordinate of the control.
width: The System.Drawing.Size.Width of the control.
height: The System.Drawing.Size.Height of the control.
UpdateBounds(self: Control)
Updates the bounds of the control with the current size and location.
"""
pass
def UpdateCellErrorText(self,columnIndex,rowIndex):
"""
UpdateCellErrorText(self: DataGridView,columnIndex: int,rowIndex: int)
Forces the cell at the specified location to update its error text.
columnIndex: The column index of the cell to update,or -1 to indicate a row header cell.
rowIndex: The row index of the cell to update,or -1 to indicate a column header cell.
"""
pass
def UpdateCellValue(self,columnIndex,rowIndex):
"""
UpdateCellValue(self: DataGridView,columnIndex: int,rowIndex: int)
Forces the control to update its display of the cell at the specified location based on its new
value,applying any automatic sizing modes currently in effect.
columnIndex: The zero-based column index of the cell with the new value.
rowIndex: The zero-based row index of the cell with the new value.
"""
pass
def UpdateRowErrorText(self,*__args):
"""
UpdateRowErrorText(self: DataGridView,rowIndexStart: int,rowIndexEnd: int)
Forces the rows in the given range to update their error text.
rowIndexStart: The zero-based index of the first row in the set of rows to update.
rowIndexEnd: The zero-based index of the last row in the set of rows to update.
UpdateRowErrorText(self: DataGridView,rowIndex: int)
Forces the row at the given row index to update its error text.
rowIndex: The zero-based index of the row to update.
"""
pass
def UpdateRowHeightInfo(self,rowIndex,updateToEnd):
"""
UpdateRowHeightInfo(self: DataGridView,rowIndex: int,updateToEnd: bool)
Forces the specified row or rows to update their height information.
rowIndex: The zero-based index of the first row to update.
updateToEnd: true to update the specified row and all subsequent rows.
"""
pass
def UpdateStyles(self,*args):
"""
UpdateStyles(self: Control)
Forces the assigned styles to be reapplied to the control.
"""
pass
def UpdateZOrder(self,*args):
"""
UpdateZOrder(self: Control)
Updates the control in its parent's z-order.
"""
pass
def WndProc(self,*args):
"""
WndProc(self: DataGridView,m: Message) -> Message
Processes window messages.
m: A System.Windows.Forms.Message,passed by reference,that represents the window message to
process.
"""
pass
def __enter__(self,*args):
"""
__enter__(self: IDisposable) -> object
Provides the implementation of __enter__ for objects which implement IDisposable.
"""
pass
def __exit__(self,*args):
"""
__exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)
Provides the implementation of __exit__ for objects which implement IDisposable.
"""
pass
def __getitem__(self,*args):
""" x.__getitem__(y) <==> x[y]x.__getitem__(y) <==> x[y] """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __setitem__(self,*args):
""" x.__setitem__(i,y) <==> x[i]=x.__setitem__(i,y) <==> x[i]= """
pass
def __str__(self,*args):
pass
AdjustedTopLeftHeaderBorderStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the border style for the upper-left cell in the System.Windows.Forms.DataGridView.
Get: AdjustedTopLeftHeaderBorderStyle(self: DataGridView) -> DataGridViewAdvancedBorderStyle
"""
AdvancedCellBorderStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the border style of the cells in the System.Windows.Forms.DataGridView.
Get: AdvancedCellBorderStyle(self: DataGridView) -> DataGridViewAdvancedBorderStyle
"""
AdvancedColumnHeadersBorderStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the border style of the column header cells in the System.Windows.Forms.DataGridView.
Get: AdvancedColumnHeadersBorderStyle(self: DataGridView) -> DataGridViewAdvancedBorderStyle
"""
AdvancedRowHeadersBorderStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the border style of the row header cells in the System.Windows.Forms.DataGridView.
Get: AdvancedRowHeadersBorderStyle(self: DataGridView) -> DataGridViewAdvancedBorderStyle
"""
AllowUserToAddRows=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the option to add rows is displayed to the user.
Get: AllowUserToAddRows(self: DataGridView) -> bool
Set: AllowUserToAddRows(self: DataGridView)=value
"""
AllowUserToDeleteRows=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the user is allowed to delete rows from the System.Windows.Forms.DataGridView.
Get: AllowUserToDeleteRows(self: DataGridView) -> bool
Set: AllowUserToDeleteRows(self: DataGridView)=value
"""
AllowUserToOrderColumns=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether manual column repositioning is enabled.
Get: AllowUserToOrderColumns(self: DataGridView) -> bool
Set: AllowUserToOrderColumns(self: DataGridView)=value
"""
AllowUserToResizeColumns=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether users can resize columns.
Get: AllowUserToResizeColumns(self: DataGridView) -> bool
Set: AllowUserToResizeColumns(self: DataGridView)=value
"""
AllowUserToResizeRows=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether users can resize rows.
Get: AllowUserToResizeRows(self: DataGridView) -> bool
Set: AllowUserToResizeRows(self: DataGridView)=value
"""
AlternatingRowsDefaultCellStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the default cell style applied to odd-numbered rows of the System.Windows.Forms.DataGridView.
Get: AlternatingRowsDefaultCellStyle(self: DataGridView) -> DataGridViewCellStyle
Set: AlternatingRowsDefaultCellStyle(self: DataGridView)=value
"""
AutoGenerateColumns=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether columns are created automatically when the System.Windows.Forms.DataGridView.DataSource or System.Windows.Forms.DataGridView.DataMember properties are set.
Get: AutoGenerateColumns(self: DataGridView) -> bool
Set: AutoGenerateColumns(self: DataGridView)=value
"""
AutoSize=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: AutoSize(self: DataGridView) -> bool
Set: AutoSize(self: DataGridView)=value
"""
AutoSizeColumnsMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating how column widths are determined.
Get: AutoSizeColumnsMode(self: DataGridView) -> DataGridViewAutoSizeColumnsMode
Set: AutoSizeColumnsMode(self: DataGridView)=value
"""
AutoSizeRowsMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating how row heights are determined.
Get: AutoSizeRowsMode(self: DataGridView) -> DataGridViewAutoSizeRowsMode
Set: AutoSizeRowsMode(self: DataGridView)=value
"""
BackColor=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the background color for the control.
Get: BackColor(self: DataGridView) -> Color
Set: BackColor(self: DataGridView)=value
"""
BackgroundColor=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the background color of the System.Windows.Forms.DataGridView.
Get: BackgroundColor(self: DataGridView) -> Color
Set: BackgroundColor(self: DataGridView)=value
"""
BackgroundImage=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the background image displayed in the control.
Get: BackgroundImage(self: DataGridView) -> Image
Set: BackgroundImage(self: DataGridView)=value
"""
BackgroundImageLayout=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the background image layout as defined in the System.Windows.Forms.ImageLayout enumeration.
Get: BackgroundImageLayout(self: DataGridView) -> ImageLayout
Set: BackgroundImageLayout(self: DataGridView)=value
"""
BorderStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the border style for the System.Windows.Forms.DataGridView.
Get: BorderStyle(self: DataGridView) -> BorderStyle
Set: BorderStyle(self: DataGridView)=value
"""
CanEnableIme=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the System.Windows.Forms.Control.ImeMode property can be set to an active value,to enable IME support.
"""
CanRaiseEvents=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Determines if events can be raised on the control.
"""
CellBorderStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the cell border style for the System.Windows.Forms.DataGridView.
Get: CellBorderStyle(self: DataGridView) -> DataGridViewCellBorderStyle
Set: CellBorderStyle(self: DataGridView)=value
"""
ClipboardCopyMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value that indicates whether users can copy cell text values to the System.Windows.Forms.Clipboard and whether row and column header text is included.
Get: ClipboardCopyMode(self: DataGridView) -> DataGridViewClipboardCopyMode
Set: ClipboardCopyMode(self: DataGridView)=value
"""
ColumnCount=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the number of columns displayed in the System.Windows.Forms.DataGridView.
Get: ColumnCount(self: DataGridView) -> int
Set: ColumnCount(self: DataGridView)=value
"""
ColumnHeadersBorderStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the border style applied to the column headers.
Get: ColumnHeadersBorderStyle(self: DataGridView) -> DataGridViewHeaderBorderStyle
Set: ColumnHeadersBorderStyle(self: DataGridView)=value
"""
ColumnHeadersDefaultCellStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the default column header style.
Get: ColumnHeadersDefaultCellStyle(self: DataGridView) -> DataGridViewCellStyle
Set: ColumnHeadersDefaultCellStyle(self: DataGridView)=value
"""
ColumnHeadersHeight=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the height,in pixels,of the column headers row
Get: ColumnHeadersHeight(self: DataGridView) -> int
Set: ColumnHeadersHeight(self: DataGridView)=value
"""
ColumnHeadersHeightSizeMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the height of the column headers is adjustable and whether it can be adjusted by the user or is automatically adjusted to fit the contents of the headers.
Get: ColumnHeadersHeightSizeMode(self: DataGridView) -> DataGridViewColumnHeadersHeightSizeMode
Set: ColumnHeadersHeightSizeMode(self: DataGridView)=value
"""
ColumnHeadersVisible=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the column header row is displayed.
Get: ColumnHeadersVisible(self: DataGridView) -> bool
Set: ColumnHeadersVisible(self: DataGridView)=value
"""
Columns=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a collection that contains all the columns in the control.
Get: Columns(self: DataGridView) -> DataGridViewColumnCollection
"""
CreateParams=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the required creation parameters when the control handle is created.
"""
CurrentCell=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the currently active cell.
Get: CurrentCell(self: DataGridView) -> DataGridViewCell
Set: CurrentCell(self: DataGridView)=value
"""
CurrentCellAddress=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the row and column indexes of the currently active cell.
Get: CurrentCellAddress(self: DataGridView) -> Point
"""
CurrentRow=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the row containing the current cell.
Get: CurrentRow(self: DataGridView) -> DataGridViewRow
"""
DataMember=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the name of the list or table in the data source for which the System.Windows.Forms.DataGridView is displaying data.
Get: DataMember(self: DataGridView) -> str
Set: DataMember(self: DataGridView)=value
"""
DataSource=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the data source that the System.Windows.Forms.DataGridView is displaying data for.
Get: DataSource(self: DataGridView) -> object
Set: DataSource(self: DataGridView)=value
"""
DefaultCellStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the default cell style to be applied to the cells in the System.Windows.Forms.DataGridView if no other cell style properties are set.
Get: DefaultCellStyle(self: DataGridView) -> DataGridViewCellStyle
Set: DefaultCellStyle(self: DataGridView)=value
"""
DefaultCursor=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the default cursor for the control.
"""
DefaultImeMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the default Input Method Editor (IME) mode supported by the control.
"""
DefaultMargin=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the space,in pixels,that is specified by default between controls.
"""
DefaultMaximumSize=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the length and height,in pixels,that is specified as the default maximum size of a control.
"""
DefaultMinimumSize=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the length and height,in pixels,that is specified as the default minimum size of a control.
"""
DefaultPadding=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the internal spacing,in pixels,of the contents of a control.
"""
DefaultSize=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the default initial size of the control.
"""
DesignMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value that indicates whether the System.ComponentModel.Component is currently in design mode.
"""
DisplayRectangle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the rectangle that represents the display area of the control.
Get: DisplayRectangle(self: DataGridView) -> Rectangle
"""
DoubleBuffered=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether this control should redraw its surface using a secondary buffer to reduce or prevent flicker.
"""
EditingControl=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the control hosted by the current cell,if a cell with an editing control is in edit mode.
Get: EditingControl(self: DataGridView) -> Control
"""
EditingPanel=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the panel that contains the System.Windows.Forms.DataGridView.EditingControl.
Get: EditingPanel(self: DataGridView) -> Panel
"""
EditMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating how to begin editing a cell.
Get: EditMode(self: DataGridView) -> DataGridViewEditMode
Set: EditMode(self: DataGridView)=value
"""
EnableHeadersVisualStyles=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether row and column headers use the visual styles of the user's current theme if visual styles are enabled for the application.
Get: EnableHeadersVisualStyles(self: DataGridView) -> bool
Set: EnableHeadersVisualStyles(self: DataGridView)=value
"""
Events=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the list of event handlers that are attached to this System.ComponentModel.Component.
"""
FirstDisplayedCell=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the first cell currently displayed in the System.Windows.Forms.DataGridView; typically,this cell is in the upper left corner.
Get: FirstDisplayedCell(self: DataGridView) -> DataGridViewCell
Set: FirstDisplayedCell(self: DataGridView)=value
"""
FirstDisplayedScrollingColumnHiddenWidth=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the width of the portion of the column that is currently scrolled out of view..
Get: FirstDisplayedScrollingColumnHiddenWidth(self: DataGridView) -> int
"""
FirstDisplayedScrollingColumnIndex=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the index of the column that is the first column displayed on the System.Windows.Forms.DataGridView.
Get: FirstDisplayedScrollingColumnIndex(self: DataGridView) -> int
Set: FirstDisplayedScrollingColumnIndex(self: DataGridView)=value
"""
FirstDisplayedScrollingRowIndex=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the index of the row that is the first row displayed on the System.Windows.Forms.DataGridView.
Get: FirstDisplayedScrollingRowIndex(self: DataGridView) -> int
Set: FirstDisplayedScrollingRowIndex(self: DataGridView)=value
"""
Font=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the font of the text displayed by the System.Windows.Forms.DataGridView.
Get: Font(self: DataGridView) -> Font
Set: Font(self: DataGridView)=value
"""
FontHeight=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the height of the font of the control.
"""
ForeColor=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the foreground color of the System.Windows.Forms.DataGridView.
Get: ForeColor(self: DataGridView) -> Color
Set: ForeColor(self: DataGridView)=value
"""
GridColor=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the color of the grid lines separating the cells of the System.Windows.Forms.DataGridView.
Get: GridColor(self: DataGridView) -> Color
Set: GridColor(self: DataGridView)=value
"""
HorizontalScrollBar=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the horizontal scroll bar of the control.
"""
HorizontalScrollingOffset=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the number of pixels by which the control is scrolled horizontally.
Get: HorizontalScrollingOffset(self: DataGridView) -> int
Set: HorizontalScrollingOffset(self: DataGridView)=value
"""
ImeModeBase=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the IME mode of a control.
"""
IsCurrentCellDirty=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the current cell has uncommitted changes.
Get: IsCurrentCellDirty(self: DataGridView) -> bool
"""
IsCurrentCellInEditMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the currently active cell is being edited.
Get: IsCurrentCellInEditMode(self: DataGridView) -> bool
"""
IsCurrentRowDirty=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the current row has uncommitted changes.
Get: IsCurrentRowDirty(self: DataGridView) -> bool
"""
MultiSelect=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the user is allowed to select more than one cell,row,or column of the System.Windows.Forms.DataGridView at a time.
Get: MultiSelect(self: DataGridView) -> bool
Set: MultiSelect(self: DataGridView)=value
"""
NewRowIndex=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the index of the row for new records.
Get: NewRowIndex(self: DataGridView) -> int
"""
Padding=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""This property is not relevant for this control.
Get: Padding(self: DataGridView) -> Padding
Set: Padding(self: DataGridView)=value
"""
ReadOnly=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the user can edit the cells of the System.Windows.Forms.DataGridView control.
Get: ReadOnly(self: DataGridView) -> bool
Set: ReadOnly(self: DataGridView)=value
"""
RenderRightToLeft=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""This property is now obsolete.
"""
ResizeRedraw=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the control redraws itself when resized.
"""
RowCount=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the number of rows displayed in the System.Windows.Forms.DataGridView.
Get: RowCount(self: DataGridView) -> int
Set: RowCount(self: DataGridView)=value
"""
RowHeadersBorderStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the border style of the row header cells.
Get: RowHeadersBorderStyle(self: DataGridView) -> DataGridViewHeaderBorderStyle
Set: RowHeadersBorderStyle(self: DataGridView)=value
"""
RowHeadersDefaultCellStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the default style applied to the row header cells.
Get: RowHeadersDefaultCellStyle(self: DataGridView) -> DataGridViewCellStyle
Set: RowHeadersDefaultCellStyle(self: DataGridView)=value
"""
RowHeadersVisible=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the column that contains row headers is displayed.
Get: RowHeadersVisible(self: DataGridView) -> bool
Set: RowHeadersVisible(self: DataGridView)=value
"""
RowHeadersWidth=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the width,in pixels,of the column that contains the row headers.
Get: RowHeadersWidth(self: DataGridView) -> int
Set: RowHeadersWidth(self: DataGridView)=value
"""
RowHeadersWidthSizeMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the width of the row headers is adjustable and whether it can be adjusted by the user or is automatically adjusted to fit the contents of the headers.
Get: RowHeadersWidthSizeMode(self: DataGridView) -> DataGridViewRowHeadersWidthSizeMode
Set: RowHeadersWidthSizeMode(self: DataGridView)=value
"""
Rows=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a collection that contains all the rows in the System.Windows.Forms.DataGridView control.
Get: Rows(self: DataGridView) -> DataGridViewRowCollection
"""
RowsDefaultCellStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the default style applied to the row cells of the System.Windows.Forms.DataGridView.
Get: RowsDefaultCellStyle(self: DataGridView) -> DataGridViewCellStyle
Set: RowsDefaultCellStyle(self: DataGridView)=value
"""
RowTemplate=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the row that represents the template for all the rows in the control.
Get: RowTemplate(self: DataGridView) -> DataGridViewRow
Set: RowTemplate(self: DataGridView)=value
"""
ScaleChildren=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value that determines the scaling of child controls.
"""
ScrollBars=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the type of scroll bars to display for the System.Windows.Forms.DataGridView control.
Get: ScrollBars(self: DataGridView) -> ScrollBars
Set: ScrollBars(self: DataGridView)=value
"""
SelectedCells=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the collection of cells selected by the user.
Get: SelectedCells(self: DataGridView) -> DataGridViewSelectedCellCollection
"""
SelectedColumns=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the collection of columns selected by the user.
Get: SelectedColumns(self: DataGridView) -> DataGridViewSelectedColumnCollection
"""
SelectedRows=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the collection of rows selected by the user.
Get: SelectedRows(self: DataGridView) -> DataGridViewSelectedRowCollection
"""
SelectionMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating how the cells of the System.Windows.Forms.DataGridView can be selected.
Get: SelectionMode(self: DataGridView) -> DataGridViewSelectionMode
Set: SelectionMode(self: DataGridView)=value
"""
ShowCellErrors=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether to show cell errors.
Get: ShowCellErrors(self: DataGridView) -> bool
Set: ShowCellErrors(self: DataGridView)=value
"""
ShowCellToolTips=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether or not ToolTips will show when the mouse pointer pauses on a cell.
Get: ShowCellToolTips(self: DataGridView) -> bool
Set: ShowCellToolTips(self: DataGridView)=value
"""
ShowEditingIcon=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether or not the editing glyph is visible in the row header of the cell being edited.
Get: ShowEditingIcon(self: DataGridView) -> bool
Set: ShowEditingIcon(self: DataGridView)=value
"""
ShowFocusCues=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the control should display focus rectangles.
"""
ShowKeyboardCues=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the user interface is in the appropriate state to show or hide keyboard accelerators.
"""
ShowRowErrors=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether row headers will display error glyphs for each row that contains a data entry error.
Get: ShowRowErrors(self: DataGridView) -> bool
Set: ShowRowErrors(self: DataGridView)=value
"""
SortedColumn=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the column by which the System.Windows.Forms.DataGridView contents are currently sorted.
Get: SortedColumn(self: DataGridView) -> DataGridViewColumn
"""
SortOrder=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the items in the System.Windows.Forms.DataGridView control are sorted in ascending or descending order,or are not sorted.
Get: SortOrder(self: DataGridView) -> SortOrder
"""
StandardTab=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the TAB key moves the focus to the next control in the tab order rather than moving focus to the next cell in the control.
Get: StandardTab(self: DataGridView) -> bool
Set: StandardTab(self: DataGridView)=value
"""
Text=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the text associated with the control.
Get: Text(self: DataGridView) -> str
Set: Text(self: DataGridView)=value
"""
TopLeftHeaderCell=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the header cell located in the upper left corner of the System.Windows.Forms.DataGridView control.
Get: TopLeftHeaderCell(self: DataGridView) -> DataGridViewHeaderCell
Set: TopLeftHeaderCell(self: DataGridView)=value
"""
UserSetCursor=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the default or user-specified value of the System.Windows.Forms.Control.Cursor property.
Get: UserSetCursor(self: DataGridView) -> Cursor
"""
VerticalScrollBar=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the vertical scroll bar of the control.
"""
VerticalScrollingOffset=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the number of pixels by which the control is scrolled vertically.
Get: VerticalScrollingOffset(self: DataGridView) -> int
"""
VirtualMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether you have provided your own data-management operations for the System.Windows.Forms.DataGridView control.
Get: VirtualMode(self: DataGridView) -> bool
Set: VirtualMode(self: DataGridView)=value
"""
AllowUserToAddRowsChanged=None
AllowUserToDeleteRowsChanged=None
AllowUserToOrderColumnsChanged=None
AllowUserToResizeColumnsChanged=None
AllowUserToResizeRowsChanged=None
AlternatingRowsDefaultCellStyleChanged=None
AutoGenerateColumnsChanged=None
AutoSizeColumnModeChanged=None
AutoSizeColumnsModeChanged=None
AutoSizeRowsModeChanged=None
BackColorChanged=None
BackgroundColorChanged=None
BackgroundImageChanged=None
BackgroundImageLayoutChanged=None
BorderStyleChanged=None
CancelRowEdit=None
CellBeginEdit=None
CellBorderStyleChanged=None
CellClick=None
CellContentClick=None
CellContentDoubleClick=None
CellContextMenuStripChanged=None
CellContextMenuStripNeeded=None
CellDoubleClick=None
CellEndEdit=None
CellEnter=None
CellErrorTextChanged=None
CellErrorTextNeeded=None
CellFormatting=None
CellLeave=None
CellMouseClick=None
CellMouseDoubleClick=None
CellMouseDown=None
CellMouseEnter=None
CellMouseLeave=None
CellMouseMove=None
CellMouseUp=None
CellPainting=None
CellParsing=None
CellStateChanged=None
CellStyleChanged=None
CellStyleContentChanged=None
CellToolTipTextChanged=None
CellToolTipTextNeeded=None
CellValidated=None
CellValidating=None
CellValueChanged=None
CellValueNeeded=None
CellValuePushed=None
ColumnAdded=None
ColumnContextMenuStripChanged=None
ColumnDataPropertyNameChanged=None
ColumnDefaultCellStyleChanged=None
ColumnDisplayIndexChanged=None
ColumnDividerDoubleClick=None
ColumnDividerWidthChanged=None
ColumnHeaderCellChanged=None
ColumnHeaderMouseClick=None
ColumnHeaderMouseDoubleClick=None
ColumnHeadersBorderStyleChanged=None
ColumnHeadersDefaultCellStyleChanged=None
ColumnHeadersHeightChanged=None
ColumnHeadersHeightSizeModeChanged=None
ColumnMinimumWidthChanged=None
ColumnNameChanged=None
ColumnRemoved=None
ColumnSortModeChanged=None
ColumnStateChanged=None
ColumnToolTipTextChanged=None
ColumnWidthChanged=None
CurrentCellChanged=None
CurrentCellDirtyStateChanged=None
DataBindingComplete=None
DataError=None
DataGridViewAccessibleObject=None
DataGridViewControlCollection=None
DataGridViewTopRowAccessibleObject=None
DataMemberChanged=None
DataSourceChanged=None
DefaultCellStyleChanged=None
DefaultValuesNeeded=None
EditingControlShowing=None
EditModeChanged=None
FontChanged=None
ForeColorChanged=None
GridColorChanged=None
HitTestInfo=None
MultiSelectChanged=None
NewRowNeeded=None
PaddingChanged=None
ReadOnlyChanged=None
RowContextMenuStripChanged=None
RowContextMenuStripNeeded=None
RowDefaultCellStyleChanged=None
RowDirtyStateNeeded=None
RowDividerDoubleClick=None
RowDividerHeightChanged=None
RowEnter=None
RowErrorTextChanged=None
RowErrorTextNeeded=None
RowHeaderCellChanged=None
RowHeaderMouseClick=None
RowHeaderMouseDoubleClick=None
RowHeadersBorderStyleChanged=None
RowHeadersDefaultCellStyleChanged=None
RowHeadersWidthChanged=None
RowHeadersWidthSizeModeChanged=None
RowHeightChanged=None
RowHeightInfoNeeded=None
RowHeightInfoPushed=None
RowLeave=None
RowMinimumHeightChanged=None
RowPostPaint=None
RowPrePaint=None
RowsAdded=None
RowsDefaultCellStyleChanged=None
RowsRemoved=None
RowStateChanged=None
RowUnshared=None
RowValidated=None
RowValidating=None
Scroll=None
SelectionChanged=None
SortCompare=None
Sorted=None
StyleChanged=None
TextChanged=None
UserAddedRow=None
UserDeletedRow=None
UserDeletingRow=None
|
bitshares/aio/wallet.py | silverchen0402/python-bitshares | 102 | 11088271 | # -*- coding: utf-8 -*-
from bitsharesbase.account import PrivateKey
from graphenecommon.aio.wallet import Wallet as GrapheneWallet
from ..instance import BlockchainInstance
# Uses synchronous BlockchainInstance because it's __init__ is synchronous.
# Other methods will use async Instance.
@BlockchainInstance.inject
class Wallet(GrapheneWallet):
def define_classes(self):
# identical to those in bitshares.py!
self.default_key_store_app_name = "bitshares"
self.privatekey_class = PrivateKey
|
setup.py | Tonow/cookiecutter | 7,210 | 11088272 | #! /usr/bin/env python3
"""cookiecutter distutils configuration.
The presence of this file ensures the support
of pip editable mode *with setuptools only*.
"""
import setuptools
# https://github.com/jazzband/pip-tools/issues/1278
setuptools.setup(
use_scm_version={"local_scheme": "no-local-version"},
setup_requires=["setuptools_scm[toml]>=3.5.0"],
)
|
knover/models/nsp_model.py | youth123/Knover | 1,373 | 11088273 | <reponame>youth123/Knover
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""NSP model."""
import paddle.fluid as fluid
import paddle.fluid.layers as layers
from knover.core.model import Model
from knover.models import register_model
from knover.models.unified_transformer import UnifiedTransformer
from knover.utils import str2bool
@register_model("NSPModel")
class NSPModel(UnifiedTransformer):
"""NSP model."""
@classmethod
def add_cmdline_args(cls, parser):
"""Add cmdline arguments."""
group = UnifiedTransformer.add_cmdline_args(parser)
group.add_argument("--use_mlm", type=str2bool, default=True,
help="Whether to train NSP model with MLM loss.")
return group
def __init__(self, args, place):
self.use_mlm = args.use_mlm
super(NSPModel, self).__init__(args, place)
def _get_feed_dict(self, is_infer=False):
"""Get model's input feed dict.
Args:
is_infer: If true, get inference input feed dict, otherwise get training / evaluation input feed dict.
Returns:
feed_dict: A feed dict mapping keys to feed input variable.
"""
feed_dict = {}
feed_dict["token_ids"] = layers.data(name="token_ids", shape=[-1, self.max_seq_len, 1], dtype="int64")
feed_dict["type_ids"] = layers.data(name="type_ids", shape=[-1, self.max_seq_len, 1], dtype="int64")
feed_dict["pos_ids"] = layers.data(name="pos_ids", shape=[-1, self.max_seq_len, 1], dtype="int64")
if self.use_role:
feed_dict["role_ids"] = layers.data(name="role_ids", shape=[-1, self.max_seq_len, 1], dtype="int64")
feed_dict["attention_mask"] = layers.data(
name="attention_mask", shape=[-1, self.max_seq_len, self.max_seq_len], dtype=self.dtype)
feed_dict["label_idx"] = layers.data(name="label_idx", shape=[-1, 2], dtype="int64")
if not is_infer:
feed_dict["label"] = layers.data(name="label", shape=[-1, 1], dtype="int64")
feed_dict["tgt_label"] = layers.data(name="tgt_label", shape=[-1, 1], dtype="int64")
feed_dict["tgt_idx"] = layers.data(name="tgt_idx", shape=[-1, 2], dtype="int64")
else:
feed_dict["data_id"] = layers.data(name="data_id", shape=[-1, 1], dtype="int64")
return feed_dict
def forward(self, inputs, is_infer=False):
"""Run model main forward."""
outputs = {}
self.generation_caches = None
outputs["enc_out"], outputs["checkpoints"] = self._generation_network(
token_ids=inputs["token_ids"],
type_ids=inputs["type_ids"],
pos_ids=inputs["pos_ids"],
role_ids=inputs.get("role_ids", None),
generation_mask=inputs["attention_mask"]
)
return outputs
def get_metrics(self, inputs, outputs):
"""Get metrics."""
metrics = {}
tgt_logits = self._calc_logits(outputs["enc_out"], inputs["tgt_idx"])
lm_loss = layers.softmax_with_cross_entropy(logits=tgt_logits, label=inputs["tgt_label"])
need_cal = layers.not_equal(
inputs["tgt_label"], layers.fill_constant(shape=[1], dtype="int64", value=1)
)
need_cal = layers.cast(need_cal, self.dtype)
mean_lm_loss = layers.reduce_sum(lm_loss * need_cal) / (layers.reduce_sum(need_cal) + 1e-10)
pooled_out = self._get_pooled_output(outputs["enc_out"], inputs["label_idx"])
nsp_logits = self._get_classifier_output(pooled_out, name="next_sent")
nsp_loss, nsp_softmax = layers.softmax_with_cross_entropy(
logits=nsp_logits, label=inputs["label"], return_softmax=True)
nsp_acc = layers.accuracy(nsp_softmax, inputs["label"])
mean_nsp_loss = layers.mean(nsp_loss)
loss = mean_nsp_loss
if self.use_mlm:
loss = loss + mean_lm_loss
metrics["token_lm_loss"] = mean_lm_loss
metrics["loss"] = loss
metrics["nsp_loss"] = mean_nsp_loss
metrics["nsp_acc"] = nsp_acc
return metrics
def infer(self, inputs, outputs):
"""Run model inference."""
pooled_out = self._get_pooled_output(outputs["enc_out"], inputs["label_idx"])
nsp_logits = self._get_classifier_output(pooled_out, name="next_sent")
scores = layers.softmax(nsp_logits)
predictions = {"scores": scores, "data_id": inputs["data_id"]}
return predictions
def infer_step(self, inputs):
"""Run one inference step."""
return Model.infer_step(self, inputs)
|
src/oci/database/models/create_db_home_base.py | Manny27nyc/oci-python-sdk | 249 | 11088276 | <filename>src/oci/database/models/create_db_home_base.py
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class CreateDbHomeBase(object):
"""
Details for creating a Database Home.
**Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.
"""
#: A constant which can be used with the source property of a CreateDbHomeBase.
#: This constant has a value of "NONE"
SOURCE_NONE = "NONE"
#: A constant which can be used with the source property of a CreateDbHomeBase.
#: This constant has a value of "DB_BACKUP"
SOURCE_DB_BACKUP = "DB_BACKUP"
#: A constant which can be used with the source property of a CreateDbHomeBase.
#: This constant has a value of "DATABASE"
SOURCE_DATABASE = "DATABASE"
#: A constant which can be used with the source property of a CreateDbHomeBase.
#: This constant has a value of "VM_CLUSTER_BACKUP"
SOURCE_VM_CLUSTER_BACKUP = "VM_CLUSTER_BACKUP"
#: A constant which can be used with the source property of a CreateDbHomeBase.
#: This constant has a value of "VM_CLUSTER_NEW"
SOURCE_VM_CLUSTER_NEW = "VM_CLUSTER_NEW"
def __init__(self, **kwargs):
"""
Initializes a new CreateDbHomeBase object with values from keyword arguments. This class has the following subclasses and if you are using this class as input
to a service operations then you should favor using a subclass over the base class:
* :class:`~oci.database.models.CreateDbHomeWithDbSystemIdFromDatabaseDetails`
* :class:`~oci.database.models.CreateDbHomeWithDbSystemIdFromBackupDetails`
* :class:`~oci.database.models.CreateDbHomeWithVmClusterIdFromBackupDetails`
* :class:`~oci.database.models.CreateDbHomeWithDbSystemIdDetails`
* :class:`~oci.database.models.CreateDbHomeWithVmClusterIdDetails`
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param display_name:
The value to assign to the display_name property of this CreateDbHomeBase.
:type display_name: str
:param kms_key_id:
The value to assign to the kms_key_id property of this CreateDbHomeBase.
:type kms_key_id: str
:param kms_key_version_id:
The value to assign to the kms_key_version_id property of this CreateDbHomeBase.
:type kms_key_version_id: str
:param database_software_image_id:
The value to assign to the database_software_image_id property of this CreateDbHomeBase.
:type database_software_image_id: str
:param freeform_tags:
The value to assign to the freeform_tags property of this CreateDbHomeBase.
:type freeform_tags: dict(str, str)
:param defined_tags:
The value to assign to the defined_tags property of this CreateDbHomeBase.
:type defined_tags: dict(str, dict(str, object))
:param source:
The value to assign to the source property of this CreateDbHomeBase.
Allowed values for this property are: "NONE", "DB_BACKUP", "DATABASE", "VM_CLUSTER_BACKUP", "VM_CLUSTER_NEW"
:type source: str
:param is_desupported_version:
The value to assign to the is_desupported_version property of this CreateDbHomeBase.
:type is_desupported_version: bool
"""
self.swagger_types = {
'display_name': 'str',
'kms_key_id': 'str',
'kms_key_version_id': 'str',
'database_software_image_id': 'str',
'freeform_tags': 'dict(str, str)',
'defined_tags': 'dict(str, dict(str, object))',
'source': 'str',
'is_desupported_version': 'bool'
}
self.attribute_map = {
'display_name': 'displayName',
'kms_key_id': 'kmsKeyId',
'kms_key_version_id': 'kmsKeyVersionId',
'database_software_image_id': 'databaseSoftwareImageId',
'freeform_tags': 'freeformTags',
'defined_tags': 'definedTags',
'source': 'source',
'is_desupported_version': 'isDesupportedVersion'
}
self._display_name = None
self._kms_key_id = None
self._kms_key_version_id = None
self._database_software_image_id = None
self._freeform_tags = None
self._defined_tags = None
self._source = None
self._is_desupported_version = None
@staticmethod
def get_subtype(object_dictionary):
"""
Given the hash representation of a subtype of this class,
use the info in the hash to return the class of the subtype.
"""
type = object_dictionary['source']
if type == 'DATABASE':
return 'CreateDbHomeWithDbSystemIdFromDatabaseDetails'
if type == 'DB_BACKUP':
return 'CreateDbHomeWithDbSystemIdFromBackupDetails'
if type == 'VM_CLUSTER_BACKUP':
return 'CreateDbHomeWithVmClusterIdFromBackupDetails'
if type == 'NONE':
return 'CreateDbHomeWithDbSystemIdDetails'
if type == 'VM_CLUSTER_NEW':
return 'CreateDbHomeWithVmClusterIdDetails'
else:
return 'CreateDbHomeBase'
@property
def display_name(self):
"""
Gets the display_name of this CreateDbHomeBase.
The user-provided name of the Database Home.
:return: The display_name of this CreateDbHomeBase.
:rtype: str
"""
return self._display_name
@display_name.setter
def display_name(self, display_name):
"""
Sets the display_name of this CreateDbHomeBase.
The user-provided name of the Database Home.
:param display_name: The display_name of this CreateDbHomeBase.
:type: str
"""
self._display_name = display_name
@property
def kms_key_id(self):
"""
Gets the kms_key_id of this CreateDbHomeBase.
The OCID of the key container that is used as the master encryption key in database transparent data encryption (TDE) operations.
:return: The kms_key_id of this CreateDbHomeBase.
:rtype: str
"""
return self._kms_key_id
@kms_key_id.setter
def kms_key_id(self, kms_key_id):
"""
Sets the kms_key_id of this CreateDbHomeBase.
The OCID of the key container that is used as the master encryption key in database transparent data encryption (TDE) operations.
:param kms_key_id: The kms_key_id of this CreateDbHomeBase.
:type: str
"""
self._kms_key_id = kms_key_id
@property
def kms_key_version_id(self):
"""
Gets the kms_key_version_id of this CreateDbHomeBase.
The OCID of the key container version that is used in database transparent data encryption (TDE) operations KMS Key can have multiple key versions. If none is specified, the current key version (latest) of the Key Id is used for the operation.
:return: The kms_key_version_id of this CreateDbHomeBase.
:rtype: str
"""
return self._kms_key_version_id
@kms_key_version_id.setter
def kms_key_version_id(self, kms_key_version_id):
"""
Sets the kms_key_version_id of this CreateDbHomeBase.
The OCID of the key container version that is used in database transparent data encryption (TDE) operations KMS Key can have multiple key versions. If none is specified, the current key version (latest) of the Key Id is used for the operation.
:param kms_key_version_id: The kms_key_version_id of this CreateDbHomeBase.
:type: str
"""
self._kms_key_version_id = kms_key_version_id
@property
def database_software_image_id(self):
"""
Gets the database_software_image_id of this CreateDbHomeBase.
The database software image `OCID`__
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:return: The database_software_image_id of this CreateDbHomeBase.
:rtype: str
"""
return self._database_software_image_id
@database_software_image_id.setter
def database_software_image_id(self, database_software_image_id):
"""
Sets the database_software_image_id of this CreateDbHomeBase.
The database software image `OCID`__
__ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm
:param database_software_image_id: The database_software_image_id of this CreateDbHomeBase.
:type: str
"""
self._database_software_image_id = database_software_image_id
@property
def freeform_tags(self):
"""
Gets the freeform_tags of this CreateDbHomeBase.
Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace.
For more information, see `Resource Tags`__.
Example: `{\"Department\": \"Finance\"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The freeform_tags of this CreateDbHomeBase.
:rtype: dict(str, str)
"""
return self._freeform_tags
@freeform_tags.setter
def freeform_tags(self, freeform_tags):
"""
Sets the freeform_tags of this CreateDbHomeBase.
Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace.
For more information, see `Resource Tags`__.
Example: `{\"Department\": \"Finance\"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param freeform_tags: The freeform_tags of this CreateDbHomeBase.
:type: dict(str, str)
"""
self._freeform_tags = freeform_tags
@property
def defined_tags(self):
"""
Gets the defined_tags of this CreateDbHomeBase.
Defined tags for this resource. Each key is predefined and scoped to a namespace.
For more information, see `Resource Tags`__.
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The defined_tags of this CreateDbHomeBase.
:rtype: dict(str, dict(str, object))
"""
return self._defined_tags
@defined_tags.setter
def defined_tags(self, defined_tags):
"""
Sets the defined_tags of this CreateDbHomeBase.
Defined tags for this resource. Each key is predefined and scoped to a namespace.
For more information, see `Resource Tags`__.
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param defined_tags: The defined_tags of this CreateDbHomeBase.
:type: dict(str, dict(str, object))
"""
self._defined_tags = defined_tags
@property
def source(self):
"""
Gets the source of this CreateDbHomeBase.
The source of database: NONE for creating a new database. DB_BACKUP for creating a new database by restoring from a database backup.
Allowed values for this property are: "NONE", "DB_BACKUP", "DATABASE", "VM_CLUSTER_BACKUP", "VM_CLUSTER_NEW"
:return: The source of this CreateDbHomeBase.
:rtype: str
"""
return self._source
@source.setter
def source(self, source):
"""
Sets the source of this CreateDbHomeBase.
The source of database: NONE for creating a new database. DB_BACKUP for creating a new database by restoring from a database backup.
:param source: The source of this CreateDbHomeBase.
:type: str
"""
allowed_values = ["NONE", "DB_BACKUP", "DATABASE", "VM_CLUSTER_BACKUP", "VM_CLUSTER_NEW"]
if not value_allowed_none_or_none_sentinel(source, allowed_values):
raise ValueError(
"Invalid value for `source`, must be None or one of {0}"
.format(allowed_values)
)
self._source = source
@property
def is_desupported_version(self):
"""
Gets the is_desupported_version of this CreateDbHomeBase.
If true, the customer acknowledges that the specified Oracle Database software is an older release that is not currently supported by OCI.
:return: The is_desupported_version of this CreateDbHomeBase.
:rtype: bool
"""
return self._is_desupported_version
@is_desupported_version.setter
def is_desupported_version(self, is_desupported_version):
"""
Sets the is_desupported_version of this CreateDbHomeBase.
If true, the customer acknowledges that the specified Oracle Database software is an older release that is not currently supported by OCI.
:param is_desupported_version: The is_desupported_version of this CreateDbHomeBase.
:type: bool
"""
self._is_desupported_version = is_desupported_version
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
|
conans/client/tools/system_pm.py | fanStefan/conan | 6,205 | 11088279 | import os
import sys
import six
from conans.client.runner import ConanRunner
from conans.client.tools.oss import OSInfo, cross_building, get_cross_building_settings
from conans.client.tools.files import which
from conans.errors import ConanException
from conans.util.env_reader import get_env
from conans.util.fallbacks import default_output
class SystemPackageTool(object):
def __init__(self, runner=None, os_info=None, tool=None, recommends=False, output=None,
conanfile=None, default_mode="enabled"):
output = output if output else conanfile.output if conanfile else None
self._output = default_output(output, 'conans.client.tools.system_pm.SystemPackageTool')
os_info = os_info or OSInfo()
self._is_up_to_date = False
self._tool = tool or self._create_tool(os_info, output=self._output)
self._tool._sudo_str = self._get_sudo_str()
self._tool._runner = runner or ConanRunner(output=self._output)
self._tool._recommends = recommends
self._conanfile = conanfile
self._default_mode = default_mode
@staticmethod
def _get_sudo_str():
if not SystemPackageTool._is_sudo_enabled():
return ""
if hasattr(sys.stdout, "isatty") and not sys.stdout.isatty():
return "sudo -A "
else:
return "sudo "
@staticmethod
def _is_sudo_enabled():
if "CONAN_SYSREQUIRES_SUDO" not in os.environ:
if not which("sudo"):
return False
if os.name == 'posix' and os.geteuid() == 0:
return False
if os.name == 'nt':
return False
return get_env("CONAN_SYSREQUIRES_SUDO", True)
@staticmethod
def _create_tool(os_info, output):
if os_info.with_apt:
return AptTool(output=output)
elif os_info.with_dnf:
return DnfTool(output=output)
elif os_info.with_yum:
return YumTool(output=output)
elif os_info.with_pacman:
return PacManTool(output=output)
elif os_info.is_macos:
return BrewTool(output=output)
elif os_info.is_freebsd:
return PkgTool(output=output)
elif os_info.is_solaris:
return PkgUtilTool(output=output)
elif os_info.with_zypper:
return ZypperTool(output=output)
else:
return NullTool(output=output)
def _get_sysrequire_mode(self):
allowed_modes = ("enabled", "verify", "disabled")
mode = get_env("CONAN_SYSREQUIRES_MODE", self._default_mode)
mode_lower = mode.lower()
if mode_lower not in allowed_modes:
raise ConanException("CONAN_SYSREQUIRES_MODE=%s is not allowed, allowed modes=%r"
% (mode, allowed_modes))
return mode_lower
def add_repository(self, repository, repo_key=None, update=True):
self._tool.add_repository(repository, repo_key=repo_key)
if update:
self.update()
def update(self):
"""
Get the system package tool update command
"""
mode = self._get_sysrequire_mode()
if mode in ("disabled", "verify"):
self._output.info("Not updating system_requirements. CONAN_SYSREQUIRES_MODE=%s" % mode)
return
self._is_up_to_date = True
self._tool.update()
def install(self, packages, update=True, force=False, arch_names=None):
""" Get the system package tool install command and install one package
:param packages: String with a package to be installed or a list with its variants e.g. "libusb-dev libxusb-devel"
:param update: Run update command before to install
:param force: Force installing all packages
:param arch_names: Package suffix/prefix name used by installer tool e.g. {"x86_64": "amd64"}
:return: None
"""
packages = [packages] if isinstance(packages, str) else list(packages)
packages = self._get_package_names(packages, arch_names)
mode = self._get_sysrequire_mode()
if mode in ("verify", "disabled"):
# Report to output packages need to be installed
if mode == "disabled":
self._output.info("The following packages need to be installed:\n %s"
% "\n".join(packages))
return
if mode == "verify" and not self._installed(packages):
self._output.error("The following packages need to be installed:\n %s"
% "\n".join(packages))
raise ConanException("Aborted due to CONAN_SYSREQUIRES_MODE=%s. "
"Some system packages need to be installed" % mode)
if not force and self._installed(packages):
return
# From here system packages can be updated/modified
if update and not self._is_up_to_date:
self.update()
self._install_any(packages)
def install_packages(self, packages, update=True, force=False, arch_names=None):
""" Get the system package tool install command and install all packages and/or variants.
Inputs:
"pkg-variant1" # (1) Install only one package
["pkg-variant1", "otherpkg", "thirdpkg"] # (2) All must be installed
[("pkg-variant1", "pkg-variant2"), "otherpkg", "thirdpkg"] # (3) Install only one variant
and all other packages
"pkg1 pkg2", "pkg3 pkg4" # (4) Invalid
["pkg1 pkg2", "pkg3 pkg4"] # (5) Invalid
:param packages: Supports multiple formats (string,list,tuple). Lists and tuples into a list
are considered variants and is processed just like self.install(). A list of string is
considered a list of packages to be installed (only not installed yet).
:param update: Run update command before to install
:param force: Force installing all packages, including all installed.
:param arch_names: Package suffix/prefix name used by installer tool e.g. {"x86_64": "amd64"}
:return: None
"""
packages = [packages] if isinstance(packages, six.string_types) else list(packages)
# only one (first) variant will be installed
list_variants = list(filter(lambda x: isinstance(x, (tuple, list)), packages))
# all packages will be installed
packages = list(filter(lambda x: not isinstance(x, (tuple, list)), packages))
if [pkg for pkg in packages if " " in pkg]:
raise ConanException("Each string must contain only one package to be installed. "
"Use a list instead e.g. ['foo', 'bar'].")
for variant in list_variants:
self.install(variant, update=update, force=force, arch_names=arch_names)
packages = self._get_package_names(packages, arch_names)
mode = self._get_sysrequire_mode()
if mode in ("verify", "disabled"):
# Report to output packages need to be installed
if mode == "disabled":
self._output.info("The following packages need to be installed:\n %s"
% "\n".join(packages))
return
if mode == "verify" and not self._installed(packages):
self._output.error("The following packages need to be installed:\n %s"
% "\n".join(packages))
raise ConanException("Aborted due to CONAN_SYSREQUIRES_MODE=%s. "
"Some system packages need to be installed" % mode)
packages = packages if force else self._to_be_installed(packages)
if not force and not packages:
return
# From here system packages can be updated/modified
if update and not self._is_up_to_date:
self.update()
self._install_all(packages)
def _get_package_names(self, packages, arch_names):
""" Parse package names according it architecture
:param packages: list with all package to be installed e.g. ["libusb-dev libfoobar-dev"]
:param arch_names: Package suffix/prefix name used by installer tool
:return: list with all parsed names e.g. ["libusb-dev:armhf libfoobar-dev:armhf"]
"""
if self._conanfile and self._conanfile.settings and cross_building(self._conanfile):
_, build_arch, _, host_arch = get_cross_building_settings(self._conanfile)
arch = host_arch or build_arch
parsed_packages = []
for package in packages:
if isinstance(package, (tuple, list)):
parsed_packages.append(tuple(self._get_package_names(package, arch_names)))
else:
for package_name in package.split(" "):
parsed_packages.append(self._tool.get_package_name(package_name, arch,
arch_names))
return parsed_packages
return packages
def installed(self, package_name):
return self._tool.installed(package_name)
def _to_be_installed(self, packages):
""" Returns a list with all not installed packages.
"""
not_installed = [pkg for pkg in packages if not self._tool.installed(pkg)]
return not_installed
def _installed(self, packages):
""" Return True if at least one of the packages is installed.
"""
if not packages:
return True
for pkg in packages:
if self._tool.installed(pkg):
self._output.info("Package already installed: %s" % pkg)
return True
return False
def _install_all(self, packages):
self._tool.install(" ".join(sorted(packages)))
def _install_any(self, packages):
if len(packages) == 1:
return self._tool.install(packages[0])
for pkg in packages:
try:
return self._tool.install(pkg)
except ConanException:
pass
raise ConanException("Could not install any of %s" % packages)
class BaseTool(object):
def __init__(self, output=None):
self._output = default_output(output, 'conans.client.tools.system_pm.BaseTool')
def get_package_name(self, package, arch, arch_names):
""" Retrieve package name to installed according the target arch.
:param package: Regular package name e.g libusb-dev
:param arch: Host arch from Conanfile.settings
:param arch_names: Dictionary with suffix/prefix names e.g {"x86_64": "amd64"}
:return: Package name for Tool e.g. libusb-dev:i386
"""
return package
class NullTool(BaseTool):
def add_repository(self, repository, repo_key=None):
pass
def update(self):
pass
def install(self, package_name):
self._output.warn("Only available for linux with apt-get, yum, or pacman or OSX with brew or"
" FreeBSD with pkg or Solaris with pkgutil")
def installed(self, package_name):
return False
class AptTool(BaseTool):
def add_repository(self, repository, repo_key=None):
if repo_key:
_run(self._runner, "wget -qO - %s | %sapt-key add -" % (repo_key, self._sudo_str),
output=self._output)
_run(self._runner, "%sapt-add-repository %s" % (self._sudo_str, repository),
output=self._output)
def update(self):
_run(self._runner, "%sapt-get update" % self._sudo_str, output=self._output)
def install(self, package_name):
recommends_str = '' if self._recommends else '--no-install-recommends '
_run(self._runner,
"%sapt-get install -y %s%s" % (self._sudo_str, recommends_str, package_name),
output=self._output)
def installed(self, package_name):
exit_code = self._runner("dpkg-query -W -f='${Status}' %s | grep -q \"ok installed\""
% package_name, None)
return exit_code == 0
def get_package_name(self, package, arch, arch_names):
if arch_names is None:
arch_names = {"x86_64": "amd64",
"x86": "i386",
"ppc32": "powerpc",
"ppc64le": "ppc64el",
"armv7": "arm",
"armv7hf": "armhf",
"armv8": "arm64",
"s390x": "s390x"}
if arch in arch_names:
return "%s:%s" % (package, arch_names[arch])
return package
class YumTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("YumTool::add_repository not implemented")
def update(self):
_run(self._runner, "%syum check-update -y" % self._sudo_str, accepted_returns=[0, 100],
output=self._output)
def install(self, package_name):
_run(self._runner, "%syum install -y %s" % (self._sudo_str, package_name),
output=self._output)
def installed(self, package_name):
exit_code = self._runner("rpm -q %s" % package_name, None)
return exit_code == 0
def get_package_name(self, package, arch, arch_names):
if arch_names is None:
arch_names = {"x86_64": "x86_64",
"x86": "i?86",
"ppc32": "powerpc",
"ppc64le": "ppc64le",
"armv7": "armv7",
"armv7hf": "armv7hl",
"armv8": "aarch64",
"s390x": "s390x"}
if arch in arch_names:
return "%s.%s" % (package, arch_names[arch])
return package
class DnfTool(YumTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("DnfTool::add_repository not implemented")
def update(self):
_run(self._runner, "%sdnf check-update -y" % self._sudo_str, accepted_returns=[0, 100],
output=self._output)
def install(self, package_name):
_run(self._runner, "%sdnf install -y %s" % (self._sudo_str, package_name),
output=self._output)
class BrewTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("BrewTool::add_repository not implemented")
def update(self):
_run(self._runner, "brew update", output=self._output)
def install(self, package_name):
_run(self._runner, "brew install %s" % package_name, output=self._output)
def installed(self, package_name):
exit_code = self._runner('test -n "$(brew ls --versions %s)"' % package_name, None)
return exit_code == 0
class PkgTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("PkgTool::add_repository not implemented")
def update(self):
_run(self._runner, "%spkg update" % self._sudo_str, output=self._output)
def install(self, package_name):
_run(self._runner, "%spkg install -y %s" % (self._sudo_str, package_name),
output=self._output)
def installed(self, package_name):
exit_code = self._runner("pkg info %s" % package_name, None)
return exit_code == 0
class PkgUtilTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("PkgUtilTool::add_repository not implemented")
def update(self):
_run(self._runner, "%spkgutil --catalog" % self._sudo_str, output=self._output)
def install(self, package_name):
_run(self._runner, "%spkgutil --install --yes %s" % (self._sudo_str, package_name),
output=self._output)
def installed(self, package_name):
exit_code = self._runner('test -n "`pkgutil --list %s`"' % package_name, None)
return exit_code == 0
class ChocolateyTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("ChocolateyTool::add_repository not implemented")
def update(self):
_run(self._runner, "choco outdated", output=self._output)
def install(self, package_name):
_run(self._runner, "choco install --yes %s" % package_name, output=self._output)
def installed(self, package_name):
exit_code = self._runner('choco search --local-only --exact %s | '
'findstr /c:"1 packages installed."' % package_name, None)
return exit_code == 0
class PacManTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("PacManTool::add_repository not implemented")
def update(self):
_run(self._runner, "%spacman -Syyu --noconfirm" % self._sudo_str, output=self._output)
def install(self, package_name):
_run(self._runner, "%spacman -S --noconfirm %s" % (self._sudo_str, package_name),
output=self._output)
def installed(self, package_name):
exit_code = self._runner("pacman -Qi %s" % package_name, None)
return exit_code == 0
def get_package_name(self, package, arch, arch_names):
if arch_names is None:
arch_names = {"x86": "lib32"}
if arch in arch_names:
return "%s-%s" % (arch_names[arch], package)
return package
class ZypperTool(BaseTool):
def add_repository(self, repository, repo_key=None):
raise ConanException("ZypperTool::add_repository not implemented")
def update(self):
_run(self._runner, "%szypper --non-interactive ref" % self._sudo_str, output=self._output)
def install(self, package_name):
_run(self._runner, "%szypper --non-interactive in %s" % (self._sudo_str, package_name),
output=self._output)
def installed(self, package_name):
exit_code = self._runner("rpm -q %s" % package_name, None)
return exit_code == 0
def get_package_name(self, package, arch, arch_names):
if arch_names is None:
arch_names = {"x86": "i586"}
if arch in arch_names:
return "%s.%s" % (arch_names[arch], package)
return package
def _run(runner, command, output, accepted_returns=None):
accepted_returns = accepted_returns or [0, ]
output.info("Running: %s" % command)
if runner(command, True) not in accepted_returns:
raise ConanException("Command '%s' failed" % command)
|
src/masonite/filesystem/drivers/LocalDriver.py | StevenMHernandez/masonite | 1,816 | 11088295 | <gh_stars>1000+
import os
from shutil import copyfile, move
from ..FileStream import FileStream
import uuid
import os
class LocalDriver:
def __init__(self, application):
self.application = application
self.options = {}
def set_options(self, options):
self.options = options
return self
def get_path(self, path):
file_path = os.path.join(self.options.get("path"), path)
self.make_file_path_if_not_exists(file_path)
return file_path
def get_name(self, path, alias):
extension = os.path.splitext(path)[1]
return f"{alias}{extension}"
def put(self, file_path, content):
with open(self.get_path(os.path.join(file_path)), "w") as f:
f.write(content)
return content
def put_file(self, file_path, content, name=None):
file_name = self.get_name(content.name, name or str(uuid.uuid4()))
if hasattr(content, "get_content"):
content = content.get_content()
if isinstance(content, str):
content = bytes(content, "utf-8")
with open(self.get_path(os.path.join(file_path, file_name)), "wb") as f:
f.write(content)
return os.path.join(file_path, file_name)
def get(self, file_path):
try:
with open(self.get_path(file_path), "r") as f:
content = f.read()
return content
except FileNotFoundError:
return None
def exists(self, file_path):
return os.path.exists(self.get_path(file_path))
def missing(self, file_path):
return not self.exists(file_path)
def stream(self, file_path):
with open(self.get_path(file_path), "r") as f:
content = f
return FileStream(content)
def copy(self, from_file_path, to_file_path):
return copyfile(from_file_path, to_file_path)
def move(self, from_file_path, to_file_path):
return move(self.get_path(from_file_path), self.get_path(to_file_path))
def prepend(self, file_path, content):
value = self.get(file_path)
content = content + value
self.put(file_path, content)
return content
def append(self, file_path, content):
with open(self.get_path(file_path), "a") as f:
f.write(content)
return content
def delete(self, file_path):
return os.remove(self.get_path(file_path))
def make_directory(self, directory):
pass
def store(self, file, name=None):
if name:
name = f"{name}{file.extension()}"
full_path = self.get_path(name or file.hash_path_name())
with open(full_path, "wb") as f:
f.write(file.stream())
return full_path
def make_file_path_if_not_exists(self, file_path):
if not os.path.isfile(file_path):
if not os.path.exists(os.path.dirname(file_path)):
# Create the path to the model if it does not exist
os.makedirs(os.path.dirname(file_path))
return True
return False
|
python/ql/test/query-tests/Imports/cyclic-module/module6.py | vadi2/codeql | 4,036 | 11088314 | def foo():
import module7 |
tests/slice_getattribute.py | ZYAZP/python2 | 1,062 | 11088316 | class M(type):
__getattribute__ = None
class G(object):
__metaclass__ = M
__getattribute__ = None
def __get__(self, instance, owner):
def f(*args):
print args
return f
class C(object):
__metaclass__ = M
__getattribute__ = None
__getitem__ = G()
__setitem__ = G()
__delitem__ = G()
o = C()
o.__getitem__ = None
o.__setitem__ = None
o.__delitem__ = None
o[:]
o[::]
o[:] = []
o[::] = []
del o[:]
del o[::]
|
luigi/contrib/lsf_runner.py | gaybro8777/luigi | 14,755 | 11088330 | # -*- coding: utf-8 -*-
"""
.. Copyright 2012-2015 Spotify AB
Copyright 2018
Copyright 2018 EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import sys
try:
# Dill is used for handling pickling and unpickling if there is a deference
# in server setups between the LSF submission node and the nodes in the
# cluster
import dill as pickle
except ImportError:
import pickle
import logging
import tarfile
def do_work_on_compute_node(work_dir):
# Extract the necessary dependencies
extract_packages_archive(work_dir)
# Open up the pickle file with the work to be done
os.chdir(work_dir)
with open("job-instance.pickle", "r") as pickle_file_handle:
job = pickle.load(pickle_file_handle)
# Do the work contained
job.work()
def extract_packages_archive(work_dir):
package_file = os.path.join(work_dir, "packages.tar")
if not os.path.exists(package_file):
return
curdir = os.path.abspath(os.curdir)
os.chdir(work_dir)
tar = tarfile.open(package_file)
for tarinfo in tar:
tar.extract(tarinfo)
tar.close()
if '' not in sys.path:
sys.path.insert(0, '')
os.chdir(curdir)
def main(args=sys.argv):
"""Run the work() method from the class instance in the file "job-instance.pickle".
"""
try:
# Set up logging.
logging.basicConfig(level=logging.WARN)
work_dir = args[1]
assert os.path.exists(work_dir), "First argument to lsf_runner.py must be a directory that exists"
do_work_on_compute_node(work_dir)
except Exception as exc:
# Dump encoded data that we will try to fetch using mechanize
print(exc)
raise
if __name__ == '__main__':
main()
|
mmaction/models/tenons/cls_heads/__init__.py | shreyas-bk/TPN | 353 | 11088332 | <filename>mmaction/models/tenons/cls_heads/__init__.py
from .cls_head import ClsHead
__all__ = [
'ClsHead',
]
|
fury/ui/__init__.py | SunTzunami/fury | 149 | 11088338 | <gh_stars>100-1000
from fury.ui.core import *
from fury.ui.containers import *
from fury.ui.elements import *
|
tests/test_fitness_shaping.py | mahi97/evosax | 102 | 11088358 | import jax.numpy as jnp
from evosax import FitnessShaper
def test_fitness_shaping_rank():
shaper = FitnessShaper(centered_rank=True)
x = jnp.array([[1.0], [2.0], [3.0]])
fit = jnp.array([0.0, 1.0, 2.0])
fit_re = shaper.apply(x, fit)
assert jnp.allclose(fit_re, jnp.array([-0.5, 0.0, 0.5]), atol=1e-03)
def test_fitness_shaping_decay():
shaper = FitnessShaper(w_decay=0.01)
x = jnp.array([[1.0], [2.0], [3.0]])
fit = jnp.array([0.0, 1.0, 2.0])
fit_re = shaper.apply(x, fit)
assert jnp.allclose(
fit_re, jnp.array([0.01, 1 + 0.04, 2 + 0.09]), atol=1e-03
)
def test_fitness_shaping_zscore():
shaper = FitnessShaper(z_score=True)
x = jnp.array([[1.0], [2.0], [3.0]])
fit = jnp.array([0.0, 1.0, 2.0])
fit_re = shaper.apply(x, fit)
assert jnp.allclose(
fit_re, jnp.array([-1.2247448, 0.0, 1.2247448]), atol=1e-03
)
def test_fitness_shaping_max():
shaper = FitnessShaper(w_decay=0.01, maximize=True)
x = jnp.array([[1.0], [2.0], [3.0]])
fit = jnp.array([0.0, 1.0, 2.0])
fit_re = shaper.apply(x, fit)
assert jnp.allclose(
fit_re, jnp.array([-0.01, -(1 + 0.04), -(2 + 0.09)]), atol=1e-03
)
|
dashboard/reporter.py | vzhong/dashboard | 155 | 11088359 | from collections import defaultdict
class Reporter:
"""
Utility for aggregating metrics
"""
def __init__(self):
self.log = []
self.keys = set()
def add(self, metrics):
"""
Adds metrics to the cache
"""
for k in metrics.keys():
self.keys.add(k)
self.log.append(metrics)
def clear(self):
"""
Empties the cache of stored metrics
"""
self.log[:] = [] # .clear is not python2 compatible
self.keys.clear()
def summary(self, ignore=('epoch', 'iteration')):
"""
Computes averages of metrics stored in the cache
Args:
ignore (list): these metrics will be ignored and removed from the summary
"""
s = defaultdict(list)
for m in self.log:
for k, v in m.items():
if k not in ignore:
s[k].append(v)
for k, v in s.items():
s[k] = sum(v) / len(v)
return s
if __name__ == '__main__':
from dashboard import writer
import time
r = Reporter()
writers = [writer.ConsoleWriter()]
for i in range(10):
d = {'iteration': i, 'score': i * 2}
r.add(d)
for w in writers:
w.add(d)
time.sleep(1)
|
multi_video_sim/generate_test_video.py | matvaibhav/pensieve | 462 | 11088396 | import os
import numpy as np
VIDEO_SOURCE_FOLDER = '../video_server/'
VIDEO_FOLDER = 'video'
VIDEO_OUTPUT_FOLDER = './test_video/'
TOTAL_VIDEO_CHUNCK = 49
BITRATE_LEVELS = 6
MASK = [0, 1, 0, 1, 1, 1, 1, 1, 0, 0]
M_IN_B = 1000000.0
video_chunk_sizes = []
for bitrate in xrange(BITRATE_LEVELS):
video_chunk_sizes.append([])
for chunk_idx in xrange(1, TOTAL_VIDEO_CHUNCK + 1):
video_chunk_path = VIDEO_SOURCE_FOLDER + \
VIDEO_FOLDER + \
str(BITRATE_LEVELS - bitrate) + \
'/' + \
str(chunk_idx) + \
'.m4s'
chunk_size = os.path.getsize(video_chunk_path) / M_IN_B
video_chunk_sizes[bitrate].append(chunk_size)
assert len(video_chunk_sizes[-1]) == TOTAL_VIDEO_CHUNCK
assert len(video_chunk_sizes) == BITRATE_LEVELS
with open(VIDEO_OUTPUT_FOLDER + '0', 'wb') as f:
f.write(str(BITRATE_LEVELS) + '\t' + str(TOTAL_VIDEO_CHUNCK) + '\n')
for m in MASK:
f.write(str(m) + '\t')
f.write('\n')
for chunk_idx in xrange(TOTAL_VIDEO_CHUNCK):
for i in xrange(BITRATE_LEVELS):
f.write(str(video_chunk_sizes[i][chunk_idx]) + '\t')
f.write('\n')
|
uasyncio.udp/example_dns_junk.py | Carglglz/micropython-lib | 126 | 11088403 | <filename>uasyncio.udp/example_dns_junk.py<gh_stars>100-1000
# This example is intended to run with dnsmasq running on localhost
# (Ubuntu comes configured like that by default). Dnsmasq, receiving
# some junk, is still kind to reply something back, which we employ
# here.
import uasyncio
import uasyncio.udp
import usocket
def udp_req(addr):
s = uasyncio.udp.socket()
print(s)
yield from uasyncio.udp.sendto(s, b"!eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", addr)
try:
resp = yield from uasyncio.wait_for(uasyncio.udp.recv(s, 1024), 1)
print(resp)
except uasyncio.TimeoutError:
print("timed out")
import logging
logging.basicConfig(level=logging.INFO)
addr = usocket.getaddrinfo("127.0.0.1", 53)[0][-1]
loop = uasyncio.get_event_loop()
loop.run_until_complete(udp_req(addr))
loop.close()
|
homeassistant/components/airzone/climate.py | liangleslie/core | 30,023 | 11088407 | <reponame>liangleslie/core
"""Support for the Airzone climate."""
from __future__ import annotations
import logging
from typing import Any, Final
from aioairzone.common import OperationMode
from aioairzone.const import (
API_MODE,
API_ON,
API_SET_POINT,
API_SYSTEM_ID,
API_ZONE_ID,
AZD_DEMAND,
AZD_HUMIDITY,
AZD_MASTER,
AZD_MODE,
AZD_MODES,
AZD_NAME,
AZD_ON,
AZD_TEMP,
AZD_TEMP_MAX,
AZD_TEMP_MIN,
AZD_TEMP_SET,
AZD_TEMP_UNIT,
AZD_ZONES,
)
from aioairzone.exceptions import AirzoneError
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
ClimateEntityFeature,
HVACAction,
HVACMode,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_TEMPERATURE
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import API_TEMPERATURE_STEP, DOMAIN, TEMP_UNIT_LIB_TO_HASS
from .coordinator import AirzoneUpdateCoordinator
from .entity import AirzoneZoneEntity
_LOGGER = logging.getLogger(__name__)
HVAC_ACTION_LIB_TO_HASS: Final[dict[OperationMode, HVACAction]] = {
OperationMode.STOP: HVACAction.OFF,
OperationMode.COOLING: HVACAction.COOLING,
OperationMode.HEATING: HVACAction.HEATING,
OperationMode.FAN: HVACAction.FAN,
OperationMode.DRY: HVACAction.DRYING,
}
HVAC_MODE_LIB_TO_HASS: Final[dict[OperationMode, HVACMode]] = {
OperationMode.STOP: HVACMode.OFF,
OperationMode.COOLING: HVACMode.COOL,
OperationMode.HEATING: HVACMode.HEAT,
OperationMode.FAN: HVACMode.FAN_ONLY,
OperationMode.DRY: HVACMode.DRY,
OperationMode.AUTO: HVACMode.HEAT_COOL,
}
HVAC_MODE_HASS_TO_LIB: Final[dict[HVACMode, OperationMode]] = {
HVACMode.OFF: OperationMode.STOP,
HVACMode.COOL: OperationMode.COOLING,
HVACMode.HEAT: OperationMode.HEATING,
HVACMode.FAN_ONLY: OperationMode.FAN,
HVACMode.DRY: OperationMode.DRY,
HVACMode.HEAT_COOL: OperationMode.AUTO,
}
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Add Airzone sensors from a config_entry."""
coordinator = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
AirzoneClimate(
coordinator,
entry,
system_zone_id,
zone_data,
)
for system_zone_id, zone_data in coordinator.data[AZD_ZONES].items()
)
class AirzoneClimate(AirzoneZoneEntity, ClimateEntity):
"""Define an Airzone sensor."""
def __init__(
self,
coordinator: AirzoneUpdateCoordinator,
entry: ConfigEntry,
system_zone_id: str,
zone_data: dict,
) -> None:
"""Initialize Airzone climate entity."""
super().__init__(coordinator, entry, system_zone_id, zone_data)
self._attr_name = f"{zone_data[AZD_NAME]}"
self._attr_unique_id = f"{self._attr_unique_id}_{system_zone_id}"
self._attr_supported_features = ClimateEntityFeature.TARGET_TEMPERATURE
self._attr_target_temperature_step = API_TEMPERATURE_STEP
self._attr_max_temp = self.get_airzone_value(AZD_TEMP_MAX)
self._attr_min_temp = self.get_airzone_value(AZD_TEMP_MIN)
self._attr_temperature_unit = TEMP_UNIT_LIB_TO_HASS[
self.get_airzone_value(AZD_TEMP_UNIT)
]
self._attr_hvac_modes = [
HVAC_MODE_LIB_TO_HASS[mode] for mode in self.get_airzone_value(AZD_MODES)
]
self._async_update_attrs()
async def _async_update_hvac_params(self, params: dict[str, Any]) -> None:
"""Send HVAC parameters to API."""
_params = {
API_SYSTEM_ID: self.system_id,
API_ZONE_ID: self.zone_id,
**params,
}
_LOGGER.debug("update_hvac_params=%s", _params)
try:
await self.coordinator.airzone.set_hvac_parameters(_params)
except AirzoneError as error:
raise HomeAssistantError(
f"Failed to set zone {self.name}: {error}"
) from error
else:
self.coordinator.async_set_updated_data(self.coordinator.airzone.data())
async def async_turn_on(self) -> None:
"""Turn the entity on."""
params = {
API_ON: 1,
}
await self._async_update_hvac_params(params)
async def async_turn_off(self) -> None:
"""Turn the entity off."""
params = {
API_ON: 0,
}
await self._async_update_hvac_params(params)
async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
"""Set hvac mode."""
params = {}
if hvac_mode == HVACMode.OFF:
params[API_ON] = 0
else:
mode = HVAC_MODE_HASS_TO_LIB[hvac_mode]
if mode != self.get_airzone_value(AZD_MODE):
if self.get_airzone_value(AZD_MASTER):
params[API_MODE] = mode
else:
raise HomeAssistantError(
f"Mode can't be changed on slave zone {self.name}"
)
params[API_ON] = 1
await self._async_update_hvac_params(params)
async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set new target temperature."""
params = {
API_SET_POINT: kwargs.get(ATTR_TEMPERATURE),
}
await self._async_update_hvac_params(params)
@callback
def _handle_coordinator_update(self) -> None:
"""Update attributes when the coordinator updates."""
self._async_update_attrs()
super()._handle_coordinator_update()
@callback
def _async_update_attrs(self) -> None:
"""Update climate attributes."""
self._attr_current_temperature = self.get_airzone_value(AZD_TEMP)
self._attr_current_humidity = self.get_airzone_value(AZD_HUMIDITY)
if self.get_airzone_value(AZD_ON):
mode = self.get_airzone_value(AZD_MODE)
self._attr_hvac_mode = HVAC_MODE_LIB_TO_HASS[mode]
if self.get_airzone_value(AZD_DEMAND):
self._attr_hvac_action = HVAC_ACTION_LIB_TO_HASS[mode]
else:
self._attr_hvac_action = HVACAction.IDLE
else:
self._attr_hvac_action = HVACAction.OFF
self._attr_hvac_mode = HVACMode.OFF
self._attr_target_temperature = self.get_airzone_value(AZD_TEMP_SET)
|
colour/colorimetry/cmfs.py | rift-labs-developer/colour | 1,380 | 11088408 | # -*- coding: utf-8 -*-
"""
Colour Matching Functions
=========================
Defines the colour matching functions classes for the datasets from
the :mod:`colour.colorimetry.datasets.cmfs` module:
- :class:`colour.colorimetry.LMS_ConeFundamentals`: Implements support for
the *Stockman and Sharpe* *LMS* cone fundamentals colour matching
functions.
- :class:`colour.colorimetry.RGB_ColourMatchingFunctions`: Implements support
for the *CIE RGB* colour matching functions.
- :class:`colour.colorimetry.XYZ_ColourMatchingFunctions`: Implements support
for the *CIE Standard Observers* *XYZ* colour matching functions.
"""
from colour.colorimetry import MultiSpectralDistributions
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013-2021 - Colour Developers'
__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = 'Colour Developers'
__email__ = '<EMAIL>'
__status__ = 'Production'
__all__ = [
'LMS_ConeFundamentals', 'RGB_ColourMatchingFunctions',
'XYZ_ColourMatchingFunctions'
]
class LMS_ConeFundamentals(MultiSpectralDistributions):
"""
Implements support for the Stockman and Sharpe *LMS* cone fundamentals
colour matching functions.
Parameters
----------
data : Series or Dataframe or Signal or MultiSignals or \
MultiSpectralDistributions or array_like or dict_like, optional
Data to be stored in the multi-spectral distributions.
domain : array_like, optional
class instances :attr:`colour.continuous.Signal.wavelengths` attribute
with. If both ``data`` and ``domain`` arguments are defined, the latter
will be used to initialise the
Values to initialise the multiple :class:`colour.SpectralDistribution`
:attr:`colour.continuous.Signal.wavelengths` attribute.
labels : array_like, optional
Names to use for the :class:`colour.SpectralDistribution` class
instances.
Other Parameters
----------------
name : unicode, optional
Multi-spectral distributions name.
interpolator : object, optional
Interpolator class type to use as interpolating function for the
:class:`colour.SpectralDistribution` class instances.
interpolator_kwargs : dict_like, optional
Arguments to use when instantiating the interpolating function
of the :class:`colour.SpectralDistribution` class instances.
extrapolator : object, optional
Extrapolator class type to use as extrapolating function for the
:class:`colour.SpectralDistribution` class instances.
extrapolator_kwargs : dict_like, optional
Arguments to use when instantiating the extrapolating function
of the :class:`colour.SpectralDistribution` class instances.
strict_labels : array_like, optional
Multi-spectral distributions labels for figures, default to
:attr:`colour.colorimetry.LMS_ConeFundamentals.labels` attribute value.
"""
def __init__(self, data=None, domain=None, labels=None, **kwargs):
super(LMS_ConeFundamentals, self).__init__(
data,
domain,
labels=('l_bar', 'm_bar', 's_bar'),
strict_labels=('$\\bar{l}$', '$\\bar{m}$', '$\\bar{s}$'),
**kwargs)
class RGB_ColourMatchingFunctions(MultiSpectralDistributions):
"""
Implements support for the *CIE RGB* colour matching functions.
Parameters
----------
data : Series or Dataframe or Signal or MultiSignals or \
MultiSpectralDistributions or array_like or dict_like, optional
Data to be stored in the multi-spectral distributions.
domain : array_like, optional
Values to initialise the multiple :class:`colour.SpectralDistribution`
class instances :attr:`colour.continuous.Signal.wavelengths` attribute
with. If both ``data`` and ``domain`` arguments are defined, the latter
will be used to initialise the
:attr:`colour.continuous.Signal.wavelengths` attribute.
labels : array_like, optional
Names to use for the :class:`colour.SpectralDistribution` class
instances.
Other Parameters
----------------
name : unicode, optional
Multi-spectral distributions name.
interpolator : object, optional
Interpolator class type to use as interpolating function for the
:class:`colour.SpectralDistribution` class instances.
interpolator_kwargs : dict_like, optional
Arguments to use when instantiating the interpolating function
of the :class:`colour.SpectralDistribution` class instances.
extrapolator : object, optional
Extrapolator class type to use as extrapolating function for the
:class:`colour.SpectralDistribution` class instances.
extrapolator_kwargs : dict_like, optional
Arguments to use when instantiating the extrapolating function
of the :class:`colour.SpectralDistribution` class instances.
strict_labels : array_like, optional
Multi-spectral distributions labels for figures, default to
:attr:`colour.colorimetry.RGB_ColourMatchingFunctions.labels` attribute
value.
"""
def __init__(self, data=None, domain=None, labels=None, **kwargs):
super(RGB_ColourMatchingFunctions, self).__init__(
data,
domain,
labels=('r_bar', 'g_bar', 'b_bar'),
strict_labels=('$\\bar{r}$', '$\\bar{g}$', '$\\bar{b}$'),
**kwargs)
class XYZ_ColourMatchingFunctions(MultiSpectralDistributions):
"""
Implements support for the *CIE* Standard Observers *XYZ* colour matching
functions.
Parameters
----------
data : Series or Dataframe or Signal or MultiSignals or \
MultiSpectralDistributions or array_like or dict_like, optional
Data to be stored in the multi-spectral distributions.
domain : array_like, optional
Values to initialise the multiple :class:`colour.SpectralDistribution`
class instances :attr:`colour.continuous.Signal.wavelengths` attribute
with. If both ``data`` and ``domain`` arguments are defined, the latter
will be used to initialise the
:attr:`colour.continuous.Signal.wavelengths` attribute.
labels : array_like, optional
Names to use for the :class:`colour.SpectralDistribution` class
instances.
Other Parameters
----------------
name : unicode, optional
Multi-spectral distributions name.
interpolator : object, optional
Interpolator class type to use as interpolating function for the
:class:`colour.SpectralDistribution` class instances.
interpolator_kwargs : dict_like, optional
Arguments to use when instantiating the interpolating function
of the :class:`colour.SpectralDistribution` class instances.
extrapolator : object, optional
Extrapolator class type to use as extrapolating function for the
:class:`colour.SpectralDistribution` class instances.
extrapolator_kwargs : dict_like, optional
Arguments to use when instantiating the extrapolating function
of the :class:`colour.SpectralDistribution` class instances.
strict_labels : array_like, optional
Multi-spectral distributions labels for figures, default to
:attr:`colour.colorimetry.XYZ_ColourMatchingFunctions.labels` attribute
value.
"""
def __init__(self, data=None, domain=None, labels=None, **kwargs):
super(XYZ_ColourMatchingFunctions, self).__init__(
data,
domain,
labels=('x_bar', 'y_bar', 'z_bar'),
strict_labels=('$\\bar{x}$', '$\\bar{y}$', '$\\bar{z}$'),
**kwargs)
|
pyflux/__check_build/__init__.py | ThomasHoppe/pyflux | 2,091 | 11088449 | """ Module to give helpful messages to the user that did not
compile package properly,
This code was adapted from scikit-learn's check_build utility.
"""
import os
PACKAGE_NAME = 'pyflux'
INPLACE_MSG = """
It appears that you are importing {package} from within the source tree.
Please either use an inplace install or try from another location.
""".format(package=PACKAGE_NAME)
STANDARD_MSG = """
If you have used an installer, please check that it is suited for your
Python version, your operating system and your platform.
"""
ERROR_TEMPLATE = """{error}
___________________________________________________________________________
Contents of {local_dir}:
{contents}
___________________________________________________________________________
It seems that the {package} has not been built correctly.
If you have installed {package} from source, please do not forget
to build the package before using it: run `python setup.py install`
in the source directory.
{msg}"""
def raise_build_error(e):
# Raise a comprehensible error and list the contents of the
# directory to help debugging on the mailing list.
local_dir = os.path.split(__file__)[0]
msg = STANDARD_MSG
if local_dir == "pyflux/__check_build":
# Picking up the local install: this will work only if the
# install is an 'inplace build'
msg = INPLACE_MSG
dir_content = list()
for i, filename in enumerate(os.listdir(local_dir)):
if ((i + 1) % 3):
dir_content.append(filename.ljust(26))
else:
dir_content.append(filename + '\n')
contents = ''.join(dir_content).strip()
raise ImportError(ERROR_TEMPLATE.format(error=e,
local_dir=local_dir,
contents=contents,
package=PACKAGE_NAME,
msg=msg))
try:
from ._check_build import check_build
except ImportError as e:
raise_build_error(e) |
revitAPI/applicationGetAllFailureMessages.py | sixtysecondrevit/dynamoPython | 114 | 11088451 |
'''
GET ALL POSSIBLE FAILURE MESSAGES
'''
__author__ = '<NAME> - <EMAIL>'
__twitter__ = '@60secondrevit'
__github__ = '@sixtysecondrevit'
__version__ ='1.0.0'
# dynamo version - 1.3.3
# import common language runtime
import clr
# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
import RevitServices
# Import RevitAPI
clr.AddReference("RevitAPI")
# import all classes from Revit DB
from Autodesk.Revit.DB import *
# import document manager
from RevitServices.Persistence import DocumentManager
# import transaction manager
from RevitServices.Transactions import TransactionManager
# instantiate current document and application
doc = DocumentManager.Instance.CurrentDBDocument
uiapp = DocumentManager.Instance.CurrentUIApplication
app = uiapp.Application
# obtain all failure message Revit.DB elements
failureDefinitions = app.GetFailureDefinitionRegistry().ListAllFailureDefinitions()
# declare a list to append descriptions to
failureDescriptions = []
# iterate through the failure definitions and append description to output
for i in failureDefinitions:
failureDescriptions.append(i.GetDescriptionText())
# return the results
OUT = failureDescriptions
|
pandasdmx/tests/__init__.py | vedal/pandaSDMX | 105 | 11088452 | <filename>pandasdmx/tests/__init__.py
import importlib
from distutils import version
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from .data import BASE_PATH
def assert_pd_equal(left, right, **kwargs):
"""Assert equality of two pandas objects."""
if left is None:
return
method = {
pd.Series: pd.testing.assert_series_equal,
pd.DataFrame: pd.testing.assert_frame_equal,
np.ndarray: np.testing.assert_array_equal,
}[left.__class__]
method(left, right, **kwargs)
class MessageTest:
path: Path = BASE_PATH
filename: str
@pytest.fixture(scope="class")
def msg(self):
import pandasdmx
return pandasdmx.read_sdmx(self.path / self.filename)
# thanks to xarray
def _importorskip(modname, minversion=None):
try:
mod = importlib.import_module(modname)
has = True
if minversion is not None:
if LooseVersion(mod.__version__) < LooseVersion(minversion):
raise ImportError("Minimum version not satisfied")
except ImportError:
has = False
func = pytest.mark.skipif(not has, reason="requires {}".format(modname))
return has, func
def LooseVersion(vstring):
# When the development version is something like '0.10.9+aac7bfc', this
# function will just discard the git commit id.
vstring = vstring.split("+")[0]
return version.LooseVersion(vstring)
has_requests_cache, requires_requests_cache = _importorskip("requests_cache")
|
example/configure/app.py | RonnyPfannschmidt/dynaconf | 2,293 | 11088532 | from dynaconf import settings
settings.configure(settings_module="/tmp/configure_test/settings.py")
assert settings.MESSAGE == "Hello from tmp"
print(settings.MESSAGE) # noqa
|
alipay/aop/api/response/AlipayDaoweiOrderQueryResponse.py | snowxmas/alipay-sdk-python-all | 213 | 11088558 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.OrderLogisticsInfo import OrderLogisticsInfo
from alipay.aop.api.domain.ServiceOrderInfo import ServiceOrderInfo
class AlipayDaoweiOrderQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayDaoweiOrderQueryResponse, self).__init__()
self._buyer_user_id = None
self._gmt_create = None
self._gmt_modified = None
self._gmt_payment = None
self._gmt_refund = None
self._logistics_info = None
self._memo = None
self._order_no = None
self._order_status = None
self._payment_amount = None
self._real_amount = None
self._refund_amount = None
self._service_order_list = None
self._total_amount = None
@property
def buyer_user_id(self):
return self._buyer_user_id
@buyer_user_id.setter
def buyer_user_id(self, value):
self._buyer_user_id = value
@property
def gmt_create(self):
return self._gmt_create
@gmt_create.setter
def gmt_create(self, value):
self._gmt_create = value
@property
def gmt_modified(self):
return self._gmt_modified
@gmt_modified.setter
def gmt_modified(self, value):
self._gmt_modified = value
@property
def gmt_payment(self):
return self._gmt_payment
@gmt_payment.setter
def gmt_payment(self, value):
self._gmt_payment = value
@property
def gmt_refund(self):
return self._gmt_refund
@gmt_refund.setter
def gmt_refund(self, value):
self._gmt_refund = value
@property
def logistics_info(self):
return self._logistics_info
@logistics_info.setter
def logistics_info(self, value):
if isinstance(value, OrderLogisticsInfo):
self._logistics_info = value
else:
self._logistics_info = OrderLogisticsInfo.from_alipay_dict(value)
@property
def memo(self):
return self._memo
@memo.setter
def memo(self, value):
self._memo = value
@property
def order_no(self):
return self._order_no
@order_no.setter
def order_no(self, value):
self._order_no = value
@property
def order_status(self):
return self._order_status
@order_status.setter
def order_status(self, value):
self._order_status = value
@property
def payment_amount(self):
return self._payment_amount
@payment_amount.setter
def payment_amount(self, value):
self._payment_amount = value
@property
def real_amount(self):
return self._real_amount
@real_amount.setter
def real_amount(self, value):
self._real_amount = value
@property
def refund_amount(self):
return self._refund_amount
@refund_amount.setter
def refund_amount(self, value):
self._refund_amount = value
@property
def service_order_list(self):
return self._service_order_list
@service_order_list.setter
def service_order_list(self, value):
if isinstance(value, list):
self._service_order_list = list()
for i in value:
if isinstance(i, ServiceOrderInfo):
self._service_order_list.append(i)
else:
self._service_order_list.append(ServiceOrderInfo.from_alipay_dict(i))
@property
def total_amount(self):
return self._total_amount
@total_amount.setter
def total_amount(self, value):
self._total_amount = value
def parse_response_content(self, response_content):
response = super(AlipayDaoweiOrderQueryResponse, self).parse_response_content(response_content)
if 'buyer_user_id' in response:
self.buyer_user_id = response['buyer_user_id']
if 'gmt_create' in response:
self.gmt_create = response['gmt_create']
if 'gmt_modified' in response:
self.gmt_modified = response['gmt_modified']
if 'gmt_payment' in response:
self.gmt_payment = response['gmt_payment']
if 'gmt_refund' in response:
self.gmt_refund = response['gmt_refund']
if 'logistics_info' in response:
self.logistics_info = response['logistics_info']
if 'memo' in response:
self.memo = response['memo']
if 'order_no' in response:
self.order_no = response['order_no']
if 'order_status' in response:
self.order_status = response['order_status']
if 'payment_amount' in response:
self.payment_amount = response['payment_amount']
if 'real_amount' in response:
self.real_amount = response['real_amount']
if 'refund_amount' in response:
self.refund_amount = response['refund_amount']
if 'service_order_list' in response:
self.service_order_list = response['service_order_list']
if 'total_amount' in response:
self.total_amount = response['total_amount']
|
tests/test_rtcrtptransceiver.py | thedilletante/aiortc | 1,992 | 11088560 | <filename>tests/test_rtcrtptransceiver.py
from unittest import TestCase
from aiortc.rtcrtpparameters import RTCRtpCodecCapability
from aiortc.rtcrtptransceiver import RTCRtpTransceiver
class RTCRtpTransceiverTest(TestCase):
def test_codec_preferences(self):
transceiver = RTCRtpTransceiver("audio", None, None)
self.assertEqual(transceiver._preferred_codecs, [])
# set empty preferences
transceiver.setCodecPreferences([])
self.assertEqual(transceiver._preferred_codecs, [])
# set single codec
transceiver.setCodecPreferences(
[RTCRtpCodecCapability(mimeType="audio/PCMU", clockRate=8000, channels=1)]
)
self.assertEqual(
transceiver._preferred_codecs,
[RTCRtpCodecCapability(mimeType="audio/PCMU", clockRate=8000, channels=1)],
)
# set single codec (duplicated)
transceiver.setCodecPreferences(
[
RTCRtpCodecCapability(
mimeType="audio/PCMU", clockRate=8000, channels=1
),
RTCRtpCodecCapability(
mimeType="audio/PCMU", clockRate=8000, channels=1
),
]
)
self.assertEqual(
transceiver._preferred_codecs,
[RTCRtpCodecCapability(mimeType="audio/PCMU", clockRate=8000, channels=1)],
)
# set single codec (invalid)
with self.assertRaises(ValueError) as cm:
transceiver.setCodecPreferences(
[
RTCRtpCodecCapability(
mimeType="audio/bogus", clockRate=8000, channels=1
)
]
)
self.assertEqual(str(cm.exception), "Codec is not in capabilities")
|
src/gluonnlp/torch/models/__init__.py | leezu/gluon-nlp | 2,461 | 11088576 | <gh_stars>1000+
from . import transformer
from . import bert
|
malwareconfig/fileparser.py | BA7JCM/RATDecoders | 905 | 11088578 | import re
import hashlib
import pefile
import io
import yara
from binascii import hexlify
from androguard.core.bytecodes import apk
from androguard.core.bytecodes import dvm
from androguard import misc
from malwareconfig.yarascanner import YaraScanner
from zipfile import ZipFile
class FileParser:
def __init__(self, file_path=None, rawdata=None):
if file_path:
file_object = open(file_path, 'rb')
else:
file_object = io.BytesIO(rawdata)
file_object.name = "DummyFile.ext"
self.file_name = file_object.name
self.file_data = file_object.read()
self.file_size = len(self.file_data)
self.malware_name = ''
self.yarascan()
file_object.close()
def yarascan(self):
scanner = YaraScanner()
scanner.yara_scan(self.file_data)
if len(scanner.rule_list) > 0:
self.malware_name = scanner.rule_list[0]
def file_hash(self, hash_type="sha256"):
filehash = ''
if hash_type == "sha256":
filehash = hashlib.sha256(self.file_data).hexdigest()
if hash_type == 'md5':
filehash = hashlib.md5(self.file_data).hexdigest()
return filehash
def pe_resource_id(self, res_id):
"""
Read resource by its ID. Useful where normal pe file fails.
:return: list
"""
try:
rules = yara.compile(source='import "pe" rule a { condition: false }')
except yara.SyntaxError:
print("Error using Yara DotNet did you enable it?")
resource_list = []
def modules_callback(data):
for i, resource in enumerate(data.get('resources', [])):
if 'id' in resource:
if resource['id'] == res_id:
offset = resource['offset']
length = resource['length']
self.res_data = self.file_data[offset:offset + length]
elif 'name_string' in resource:
# Remove null bytes for a better comparison
res_name = resource['name_string'].decode('UTF-8').replace('\x00', '')
# Check both unicode and plain str versions of name
if res_name == res_id or resource['name_string'] == res_id:
offset = resource['offset']
length = resource['length']
self.res_data = self.file_data[offset:offset + length]
return yara.CALLBACK_CONTINUE
rules.match(data=self.file_data, modules_callback=modules_callback)
return self.res_data
def pe_resource_names(self):
"""
Read PE Resources and return a list of resource names
:return: list
"""
resource_names = []
pe = pefile.PE(data=self.file_data)
for rsrc in pe.DIRECTORY_ENTRY_RESOURCE.entries:
for entry in rsrc.directory.entries:
if entry.name is not None:
resource_names.append(entry.name.decode('utf-8'))
return resource_names
def pe_resource_by_name(self, resource_name):
"""
Extract a PE Resource from a binary by name
:param resource_name: str
:return: byte array
"""
offset = 0x00
size = 0x00
pe = pefile.PE(data=self.file_data)
for rsrc in pe.DIRECTORY_ENTRY_RESOURCE.entries:
for entry in rsrc.directory.entries:
if entry.name is not None:
if entry.name.__str__() == resource_name:
offset = entry.directory.entries[0].data.struct.OffsetToData
size = entry.directory.entries[0].data.struct.Size
return pe.get_memory_mapped_image()[offset:offset + size]
def dotnet_resource_names(self):
"""
Read .NET Resources and return a list of resource names
:return: list
"""
try:
rules = yara.compile(source='import "dotnet" rule a { condition: false }')
except yara.SyntaxError:
print("Error using Yara DotNet did you enable it?")
resource_list = []
def modules_callback(data):
for i, resource in enumerate(data.get('resources', [])):
resource_list.append(resource['name'])
return yara.CALLBACK_CONTINUE
rules.match(data=self.file_data, modules_callback=modules_callback)
return resource_list
def dotnet_resource_by_name(self, resource_name):
"""
Extract a .NET Resource by name
:param resource_name:
:return:
"""
try:
rules = yara.compile(source='import "dotnet" rule a { condition: false }')
except yara.SyntaxError:
print("Error using Yara DotNet did you enable it?")
def modules_callback(data):
for i, resource in enumerate(data.get('resources', [])):
if resource['name'] == resource_name:
offset = resource['offset']
length = resource['length']
self.res_data = self.file_data[offset:offset + length]
return yara.CALLBACK_CONTINUE
rules.match(data=self.file_data, modules_callback=modules_callback)
return self.res_data
def dotnet_guids(self):
"""
Exrtract GUIDS from a .NET Binary
:return: list of guids
"""
try:
rules = yara.compile(source='import "dotnet" rule a { condition: false }')
except yara.SyntaxError:
print("Error using Yara DotNet did you enable it?")
guid_list = []
def modules_callback(data):
for i, guid in enumerate(data.get('guids', [])):
guid_list.append(guid.decode('utf-8'))
# Type lib is also valid as a GUID for nanocore so lets add that.
guid_list.append(data.get('typelib').decode('utf-8'))
return yara.CALLBACK_CONTINUE
rules.match(data=self.file_data, modules_callback=modules_callback)
return guid_list
def dotnet_user_strings(self):
"""
Parse a list of User Strings from a .NET Binary file
:return: list of strings
"""
try:
rules = yara.compile(source='import "dotnet" rule a { condition: false }')
except yara.SyntaxError:
print("Error using Yara DotNet did you enable it?")
user_strings = []
def modules_callback(data):
for i, userstring in enumerate(data.get('user_strings', [])):
# Remove null bytes
userstring = userstring.replace(b'\x00', b'')
# Add string to list
try:
user_strings.append(userstring.decode('utf-8'))
except UnicodeDecodeError:
pass
return yara.CALLBACK_CONTINUE
rules.match(data=self.file_data, modules_callback=modules_callback)
return user_strings
def ascii_strings(self, min_len=4):
"""
parse a list of ascii strings from a binary file
:return:
"""
string_list = []
chars = b" !\"#\$%&\'\(\)\*\+,-\./0123456789:;<=>\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\[\]\^_`abcdefghijklmnopqrstuvwxyz\{\|\}\\\~\t"
regexp = b'[%s]{%d,}' % (chars, min_len)
pattern = re.compile(regexp)
for s in pattern.finditer(self.file_data):
string_list.append(s.group())
return string_list
def unicode_strings(self, min_len=4):
string_list = []
chars = r" !\"#\$%&\'\(\)\*\+,-\./0123456789:;<=>\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\[\]\^_`abcdefghijklmnopqrstuvwxyz\{\|\}\\\~\t"
regexp = b'((?:[%s]\x00){%d,})' % (chars, min_len)
pattern = re.compile(regexp)
for s in pattern.finditer(self.file_data):
string_list.append(s.group())
def file_from_zip(self, filename):
new_zip = io.BytesIO(self.file_data)
with ZipFile(new_zip, 'r') as open_zip:
for name in open_zip.namelist():
if name == filename:
zip_data = open_zip.read(name)
return zip_data
def zip_namelist(self):
new_zip = io.BytesIO(self.file_data)
filelist = []
with ZipFile(new_zip, 'r') as open_zip:
for name in open_zip.namelist():
filelist.append(name)
return filelist
def parse_apk(self):
a, d, dx = misc.AnalyzeAPK(self.file_data, raw=True)
return a,d,dx
def elf_list_sections(self):
"""
Read a list of sections from an elf binary
:return: list of section names
"""
try:
rules = yara.compile(source='import "elf" rule a { condition: false }')
except yara.SyntaxError:
print("Error using Yara ELF did you enable it?")
section_names = []
def modules_callback(data):
for i, section in enumerate(data.get('sections', [])):
section_names.append(section['name'].decode('utf-8'))
return yara.CALLBACK_CONTINUE
rules.match(data=self.file_data, modules_callback=modules_callback)
return section_names
def elf_section_by_name(self, resource_name):
"""
Extract an elf section by name
:param resource_name:
:return:
"""
try:
rules = yara.compile(source='import "elf" rule a { condition: false }')
except yara.SyntaxError:
print("Error using Yara ELF did you enable it?")
def modules_callback(data):
for i, section in enumerate(data.get('sections', [])):
if section['name'].decode('utf-8') == resource_name:
offset = section['offset']
length = section['size']
self.res_data = self.file_data[offset:offset + length]
return yara.CALLBACK_CONTINUE
rules.match(data=self.file_data, modules_callback=modules_callback)
return self.res_data |
tests/conftest.py | brunolnetto/python-statemachine | 264 | 11088632 | <filename>tests/conftest.py
# coding: utf-8
import pytest
from datetime import datetime
@pytest.fixture
def current_time():
return datetime.now()
@pytest.fixture
def campaign_machine():
"Define a new class for each test"
from statemachine import State, StateMachine
class CampaignMachine(StateMachine):
"A workflow machine"
draft = State('Draft', initial=True)
producing = State('Being produced')
closed = State('Closed')
add_job = draft.to(draft) | producing.to(producing)
produce = draft.to(producing)
deliver = producing.to(closed)
return CampaignMachine
@pytest.fixture
def campaign_machine_with_values():
"Define a new class for each test"
from statemachine import State, StateMachine
class CampaignMachineWithKeys(StateMachine):
"A workflow machine"
draft = State('Draft', initial=True, value=1)
producing = State('Being produced', value=2)
closed = State('Closed', value=3)
add_job = draft.to(draft) | producing.to(producing)
produce = draft.to(producing)
deliver = producing.to(closed)
return CampaignMachineWithKeys
@pytest.fixture
def traffic_light_machine():
from statemachine import StateMachine, State
class TrafficLightMachine(StateMachine):
"A traffic light machine"
green = State('Green', initial=True)
yellow = State('Yellow')
red = State('Red')
cycle = green.to(yellow) | yellow.to(red) | red.to(green)
@green.to(yellow)
def slowdown(self, *args, **kwargs):
return args, kwargs
@yellow.to(red)
def stop(self, *args, **kwargs):
return args, kwargs
@red.to(green)
def go(self, *args, **kwargs):
return args, kwargs
def on_cycle(self, *args, **kwargs):
return args, kwargs
return TrafficLightMachine
@pytest.fixture
def reverse_traffic_light_machine():
from statemachine import StateMachine, State
class ReverseTrafficLightMachine(StateMachine):
"A traffic light machine"
green = State('Green', initial=True)
yellow = State('Yellow')
red = State('Red')
stop = red.from_(yellow, green, red)
cycle = green.from_(red) | yellow.from_(green) | red.from_(yellow) | red.from_.itself()
return ReverseTrafficLightMachine
@pytest.fixture
def approval_machine(current_time):
from statemachine import StateMachine, State
class ApprovalMachine(StateMachine):
"A workflow machine"
requested = State('Requested', initial=True)
accepted = State('Accepted')
rejected = State('Rejected')
completed = State('Completed')
@requested.to(accepted, rejected)
def validate(self, *args, **kwargs):
if self.model.is_ok():
self.model.accepted_at = current_time
return self.model, self.accepted
else:
self.model.rejected_at = current_time
return self.model, self.rejected
@accepted.to(completed)
def complete(self):
self.model.completed_at = current_time
@requested.to(requested)
def update(self, **kwargs):
for k, v in kwargs.items():
setattr(self.model, k, v)
return self.model
@rejected.to(requested)
def retry(self):
self.model.rejected_at = None
return self.model
return ApprovalMachine
|
{{cookiecutter.project_name}}/src/sitesettings/serializers.py | techquila/Wagtail-Boilerplate | 124 | 11088648 | <reponame>techquila/Wagtail-Boilerplate
from rest_framework import serializers
from sitesettings.models import SiteSetting
class SiteSettingSerializer(serializers.ModelSerializer):
class Meta:
model = SiteSetting
fields = ["gtm_id", "cookie_content"]
|
MangaTaggerLib/models.py | Inpacchi/Manga-Tagger | 106 | 11088649 | <gh_stars>100-1000
import logging
from datetime import datetime
from pytz import timezone
from MangaTaggerLib.errors import MetadataNotCompleteError
from MangaTaggerLib.utils import AppSettings, compare
class Metadata:
_log = None
@classmethod
def fully_qualified_class_name(cls):
return f'{cls.__module__}.{cls.__name__}'
def __init__(self, manga_title, logging_info, jikan_details=None, anilist_details=None, details=None):
Metadata._log = logging.getLogger(self.fully_qualified_class_name())
self.search_value = manga_title
Metadata._log.info(f'Creating Metadata model for series "{manga_title}"...', extra=logging_info)
if jikan_details and anilist_details: # If details are grabbed from Jikan and Anilist APIs
self._construct_api_metadata(jikan_details, anilist_details, logging_info)
elif details: # If details were stored in the database
self._construct_database_metadata(details)
else:
Metadata._log.exception(MetadataNotCompleteError, extra=logging_info)
Metadata._log.debug(f'{self.search_value} Metadata Model: {self.__dict__.__str__()}')
logging_info['metadata'] = self.__dict__
Metadata._log.info('Successfully created Metadata model.', extra=logging_info)
def _construct_api_metadata(self, jikan_details, anilist_details, logging_info):
self._id = jikan_details['mal_id']
self.series_title = jikan_details['title']
if jikan_details['title_english'] == 'None' or jikan_details['title_english'] is None:
self.series_title_eng = None
else:
self.series_title_eng = jikan_details['title_english']
if jikan_details['title_japanese'] == 'None' or jikan_details['title_japanese'] is None:
self.series_title_jap = None
else:
self.series_title_jap = jikan_details['title_japanese']
self.status = jikan_details['status']
self.type = jikan_details['type']
self.description = jikan_details['synopsis']
self.mal_url = jikan_details['url']
self.anilist_url = anilist_details['siteUrl']
self.publish_date = None
self.genres = []
self.staff = {}
self.serializations = {}
self._construct_publish_date(jikan_details['published']['from'])
self._parse_genres(jikan_details['genres'], logging_info)
self._parse_staff(anilist_details['staff']['edges'], jikan_details['authors'], logging_info)
self._parse_serializations(jikan_details['serializations'], logging_info)
# self.scrape_date = datetime.now().date().strftime('%Y-%m-%d %I:%M %p')
self.scrape_date = timezone(AppSettings.timezone).localize(datetime.now()).strftime('%Y-%m-%d %I:%M %p %Z')
def _construct_database_metadata(self, details):
self._id = details['_id']
self.series_title = details['series_title']
self.series_title_eng = details['series_title_eng']
self.series_title_jap = details['series_title_jap']
self.status = details['status']
self.type = details['type']
self.description = details['description']
self.mal_url = details['mal_url']
self.anilist_url = details['anilist_url']
self.publish_date = details['publish_date']
self.genres = details['genres']
self.staff = details['staff']
self.serializations = details['serializations']
self.publish_date = details['publish_date']
self.scrape_date = details['scrape_date']
def _construct_publish_date(self, date):
date = date[:date.index('T')]
self.publish_date = datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m-%d')
Metadata._log.debug(f'Publish date constructed: {self.publish_date}')
def _parse_genres(self, genres, logging_info):
Metadata._log.info('Parsing genres...', extra=logging_info)
for genre in genres:
Metadata._log.debug(f'Genre found: {genre}')
self.genres.append(genre['name'])
def _parse_staff(self, anilist_staff, jikan_staff, logging_info):
Metadata._log.info('Parsing staff roles...', extra=logging_info)
roles = []
self.staff = {
'story': {},
'art': {}
}
for a_staff in anilist_staff:
Metadata._log.debug(f'Staff Member (Anilist): {a_staff}')
anilist_staff_name = ''
if a_staff['node']['name']['last'] is not None:
anilist_staff_name = a_staff['node']['name']['last']
if a_staff['node']['name']['first'] is not None:
anilist_staff_name += ', ' + a_staff['node']['name']['first']
names_to_compare = [anilist_staff_name]
if '' not in a_staff['node']['name']['alternative']:
for name in a_staff['node']['name']['alternative']:
names_to_compare.append(name)
for j_staff in jikan_staff:
for a_name in names_to_compare:
if compare(a_name, j_staff['name']) > .7:
Metadata._log.debug(f'Staff Member (MyAnimeList): {j_staff}')
role = a_staff['role'].lower()
if 'story & art' in role:
roles.append('story')
roles.append('art')
self._add_staff_member('story', a_staff, j_staff)
self._add_staff_member('art', a_staff, j_staff)
break
elif 'story' in role:
roles.append('story')
self._add_staff_member('story', a_staff, j_staff)
break
elif 'art' in role:
roles.append('art')
self._add_staff_member('art', a_staff, j_staff)
break
else:
Metadata._log.warning(f'Expected role not found for staff member "{a_name}"; instead'
f' found "{role}"', extra=logging_info)
break
# Validate expected roles for staff members
role_set = ['story', 'art']
if set(roles) != set(role_set):
Metadata._log.warning(f'Not all expected roles are present for series "{self.search_value}"; '
f'double check ID "{self._id}"', extra=logging_info)
def _add_staff_member(self, role, a_staff, j_staff):
self.staff[role][a_staff['node']['name']['full']] = {
'mal_id': j_staff['mal_id'],
'first_name': a_staff['node']['name']['first'],
'last_name': a_staff['node']['name']['last'],
'anilist_url': a_staff['node']['siteUrl'],
'mal_url': j_staff['url']
}
def _parse_serializations(self, serializations, logging_info):
Metadata._log.info('Parsing serializations...', extra=logging_info)
for serialization in serializations:
Metadata._log.debug(serialization)
self.serializations[serialization['name'].strip('.')] = {
'mal_id': serialization['mal_id'],
'url': serialization['url']
}
def test_value(self):
return {
'series_title': self.series_title,
'series_title_eng': self.series_title_eng,
'series_title_jap': self.series_title_jap,
'status': self.status,
'mal_url': self.mal_url,
'anilist_url': self.anilist_url,
'publish_date': self.publish_date,
'genres': self.genres,
'staff': self.staff,
'serializations': self.serializations
} |
moya/tests/testproject/wsgi.py | moyaproject/moya | 129 | 11088655 | # encoding=UTF-8
# This file serves the project in production
# See http://wsgi.readthedocs.org/en/latest/
from __future__ import unicode_literals
from moya.wsgi import Application
application = Application(
"./", ["local.ini", "production.ini"], server="main", logging="prodlogging.ini"
)
|
2019/quals/hardware-flagrom/src/emu8051/crosstest.py | iicarus-bit/google-ctf | 2,757 | 11088662 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import subprocess
import random
import os
BYTES_COUNT = 0x10000
STEP_COUNT = 50
S51_LOAD = 'file "tmp/test.ihex"'
S51_INFO_REG = 'info registers'
S51_STEP = 'step'
S51_QUIT = 'quit'
def perform_test():
with open("tmp/test", "wb") as f:
f.write(os.urandom(BYTES_COUNT))
subprocess.check_call(["srec_cat", "tmp/test", "-Binary", "-Output", "tmp/test.ihex", "-intel"])
p = subprocess.Popen(["s51"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
cmds = [
"fill iram 0 0xff 0",
"fill sfr 0x80 0xff 0",
"fill xram 0 0xffff 0",
"fill rom 0 0xffff 0",
S51_LOAD,
S51_INFO_REG
]
cmds.extend([S51_STEP] * STEP_COUNT)
cmds.append(S51_QUIT)
cmd = '\n'.join(cmds)
stdout, stderr = p.communicate(cmd)
"""
print "-" * 70
print stdout
print "-" * 70
print stderr
print "-" * 70
"""
result = []
instr = []
if ('TCON' in stdout or
'SCON' in stdout or
'IE' in stdout):
print "Ignoring results due to banned keyword appearing."
return True
s = stdout.split("Stop at ")[1:]
for r in s:
lines = r.splitlines()
instr.append(lines[6].strip())
pc = int(lines[0].split(':')[0][2:], 16)
result.append("pc: %.4x" % pc)
regset = lines[1][5:][:23]
#print lines[1]
result.append("regset: %s" % regset)
a = int(lines[2].split("ACC=")[1].strip().split(" ")[0], 16)
result.append("a: %.2x" % a)
psw = int(lines[3].split("PSW=")[1].strip().split(" ")[0], 16)
# NOTE: Ignore parity flag for now
psw &= 0xfe
result.append("psw: %.2x" % psw)
dptr = int(lines[5].split("DPTR=")[1].strip().split(" ")[0], 16)
result.append("dptr: %.4x" % dptr)
result.append("")
result_s51 = result
p = subprocess.Popen(["./emu8051_crosstest", "tmp/test"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout, stderr = p.communicate("%i" % STEP_COUNT)
result_emu8051 = stdout.splitlines()
print " %-40s %-40s" % ("-- s51", "-- emu8051")
i = 0
ic = 0
all_ok = True
break_soon = 15
while i < max(len(result_s51), len(result_emu8051)):
left = "-"
right = "-"
if i < len(result_s51):
left = result_s51[i]
if i < len(result_s51):
right = result_emu8051[i]
res = "OK"
if left.strip() != right.strip():
res = "!!"
all_ok = False
print "%s %-40s %-40s" % (res, left, right)
if left.startswith("dptr:"):
print
print instr[ic].replace("?", "---> ")
ic += 1
i += 1
if all_ok is False:
break_soon -= 1
if break_soon == 0:
print "----> Fast break (skipping rest of content)."
break
return all_ok
test_i = 0
while True:
print "-" * 70, "TEST %i" % test_i
test_i +=1
if not perform_test():
break
|
betfairlightweight/__init__.py | blake3/betfair | 300 | 11088667 | import logging
from .apiclient import APIClient
from .exceptions import BetfairError
from .streaming import StreamListener
from . import filters
from .__version__ import __title__, __version__, __author__
# Set default logging handler to avoid "No handler found" warnings.
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
mmdet3d/ops/iou3d/iou3d_utils.py | collector-m/SST | 217 | 11088670 | <filename>mmdet3d/ops/iou3d/iou3d_utils.py
import torch
from . import iou3d_cuda
# to be released
# try:
# import weighted_nms_ext
# except Exception as e:
# print(f'Error {e} when import weighted_nms.')
def boxes_iou_bev(boxes_a, boxes_b):
"""Calculate boxes IoU in the bird view.
Args:
boxes_a (torch.Tensor): Input boxes a with shape (M, 5).
boxes_b (torch.Tensor): Input boxes b with shape (N, 5).
Returns:
ans_iou (torch.Tensor): IoU result with shape (M, N).
"""
ans_iou = boxes_a.new_zeros(
torch.Size((boxes_a.shape[0], boxes_b.shape[0])))
iou3d_cuda.boxes_iou_bev_gpu(boxes_a.contiguous(), boxes_b.contiguous(),
ans_iou)
return ans_iou
def nms_gpu(boxes, scores, thresh, pre_maxsize=None, post_max_size=None):
"""Nms function with gpu implementation.
Args:
boxes (torch.Tensor): Input boxes with the shape of [N, 5]
([x1, y1, x2, y2, ry]).
scores (torch.Tensor): Scores of boxes with the shape of [N].
thresh (int): Threshold.
pre_maxsize (int): Max size of boxes before nms. Default: None.
post_maxsize (int): Max size of boxes after nms. Default: None.
Returns:
torch.Tensor: Indexes after nms.
"""
order = scores.sort(0, descending=True)[1]
if pre_maxsize is not None:
order = order[:pre_maxsize]
boxes = boxes[order].contiguous()
keep = torch.zeros(boxes.size(0), dtype=torch.long)
num_out = iou3d_cuda.nms_gpu(boxes, keep, thresh, boxes.device.index)
keep = order[keep[:num_out].cuda(boxes.device)].contiguous()
if post_max_size is not None:
keep = keep[:post_max_size]
return keep
def weighted_nms(boxes, data2merge, scores, thresh, merge_thresh, pre_maxsize=None, post_max_size=None):
"""Weighted NMS function with gpu implementation.
Modification from the cpu version in https://github.com/TuSimple/RangeDet
Args:
boxes (torch.Tensor): Input boxes with the shape of [N, 5]
([x1, y1, x2, y2, ry]).
data2merge (torch.Tensor): Input data with the shape of [N, C], corresponding to boxes.
If you want to merge origin boxes, just let data2merge == boxes
scores (torch.Tensor): Scores of boxes with the shape of [N].
thresh (float): Threshold.
merge_thresh (float): boxes have IoUs with the current box higher than the threshold with weighted merged by scores.
pre_maxsize (int): Max size of boxes before nms. Default: None.
post_maxsize (int): Max size of boxes after nms. Default: None.
Returns:
torch.Tensor: Indexes after nms.
"""
sorted_scores, order = scores.sort(0, descending=True)
if pre_maxsize is not None:
order = order[:pre_maxsize]
sorted_scores = sorted_scores[:pre_maxsize]
boxes = boxes[order].contiguous()
data2merge = data2merge[order].contiguous()
data2merge_score = torch.cat([data2merge, sorted_scores[:, None]], 1).contiguous()
output = torch.zeros_like(data2merge_score)
count = torch.zeros(boxes.size(0), dtype=torch.long, device=boxes.device)
assert data2merge_score.dim() == 2
keep = torch.zeros(boxes.size(0), dtype=torch.long)
num_out = weighted_nms_ext.wnms_gpu(boxes, data2merge_score, output, keep, count, thresh, merge_thresh, boxes.device.index)
keep = order[keep[:num_out].cuda(boxes.device)].contiguous()
assert output[num_out:, :].sum() == 0
assert (count[:num_out] > 0).all()
count = count[:num_out]
output = output[:num_out, :]
if post_max_size is not None:
keep = keep[:post_max_size]
output = output[:post_max_size]
count = count[:post_max_size]
return keep, output, count
def nms_normal_gpu(boxes, scores, thresh):
"""Normal non maximum suppression on GPU.
Args:
boxes (torch.Tensor): Input boxes with shape (N, 5).
scores (torch.Tensor): Scores of predicted boxes with shape (N).
thresh (torch.Tensor): Threshold of non maximum suppression.
Returns:
torch.Tensor: Remaining indices with scores in descending order.
"""
order = scores.sort(0, descending=True)[1]
boxes = boxes[order].contiguous()
keep = torch.zeros(boxes.size(0), dtype=torch.long)
num_out = iou3d_cuda.nms_normal_gpu(boxes, keep, thresh,
boxes.device.index)
return order[keep[:num_out].cuda(boxes.device)].contiguous()
|
devito/ir/__init__.py | BrunoMot/devito | 204 | 11088682 | from devito.ir.support import * # noqa
from devito.ir.equations import * # noqa
from devito.ir.clusters import * # noqa
from devito.ir.iet import * # noqa
|
views/view_alert.py | TomasTorresB/nerve | 365 | 11088734 | from core.redis import rds
from core.security import session_required
from flask import (
Blueprint,
render_template,
flash,
redirect
)
alert = Blueprint('alert', __name__,
template_folder='templates')
@alert.route('/alert/view/<alert_id>')
@session_required
def view_alert(alert_id):
vuln = rds.get_vuln_by_id(alert_id)
if not vuln:
flash('Could not display alert.', 'error')
return redirect('/vulnerabilities')
return render_template('alert.html', vuln={'key':alert_id,'data':vuln})
@alert.route('/alert/resolve/<alert_id>')
@session_required
def view_resolve_alert(alert_id):
if not rds.get_vuln_by_id(alert_id):
flash('Could not resolve alert.', 'error')
return redirect('/vulnerabilities')
rds.delete(alert_id)
flash('Resolved alert successfully.', 'success')
return redirect('/vulnerabilities') |
Exscript/util/event.py | saveshodhan/exscript | 226 | 11088749 | #
# Copyright (C) 2010-2017 <NAME>
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
A simple signal/event mechanism.
"""
from __future__ import print_function, absolute_import
from builtins import object
from threading import Lock
from . import weakmethod
class Event(object):
"""
A simple signal/event mechanism, to be used like this::
def mycallback(arg, **kwargs):
print(arg, kwargs['foo'])
myevent = Event()
myevent.connect(mycallback)
myevent.emit('test', foo = 'bar')
# Or just: myevent('test', foo = 'bar')
"""
def __init__(self):
"""
Constructor.
"""
# To save memory, we do NOT init the subscriber attributes with
# lists. Unfortunately this makes a lot of the code in this class
# more messy than it should be, but events are used so widely in
# Exscript that this change makes a huge difference to the memory
# footprint.
self.lock = None
self.weak_subscribers = None
self.hard_subscribers = None
def __call__(self, *args, **kwargs):
"""
Like emit().
"""
return self.emit(*args, **kwargs)
def connect(self, callback, *args, **kwargs):
"""
Connects the event with the given callback.
When the signal is emitted, the callback is invoked.
.. HINT::
The signal handler is stored with a hard reference, so you
need to make sure to call :class:`disconnect()` if you want the handler
to be garbage collected.
:type callback: object
:param callback: The callback function.
:type args: tuple
:param args: Optional arguments passed to the callback.
:type kwargs: dict
:param kwargs: Optional keyword arguments passed to the callback.
"""
if self.is_connected(callback):
raise AttributeError('callback is already connected')
if self.hard_subscribers is None:
self.hard_subscribers = []
self.hard_subscribers.append((callback, args, kwargs))
def listen(self, callback, *args, **kwargs):
"""
Like :class:`connect()`, but uses a weak reference instead of a
normal reference.
The signal is automatically disconnected as soon as the handler
is garbage collected.
.. HINT::
Storing signal handlers as weak references means that if
your handler is a local function, it may be garbage collected. To
prevent this, use :class:`connect()` instead.
:type callback: object
:param callback: The callback function.
:type args: tuple
:param args: Optional arguments passed to the callback.
:type kwargs: dict
:param kwargs: Optional keyword arguments passed to the callback.
:rtype: :class:`Exscript.util.weakmethod.WeakMethod`
:return: The newly created weak reference to the callback.
"""
if self.lock is None:
self.lock = Lock()
with self.lock:
if self.is_connected(callback):
raise AttributeError('callback is already connected')
if self.weak_subscribers is None:
self.weak_subscribers = []
ref = weakmethod.ref(callback, self._try_disconnect)
self.weak_subscribers.append((ref, args, kwargs))
return ref
def n_subscribers(self):
"""
Returns the number of connected subscribers.
:rtype: int
:return: The number of subscribers.
"""
hard = self.hard_subscribers and len(self.hard_subscribers) or 0
weak = self.weak_subscribers and len(self.weak_subscribers) or 0
return hard + weak
def _hard_callbacks(self):
return [s[0] for s in self.hard_subscribers]
def _weakly_connected_index(self, callback):
if self.weak_subscribers is None:
return None
weak = [s[0].get_function() for s in self.weak_subscribers]
try:
return weak.index(callback)
except ValueError:
return None
def is_connected(self, callback):
"""
Returns True if the event is connected to the given function.
:type callback: object
:param callback: The callback function.
:rtype: bool
:return: Whether the signal is connected to the given function.
"""
index = self._weakly_connected_index(callback)
if index is not None:
return True
if self.hard_subscribers is None:
return False
return callback in self._hard_callbacks()
def emit(self, *args, **kwargs):
"""
Emits the signal, passing the given arguments to the callbacks.
If one of the callbacks returns a value other than None, no further
callbacks are invoked and the return value of the callback is
returned to the caller of emit().
:type args: tuple
:param args: Optional arguments passed to the callbacks.
:type kwargs: dict
:param kwargs: Optional keyword arguments passed to the callbacks.
:rtype: object
:return: Returns None if all callbacks returned None. Returns
the return value of the last invoked callback otherwise.
"""
if self.hard_subscribers is not None:
for callback, user_args, user_kwargs in self.hard_subscribers:
kwargs.update(user_kwargs)
result = callback(*args + user_args, **kwargs)
if result is not None:
return result
if self.weak_subscribers is not None:
for callback, user_args, user_kwargs in self.weak_subscribers:
kwargs.update(user_kwargs)
# Even though WeakMethod notifies us when the underlying
# function is destroyed, and we remove the item from the
# the list of subscribers, there is no guarantee that
# this notification has already happened because the garbage
# collector may run while this loop is executed.
# Disabling the garbage collector temporarily also does
# not work, because other threads may be trying to do
# the same, causing yet another race condition.
# So the only solution is to skip such functions.
function = callback.get_function()
if function is None:
continue
result = function(*args + user_args, **kwargs)
if result is not None:
return result
def _try_disconnect(self, ref):
"""
Called by the weak reference when its target dies.
In other words, we can assert that self.weak_subscribers is not
None at this time.
"""
with self.lock:
weak = [s[0] for s in self.weak_subscribers]
try:
index = weak.index(ref)
except ValueError:
# subscriber was already removed by a call to disconnect()
pass
else:
self.weak_subscribers.pop(index)
def disconnect(self, callback):
"""
Disconnects the signal from the given function.
:type callback: object
:param callback: The callback function.
"""
if self.weak_subscribers is not None:
with self.lock:
index = self._weakly_connected_index(callback)
if index is not None:
self.weak_subscribers.pop(index)[0]
if self.hard_subscribers is not None:
try:
index = self._hard_callbacks().index(callback)
except ValueError:
pass
else:
self.hard_subscribers.pop(index)
def disconnect_all(self):
"""
Disconnects all connected functions from all signals.
"""
self.hard_subscribers = None
self.weak_subscribers = None
|
FreeRTOS/Test/VeriFast/scripts/extract.py | JVVJV/FreeRTOS | 2,603 | 11088796 | #!/usr/bin/env python3
from __future__ import print_function
import sys
from enum import Enum
class Extractor(object):
@staticmethod
def __parse_ctags(tags_filename):
def convert_excmd(excmd):
assert excmd.endswith(';"')
linenum = excmd[:-2] # remove ';"'
return int(linenum)
result = {}
with open(tags_filename) as f:
for line in f:
if line.startswith('!'):
continue
parts = line.split('\t')
funcname = parts[0]
funcfile = parts[1]
linenum = convert_excmd(parts[2])
result[funcname] = (funcfile, linenum)
return result
def __init__(self, tags_filename):
self.map = Extractor.__parse_ctags(tags_filename)
class State(Enum):
INIT = 0
HEAD = 1
BODY = 2
def text_of_funcname(self, funcname):
if funcname not in self.map:
return []
funcfile, linenum = self.map[funcname]
result = []
state, bracecount = Extractor.State.INIT, 0
with open(funcfile) as f:
for i, line in enumerate(f, start=1): # ctags counts linenums from 1
if state == Extractor.State.INIT and linenum <= i:
state = Extractor.State.HEAD
if state == Extractor.State.HEAD:
result.append(line)
lbrace = line.count('{')
rbrace = line.count('}')
bracecount += lbrace
bracecount -= rbrace
if '{' in line:
state = Extractor.State.BODY
continue
if state == Extractor.State.BODY:
result.append(line)
lbrace = line.count('{')
rbrace = line.count('}')
bracecount += lbrace
bracecount -= rbrace
if bracecount == 0:
break
return result
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: %s <tagfile> <funcname>" % sys.argv[0])
sys.exit(1)
tag_filename = sys.argv[1]
funcname = sys.argv[2]
extractor = Extractor('tags')
result = extractor.text_of_funcname(funcname)
print(''.join(result))
sys.exit(0)
|
components/crud-web-apps/common/backend/kubeflow/kubeflow/crud_backend/authn.py | zhyon404/kubeflow | 9,272 | 11088811 | <reponame>zhyon404/kubeflow<filename>components/crud-web-apps/common/backend/kubeflow/kubeflow/crud_backend/authn.py
import logging
from flask import Blueprint, current_app, request
from werkzeug.exceptions import Unauthorized
from . import config, settings
bp = Blueprint("authn", __name__)
log = logging.getLogger(__name__)
def get_username():
if settings.USER_HEADER not in request.headers:
log.debug("User header not present!")
username = None
else:
user = request.headers[settings.USER_HEADER]
username = user.replace(settings.USER_PREFIX, "")
log.debug("User: '%s' | Headers: '%s' '%s'",
username, settings.USER_HEADER, settings.USER_PREFIX)
return username
def no_authentication(func):
"""
This decorator will be used to disable the default authentication check
for the decorated endpoint.
"""
func.no_authentication = True
return func
@bp.before_app_request
def check_authentication():
"""
By default all the app's routes will be subject to authentication. If we
want a function to not have authentication check then we can decorate it
with the `no_authentication` decorator.
"""
if config.dev_mode_enabled():
log.debug("Skipping authentication check in development mode")
return
if settings.DISABLE_AUTH:
log.info("APP_DISABLE_AUTH set to True. Skipping authentication check")
return
# If a function was decorated with `no_authentication` then we will skip
# the authn check
if request.endpoint and getattr(
current_app.view_functions[request.endpoint],
"no_authentication",
False,
):
# when no return value is specified the designated route function will
# be called.
return
user = get_username()
if user is None:
# Return an unauthenticated response and don't call the route's
# assigned function.
raise Unauthorized("No user detected.")
else:
log.info("Handling request for user: %s", user)
return
|
notebooks-text-format/gaussian_param_inf_1d_numpyro.py | arpitvaghela/probml-notebooks | 166 | 11088830 | # ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.3
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/gaussian_param_inf_1d_numpyro.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="11FOMaCs74vK"
# # Inference for the parameters of a 1d Gaussian using a non-conjugate prior
#
# We illustrate various inference methods using the example in sec 4.3 ("Gaussian model of height") of [Statistical Rethinking ed 2](https://xcelab.net/rm/statistical-rethinking/). This requires computing $p(\mu,\sigma|D)$ using a Gaussian likelihood but a non-conjugate prior.
# The numpyro code is from [Du Phan's site](https://fehiepsi.github.io/rethinking-numpyro/04-geocentric-models.html).
#
#
#
#
# + id="Z5wEIBws1D6i"
import numpy as np
np.set_printoptions(precision=3)
import matplotlib.pyplot as plt
import math
import os
import warnings
import pandas as pd
#from scipy.interpolate import BSpline
#from scipy.stats import gaussian_kde
# + colab={"base_uri": "https://localhost:8080/"} id="Rn0dCvGCr1YC" outputId="5a6919ff-fd7b-4205-d534-f4daae657c20"
# !mkdir figures
# + id="Xo0ejB5-7M3-"
# !pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro
# + colab={"base_uri": "https://localhost:8080/"} id="qB5V5upMOMkP" outputId="47aa9cd9-16c9-4033-b48f-8dfa0ef5ff0d"
import jax
print("jax version {}".format(jax.__version__))
print("jax backend {}".format(jax.lib.xla_bridge.get_backend().platform))
import jax.numpy as jnp
from jax import random, vmap
rng_key = random.PRNGKey(0)
rng_key, rng_key_ = random.split(rng_key)
# + id="lfOH0V2Knz_p"
import numpyro
import numpyro.distributions as dist
from numpyro.distributions import constraints
from numpyro.distributions.transforms import AffineTransform
from numpyro.diagnostics import hpdi, print_summary
from numpyro.infer import Predictive
from numpyro.infer import MCMC, NUTS
from numpyro.infer import SVI, Trace_ELBO, init_to_value
from numpyro.infer.autoguide import AutoLaplaceApproximation
import numpyro.optim as optim
# + colab={"base_uri": "https://localhost:8080/"} id="JZjT_8cKA1pP" outputId="113013a5-dc9d-4862-ef72-b6f2fa8b7dbd"
# !pip install arviz
import arviz as az
# + [markdown] id="qB83jECL_oWq"
# # Data
#
# We use the "Howell" dataset, which consists of measurements of height, weight, age and sex, of a certain foraging tribe, collected by <NAME>.
# + colab={"base_uri": "https://localhost:8080/", "height": 370} id="312Xjmye_2Lg" outputId="ae77d5a6-593e-43f5-a80a-009beff4f51c"
#url = 'https://github.com/fehiepsi/rethinking-numpyro/tree/master/data/Howell1.csv?raw=True'
url = 'https://raw.githubusercontent.com/fehiepsi/rethinking-numpyro/master/data/Howell1.csv'
Howell1 = pd.read_csv(url, sep=';')
d = Howell1
d.info()
d.head()
# + id="_mrNmkiEBPlH"
# get data for adults
d2 = d[d.age >= 18]
N = len(d2)
ndx = jax.random.permutation(rng_key, N)
data = d2.height.values[ndx]
N = 20 # take a subset of the 354 samples
data = data[:N]
# + [markdown] id="aSAr5iy2E0Cr"
# Empirical mean and std.
# + colab={"base_uri": "https://localhost:8080/"} id="QFYvhonkEpb-" outputId="7eb59b2c-fb2b-4a4f-d344-f9b1929f3ac4"
print(len(data))
print(np.mean(data))
print(np.std(data))
# + [markdown] id="oXUj4nsaCbR1"
# # Model
#
# We use the following model for the heights (in cm):
# $$
# \begin{align}
# h_i &\sim N(\mu,\sigma) \\
# \mu &\sim N(178, 20) \\
# \sigma &\sim U(0,50)
# \end{align}
# $$
#
# The prior for $\mu$ has a mean 178cm, since that is the height of
# Richard McElreath, the author of the "Statisical Rethinking" book.
# The standard deviation is 20, so that 90\% of people lie in the range 138--218.
#
# The prior for $\sigma$ has a lower bound of 0 (since it must be positive), and an upper bound of 50, so that the interval $[\mu-\sigma, \mu+\sigma]$ has width 100cm, which seems sufficiently large to capture human heights.
#
#
# Note that this is not a conjugate prior, so we will just approximate the posterior.
# But since there are just 2 unknowns, this will be easy.
#
# + [markdown] id="52c6OQskEZiT"
# # Grid posterior
# + colab={"base_uri": "https://localhost:8080/"} id="6lFJF82pEac_" outputId="96bd96a9-2444-481b-d458-436ea79a4e7e"
mu_prior = dist.Normal(178, 20)
sigma_prior = dist.Uniform(0, 50)
mu_range = [150, 160]
sigma_range = [4, 14]
ngrid = 100
plot_square = False
mu_list = jnp.linspace(start=mu_range[0], stop=mu_range[1], num=ngrid)
sigma_list = jnp.linspace(start=sigma_range[0], stop=sigma_range[1], num=ngrid)
mesh = jnp.meshgrid(mu_list, sigma_list)
print([mesh[0].shape, mesh[1].shape])
print(mesh[0].reshape(-1).shape)
post = {"mu": mesh[0].reshape(-1), "sigma": mesh[1].reshape(-1)}
post["LL"] = vmap(
lambda mu, sigma: jnp.sum(dist.Normal(mu, sigma).log_prob(data))
)(post["mu"], post["sigma"])
logprob_mu = mu_prior.log_prob(post["mu"])
logprob_sigma = sigma_prior.log_prob(post["sigma"])
post["prob"] = post["LL"] + logprob_mu + logprob_sigma
post["prob"] = jnp.exp(post["prob"] - jnp.max(post["prob"]))
prob = post["prob"] / jnp.sum(post["prob"]) # normalize over the grid
# + colab={"base_uri": "https://localhost:8080/", "height": 512} id="Cwg1FZlhGS-T" outputId="1f230ecd-f166-4a85-8988-e853989d03b6"
prob2d = prob.reshape(ngrid, ngrid)
prob_mu = jnp.sum(prob2d, axis=0)
prob_sigma = jnp.sum(prob2d, axis=1)
plt.figure()
plt.plot(mu_list, prob_mu, label='mu')
plt.legend()
plt.savefig('figures/gauss_params_1d_post_grid_marginal_mu.pdf', dpi=300)
plt.show()
plt.figure()
plt.plot(sigma_list, prob_sigma, label='sigma')
plt.legend()
plt.savefig('figures/gauss_params_1d_post_grid_marginal_sigma.pdf', dpi=300)
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 285} id="9wjZvO2GEfn-" outputId="4f68306b-ec27-499f-9924-85a382fef05b"
plt.contour(
post["mu"].reshape(ngrid, ngrid),
post["sigma"].reshape(ngrid, ngrid),
post["prob"].reshape(ngrid, ngrid),
)
plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$')
if plot_square: plt.axis('square')
plt.savefig('figures/gauss_params_1d_post_grid_contours.pdf', dpi=300)
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 285} id="ARQMye8bEf2J" outputId="392e01a8-d763-474b-ac32-9a5cfd84d5e6"
plt.imshow(
post["prob"].reshape(ngrid, ngrid),
origin="lower",
extent=(mu_range[0], mu_range[1], sigma_range[0], sigma_range[1]),
aspect="auto",
)
plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$')
if plot_square: plt.axis('square')
plt.savefig('figures/gauss_params_1d_post_grid_heatmap.pdf', dpi=300)
plt.show()
# + [markdown] id="YYSMPLUYF_0b"
# Posterior samples.
# + id="qx_q5zTYFzsa"
nsamples = 5000 #int(1e4)
sample_rows = dist.Categorical(probs=prob).sample(random.PRNGKey(0), (nsamples,))
sample_mu = post["mu"][sample_rows]
sample_sigma = post["sigma"][sample_rows]
samples = {'mu': sample_mu, 'sigma': sample_sigma}
# + colab={"base_uri": "https://localhost:8080/", "height": 658} id="j71jJlWnpLRP" outputId="3af318a1-076e-4668-d7e0-2453722f3efe"
print_summary(samples, 0.95, False)
plt.scatter(samples['mu'], samples['sigma'], s=64, alpha=0.1, edgecolor="none")
plt.xlim(mu_range[0], mu_range[1])
plt.ylim(sigma_range[0], sigma_range[1])
plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$')
plt.axis('square')
plt.show()
az.plot_kde(samples['mu'], samples['sigma']);
plt.xlim(mu_range[0], mu_range[1])
plt.ylim(sigma_range[0], sigma_range[1])
plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$')
if plot_square: plt.axis('square')
plt.savefig('figures/gauss_params_1d_post_grid.pdf', dpi=300)
plt.show()
# + [markdown] id="GFzitSc_ksgZ"
# posterior marginals.
# + colab={"base_uri": "https://localhost:8080/", "height": 570} id="depUbCulkuB9" outputId="5a9539a6-b4ac-4ac5-e24b-a59b6c93dbb0"
print(hpdi(samples['mu'], 0.95))
print(hpdi(samples['sigma'], 0.95))
fig, ax = plt.subplots()
az.plot_kde(samples['mu'], ax=ax, label=r'$\mu$')
fig, ax = plt.subplots()
az.plot_kde(samples['sigma'], ax=ax, label=r'$\sigma$')
# + [markdown] id="luc7FkMXGmEw"
# # Laplace approximation
#
# See [the documentation](http://num.pyro.ai/en/stable/autoguide.html#autolaplaceapproximation)
# + [markdown] id="4lpe17A-LUUE"
# ## Optimization
# + colab={"base_uri": "https://localhost:8080/", "height": 297} id="GiStL67NGnJi" outputId="9841d3e4-5e77-4241-b8d5-367cc9fad1b4"
def model(data):
mu = numpyro.sample("mu", mu_prior)
sigma = numpyro.sample("sigma", sigma_prior)
numpyro.sample("height", dist.Normal(mu, sigma), obs=data)
guide = AutoLaplaceApproximation(model)
svi = SVI(model, guide, optim.Adam(1), Trace_ELBO(), data=data)
svi_result = svi.run(random.PRNGKey(0), 2000)
plt.figure()
plt.plot(svi_result.losses)
# + colab={"base_uri": "https://localhost:8080/", "height": 297} id="bwrwHS73IJec" outputId="b044a435-9ec7-46da-d053-b1ae0a475ead"
start = {"mu": data.mean(), "sigma": data.std()}
guide = AutoLaplaceApproximation(model, init_loc_fn=init_to_value(values=start))
svi = SVI(model, guide, optim.Adam(0.1), Trace_ELBO(), data=data)
svi_result = svi.run(random.PRNGKey(0), 2000)
plt.figure()
plt.plot(svi_result.losses)
# + [markdown] id="6_s0bDxqIUEi"
# ## Posterior samples.
# + id="K6dQBDTGH3ex"
samples = guide.sample_posterior(random.PRNGKey(1), svi_result.params, (nsamples,))
# + colab={"base_uri": "https://localhost:8080/", "height": 662} id="PKb6dlS_pSKk" outputId="9fcc3d9f-62a5-43de-d535-b206a42df86d"
print_summary(samples, 0.95, False)
plt.scatter(samples['mu'], samples['sigma'], s=64, alpha=0.1, edgecolor="none")
plt.xlim(mu_range[0], mu_range[1])
plt.ylim(sigma_range[0], sigma_range[1])
plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$')
plt.show()
az.plot_kde(samples['mu'], samples['sigma']);
plt.xlim(mu_range[0], mu_range[1])
plt.ylim(sigma_range[0], sigma_range[1])
plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$')
if plot_square: plt.axis('square')
plt.savefig('figures/gauss_params_1d_post_laplace.pdf', dpi=300)
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 570} id="hag3rzUcpcv3" outputId="ae69555f-63cc-4897-e6aa-62a7784ad044"
print(hpdi(samples['mu'], 0.95))
print(hpdi(samples['sigma'], 0.95))
fig, ax = plt.subplots()
az.plot_kde(samples['mu'], ax=ax, label=r'$\mu$')
fig, ax = plt.subplots()
az.plot_kde(samples['sigma'], ax=ax, label=r'$\sigma$')
# + [markdown] id="gZHkO4iBLBv-"
# ## Extract 2d joint posterior
# + [markdown] id="E21dH5NjMnJJ"
# The Gaussian approximation is over transformed parameters.
# + colab={"base_uri": "https://localhost:8080/"} id="nUPNkY_ILDz2" outputId="4bf84d41-feea-460d-972b-f0043a290d9b"
post = guide.get_posterior(svi_result.params)
print(post.mean)
print(post.covariance_matrix)
# + colab={"base_uri": "https://localhost:8080/"} id="kckoWeKhUPDr" outputId="e1d56ba4-db33-4cf3-c790-210b331dd10d"
def logit(p):
return jnp.log(p/(1-p))
def sigmoid(a):
return 1/(1+jnp.exp(-a))
scale=50; print(logit(7.7/scale)); print(sigmoid(-1.7)*scale)
# + colab={"base_uri": "https://localhost:8080/"} id="pzubiiMsXJPG" outputId="b8a16edb-5a94-402d-b0da-359642a5911f"
unconstrained_samples = post.sample(rng_key, sample_shape=(nsamples,))
constrained_samples = guide._unpack_and_constrain(unconstrained_samples, svi_result.params)
print(unconstrained_samples.shape)
print(jnp.mean(unconstrained_samples, axis=0))
print(jnp.mean(constrained_samples['mu'], axis=0))
print(jnp.mean(constrained_samples['sigma'], axis=0))
# + [markdown] id="rMv_7FRZMqAY"
# We can sample from the posterior, which return results in the original parameterization.
# + colab={"base_uri": "https://localhost:8080/"} id="UdnupIg0IuTk" outputId="31ec5ce9-fdcd-44bf-cca7-e0a117f97366"
samples = guide.sample_posterior(random.PRNGKey(1), params, (nsamples,))
x = jnp.stack(list(samples.values()), axis=0)
print(x.shape)
print('mean of ssamples\n', jnp.mean(x, axis=1))
vcov = jnp.cov(x)
print('cov of samples\n', vcov) # variance-covariance matrix
# correlation matrix
R = vcov / jnp.sqrt(jnp.outer(jnp.diagonal(vcov), jnp.diagonal(vcov)))
print('corr of samples\n', R)
# + [markdown] id="rjvvHbB0NNme"
# # Variational inference
#
# We use
# $q(\mu,\sigma) = N(\mu|m,s) Ga(\sigma|a,b)$
#
# + colab={"base_uri": "https://localhost:8080/", "height": 363} id="rE6C50KlL3hQ" outputId="24887973-fe0d-4fd0-b283-6b8129d05129"
def guide(data):
data_mean = jnp.mean(data)
data_std = jnp.std(data)
m = numpyro.param("m", data_mean)
s = numpyro.param("s", 10, constraint=constraints.positive)
a = numpyro.param("a", data_std, constraint=constraints.positive)
b = numpyro.param("b", 1, constraint=constraints.positive)
mu = numpyro.sample("mu", dist.Normal(m, s))
sigma = numpyro.sample("sigma", dist.Gamma(a, b))
optimizer = numpyro.optim.Momentum(step_size=0.001, mass=0.1)
svi = SVI(model, guide, optimizer, loss=Trace_ELBO())
nsteps = 2000
svi_result = svi.run(rng_key_, nsteps, data=data)
print(svi_result.params)
print(svi_result.losses.shape)
plt.plot(svi_result.losses)
plt.title("ELBO")
plt.xlabel("step")
plt.ylabel("loss");
# + [markdown] id="k779nIjdTxu4"
# ## Extract Variational parameters.
#
# + colab={"base_uri": "https://localhost:8080/"} id="7ufCMqoZTpNV" outputId="3d32cd2f-a6c0-4f64-8ac6-bcbbb4337871"
print(svi_result.params)
a = np.array(svi_result.params['a'])
b = np.array(svi_result.params['b'])
m = np.array(svi_result.params['m'])
s = np.array(svi_result.params['s'])
# + colab={"base_uri": "https://localhost:8080/"} id="v51AAfH0Vh6G" outputId="4c51c80c-bb25-4f43-9267-0b04e0726d2a"
print('empirical mean', jnp.mean(data))
print('empirical std', jnp.std(data))
print(r'posterior mean and std of $\mu$')
post_mean = dist.Normal(m, s)
print([post_mean.mean, jnp.sqrt(post_mean.variance)])
print(r'posterior mean and std of unconstrained $\sigma$')
post_sigma = dist.Gamma(a,b)
print([post_sigma.mean, jnp.sqrt(post_sigma.variance)])
# + [markdown] id="jMb50OhpT10F"
# ## Posterior samples
# + id="l9KzXRibQaA2"
predictive = Predictive(guide, params=svi_result.params, num_samples=nsamples)
samples = predictive(rng_key, data)
# + colab={"base_uri": "https://localhost:8080/", "height": 662} id="qiVYfYuUqYCO" outputId="bad3ed9c-c808-485c-c510-92472b5f6356"
print_summary(samples, 0.95, False)
plt.scatter(samples['mu'], samples['sigma'], s=64, alpha=0.1, edgecolor="none")
plt.xlim(mu_range[0], mu_range[1])
plt.ylim(sigma_range[0], sigma_range[1])
plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$')
plt.show()
az.plot_kde(samples['mu'], samples['sigma']);
plt.xlim(mu_range[0], mu_range[1])
plt.ylim(sigma_range[0], sigma_range[1])
plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$')
if plot_square: plt.axis('square')
plt.savefig('figures/gauss_params_1d_post_vi.pdf', dpi=300)
plt.show()
# + colab={"base_uri": "https://localhost:8080/", "height": 570} id="98TZ70O_q34k" outputId="901b6055-d0ea-4960-88b2-e41045ccaed1"
print(hpdi(samples['mu'], 0.95))
print(hpdi(samples['sigma'], 0.95))
fig, ax = plt.subplots()
az.plot_kde(samples['mu'], ax=ax, label=r'$\mu$')
fig, ax = plt.subplots()
az.plot_kde(samples['sigma'], ax=ax, label=r'$\sigma$')
# + [markdown] id="Egqg5eCHcGP2"
# # MCMC
# + colab={"base_uri": "https://localhost:8080/"} id="3qy3_SVgcCpR" outputId="c157d168-48bb-415c-a18b-81fedb66695a"
conditioned_model = numpyro.handlers.condition(model, {'data': data})
nuts_kernel = NUTS(conditioned_model)
mcmc = MCMC(nuts_kernel, num_warmup=100, num_samples=nsamples)
mcmc.run(rng_key_, data)
mcmc.print_summary()
samples = mcmc.get_samples()
# + colab={"base_uri": "https://localhost:8080/", "height": 662} id="R7ZEfXCkq0gI" outputId="d363495e-4c96-4bfc-9d65-f341ae1cbbbe"
print_summary(samples, 0.95, False)
plt.scatter(samples['mu'], samples['sigma'], s=64, alpha=0.1, edgecolor="none")
plt.xlim(mu_range[0], mu_range[1])
plt.ylim(sigma_range[0], sigma_range[1])
plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$')
plt.show()
az.plot_kde(samples['mu'], samples['sigma']);
plt.xlim(mu_range[0], mu_range[1])
plt.ylim(sigma_range[0], sigma_range[1])
plt.xlabel(r'$\mu$')
plt.ylabel(r'$\sigma$')
if plot_square: plt.axis('square')
plt.savefig('figures/gauss_params_1d_post_mcmc.pdf', dpi=300)
plt.show()
|
freight/api/serializer/__init__.py | armandomeeuwenoord/freight | 562 | 11088831 | <reponame>armandomeeuwenoord/freight<filename>freight/api/serializer/__init__.py
from .manager import serialize # NOQA
# TODO(dcramer): we cant seem to use import_submodules here as something is
# wrong w/ the code that causes it to mess up the default_manager instance
from . import app # NOQA
from . import deploy # NOQA
from . import user # NOQA
|
habanero/request_class.py | sckott/habanero | 115 | 11088852 | <filename>habanero/request_class.py
import requests
import json
import re
import math
from tqdm import tqdm
from .filterhandler import filter_handler
from .habanero_utils import (
switch_classes,
check_json,
is_json,
parse_json_err,
make_ua,
filter_dict,
rename_query_filters,
ifelsestr,
)
from .exceptions import *
class Request(object):
"""
Habanero: request class
This is the request class for all requests
"""
def __init__(
self,
mailto,
ua_string,
url,
path,
query=None,
filter=None,
offset=None,
limit=None,
sample=None,
sort=None,
order=None,
facet=None,
select=None,
cursor=None,
cursor_max=None,
agency=False,
progress_bar=False,
**kwargs
):
self.mailto = mailto
self.ua_string = ua_string
self.url = url
self.path = path
self.query = query
self.filter = filter
self.offset = offset
self.limit = limit
self.sample = sample
self.sort = sort
self.order = order
self.facet = facet
self.select = select
self.cursor = cursor
self.cursor_max = cursor_max
self.agency = agency
self.progress_bar = progress_bar
self.kwargs = kwargs
def _url(self):
tmpurl = self.url + self.path
return tmpurl.strip("/")
def do_request(self):
filt = filter_handler(self.filter)
if self.select.__class__ is list:
self.select = ",".join(self.select)
if not isinstance(self.cursor_max, (type(None), int)):
raise ValueError("cursor_max must be of class int")
payload = {
"query": self.query,
"filter": filt,
"offset": self.offset,
"rows": self.limit,
"sample": self.sample,
"sort": self.sort,
"order": self.order,
"facet": self.facet,
"select": self.select,
"cursor": self.cursor,
}
# convert limit/offset to str before removing None
# b/c 0 (zero) is falsey, so that param gets dropped
payload['offset'] = ifelsestr(payload['offset'])
payload['rows'] = ifelsestr(payload['rows'])
# remove params with value None
payload = dict((k, v) for k, v in payload.items() if v)
# add query filters
payload.update(filter_dict(self.kwargs))
# rename query filters
payload = rename_query_filters(payload)
js = self._req(payload=payload)
cu = js["message"].get("next-cursor")
max_avail = js["message"]["total-results"]
res = self._redo_req(js, payload, cu, max_avail)
return res
def _redo_req(self, js, payload, cu, max_avail):
if cu.__class__.__name__ != "NoneType" and self.cursor_max > len(
js["message"]["items"]
):
res = [js]
total = len(js["message"]["items"])
# progress bar setup
if self.progress_bar:
actual_max = (
self.cursor_max if self.cursor_max is not None else max_avail
)
if max_avail < actual_max:
actual_max = max_avail
runs = math.ceil(actual_max / (self.limit or 20))
pbar = tqdm(total=runs - 1)
while (
cu.__class__.__name__ != "NoneType"
and self.cursor_max > total
and total < max_avail
):
payload["cursor"] = cu
out = self._req(payload=payload)
cu = out["message"].get("next-cursor")
res.append(out)
total = sum([len(z["message"]["items"]) for z in res])
if self.progress_bar:
pbar.update(1)
if self.progress_bar:
pbar.close()
return res
else:
return js
def _req(self, payload):
try:
r = requests.get(
self._url(),
params=payload,
headers=make_ua(self.mailto, self.ua_string),
)
r.raise_for_status()
except requests.exceptions.HTTPError:
try:
f = r.json()
raise RequestError(r.status_code, f["message"][0]["message"])
except:
r.raise_for_status()
except requests.exceptions.RequestException as e:
print(e)
check_json(r)
return r.json()
|
examples/hf20_testnet.py | Nickfost/beem | 118 | 11088863 | <reponame>Nickfost/beem
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
from datetime import datetime, timedelta
import time
import io
import logging
from beem.blockchain import Blockchain
from beem.block import Block
from beem.account import Account
from beem.amount import Amount
from beemgraphenebase.account import PasswordKey, PrivateKey, PublicKey
from beem.steem import Steem
from beem.utils import parse_time, formatTimedelta
from beemapi.exceptions import NumRetriesReached
from beem.nodelist import NodeList
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
if __name__ == "__main__":
# stm = Steem(node="https://testnet.timcliff.com/")
# stm = Steem(node="https://testnet.steemitdev.com")
stm = Steem(node="https://api.steemit.com")
stm.wallet.unlock(pwd="<PASSWORD>")
account = Account("beembot", steem_instance=stm)
print(account.get_voting_power())
account.transfer("holger80", 0.001, "SBD", "test")
|
src/anyconfig/processors/__init__.py | Terrance-forks/python-anyconfig | 213 | 11088881 | <reponame>Terrance-forks/python-anyconfig
#
# Copyright (C) 2021 <NAME> <<EMAIL>>
# SPDX-License-Identifier: MIT
#
r"""Abstract class provides a list of :class:`anyconfig.models.processor` class
objects, related utility functions and data types.
.. versionchanged:: 0.10.2
- Split and re-organize the module and add some data types.
.. versionadded:: 0.9.5
- Add to abstract processors such like Parsers (loaders and dumpers).
"""
from .datatypes import (
ProcT, ProcClsT, ProcClssT, MaybeProcT
)
from .processors import Processors
from .utils import (
list_by_x, load_plugins
)
__all__ = [
'ProcT', 'ProcClsT', 'ProcClssT', 'MaybeProcT',
'Processors',
'list_by_x', 'load_plugins',
]
# vim:sw=4:ts=4:et:
|
todo/commands/group/add.py | tomasdanjonsson/td-cli | 154 | 11088888 | <filename>todo/commands/group/add.py
from sqlite3 import Error, IntegrityError
from todo.commands.base import Command
from todo.exceptions import TodoException
from todo.renderers import RenderOutput
class Add(Command):
def run(self, args):
try:
group_name = self.service.group.add(args.name)
RenderOutput("Created group {blue}{group_name}").render(group_name=group_name)
except IntegrityError as e:
raise TodoException("`{bold}<Group: %s>{reset}` already exists." % args.name, e)
except Error as e:
raise TodoException("Error occurred, could not create a new group", e)
|
metaflow/metadata/util.py | Netflix/metaflow | 5,821 | 11088894 | from io import BytesIO
import os
import tarfile
from distutils.dir_util import copy_tree
from metaflow import util
from metaflow.datastore.local_storage import LocalStorage
def sync_local_metadata_to_datastore(metadata_local_dir, task_ds):
with util.TempDir() as td:
tar_file_path = os.path.join(td, 'metadata.tgz')
buf = BytesIO()
with tarfile.open(name=tar_file_path, mode='w:gz', fileobj=buf) as tar:
tar.add(metadata_local_dir)
blob = buf.getvalue()
_, key = task_ds.parent_datastore.save_data([blob], len_hint=1)[0]
task_ds.save_metadata({'local_metadata': key})
def sync_local_metadata_from_datastore(metadata_local_dir, task_ds):
def echo_none(*args, **kwargs):
pass
key_to_load = task_ds.load_metadata(['local_metadata'])['local_metadata']
_, tarball = next(task_ds.parent_datastore.load_data([key_to_load]))
with util.TempDir() as td:
with tarfile.open(fileobj=BytesIO(tarball), mode='r:gz') as tar:
tar.extractall(td)
copy_tree(
os.path.join(td, metadata_local_dir),
LocalStorage.get_datastore_root_from_config(echo_none),
update=True) |
app/http_downloader.py | porcupineyhairs/rapidbay | 351 | 11088907 | import requests
import urllib
import os
import log
from common import threaded
class HttpDownloader:
downloads = {}
def clear(self, output_path):
try:
del self.downloads[output_path]
except KeyError:
pass
def download_file(self, url, output_path):
if self.downloads.get(output_path):
return
self.downloads[output_path] = 0
self._urlretrieve(url, output_path)
@threaded
@log.catch_and_log_exceptions
def _urlretrieve(self, url, output_path):
def progress(block_num, block_size, total_size):
downloaded = block_num * block_size
if downloaded < total_size:
self.downloads[output_path] = downloaded / total_size
else:
self.downloads[output_path] = 1
dirname = os.path.dirname(output_path)
os.makedirs(dirname, exist_ok=True)
urllib.request.urlretrieve(url, output_path, progress)
|
fastreid/layers/frn.py | tenghehan/reid_without_id | 2,194 | 11088924 | <filename>fastreid/layers/frn.py
# encoding: utf-8
"""
@author: liaoxingyu
@contact: <EMAIL>
"""
import torch
from torch import nn
from torch.nn.modules.batchnorm import BatchNorm2d
from torch.nn import ReLU, LeakyReLU
from torch.nn.parameter import Parameter
class TLU(nn.Module):
def __init__(self, num_features):
"""max(y, tau) = max(y - tau, 0) + tau = ReLU(y - tau) + tau"""
super(TLU, self).__init__()
self.num_features = num_features
self.tau = Parameter(torch.Tensor(num_features))
self.reset_parameters()
def reset_parameters(self):
nn.init.zeros_(self.tau)
def extra_repr(self):
return 'num_features={num_features}'.format(**self.__dict__)
def forward(self, x):
return torch.max(x, self.tau.view(1, self.num_features, 1, 1))
class FRN(nn.Module):
def __init__(self, num_features, eps=1e-6, is_eps_leanable=False):
"""
weight = gamma, bias = beta
beta, gamma:
Variables of shape [1, 1, 1, C]. if TensorFlow
Variables of shape [1, C, 1, 1]. if PyTorch
eps: A scalar constant or learnable variable.
"""
super(FRN, self).__init__()
self.num_features = num_features
self.init_eps = eps
self.is_eps_leanable = is_eps_leanable
self.weight = Parameter(torch.Tensor(num_features))
self.bias = Parameter(torch.Tensor(num_features))
if is_eps_leanable:
self.eps = Parameter(torch.Tensor(1))
else:
self.register_buffer('eps', torch.Tensor([eps]))
self.reset_parameters()
def reset_parameters(self):
nn.init.ones_(self.weight)
nn.init.zeros_(self.bias)
if self.is_eps_leanable:
nn.init.constant_(self.eps, self.init_eps)
def extra_repr(self):
return 'num_features={num_features}, eps={init_eps}'.format(**self.__dict__)
def forward(self, x):
"""
0, 1, 2, 3 -> (B, H, W, C) in TensorFlow
0, 1, 2, 3 -> (B, C, H, W) in PyTorch
TensorFlow code
nu2 = tf.reduce_mean(tf.square(x), axis=[1, 2], keepdims=True)
x = x * tf.rsqrt(nu2 + tf.abs(eps))
# This Code include TLU function max(y, tau)
return tf.maximum(gamma * x + beta, tau)
"""
# Compute the mean norm of activations per channel.
nu2 = x.pow(2).mean(dim=[2, 3], keepdim=True)
# Perform FRN.
x = x * torch.rsqrt(nu2 + self.eps.abs())
# Scale and Bias
x = self.weight.view(1, self.num_features, 1, 1) * x + self.bias.view(1, self.num_features, 1, 1)
# x = self.weight * x + self.bias
return x
def bnrelu_to_frn(module):
"""
Convert 'BatchNorm2d + ReLU' to 'FRN + TLU'
"""
mod = module
before_name = None
before_child = None
is_before_bn = False
for name, child in module.named_children():
if is_before_bn and isinstance(child, (ReLU, LeakyReLU)):
# Convert BN to FRN
if isinstance(before_child, BatchNorm2d):
mod.add_module(
before_name, FRN(num_features=before_child.num_features))
else:
raise NotImplementedError()
# Convert ReLU to TLU
mod.add_module(name, TLU(num_features=before_child.num_features))
else:
mod.add_module(name, bnrelu_to_frn(child))
before_name = name
before_child = child
is_before_bn = isinstance(child, BatchNorm2d)
return mod
def convert(module, flag_name):
mod = module
before_ch = None
for name, child in module.named_children():
if hasattr(child, flag_name) and getattr(child, flag_name):
if isinstance(child, BatchNorm2d):
before_ch = child.num_features
mod.add_module(name, FRN(num_features=child.num_features))
# TODO bn is no good...
if isinstance(child, (ReLU, LeakyReLU)):
mod.add_module(name, TLU(num_features=before_ch))
else:
mod.add_module(name, convert(child, flag_name))
return mod
def remove_flags(module, flag_name):
mod = module
for name, child in module.named_children():
if hasattr(child, 'is_convert_frn'):
delattr(child, flag_name)
mod.add_module(name, remove_flags(child, flag_name))
else:
mod.add_module(name, remove_flags(child, flag_name))
return mod
def bnrelu_to_frn2(model, input_size=(3, 128, 128), batch_size=2, flag_name='is_convert_frn'):
forard_hooks = list()
backward_hooks = list()
is_before_bn = [False]
def register_forward_hook(module):
def hook(self, input, output):
if isinstance(module, (nn.Sequential, nn.ModuleList)) or (module == model):
is_before_bn.append(False)
return
# input and output is required in hook def
is_converted = is_before_bn[-1] and isinstance(self, (ReLU, LeakyReLU))
if is_converted:
setattr(self, flag_name, True)
is_before_bn.append(isinstance(self, BatchNorm2d))
forard_hooks.append(module.register_forward_hook(hook))
is_before_relu = [False]
def register_backward_hook(module):
def hook(self, input, output):
if isinstance(module, (nn.Sequential, nn.ModuleList)) or (module == model):
is_before_relu.append(False)
return
is_converted = is_before_relu[-1] and isinstance(self, BatchNorm2d)
if is_converted:
setattr(self, flag_name, True)
is_before_relu.append(isinstance(self, (ReLU, LeakyReLU)))
backward_hooks.append(module.register_backward_hook(hook))
# multiple inputs to the network
if isinstance(input_size, tuple):
input_size = [input_size]
# batch_size of 2 for batchnorm
x = [torch.rand(batch_size, *in_size) for in_size in input_size]
# register hook
model.apply(register_forward_hook)
model.apply(register_backward_hook)
# make a forward pass
output = model(*x)
output.sum().backward() # Raw output is not enabled to use backward()
# remove these hooks
for h in forard_hooks:
h.remove()
for h in backward_hooks:
h.remove()
model = convert(model, flag_name=flag_name)
model = remove_flags(model, flag_name=flag_name)
return model
|
checkov/cloudformation/checks/resource/aws/DynamoDBTablesEncrypted.py | niradler/checkov | 4,013 | 11088926 | <gh_stars>1000+
from checkov.common.models.enums import CheckResult, CheckCategories
from checkov.cloudformation.checks.resource.base_resource_check import BaseResourceCheck
class DynamoDBTablesEncrypted(BaseResourceCheck):
def __init__(self):
name = "Ensure DynamoDB Tables are encrypted using a KMS Customer Managed CMK"
id = "CKV_AWS_119"
supported_resources = ["AWS::DynamoDB::Table"]
categories = [CheckCategories.ENCRYPTION]
super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources)
def scan_resource_conf(self, conf):
properties = conf.get('Properties')
if properties is not None:
sse_config = properties.get('SSESpecification')
if sse_config is not None:
sse_enabled = sse_config.get('SSEEnabled')
sse_key = sse_config.get('KMSMasterKeyId')
if sse_enabled and sse_key is not None:
return CheckResult.PASSED
return CheckResult.FAILED
check = DynamoDBTablesEncrypted()
|
data_collection/gazette/spiders/sc_braco_do_trombudo.py | kaiocp/querido-diario | 454 | 11088934 | from gazette.spiders.base.fecam import FecamGazetteSpider
class ScBracoDoTrombudoSpider(FecamGazetteSpider):
name = "sc_braco_do_trombudo"
FECAM_QUERY = "cod_entidade:50"
TERRITORY_ID = "4202859"
|
scripts/eval/eval_root.py | facebookresearch/banmo | 201 | 11088942 | <filename>scripts/eval/eval_root.py
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# python scripts/eval_root.py cam-files/adult7-b25/ cam-files/adult-masked-cam/ 1000
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(sys.path[0])))
os.environ["PYOPENGL_PLATFORM"] = "egl" #opengl seems to only work with TPU
curr_dir = os.path.abspath(os.getcwd())
sys.path.insert(0,curr_dir)
import pdb
import glob
import numpy as np
import torch
import cv2
import soft_renderer as sr
import argparse
import trimesh
import configparser
from utils.io import config_to_dataloader, draw_cams, load_root
from nnutils.geom_utils import rot_angle, align_sim3
root_a_dir=sys.argv[1]
root_b_dir=sys.argv[2]
cap_frame=int(sys.argv[3])
def umeyama_alignment(x, y, with_scale=False):
"""
https://github.com/Huangying-Zhan/kitti-odom-eval/blob/master/kitti_odometry.py
Computes the least squares solution parameters of an Sim(m) matrix
that minimizes the distance between a set of registered points.
Umeyama, Shinji: Least-squares estimation of transformation parameters
between two point patterns. IEEE PAMI, 1991
:param x: mxn matrix of points, m = dimension, n = nr. of data points
:param y: mxn matrix of points, m = dimension, n = nr. of data points
:param with_scale: set to True to align also the scale (default: 1.0 scale)
:return: r, t, c - rotation matrix, translation vector and scale factor
"""
if x.shape != y.shape:
assert False, "x.shape not equal to y.shape"
# m = dimension, n = nr. of data points
m, n = x.shape
# means, eq. 34 and 35
mean_x = x.mean(axis=1)
mean_y = y.mean(axis=1)
# variance, eq. 36
# "transpose" for column subtraction
sigma_x = 1.0 / n * (np.linalg.norm(x - mean_x[:, np.newaxis])**2)
# covariance matrix, eq. 38
outer_sum = np.zeros((m, m))
for i in range(n):
outer_sum += np.outer((y[:, i] - mean_y), (x[:, i] - mean_x))
cov_xy = np.multiply(1.0 / n, outer_sum)
# SVD (text betw. eq. 38 and 39)
u, d, v = np.linalg.svd(cov_xy)
# S matrix, eq. 43
s = np.eye(m)
if np.linalg.det(u) * np.linalg.det(v) < 0.0:
# Ensure a RHS coordinate system (Kabsch algorithm).
s[m - 1, m - 1] = -1
# rotation, eq. 40
r = u.dot(s).dot(v)
# scale & translation, eq. 42 and 41
c = 1 / sigma_x * np.trace(np.diag(d).dot(s)) if with_scale else 1.0
t = mean_y - np.multiply(c, r.dot(mean_x))
return r, t, c
def main():
rootlist_a = load_root(root_a_dir, cap_frame)
rootlist_b = load_root(root_b_dir, cap_frame)
# align
rootlist_b = align_sim3(rootlist_a, rootlist_b)
# construct camera mesh
mesh_a = draw_cams(rootlist_a, color='gray')
mesh_b = draw_cams(rootlist_b)
mesh = trimesh.util.concatenate([mesh_a, mesh_b])
mesh.export('0.obj')
# python ... path to camera folder
# will draw a trajectory of camera locations
if __name__ == '__main__':
main()
|
saleor/order/migrations/0107_set_origin_and_original_values.py | fairhopeweb/saleor | 15,337 | 11088945 | from django.db import migrations
def set_origin_and_original_order_values(apps, schema_editor):
Order = apps.get_model("order", "Order")
draft_events = ["placed_from_draft", "draft_created"]
Order.objects.filter(events__type__in=draft_events).update(origin="draft")
orders = []
for order in Order.objects.filter(
events__type="draft_created_from_replace"
).iterator():
order.origin = "reissue"
order.original_id = order.events.get(
type="draft_created_from_replace"
).parameters.get("related_order_pk")
orders.append(order)
Order.objects.bulk_update(orders, ["origin", "original"])
Order.objects.exclude(
events__type__in=draft_events + ["draft_created_from_replace"]
).update(origin="checkout")
class Migration(migrations.Migration):
dependencies = [
("order", "0106_origin_and_original"),
]
operations = [
migrations.RunPython(
set_origin_and_original_order_values, migrations.RunPython.noop
)
]
|
var/spack/repos/builtin/packages/py-os-service-types/package.py | LiamBindle/spack | 2,360 | 11088946 | <gh_stars>1000+
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyOsServiceTypes(PythonPackage):
"""Python library for consuming OpenStack sevice-types-authority data"""
homepage = "https://docs.openstack.org/os-service-types/"
pypi = "os-service-types/os-service-types-1.7.0.tar.gz"
maintainers = ['haampie']
version('1.7.0', sha256='31800299a82239363995b91f1ebf9106ac7758542a1e4ef6dc737a5932878c6c')
depends_on('[email protected]:2.8,3.5:', type=('build', 'run'))
depends_on('[email protected]:2.0,2.1.1:', type='build')
depends_on('py-setuptools', type='build')
|
tests/test_utils/test_module_hooks.py | Naoki-Wake/mmaction2 | 648 | 11088947 | <reponame>Naoki-Wake/mmaction2
import copy
import os.path as osp
import mmcv
import numpy as np
import pytest
import torch
from mmaction.models import build_recognizer
from mmaction.utils import register_module_hooks
from mmaction.utils.module_hooks import GPUNormalize
def test_register_module_hooks():
_module_hooks = [
dict(
type='GPUNormalize',
hooked_module='backbone',
hook_pos='forward_pre',
input_format='NCHW',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375])
]
repo_dpath = osp.dirname(osp.dirname(osp.dirname(__file__)))
config_fpath = osp.join(repo_dpath, 'configs/_base_/models/tsm_r50.py')
config = mmcv.Config.fromfile(config_fpath)
config.model['backbone']['pretrained'] = None
# case 1
module_hooks = copy.deepcopy(_module_hooks)
module_hooks[0]['hook_pos'] = 'forward_pre'
recognizer = build_recognizer(config.model)
handles = register_module_hooks(recognizer, module_hooks)
assert recognizer.backbone._forward_pre_hooks[
handles[0].id].__name__ == 'normalize_hook'
# case 2
module_hooks = copy.deepcopy(_module_hooks)
module_hooks[0]['hook_pos'] = 'forward'
recognizer = build_recognizer(config.model)
handles = register_module_hooks(recognizer, module_hooks)
assert recognizer.backbone._forward_hooks[
handles[0].id].__name__ == 'normalize_hook'
# case 3
module_hooks = copy.deepcopy(_module_hooks)
module_hooks[0]['hooked_module'] = 'cls_head'
module_hooks[0]['hook_pos'] = 'backward'
recognizer = build_recognizer(config.model)
handles = register_module_hooks(recognizer, module_hooks)
assert recognizer.cls_head._backward_hooks[
handles[0].id].__name__ == 'normalize_hook'
# case 4
module_hooks = copy.deepcopy(_module_hooks)
module_hooks[0]['hook_pos'] = '_other_pos'
recognizer = build_recognizer(config.model)
with pytest.raises(ValueError):
handles = register_module_hooks(recognizer, module_hooks)
# case 5
module_hooks = copy.deepcopy(_module_hooks)
module_hooks[0]['hooked_module'] = '_other_module'
recognizer = build_recognizer(config.model)
with pytest.raises(ValueError):
handles = register_module_hooks(recognizer, module_hooks)
def test_gpu_normalize():
def check_normalize(origin_imgs, result_imgs, norm_cfg):
"""Check if the origin_imgs are normalized correctly into result_imgs
in a given norm_cfg."""
from numpy.testing import assert_array_almost_equal
target_imgs = result_imgs.copy()
target_imgs *= norm_cfg['std']
target_imgs += norm_cfg['mean']
assert_array_almost_equal(origin_imgs, target_imgs, decimal=4)
_gpu_normalize_cfg = dict(
input_format='NCTHW',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375])
# case 1
gpu_normalize_cfg = copy.deepcopy(_gpu_normalize_cfg)
gpu_normalize_cfg['input_format'] = 'NCHW'
gpu_normalize = GPUNormalize(**gpu_normalize_cfg)
assert gpu_normalize._mean.shape == (1, 3, 1, 1)
imgs = np.random.randint(256, size=(2, 240, 320, 3), dtype=np.uint8)
_input = (torch.tensor(imgs).permute(0, 3, 1, 2), )
normalize_hook = gpu_normalize.hook_func()
_input = normalize_hook(torch.nn.Module, _input)
result_imgs = np.array(_input[0].permute(0, 2, 3, 1))
check_normalize(imgs, result_imgs, gpu_normalize_cfg)
# case 2
gpu_normalize_cfg = copy.deepcopy(_gpu_normalize_cfg)
gpu_normalize_cfg['input_format'] = 'NCTHW'
gpu_normalize = GPUNormalize(**gpu_normalize_cfg)
assert gpu_normalize._mean.shape == (1, 3, 1, 1, 1)
# case 3
gpu_normalize_cfg = copy.deepcopy(_gpu_normalize_cfg)
gpu_normalize_cfg['input_format'] = 'NCHW_Flow'
gpu_normalize = GPUNormalize(**gpu_normalize_cfg)
assert gpu_normalize._mean.shape == (1, 3, 1, 1)
# case 4
gpu_normalize_cfg = copy.deepcopy(_gpu_normalize_cfg)
gpu_normalize_cfg['input_format'] = 'NPTCHW'
gpu_normalize = GPUNormalize(**gpu_normalize_cfg)
assert gpu_normalize._mean.shape == (1, 1, 1, 3, 1, 1)
# case 5
gpu_normalize_cfg = copy.deepcopy(_gpu_normalize_cfg)
gpu_normalize_cfg['input_format'] = '_format'
with pytest.raises(ValueError):
gpu_normalize = GPUNormalize(**gpu_normalize_cfg)
|
eagle-external/hadoop_jmx_collector/hadoop_ha_checker.py | phenixmzy/apache-eagle-0.5 | 322 | 11088960 | <filename>eagle-external/hadoop_jmx_collector/hadoop_ha_checker.py
# !/usr/bin/python
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from metric_collector import MetricCollector, JmxReader, YarnWSReader, Runner
import logging,socket,string
class HadoopNNHAChecker(MetricCollector):
def run(self):
hosts = []
for input in self.config["input"]:
if not input.has_key("host"):
input["host"] = socket.getfqdn()
if input.has_key("component") and input["component"] == "namenode":
hosts.append(input)
if not bool(hosts):
logging.warn("non hosts are configured as 'namenode' in 'input' config, exit")
return
logging.info("Checking namenode HA: " + str(hosts))
active_count = 0
standby_count = 0
failed_count = 0
failed_host_list = []
host_name_list = []
for host in hosts:
try:
if host.has_key("source_host"):
host["host"] = host["source_host"]
host_name_list.append(host["host"])
bean = JmxReader(host["host"], host["port"], host["https"]) \
.read_query("/jmx?qry=Hadoop:service=NameNode,name=FSNamesystem&anonymous=true") \
.get_jmx_bean_by_name("Hadoop:service=NameNode,name=FSNamesystem")
if not bean:
logging.error("JMX Bean[Hadoop:service=NameNode,name=FSNamesystem] is null from " + host["host"])
if bean.has_key("tag.HAState"):
logging.debug(str(host) + " is " + bean["tag.HAState"])
if bean["tag.HAState"] == "active":
active_count += 1
else:
standby_count += 1
else:
logging.info("'tag.HAState' not found from jmx of " + host["host"] + ":" + host["port"])
except Exception as e:
logging.exception("failed to read jmx from " + host["host"] + ":" + host["port"])
failed_count += 1
failed_host_list.append(host["host"])
total_count = len(hosts)
all_hosts_name = string.join(host_name_list,",")
self.collect({
"host": all_hosts_name,
"component": "namenode",
"metric": "hadoop.namenode.hastate.total.count",
"value": total_count
})
self.collect({
"host": all_hosts_name,
"component": "namenode",
"metric": "hadoop.namenode.hastate.active.count",
"value": active_count
})
self.collect({
"host": all_hosts_name,
"component": "namenode",
"metric": "hadoop.namenode.hastate.standby.count",
"value": standby_count
})
if len(failed_host_list) > 0:
all_hosts_name = string.join(failed_host_list,",")
self.collect({
"host": all_hosts_name,
"component": "namenode",
"metric": "hadoop.namenode.hastate.failed.count",
"value": failed_count
})
class HadoopHBaseHAChecker(MetricCollector):
def run(self):
hosts = []
for input in self.config["input"]:
if not input.has_key("host"):
input["host"] = socket.getfqdn()
if input.has_key("component") and input["component"] == "hbasemaster":
hosts.append(input)
if not bool(hosts):
logging.warn("non hosts are configured as 'hbasemaster' in 'input' config, exit")
return
logging.info("Checking HBase HA: " + str(hosts))
active_count = 0
standby_count = 0
failed_count = 0
failed_host_list = []
host_name_list = []
for host in hosts:
try:
if host.has_key("source_host"):
host["host"] = host["source_host"]
host_name_list.append(host["host"])
bean = JmxReader(host["host"], host["port"], host["https"]) \
.read_query("/jmx?qry=Hadoop:service=HBase,name=Master,sub=Server&anonymous=true") \
.get_jmx_bean_by_name("Hadoop:service=HBase,name=Master,sub=Server")
if not bean:
logging.error("JMX Bean[Hadoop:service=HBase,name=Master,sub=Server] is null from " + host["host"])
if bean.has_key("tag.isActiveMaster"):
logging.debug(str(host) + " is " + bean["tag.isActiveMaster"])
if bean["tag.isActiveMaster"] == "true":
active_count += 1
else:
standby_count += 1
else:
logging.info("'tag.isActiveMaster' not found from jmx of " + host["host"] + ":" + host["port"])
except Exception as e:
logging.exception("failed to read jmx from " + host["host"] + ":" + host["port"])
failed_count += 1
failed_host_list.append(host["host"])
total_count = len(hosts)
all_hosts_name = string.join(host_name_list,",")
self.collect({
"host": all_hosts_name,
"component": "hbasemaster",
"metric": "hadoop.hbasemaster.hastate.total.count",
"value": total_count
})
self.collect({
"host": all_hosts_name,
"component": "hbasemaster",
"metric": "hadoop.hbasemaster.hastate.active.count",
"value": active_count
})
self.collect({
"host": all_hosts_name,
"component": "hbasemaster",
"metric": "hadoop.hbasemaster.hastate.standby.count",
"value": standby_count
})
if len(failed_host_list) > 0:
all_hosts_name = string.join(failed_host_list,",")
self.collect({
"host": all_hosts_name,
"component": "hbasemaster",
"metric": "hadoop.hbasemaster.hastate.failed.count",
"value": failed_count
})
class HadoopRMHAChecker(MetricCollector):
def run(self):
hosts = []
all_hosts = []
for input in self.config["input"]:
if not input.has_key("host"):
input["host"] = socket.getfqdn()
if input.has_key("component") and input["component"] == "resourcemanager":
hosts.append(input)
all_hosts.append(input["host"])
if not bool(hosts):
logging.warn("Non hosts are configured as 'resourcemanager' in 'input' config, exit")
return
logging.info("Checking resource manager HA: " + str(hosts))
active_count = 0
standby_count = 0
failed_count = 0
failed_host_list = []
for host in hosts:
try:
cluster_info = YarnWSReader(host["host"], host["port"], host["https"]).read_cluster_info()
if not cluster_info:
logging.error("Cluster info is null from web service of " + host["host"])
raise Exception("cluster info is null from " + host["host"])
if cluster_info["clusterInfo"]["haState"] == "ACTIVE":
active_count += 1
else:
standby_count += 1
except Exception as e:
logging.error("Failed to read yarn ws from " + str(host))
failed_count += 1
failed_host_list.append(host["host"])
total_count = len(hosts)
all_hosts_name = string.join(all_hosts,",")
self.collect({
"host": all_hosts_name,
"component": "resourcemanager",
"metric": "hadoop.resourcemanager.hastate.total.count",
"value": total_count
})
self.collect({
"host": all_hosts_name,
"component": "resourcemanager",
"metric": "hadoop.resourcemanager.hastate.active.count",
"value": active_count
})
self.collect({
"host": all_hosts_name,
"component": "resourcemanager",
"metric": "hadoop.resourcemanager.hastate.standby.count",
"value": standby_count
})
if len(failed_host_list) > 0:
all_hosts_name = string.join(failed_host_list,",")
self.collect({
"host": all_hosts_name,
"component": "resourcemanager",
"metric": "hadoop.resourcemanager.hastate.failed.count",
"value": failed_count
})
if __name__ == '__main__':
Runner.run(HadoopNNHAChecker(), HadoopHBaseHAChecker(), HadoopRMHAChecker()) |
coarse_to_fine/refine_cityscapes_coarse.py | jblanche/STEAL | 478 | 11088962 | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import tqdm
from coarse_to_fine.input_reader import InputReader, InputReaderBaseName, InputReaderSemMat2BaseName, InputReaderSemMat2
from contours import ContourBox
import argparse
import ast
import numpy as np
import os
from PIL import Image
class GenerateGT_PNGMask:
def __init__(self, classes_to_keep, output_dir):
self.classes_to_keep = classes_to_keep # Object classes: [11, 12, 13, 14, 15, 16, 17, 18]
self.output_dir = output_dir
def _save_fname(self, filename):
city_name = filename.split('_')[0]
gt_name = filename.split('_leftImg8bit')[0] + 'gtCoarseR_labelIds.png'
def generate_save(self, gt, improved, filename):
only_objects_updated, fully_improved = self._generate_single_mask(gt, improved)
city_name = filename.split('_')[0]
gt_name_objects = filename.split('_leftImg8bit')[0] + '_gtCoarseRefObj_labelIds.png'
gt_name_alls = filename.split('_leftImg8bit')[0] + '_gtCoarseRefAll_labelIds.png'
output_dir = os.path.join(self.output_dir, city_name)
if not os.path.isdir(output_dir):
os.makedirs(output_dir)
gt_name_alls = os.path.join(output_dir, gt_name_alls)
fully_improved = Image.fromarray(fully_improved)
fully_improved.save(gt_name_alls, 'png')
gt_name_objects = os.path.join(output_dir, gt_name_objects)
only_objects_updated = Image.fromarray(only_objects_updated)
only_objects_updated.save(gt_name_objects, 'png')
def _generate_single_mask(self, gt, improved):
final_canvas = np.zeros(gt.shape[1:]).astype(np.uint8)
all_updated_canvas = np.zeros(gt.shape[1:]).astype(np.uint8)
for k, (gt_k, improved_k) in enumerate(zip(gt, improved), start=0):
if k not in self.classes_to_keep:
if np.any(gt_k):
final_canvas[gt_k != 0] = k
else:
if np.any(improved_k) and np.any(gt_k):
final_canvas[improved_k != 0] = k
all_updated_canvas[improved_k != 0] = k
#
return final_canvas, all_updated_canvas
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--coarse_dir', type=str,
default='./cityscapes-preprocess/gt_eval_coarse/gt_thin')
parser.add_argument('--in_dir', type=str,
default='./prediction_scaled_0_5')
parser.add_argument('--val_file_list', type=str,
default='./Cityscapes/benchmark/datadir/val.txt')
parser.add_argument('--n_classes', type=int, default=19)
parser.add_argument('--n_classes_start', type=int, default=1)
parser.add_argument('--level_set_method', type=str, default='MLS')
parser.add_argument('--level_set_config_dict', type=dict, default={})
# ---
parser.add_argument('--n_workers', type=int, default=8)
parser.add_argument('--smooth_lsteps', type=int, default=1)
parser.add_argument('--lambda_', type=float, default=0.0)
parser.add_argument('--alpha', type=float, default=1.0)
parser.add_argument('--step_ckpts', type=str, default="[0,60]")
parser.add_argument('--exp_name', type=str, default='test')
parser.add_argument('--output_dir', type=str, default='./refined_data_test')
parser.add_argument('--classes_to_keep', type=list, default=[])
parser.add_argument('--balloon', type=float, default=1)
parser.add_argument('--threshold', type=float, default=0.99)
parser.add_argument('--merge_weight', type=float, default=0.5)
args = parser.parse_args()
level_set_config_dict = {
'lambda_': args.lambda_,
'alpha': args.alpha,
'smoothing': args.smooth_lsteps,
'render_radius': -1,
'is_gt_semantic': True,
'method': args.level_set_method,
'balloon': args.balloon,
'threshold': args.threshold,
'merge_weight': args.merge_weight,
'step_ckpts': ast.literal_eval(args.step_ckpts)
}
args.level_set_config_dict = level_set_config_dict
return args
def do_it(args):
in_dir = args.in_dir
val_file_list = args.val_file_list
coarse_dir = args.coarse_dir
n_classes_interval = (args.n_classes_start, args.n_classes)
level_set_config_dict = args.level_set_config_dict
classes_to_keep = [11, 12, 13, 14, 15, 16, 17, 18] # args.classes_to_keep
ireader = InputReaderBaseName(in_dir, val_file_list, n_classes_interval)
#
ireader_coarse = InputReaderSemMat2BaseName(coarse_dir, val_file_list, n_classes_interval)
#
ireader_coarse.set_external_list(ireader._read_list)
cbox = ContourBox.LevelSetAlignment(n_workers=1,
fn_post_process_callback=None,
config=level_set_config_dict)
mask_generator = GenerateGT_PNGMask(classes_to_keep, args.output_dir)
for (im_filename, pred_ch), (seg_fname, seg_coarse) in tqdm.tqdm(
zip(ireader, ireader_coarse), total=len(ireader)):
assert len(pred_ch) == len(seg_coarse), 'num ch should match'
output, _ = cbox({'seg': np.expand_dims(seg_coarse, 0), 'bdry': None},
np.expand_dims(np.stack(pred_ch), 0))
# assuming the last ckpts is the one we are going to use
improved_mask = output[0, :, -1, :, :]
seg_coarse = np.stack(seg_coarse)
mask_generator.generate_save(seg_coarse, improved_mask, seg_fname)
if __name__ == "__main__":
args = parse_args()
do_it(args)
|
StackApp/env/lib/python2.7/site-packages/flask_api/tests/test_request.py | jonathanmusila/StackOverflow-Lite | 555 | 11088967 | <reponame>jonathanmusila/StackOverflow-Lite
# coding: utf8
from __future__ import unicode_literals
from flask import request
from flask_api import exceptions
import flask_api
import io
import unittest
app = flask_api.FlaskAPI(__name__)
class MediaTypeParsingTests(unittest.TestCase):
def test_json_request(self):
kwargs = {
'method': 'PUT',
'input_stream': io.BytesIO(b'{"key": 1, "other": "two"}'),
'content_type': 'application/json'
}
with app.test_request_context(**kwargs):
self.assertEqual(request.data, {"key": 1, "other": "two"})
def test_invalid_content_type_request(self):
kwargs = {
'method': 'PUT',
'input_stream': io.BytesIO(b'Cannot parse this content type.'),
'content_type': 'text/plain'
}
with app.test_request_context(**kwargs):
with self.assertRaises(exceptions.UnsupportedMediaType):
request.data
def test_no_content_request(self):
"""
Ensure that requests with no data do not populate the
`.data`, `.form` or `.files` attributes.
"""
with app.test_request_context(method='PUT'):
self.assertFalse(request.data)
with app.test_request_context(method='PUT'):
self.assertFalse(request.form)
with app.test_request_context(method='PUT'):
self.assertFalse(request.files)
def test_encode_request(self):
"""
Ensure that `.full_path` is correctly decoded in python 3
"""
with app.test_request_context(method='GET', path='/?a=b'):
self.assertEqual(request.full_path, '/?a=b')
|
cooka/service/process_monitor.py | highboo52na/Cooka | 222 | 11088975 | <reponame>highboo52na/Cooka<filename>cooka/service/process_monitor.py
# -*- encoding: utf-8 -*-
import threading
import time
import psutil
from psutil import _common as ps_cons
from cooka.common.model import Model, JobStep, TrainStep
from cooka.service.experiment_service import ExperimentService
from cooka.common.log import log_web as logger
class ProcessMonitor(threading.Thread):
"""
Fix some process end but never send back event sometimes , such as server restart
"""
experiment_service = ExperimentService()
def __init__(self):
super(ProcessMonitor, self).__init__(name="ProcessMonitorThread", daemon=True) # stop if parent Thread finished
self.process_status_mapping = {}
def run(self) -> None:
logger.info("[MonitorThread] loop running...")
while 1:
time.sleep(1)
# 1. select all running models
models = self.experiment_service.find_running_model()
# 2. check process of running model
self.handle_models(models)
def handle_models(self, models: list):
for m in models:
m: Model = m
pid = m.pid
if pid is None:
pass
# logger.warning(f"Model {m.name} , training process pid is None. ")
else:
try:
status = psutil.Process(pid).status()
if pid not in self.process_status_mapping:
self.process_status_mapping[pid] = status
logger.info(f"Model {m.name} , pid is {pid} process status is {status} ")
else:
if self.process_status_mapping[pid] != status:
logger.info(f"Model {m.name} , pid is {pid} process status changed from{ self.process_status_mapping[pid] } to {status} ")
self.process_status_mapping[pid] = status
except Exception as e: # usually is NoSuchProcess
# update if process finished
logger.warning(f"Model {m.name} , training process pid = {pid} not exists. ")
self.experiment_service.train_process_terminated(m.name)
|
trainers/base_trainer.py | zekunhao1995/DualSDF | 107 | 11088978 | <filename>trainers/base_trainer.py
import torch
import torch.nn as nn
class BaseTrainer(nn.Module):
def __init__(self, cfg, args, device):
self.cfg = cfg
self.args = args
self.device = device
|
src/account/azext_account/generated/_params.py | Mannan2812/azure-cli-extensions | 207 | 11088989 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long
# pylint: disable=too-many-lines
# pylint: disable=too-many-statements
from azure.cli.core.commands.parameters import get_enum_type
from ._validators import alias_validator
def load_arguments(self, _):
with self.argument_context('account subscription rename') as c:
c.argument('subscription_id', options_list=['--id', '--subscription-id'], help='Subscription Id.')
c.argument('subscription_name', options_list=['--name', '-n', '--subscription-name'], help='New subscription name')
with self.argument_context('account subscription cancel') as c:
c.argument('subscription_id', options_list=['--id', '--subscription-id'], help='Subscription Id.')
with self.argument_context('account subscription enable') as c:
c.argument('subscription_id', options_list=['--id', '--subscription-id'], help='Subscription Id.')
with self.argument_context('account subscription list') as c:
pass
with self.argument_context('account subscription show') as c:
c.argument('subscription_id', options_list=['--id', '--subscription-id'], help='The ID of the target subscription.', id_part='subscription')
with self.argument_context('account subscription list-location') as c:
c.argument('subscription_id', options_list=['--id', '--subscription-id'], help='The ID of the target subscription.')
with self.argument_context('account tenant list') as c:
pass
with self.argument_context('account alias list') as c:
pass
with self.argument_context('account alias show') as c:
c.argument('alias_name', options_list=['--name', '-n'], help='Alias Name')
with self.argument_context('account alias create', validator=alias_validator) as c:
c.argument('alias_name', options_list=['--name', '-n'], type=str, help='Alias Name')
c.argument('display_name', type=str, help='The friendly name of the subscription.')
c.argument('workload', arg_type=get_enum_type(['Production', 'DevTest']), help='The workload type of the '
'subscription. It can be either Production or DevTest.')
c.argument('billing_scope', type=str, help='Billing scope. It determines whether the subscription is Field-Led, Partner-Led or '
'LegacyEA')
c.argument('subscription_id', type=str, help='This parameter can be used to create alias for existing '
'subscription ID')
c.argument('reseller_id', type=str, help='Reseller ID, basically MPN Id')
with self.argument_context('account alias delete') as c:
c.argument('alias_name', options_list=['--name', '-n'], help='Alias Name')
with self.argument_context('account alias wait') as c:
c.argument('alias_name', options_list=['--name', '-n'], help='Alias Name')
|
simulation/scenario_seven.py | Barala/doorman | 1,831 | 11089030 | <filename>simulation/scenario_seven.py
#!/usr/bin/python2.7
# Copyright 2016 Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import random
from client import Client
from scenario_five import scenario_five
from scheduler import scheduler
from server_job import ServerJob
from simulation import run_scenario
from utils import logger
from varz import Counter
def spike_client():
client = Client.get_random_client()
n = client.get_wants('resource0') + 100
logger.info(
'Random mishap: Setting %s wants to %d' %
(client.get_client_id(), n))
client.set_wants('resource0', n)
def trigger_master_election():
job = ServerJob.get_random_server_job()
logger.info(
'Random mishap: Triggering master election in job %s' %
job.get_job_name())
job.trigger_master_election()
def lose_master():
job = ServerJob.get_random_server_job()
t = random.randint(0, 60)
logger.info(
'Random mishap: Losing master job %s for %d seconds' %
(job.get_job_name(), t))
job.lose_master()
scheduler.add_relative(t, lambda: job.trigger_master_election())
_mishap_map = dict([
(5, lambda: spike_client()),
(10, lambda: trigger_master_election()),
(15, lambda: lose_master()),
])
# Invoke some random mishap.
def random_mishap():
scheduler.add_relative(60, lambda: random_mishap())
total = max(_mishap_map.keys())
m = random.randint(0, total - 1)
n = 0
for (key, value) in _mishap_map.iteritems():
if n >= m:
Counter.get('mishap.%d' % key).inc()
value()
return
n += key
assert False
# Uses the setup of scenario five, but runs for a (simulated) hour
# and invokes random mishap every 60 seconds.
def scenario_seven(reporter):
scenario_five(reporter)
reporter.set_filename('scenario_seven')
scheduler.add_absolute(60, lambda: random_mishap())
if __name__ == '__main__':
run_scenario(lambda reporter: scenario_seven(reporter), run_for=3600)
|
localgraphclustering/MQI_weighted.py | vishalbelsare/LocalGraphClustering | 106 | 11089052 | <filename>localgraphclustering/MQI_weighted.py<gh_stars>100-1000
from typing import *
import numpy as np
from .cpp import *
def MQI_weighted(G, ref_nodes):
"""
Max Flow Quotient Cut Improvement (MQI) for improving either the expansion or the
conductance of cuts of weighted or unweighted graphs.
For details please refer to: <NAME> (2004). Max Flow Quotient Cut Improvement (MQI)
link: https://link.springer.com/chapter/10.1007/978-3-540-25960-2_25
Parameters
----------------------
G: GraphLocal
ref_nodes: Sequence[int]
A sequence of reference nodes, i.e., nodes of interest around which
we are looking for a target cluster.
Returns
-------
It returns in a list of length 2 with the following:
output 0: list
Stores indices of the best clusters found by the last called rounding procedure.
output 1: float
Stores the value of the best conductance found by the last called rounding procedure.
"""
n = G.adjacency_matrix.shape[0]
R = list(set(ref_nodes))
nR = len(R)
(actual_length,actual_xids) = MQI_weighted_cpp(n,G.ai,G.aj,G.adjacency_matrix.data,nR,R,G.d)
return [actual_xids, G.compute_conductance(actual_xids)]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.