id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3372980
# Generated by Django 3.0.3 on 2020-05-05 08:44 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('stats', '0003_auto_20200428_2138'), ] operations = [ migrations.CreateModel( name='ContentFrequency', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('content_id', models.IntegerField()), ('content_type', models.IntegerField()), ('frequency', models.IntegerField()), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['content_type', 'frequency'], }, ), ]
StarcoderdataPython
3286791
from io import StringIO from snakefmt import DEFAULT_LINE_LENGTH from snakefmt.formatter import Formatter from snakefmt.parser.parser import Snakefile def setup_formatter(snake: str, line_length: int = DEFAULT_LINE_LENGTH): stream = StringIO(snake) smk = Snakefile(stream) return Formatter(smk, line_length=line_length)
StarcoderdataPython
3341988
# Generated by Django 3.1.2 on 2020-11-21 16:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('discourse', '0031_topic_image_of_topic'), ] operations = [ migrations.AddField( model_name='topic', name='image_url', field=models.CharField(blank=True, max_length=1000, null=True), ), ]
StarcoderdataPython
190584
from .sorting_algorithms import * class Policy: context = None def __init__(self, context): self.context = context def configure(self): if len(self.context.numbers) > 10: print('More than 10 numbers, choosing merge sort!') self.context.sorting_algorithm = MergeSort() else: print('Less or equal than 10 numbers, choosing bubble sort!') self.context.sorting_algorithm = BubbleSort()
StarcoderdataPython
1706930
""" Create db table """ import os import psycopg2 QUERIES = ( """ CREATE TABLE IF NOT EXISTS users( user_id SERIAL PRIMARY KEY NOT NULL, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(100) NOT NULL ) """, """ CREATE TABLE IF NOT EXISTS questions( question_id SERIAL PRIMARY KEY NOT NULL, user_id int null references users(user_id)on delete cascade, title VARCHAR(80) NOT NULL UNIQUE, question VARCHAR(500) NOT NULL, answers int default 0 ) """, """ CREATE TABLE IF NOT EXISTS answers( answer_id SERIAL PRIMARY KEY NOT NULL, user_id int null references users(user_id) on delete cascade, question_id int references questions(question_id) on delete cascade, answer VARCHAR(500) NOT NULL, status varchar(80) default 'pending' ) """ ) def create_tables(db_url): """ Create tables for the database """ conn = psycopg2.connect(db_url) cur = conn.cursor() #create tables for query in QUERIES: cur.execute(query) cur.close() conn.commit() conn.close() if __name__ == '__main__': TEST_DB = os.getenv("DATABASE_URL") create_tables(TEST_DB)
StarcoderdataPython
1757761
import pyabc import tempfile import pytest import os import numpy as np # create and run some model def model(p): return {'ss0': p['p0'] + 0.1 * np.random.uniform(), 'ss1': p['p1'] + 0.1 * np.random.uniform()} p_true = {'p0': 3, 'p1': 4} observation = {'ss0': p_true['p0'], 'ss1': p_true['p1']} limits = {'p0': (0, 5), 'p1': (1, 8)} prior = pyabc.Distribution(**{ key: pyabc.RV('uniform', limits[key][0], limits[key][1] - limits[key][0]) for key in p_true.keys()}) db_path = "sqlite:///" \ + os.path.join(tempfile.gettempdir(), "test_visualize.db") distance = pyabc.PNormDistance(p=2) n_history = 2 sampler = pyabc.sampler.MulticoreEvalParallelSampler(n_procs=2) for _ in range(n_history): abc = pyabc.ABCSMC(model, prior, distance, 20, sampler=sampler) abc.new(db_path, observation) abc.run(minimum_epsilon=.1, max_nr_populations=3) histories = [] labels = [] for j in range(n_history): history = pyabc.History(db_path) history.id = j + 1 histories.append(history) labels.append("Some run " + str(j)) def test_epsilons(): pyabc.visualization.plot_sample_numbers(histories) pyabc.visualization.plot_sample_numbers(histories, labels) with pytest.raises(ValueError): pyabc.visualization.plot_sample_numbers(histories, [labels[0]]) def test_sample_numbers(): pyabc.visualization.plot_sample_numbers(histories, labels, rotation=90) def test_effective_sample_sizes(): pyabc.visualization.plot_effective_sample_sizes( histories, labels, rotation=45) def test_histograms(): pyabc.visualization.plot_histogram_1d(histories[0], 'p0', bins=20) pyabc.visualization.plot_histogram_2d(histories[0], 'p0', 'p1') pyabc.visualization.plot_histogram_matrix(histories[0], bins=1000) def test_kdes(): df, w = histories[0].get_distribution(m=0, t=None) pyabc.visualization.plot_kde_1d( df, w, x='p0', xmin=limits['p0'][0], xmax=limits['p0'][1], label="PDF") pyabc.visualization.plot_kde_2d(df, w, x='p0', y='p1') pyabc.visualization.plot_kde_matrix(df, w) def test_confidence_intervals(): pyabc.visualization.plot_confidence_intervals(histories[0]) pyabc.visualization.plot_confidence_intervals( histories[0], confidences=[0.2, 0.5, 0.9]) def test_model_probabilities(): pyabc.visualization.plot_model_probabilities(histories[0])
StarcoderdataPython
1677273
<gh_stars>1-10 from web3 import Web3, HTTPProvider infura_api = "" def verify(address, assigned_content, txn_addr): w3 = Web3(HTTPProvider(infura_api)) func_header = 'leaveMsg(string)' txn_receipt = w3.eth.getTransactionReceipt(txn_addr) if txn_receipt['to'] != address: return False if txn_receipt['status'] == 0: # maybe reverted return False else: txn = w3.eth.getTransaction(txn_addr) hash_func_header = w3.toHex(w3.keccak(text=func_header)[:4]) assigned_content = w3.toHex(assigned_content.encode())[2:] return assigned_content in txn['input'] and txn['input'][:10] == hash_func_header
StarcoderdataPython
4829137
import sentry_sdk from framework.util.settings import get_setting sentry_sdk.init(get_setting("SENTRY_DSN"), traces_sample_rate=1.0) def application(environ, start_response): if environ["PATH_INFO"] == "/e/": division = 1 / 0 status = "200 OK" headers = { "Content-type": "text/html", } payload = ( b"<!DOCTYPE html>" b"<html>" b"<head>" b"<title>Alpha</title>" b'<meta charset="utf-8">' b"</head>" b"<body>" b"<h1>Project Alpha</h1>" b"<hr>" b"<p>This is a template project.</p>" b"</body>" b"</html>" ) start_response(status, list(headers.items())) yield payload
StarcoderdataPython
3285426
### Not working!!! ### Alternative trianing of Faster R-CNN, # which means we are going to train RPN first, then detector, then RPN, then detector... import sys from pathlib import Path import pickle import random from copy import copy import numpy as np import pandas as pd import tensorflow as tf from tensorflow.image import non_max_suppression_with_scores from tensorflow.keras import Model from tensorflow.keras.layers import Input, Dense, Conv2D, Dropout, Flatten, Reshape, Softmax from tensorflow.keras.optimizers import Adam from tensorflow.keras.metrics import CategoricalAccuracy util_dir = Path.cwd().parent.joinpath('Utility') sys.path.insert(1, str(util_dir)) from Abstract import * from Information import * from Configuration import frcnn_config from Layers import rpn, RoIPooling from Loss import * from Metric import * from Information import * def rpn_to_roi(C, score_maps, delta_maps): ### pass output through nms # make anchors anchors = make_anchors(C.input_shape, C.base_net.ratio, C.anchor_scales, C.anchor_ratios) # initialize parameters bbox_idx = 0 dict_for_df={} # prepare reference and prediction dataframes df_r = pd.read_csv(C.bbox_reference_file, index_col=0) imgNames = df_r['FileName'].unique().tolist() for img_name, score_map, delta_map in zip(imgNames, score_maps, delta_maps): score_bbox_pairs = propose_score_bbox_list(anchors, score_map, delta_map) scores, bboxes_raw = [], [] for score_bbox in score_bbox_pairs: scores.append(score_bbox[0]) bboxes_raw.append(score_bbox[1]) # trimming bboxes for i, bbox in enumerate(bboxes_raw): if bbox[0] < 0: bboxes_raw[i][0] = 0 if bbox[1] > 1: bboxes_raw[i][1] = 1 if bbox[2] < 0: bboxes_raw[i][2] = 0 if bbox[3] > 1: bboxes_raw[i][3] = 1 scores_tf = tf.constant(scores, dtype=tf.float32) bboxes_raw_tf = [ [ymax, xmin, ymin, xmax] for [xmin, xmax, ymin, ymax] in bboxes_raw ] bboxes_raw_tf = tf.constant(bboxes_raw_tf, dtype=tf.float32) selected_indices, selected_scores =\ non_max_suppression_with_scores(bboxes_raw_tf, scores_tf,\ max_output_size=100,\ iou_threshold=0.7, score_threshold=0.9,\ soft_nms_sigma=0.0) selected_indices_list = selected_indices.numpy().tolist() bboxes = [ bboxes_raw[index] for index in selected_indices_list ] for score, bbox in zip(scores, bboxes): dict_for_df[bbox_idx] = {'FileName': str(img_name),\ 'XMin':bbox[0],\ 'XMax':bbox[1],\ 'YMin':bbox[2],\ 'YMax':bbox[3],\ 'Score':score} bbox_idx += 1 df_p = pd.DataFrame.from_dict(dict_for_df, "index") ### make training data for detector # register memory for input and output data oneHotEncoder = C.oneHotEncoder inputs = np.load(C.img_inputs_npy) imgNum = inputs.shape[0] rois = np.zeros(shape=(imgNum, C.roiNum, 4)) rois[:] = np.nan outputs_classifier = np.zeros(shape=(imgNum, C.roiNum, len(oneHotEncoder)), dtype=np.float32) outputs_classifier[:] = np.nan outputs_regressor = np.zeros(shape=(imgNum, C.roiNum, len(oneHotEncoder)*4), dtype=np.float32) outputs_regressor[:] = np.nan # calculate how many negative examples we want negThreshold = np.int(C.roiNum*C.negativeRate) for img_idx, img in enumerate(imgNames): sys.stdout.write(t_info(f"Parsing image: {img_idx+1}/{len(imgNames)}", '\r')) if img_idx+1 == len(imgNames): sys.stdout.write('\n') sys.stdout.flush() df_r_slice = df_r[df_r['FileName']==img] df_p_slice = df_p[df_p['FileName']==img] bbox_pdgId_pairs =\ [ [[r['XMin'], r['XMax'], r['YMin'], r['YMax']],\ r['ClassName']] \ for i, r in df_r_slice.iterrows()] proposals = [ [r['XMin'], r['XMax'], r['YMin'], r['YMax']] for i, r in df_p_slice.iterrows()] pos_tuples = [] neg_tuples = [] # iterate over proposed bboxes to sort them into positives and negatives for proposal in proposals: iou_highest=0 label = None ref_bbox = None for bbox, pdgId in bbox_pdgId_pairs: iou_tmp = iou(bbox, proposal) if iou_tmp > iou_highest: iou_highest = iou_tmp label = pdgId ref_bbox = bbox if iou_highest > 0.5: pos_tuples.append((proposal, label, ref_bbox)) elif iou_highest > 0.1: neg_tuples.append((proposal, 'bg', ref_bbox)) # calculate the number of positive example and negative example posNum = len(pos_tuples) negNum = len(neg_tuples) totNum = posNum + negNum roiNum = C.roiNum if totNum < roiNum: tuples_combined = pos_tuples+neg_tuples # The original/whole sample sampleNum = len(tuples_combined) tuples_selected = copy(tuples_combined) totNum = len(tuples_selected) roiNeedNum = roiNum-totNum while roiNeedNum != 0: if sampleNum < roiNeedNum: tuples_selected += tuples_combined totNum = len(tuples_selected) roiNeedNum = roiNum - totNum else: tuples_selected += random.sample(tuples_combined, roiNeedNum) totNum = len(tuples_selected) roiNeedNum = roiNum - totNum assert len(tuples_selected)==roiNum, pdebug(len(tuples_selected)) else: if negNum < negThreshold: negWant = negNum posWant = roiNum - negWant elif (negThreshold + posNum) >= roiNum: negWant = negThreshold posWant = roiNum - negThreshold else: posWant = posNum negWant = roiNum - posWant # randomly select RoIs for training pos_selected = random.sample(pos_tuples, posWant) neg_selected = random.sample(neg_tuples, negWant) # combine negative examples and positive examples and shuffle tuples_selected = pos_selected + neg_selected random.shuffle(tuples_selected) # copy the result to the registered memory for i, tuple in enumerate(tuples_selected): proposal, label, ref_bbox = tuple # proposal t = (x, y, w, h) as indicated in the original paper # (x,y) is the left upper corner t = [ proposal[0], proposal[3],\ (proposal[1]-proposal[0]), (proposal[3]-proposal[2]) ] rois[img_idx][i] = np.array(t, dtype=np.float32) oneHotVector = oneHotEncoder[label] outputs_classifier[img_idx][i] = oneHotVector # refernece bbox v = (x,y,w,h) as indicated in the original paper # (x,y) is the left upper corner v = [ ref_bbox[0], ref_bbox[3],\ (ref_bbox[1]-ref_bbox[0]), (ref_bbox[3]-ref_bbox[2]) ] record_start = np.where(oneHotVector==1)[0][0] *4 record_end = record_start + 4 outputs_regressor[img_idx][i][record_start:record_end] = v return rois, outputs_classifier, outputs_regressor def frcnn_train_alternative(C): pstage('Start Training') # prepare oneHotEncoder df_r = pd.read_csv(C.bbox_reference_file, index_col=0) categories = df_r['ClassName'].unique().tolist() oneHotEncoder = {} # The first entry indicates if it is a negative example (background) oneHotEncoder['bg'] = np.identity(len(categories)+1)[0] for i, pdgId in enumerate(categories): oneHotEncoder[pdgId] = np.identity(len(categories)+1)[i+1] C.set_oneHotEncoder(oneHotEncoder) # prepare training dataset inputs = np.load(C.img_inputs_npy) label_maps = np.load(C.labels_npy) delta_maps = np.load(C.deltas_npy) # outputs cwd = Path.cwd() data_dir = C.sub_data_dir weight_dir = C.data_dir.parent.joinpath('weights') C.weight_dir = weight_dir model_weights_file = weight_dir.joinpath(C.frcnn_model_name+'.h5') rpn_record_file = data_dir.joinpath(C.frcnn_record_name+'_rpn.csv') detector_record_file = data_dir.joinpath(C.frcnn_record_name+'_detector.csv') pinfo('I/O Path is configured') # build models img_input = Input(C.input_shape) base_net = C.base_net.get_base_net(img_input) rpn_layer = rpn(C.anchor_scales, C.anchor_ratios) rpn_classifier = rpn_layer.classifier(base_net) rpn_regressor = rpn_layer.regression(base_net) model_rpn = Model(inputs=img_input, outputs = [rpn_classifier,rpn_regressor]) RoI_input = Input(shape=(C.roiNum,4)) x = RoIPooling(6,6)([base_net, RoI_input]) x = Dense(4096, activation='relu')(x) x = Dense(4096, activation='relu')(x) x = Reshape((C.roiNum,6*6*4096))(x) x1 = Dense(2)(x) output_classifier = Softmax(axis=2, name='detector_out_class')(x1) output_regressor = Dense(2*4, activation='linear', name='detector_out_regr')(x) model_detector = Model(inputs=[img_input, RoI_input], outputs = [output_classifier, output_regressor]) model_all = Model(inputs=[img_input, RoI_input], outputs=[rpn_classifier,rpn_regressor,output_classifier, output_regressor]) # setup loss rpn_regr_loss = define_rpn_regr_loss(C.rpn_lambdas[1]) rpn_class_loss = define_rpn_class_loss(C.rpn_lambdas[0]) detector_class_loss = define_detector_class_loss(C.detector_lambda[0]) detector_regr_loss = define_detector_regr_loss(C.detector_lambda[1]) # setup metric ca = CategoricalAccuracy() # setup optimizer lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay( initial_learning_rate=1e-4, decay_steps=10000, decay_rate=0.9) adam = Adam(learning_rate=lr_schedule) # compile models model_rpn.compile(optimizer=adam, loss={'rpn_out_class' : rpn_class_loss,\ 'rpn_out_regress': rpn_regr_loss},\ metrics={'rpn_out_class': [unmasked_binary_accuracy, positive_number],\ 'rpn_out_regress': unmasked_IoU}) model_detector.compile(optimizer=adam, loss={'detector_out_class':detector_class_loss,\ 'detector_out_regr':detector_regr_loss},\ metrics = {'detector_out_class':ca,\ 'detector_out_regr':unmasked_IoU}) model_all.compile(optimizer=adam, loss={'rpn_out_class' : rpn_class_loss,\ 'rpn_out_regress': rpn_regr_loss,\ 'detector_out_class':detector_class_loss,\ 'detector_out_regr':detector_regr_loss}) model_all.summary() # setup record RpnCsvCallback = tf.keras.callbacks.CSVLogger(str(rpn_record_file), separator=",", append=True) DetectorCsvCallback = tf.keras.callbacks.CSVLogger(str(detector_record_file), separator=",", append=True) time_of_iterations = 2 for i in range(time_of_iterations): pinfo(f"Alternative training: iteration {i+1}/{time_of_iterations}") pinfo('RPN training') model_rpn.fit(x=inputs, y=[label_maps, delta_maps],\ validation_split=0.25,\ shuffle=True,\ batch_size=8, epochs=10,\ callbacks = [RpnCsvCallback]) pinfo('RPN is scoring anchors and proposing delta suggestions') outputs_raw = model_rpn.predict(x=inputs, batch_size=1) pinfo('Proposing RoIs') score_maps = outputs_raw[0] delta_maps = outputs_raw[1] rois, Y_labels, Y_bboxes = rpn_to_roi(C, score_maps, delta_maps) pinfo('Detector training') model_detector.fit(x=[inputs, rois], y=[Y_labels, Y_bboxes],\ validation_split=0.25,\ shuffle=True,\ batch_size=8, epochs=1,\ callbacks = [DetectorCsvCallback]) model_all.save_weights(model_weights_file, overwrite=True) pickle_train_path = Path.cwd().parent.joinpath('frcnn_mc_test/frcnn.test.config.pickle') pickle.dump(C, open(pickle_train_path, 'wb')) pcheck_point('Finished Training') return C if __name__ == "__main__": pbanner() psystem('Faster R-CNN Object Detection System') pmode('Alternative Training') pinfo('Parameters are set inside the script') cwd = Path.cwd() pickle_path = cwd.joinpath('frcnn.train.config.pickle') C = pickle.load(open(pickle_path, 'rb')) # initialize parameters roiNum = 100 negativeRate = 0.75 rpn_lambdas = [1,100] detector_lambdas = [1,100] model_name = 'frcnn_mc_00' record_name = 'frcnn_mc_record_00' C.set_roi_parameters(roiNum, negativeRate) C.set_rpn_lambda(rpn_lambdas) C.set_detector_lambda(detector_lambdas) C.set_frcnn_record(model_name, record_name) C = frcnn_train_alternative(C)
StarcoderdataPython
4834604
import uuid from ast import literal_eval from django_filters.rest_framework import DjangoFilterBackend from django.http import HttpResponse from django.db.models import Q from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin from rest_framework.viewsets import GenericViewSet from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework import generics from .APIpermissions import ProjectPermission from deployments.helpers import build_definition from projects.helpers import create_project_resources from django.contrib.auth.models import User from django.conf import settings import modules.keycloak_lib as kc from projects.models import Environment from .serializers import Model, MLModelSerializer, ModelLog, ModelLogSerializer, Metadata, MetadataSerializer, \ Report, ReportSerializer, ReportGenerator, ReportGeneratorSerializer, Project, ProjectSerializer, \ DeploymentInstance, DeploymentInstanceSerializer, DeploymentDefinition, \ DeploymentDefinitionSerializer, Session, LabSessionSerializer, UserSerializer, \ DatasetSerializer, FileModelSerializer, Dataset, FileModel, Volume, VolumeSerializer, \ ExperimentSerializer, Experiment class ModelList(GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated, ProjectPermission,) serializer_class = MLModelSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['id','name', 'version'] def get_queryset(self): """ This view should return a list of all the models for the currently authenticated user. """ return Model.objects.filter(project__pk=self.kwargs['project_pk']) def destroy(self, request, *args, **kwargs): model = self.get_object() model.delete() return HttpResponse('ok', 200) def create(self, request, *args, **kwargs): project = Project.objects.get(id=self.kwargs['project_pk']) try: model_name = request.data['name'] release_type = request.data['release_type'] description = request.data['description'] model_uid = request.data['uid'] except: return HttpResponse('Failed to create model.', 400) new_model = Model(name=model_name, release_type=release_type, description=description, uid=model_uid, project=project) new_model.save() return HttpResponse('ok', 200) class ModelLogList(GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated, ProjectPermission,) serializer_class = ModelLogSerializer filter_backends = [DjangoFilterBackend] #filterset_fields = ['id','name', 'version'] # Not sure if this kind of function is needed for ModelLog? def get_queryset(self): return ModelLog.objects.filter(project__pk=self.kwargs['project_pk']) def create(self, request, *args, **kwargs): project = Project.objects.get(id=self.kwargs['project_pk']) try: run_id = request.data['run_id'] trained_model = request.data['trained_model'] training_started_at = request.data['training_started_at'] execution_time = request.data['execution_time'] code_version = request.data['code_version'] current_git_repo = request.data['current_git_repo'] latest_git_commit = request.data['latest_git_commit'] system_details = request.data['system_details'] cpu_details = request.data['cpu_details'] training_status = request.data['training_status'] except: return HttpResponse('Failed to create training session log.', 400) new_log = ModelLog(run_id=run_id, trained_model=trained_model, project=project.name, training_started_at=training_started_at, execution_time=execution_time, code_version=code_version, current_git_repo=current_git_repo, latest_git_commit=latest_git_commit, system_details=system_details, cpu_details=cpu_details, training_status=training_status, ) new_log.save() return HttpResponse('ok', 200) class MetadataList(GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated, ProjectPermission,) serializer_class = MetadataSerializer filter_backends = [DjangoFilterBackend] #filterset_fields = ['id','name', 'version'] def create(self, request, *args, **kwargs): project = Project.objects.get(id=self.kwargs['project_pk']) try: run_id = request.data['run_id'] trained_model = request.data['trained_model'] model_details = request.data['model_details'] parameters = request.data['parameters'] metrics = request.data['metrics'] except: return HttpResponse('Failed to create metadata log.', 400) new_md = Metadata(run_id=run_id, trained_model=trained_model, project=project.name, model_details=model_details, parameters=parameters, metrics=metrics, ) new_md.save() return HttpResponse('ok', 200) class LabsList(GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated, ProjectPermission,) serializer_class = LabSessionSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['id', 'name', 'lab_session_owner'] def get_queryset(self): """ This view should return a list of all the Lab Sessions for the currently authenticated user. """ return Session.objects.filter(project__pk=self.kwargs['project_pk']) def create(self, request, *args, **kwargs): project = Project.objects.get(id=self.kwargs['project_pk']) uid = uuid.uuid4() name = str(project.slug) + str(uid)[0:7] try: flavor_slug = request.data['flavor'] environment_slug = request.data['environment'] except Exception as e: print(e) return HttpResponse('Failed to create a Lab Session.', 400) lab_session = Session(id=uid, name=name, flavor_slug=flavor_slug, environment_slug=environment_slug, project=project, lab_session_owner=request.user) lab_session.extraVols = [] if 'extraVols' in request.data: lab_session.extraVols = request.data['extraVols'] lab_session.save() return HttpResponse('Ok.', 200) class DeploymentDefinitionList(GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated,) serializer_class = DeploymentDefinitionSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['name'] @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated]) def build_definition(self, request): instance = DeploymentDefinition.objects.get(name=request.data['name']) build_definition(instance) return HttpResponse('ok', 200) def get_queryset(self): """ This view should return a list of all the deployments for the currently authenticated user. """ current_user = self.request.user return DeploymentDefinition.objects.filter(project__owner__username=current_user) class DeploymentInstanceList(GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated,) serializer_class = DeploymentInstanceSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['id'] def get_queryset(self): """ This view should return a list of all the deployments for the currently authenticated user. """ current_user = self.request.user print(self.request.query_params) project = self.request.query_params.get('project', []) model = self.request.query_params.get('model', []) if model: return DeploymentInstance.objects.filter(model__project__owner__username=current_user, model__project=project, model=model) else: return DeploymentInstance.objects.filter(model__project__owner__username=current_user, model__project=project) def destroy(self, request, *args, **kwargs): current_user = self.request.user name = self.request.query_params.get('name', []) version = self.request.query_params.get('version', []) if name and version: instance = DeploymentInstance.objects.get(model__name=name, model__version=version) print('Deleting deployment of model {}-{}.'.format(name, version)) else: return HttpResponse('Takes model and tag as parameters.', 400) if current_user == instance.model.project.owner: resource = instance.helmchart resource.delete() return HttpResponse('ok', 200) else: return HttpResponse('Not Allowed', 400) @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated]) def build_instance(self, request): model_name = request.data['name'] model_version = request.data['version'] environment = request.data['depdef'] project_id = request.data['project'] project = Project.objects.get(pk=project_id) print(model_name+':'+model_version) try: print('Check model') # TODO: Check that we have permission to access the model. if model_version=='latest': mod = Model.objects_version.latest(model_name, project) else: mod = Model.objects.get(name=model_name, version=model_version, project=project) if mod.status == 'DP': return HttpResponse('Model {}:{} already deployed.'.format(model_name, model_version), status=400) except: return HttpResponse('Model {}:{} not found.'.format(model_name, model_version), status=400) try: # TODO: Check that we have permission to access the deployment definition. dep = DeploymentDefinition.objects.get(name=environment) except: return HttpResponse('Deployment environment {} not found.'.format(environment), status=404) instance = DeploymentInstance(model=mod, deployment=dep, created_by=request.user.username) instance.params = request.data['deploy_config'] # TODO: Verify that the user is allowed to set the parameters in deploy_config. # This whole endpoint needs to be refactored: # 1. Make consistent with rest of API # 2. Authorization via ProjectPermissions. instance.save() return HttpResponse('ok', status=200) @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated]) def update_instance(self, request): # This implementation is a proof-of-concept, and is used to test # the chart controller upgrade functionality current_user = request.user name = request.data['name'] version = request.data['version'] # Currently only allows updating of the number of replicas. # This code can be improved and generalized later on. We cannot # allow general helm upgrades though, as this can cause STACKn-wide # problems. try: replicas = int(self.request.data['replicas']) except: return HttpResponse('Replicas parameter should be an integer.', 400) print(replicas) if replicas < 0 or (isinstance(replicas, int) == False): return HttpResponse('Replicas parameter should be positive integer.', 400) if name and version: instance = DeploymentInstance.objects.get(model__name=name, model__version=version) print('instance name: '+instance.model.name) else: return HttpResponse('Requires model name and version as parameters.', 400) # Who should be allowed to update the model? Currently only the owner. if current_user == instance.model.project.owner: params = instance.helmchart.params params = literal_eval(params) params['replicas'] = str(replicas) print(params) instance.helmchart.params = params instance.helmchart.save() return HttpResponse('Ok', status=200) @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated]) def auth(self, request): auth_req_red = request.headers['X-Auth-Request-Redirect'].replace('predict/','') subs = auth_req_red.split('/') release = '{}-{}-{}'.format(subs[1], subs[3], subs[4]) try: instance = DeploymentInstance.objects.get(release=release) except: return HttpResponse(status=500) if instance.access == 'PU' or instance.model.project.owner == request.user: return HttpResponse('Ok', status=200) else: return HttpResponse(status=401) class ReportList(GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated,) serializer_class = ReportSerializer def get_queryset(self): """ This view should return a list of all the reports for the currently authenticated user. """ current_user = self.request.user return Report.objects.filter(generator__project__owner__username=current_user) class ReportGeneratorList(GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated,) serializer_class = ReportGeneratorSerializer def get_queryset(self): """ This view should return a list of all the report generators for the currently authenticated user. """ current_user = self.request.user return ReportGenerator.objects.filter(project__owner__username=current_user) class MembersList(generics.ListAPIView, GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated, ProjectPermission, ) serializer_class = UserSerializer filter_backends = [DjangoFilterBackend] def get_queryset(self): """ This view should return a list of all the members of the project """ proj = Project.objects.filter(pk=self.kwargs['project_pk']) owner = proj[0].owner auth_users = proj[0].authorized.all() print(owner) print(auth_users) ids = set() ids.add(owner.pk) for user in auth_users: ids.add(user.pk) # return [owner, authorized] print(ids) users = User.objects.filter(pk__in=ids) print(users) return users def create(self, request, *args, **kwargs): project = Project.objects.get(id=self.kwargs['project_pk']) selected_users = request.data['selected_users'] role = request.data['role'] for username in selected_users.split(','): user = User.objects.get(username=username) project.authorized.add(user) kc.keycloak_add_role_to_user(project.slug, user.username, role) project.save() return HttpResponse('Successfully added members.', status=200) def destroy(self, request, *args, **kwargs): print('removing user') project = Project.objects.get(id=self.kwargs['project_pk']) user_id = self.kwargs['pk'] print(user_id) user = User.objects.get(pk=user_id) print('user') print(user) if user.username != project.owner.username: print('username'+user.username) project.authorized.remove(user) for role in settings.PROJECT_ROLES: kc.keycloak_add_role_to_user(project.slug, user.username, role, action='delete') return HttpResponse('Successfully removed members.', status=200) else: return HttpResponse('Cannot remove owner of project.', status=400) return HttpResponse('Failed to remove user.', status=400) class JobsList(generics.ListAPIView, GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated, ProjectPermission, ) serializer_class = ExperimentSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['id', 'username', 'project'] def get_queryset(self): jobs = Experiment.objects.filter(project__pk=self.kwargs['project_pk']) return jobs def create(self, request, *args, **kwargs): try: project = Project.objects.get(id=self.kwargs['project_pk']) environment = Environment.objects.get(name=request.data['environment']) job = Experiment(username=request.user.username, command=request.data['command'], environment=environment, project=project, schedule=request.data['schedule']) job.options = request.data job.save() except Exception as err: print(err) return HttpResponse('Failed to create job.', 400) return HttpResponse('ok', 200) class VolumeList(generics.ListAPIView, GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated, ProjectPermission, ) serializer_class = VolumeSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['name', 'slug', 'created_by'] def get_queryset(self): project = Project.objects.get(id=self.kwargs['project_pk']) volumes = Volume.objects.filter(project_slug=project.slug) return volumes def create(self, request, *args, **kwargs): try: project = Project.objects.get(id=self.kwargs['project_pk']) name = request.data['name'] size = request.data['size'] proj_slug = project.slug created_by = request.user.username volume = Volume(name=name, size=size, created_by=created_by, project_slug=proj_slug) volume.save() except Exception as err: print(err) return HttpResponse('Failed to create volume.', 400) return HttpResponse('ok', 200) def destroy(self, request, *args, **kwargs): project = Project.objects.get(id=self.kwargs['project_pk']) volume = Volume.objects.get(pk=self.kwargs['pk'], project_slug=project.slug) try: volume.helmchart.delete() print('OK') return HttpResponse('ok', 200) except Exception as err: print('Failed') print(err) return HttpResponse('Failed to delete volume', 400) class DatasetList(generics.ListAPIView, GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated, ProjectPermission, ) serializer_class = DatasetSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['name', 'project_slug', 'version'] def get_queryset(self): """ This view should return a list of all the members of the project """ project = Project.objects.get(pk=self.kwargs['project_pk']) return Dataset.objects.filter(project_slug=project.slug) def create(self, request, *args, **kwargs): project = Project.objects.get(id=self.kwargs['project_pk']) try: dataset_name = request.data['name'] release_type = request.data['release_type'] filenames = request.data['filenames'].split(',') description = request.data['description'] bucket = request.data['bucket'] new_dataset = Dataset(name=dataset_name, release_type=release_type, description=description, project_slug=project.slug, bucket=bucket, created_by=request.user.username) new_dataset.save() for fname in filenames: fobj = FileModel(name=fname, bucket=bucket) fobj.save() new_dataset.files.add(FileModel.objects.get(pk=fobj.pk)) new_dataset.save() except Exception as err: print(err) return HttpResponse('Failed to create dataset.', 400) return HttpResponse('ok', 200) def destroy(self, request, *args, **kwargs): print('Deleting dataset') project = Project.objects.get(id=self.kwargs['project_pk']) dataset = Dataset.objects.get(pk=self.kwargs['pk'], project_slug=project.slug) try: dataset.delete() print('OK') return HttpResponse('ok', 200) except Exception as err: print('Failed') print(err) return HttpResponse('Failed to delete dataset', 400) class ProjectList(generics.ListAPIView, GenericViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, ListModelMixin): permission_classes = (IsAuthenticated,) serializer_class = ProjectSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['name', 'slug'] def get_queryset(self): """ This view should return a list of all the projects for the currently authenticated user. """ current_user = self.request.user return Project.objects.filter(Q(owner__username=current_user) | Q(authorized__pk__exact=current_user.pk)) @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated]) def create_project(self, request): name = request.data['name'] description = request.data['description'] repository = request.data['repository'] project = Project.objects.create_project(name=name, owner=request.user, description=description, repository=repository) success = True try: create_project_resources(project, request.user, repository=repository) except: print("ERROR: could not create project resources") success = False return HttpResponse('Ok', status=400) if success: project.save() return HttpResponse('Ok', status=200)
StarcoderdataPython
3293811
def beachfront_cell(map, i, j): '''Returns the amount of beachfront for the cell at `map[i][j]`. The map is a grid of 1s and 0s where 1 means land and 0 means water. Beachfront is defined as any point where water borders land to the top, bottom, left, or right. Only land cells have beachfront (otherwise the same beachfront would be counted twice). Cells beyond the border of the map are always considered water. Arguments: map (2D rectangular list): The map of the island. i (int): The row coordinate of the cell. j (int): The column coordinate of the cell. Returns: beachfront (int): The amount of beachfront at `map[i][j]`. ''' n_rows = len(map) n_cols = len(map[0]) first_row = 0 first_col = 0 last_row = n_rows - 1 last_col = n_cols - 1 center = map[i][j] t = map[i - 1][j] if first_row < i else 0 b = map[i + 1][j] if i < last_row else 0 l = map[i][j - 1] if first_col < j else 0 r = map[i][j + 1] if j < last_col else 0 if center == 0: return 0 else: beachfront = 0 if t == 0: beachfront += 1 if b == 0: beachfront += 1 if l == 0: beachfront += 1 if r == 0: beachfront += 1 return beachfront def beachfront_island(map): '''Returns the amount of beachfront for the island described by the map. The map is a grid of 1s and 0s where 1 means land and 0 means water. Beachfront is defined as any point where water borders land to the top, bottom, left, or right. Only land cells have beachfront (otherwise the same beachfront would be counted twice). Cells beyond the border of the map are always considered water. Arguments: map (2D rectangular list): The map of the island. Returns: beachfront (int): The amount of beachfront on the entire map. ''' perimeter = 0 for i, row in enumerate(map): for j, _ in enumerate(row): perimeter += beachfront_cell(map, i, j) return perimeter def test(): assert beachfront_island([ [0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0], ]) == 16
StarcoderdataPython
156651
import os from pathlib import Path import subprocess import paramiko from paramiko.rsakey import RSAKey from .box_config import BoxConfig class SSH: """Manage SSH connections""" ip: str user: str client: paramiko.SSHClient def __init__(self, user: str, ip: str, cfg: BoxConfig) -> None: self.user = user self.ip = ip self.client = paramiko.SSHClient() def __enter__(self): return self def __exit__(self, type, value, traceback) -> None: self.client.close() def open(self, folder: Path) -> None: """Open an SSH connection into a provided host, using native SSH""" _, ssh_private_path = SSH.save_keypair(folder) subprocess.run( f'ssh {self.user}@{self.ip} -i {ssh_private_path}', shell=True) def run(self, folder: Path, cmd: str) -> None: """Run an SSH command, and print the output""" _, ssh_private_path = self.save_keypair(folder) self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.client.connect(self.ip, username=self.user, key_filename=str(ssh_private_path)) _, stdout, stderr = self.client.exec_command(cmd, get_pty=True) for line in iter(stderr.readline, ''): print(line, end='') for line in iter(stdout.readline, ''): print(line, end='') @staticmethod def save_keypair(build_folder: Path): """Save RSA public, private keys to a file""" # -- do the credentials exist? build_folder.chmod(0o700) if not os.path.isdir(build_folder): raise FileNotFoundError(f'{build_folder} does not exist') public_key_path = build_folder / 'mystery_box.pub' private_key_path = build_folder / 'mystery_box' public_key_exists = os.path.isfile(public_key_path) private_key_exists = os.path.isfile(private_key_path) if public_key_exists and private_key_exists: return public_key_path, private_key_path # -- if one, but not both exists, wipe the keys if public_key_exists or private_key_exists: if public_key_exists: os. remove(public_key_path) if private_key_exists: os.remove(private_key_path) # -- neither exists; save newly generated credentials # -- save a private-key priv_key = RSAKey.generate(bits=4096) priv_key.write_private_key_file(str(private_key_path), password='') # -- save a public-key pub_key = RSAKey(filename=str(private_key_path), password='') with open(public_key_path, 'w') as conn: conn.write('{0} {1}'.format( pub_key.get_name(), pub_key.get_base64())) return public_key_path, private_key_path
StarcoderdataPython
118155
from django.db import models from users.models import User class Event(models.Model): title = models.CharField(verbose_name="事件名", max_length=64) time = models.DateField(verbose_name="事件执行日期") finished = models.BooleanField(verbose_name="是否完成", default=False) creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="events", related_query_name="event") def __str__(self): return self.title class Meta: db_table = 'events' verbose_name = '事件' verbose_name_plural = verbose_name
StarcoderdataPython
3391039
import json import os.path import posixpath import platform import sys from subprocess import Popen, PIPE, STDOUT if __name__ == '__main__': print "Running " + str(__file__) + "..." #Run the XFoil simulation ------------------------------------------------------------------------------------------ print "Opening 'script.xfoil'..." with open('script.xfoil', 'r') as f_in: xfoil_script = f_in.read() files = ["plot.ps", "polar.txt"] for f in files: if os.path.exists(f): os.remove(f) print "Running XFOIL simulation..." if platform.system() == 'Windows': p = Popen(['C:/OpenMETA/xfoil-and-nrel-codes/bin/xfoil.exe'], stdin=PIPE, stdout=PIPE, stderr=STDOUT) result = p.communicate(input=xfoil_script) elif platform.system() == 'Darwin': p = Popen(['/Applications/Xfoil.app/Contents/Resources/xfoil'], stdin=PIPE, stdout=PIPE, stderr=STDOUT) result = p.communicate(input=xfoil_script) #Save log files print "Saving log files..." with open(os.path.join('log', 'xfoil-stdout.log'), 'w') as f_out: f_out.write(result[0]) with open(os.path.join('log', 'xfoil-stderr.log'), 'w') as f_out: if result[1]: f_out.write(result[1]) else: # empty file pass #Add artifacts to "artifacts" in testbench_manifest.json print "Recording artifacts..." with open('testbench_manifest.json', 'r') as f_in: testbench_manifest = json.load(f_in) expected_files = {"plot": "plot.ps", "polar table": "polar.txt", "XFOIL stdout log": posixpath.join("log", "xfoil-stdout.log"), "XFOIL stderr log": posixpath.join("log", "xfoil-stderr.log")} artifacts = testbench_manifest["Artifacts"] for k, v in expected_files.iteritems(): if os.path.exists(v): artifacts.append({"Tag": k, "Location": v}) with open('testbench_manifest.json', 'w') as f_out: json.dump(testbench_manifest, f_out, indent=2) print "Done." #Let the testbench executor know how the job went sys.exit(p.returncode)
StarcoderdataPython
1769295
<filename>mymongolib/mysql.py import signal import sys import logging from pymysqlreplication import BinLogStreamReader from pymysqlreplication.row_event import ( DeleteRowsEvent, UpdateRowsEvent, WriteRowsEvent, ) def mysql_stream(conf, mongo, queue_out): logger = logging.getLogger(__name__) # server_id is your slave identifier, it should be unique. # set blocking to True if you want to block and wait for the next event at # the end of the stream mysql_settings = { "host": conf['host'], "port": conf.getint('port'), "user": conf['user'], "passwd": conf['password'] } last_log = mongo.get_log_pos() if last_log['log_file'] == 'NA': log_file = None log_pos = None resume_stream = False else: log_file = last_log['log_file'] log_pos = int(last_log['log_pos']) resume_stream = True stream = BinLogStreamReader(connection_settings=mysql_settings, server_id=conf.getint('slaveid'), only_events=[DeleteRowsEvent, WriteRowsEvent, UpdateRowsEvent], blocking=True, resume_stream=resume_stream, log_file=log_file, log_pos=log_pos, only_schemas=conf['databases'].split(',')) for binlogevent in stream: binlogevent.dump() schema = "%s" % binlogevent.schema table = "%s" % binlogevent.table for row in binlogevent.rows: if isinstance(binlogevent, DeleteRowsEvent): vals = row["values"] event_type = 'delete' elif isinstance(binlogevent, UpdateRowsEvent): vals = dict() vals["before"] = row["before_values"] vals["after"] = row["after_values"] event_type = 'update' elif isinstance(binlogevent, WriteRowsEvent): vals = row["values"] event_type = 'insert' seqnum = mongo.write_to_queue(event_type, vals, schema, table) mongo.write_log_pos(stream.log_file, stream.log_pos) queue_out.put({'seqnum': seqnum}) logger.debug(row) logger.debug(stream.log_pos) logger.debug(stream.log_file) stream.close()
StarcoderdataPython
1745495
# -*- coding:utf-8 -*- from unittest import TestCase from simstring.measure.dice import DiceMeasure class TestCosine(TestCase): measure = DiceMeasure() def test_min_feature_size(self): self.assertEqual(self.measure.min_feature_size(5, 1.0), 5) self.assertEqual(self.measure.min_feature_size(5, 0.5), 2) def test_max_feature_size(self): self.assertEqual(self.measure.max_feature_size(5, 1.0), 5) self.assertEqual(self.measure.max_feature_size(5, 0.5), 15) def test_minimum_common_feature_count(self): self.assertEqual(self.measure.minimum_common_feature_count(5, 5, 1.0), 13) self.assertEqual(self.measure.minimum_common_feature_count(5, 20, 1.0), 50) self.assertEqual(self.measure.minimum_common_feature_count(5, 5, 0.5), 7) def test_similarity(self): x = [1, 2, 3] y = [1, 2, 3, 4] self.assertEqual(round(self.measure.similarity(x, x), 2), 1.0) self.assertEqual(round(self.measure.similarity(x, y), 2), 0.86)
StarcoderdataPython
4800091
<filename>setup.py from setuptools import setup, find_packages from os import path from io import open here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup(name='veriservice', version='0.0.34', description='Python client for Veri', long_description=long_description, long_description_content_type='text/markdown', url='http://github.com/bgokden/veri-python-client', author='<NAME>', author_email='<EMAIL>', license='Apache Software License', keywords='veri service python client', packages=find_packages(exclude=['tests*']), install_requires=['grpcio-tools','googleapis-common-protos'])
StarcoderdataPython
3201092
<reponame>hsivan/automon import autograd.numpy as np from autograd import hessian from scipy.optimize import minimize import matplotlib.pyplot as plt from matplotlib import rcParams, rcParamsDefault from scipy.optimize import brentq from autograd import grad from experiments.visualization.visualization_utils import get_figsize def func_sine(X): return np.sin(X) def plot_admissible_region(X0, xlim, ylim, func_to_convex, l_thresh, u_thresh, left_range, right_range): rcParams['pdf.fonttype'] = 42 rcParams['ps.fonttype'] = 42 rcParams.update({'legend.fontsize': 5.4}) rcParams.update({'font.size': 5.8}) # textwidth is 506.295, columnwidth is 241.14749 fig = plt.figure(figsize=get_figsize(columnwidth=506.295, wf=0.32, hf=0.42)) ax = fig.gca() ax.set_xlim(xlim) ax.set_ylim(ylim) # Make data X = np.arange(xlim[0], xlim[1], 0.01) Y = func_to_convex(X) # Plot the sine in the domain ax.plot(X, Y, label="$sin(x)$", color="black", linewidth=0.9) ax.plot(X0, func_to_convex(X0), 'o', label="$x_0$", color="black", markersize=3) ax.axvspan(xmin=left_range, xmax=right_range, edgecolor="none", facecolor="grey", alpha=0.25) plt.xticks([left_range, right_range]) ax.hlines(y=u_thresh, xmin=xlim[0], xmax=xlim[1], colors='tab:blue', linestyles="--", label='$U$', linewidth=0.9) ax.hlines(y=l_thresh, xmin=xlim[0], xmax=xlim[1], colors='tab:red', linestyles="--", label='$L$', linewidth=0.9) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_linewidth(0.5) ax.spines['left'].set_linewidth(0.5) ax.tick_params(width=0.5) handles, labels = ax.get_legend_handles_labels() plt.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5, 1.34), ncol=4, columnspacing=1, handlelength=1.7, frameon=False) plt.subplots_adjust(top=0.82, bottom=0.18, left=0.09, right=0.96, hspace=0.08, wspace=0.2) fig_file_name = "sine_admissible_region.pdf" plt.savefig(fig_file_name) plt.close(fig) rcParams.update(rcParamsDefault) def plot_2d_convex_diff(X0, xlim, ylim, func_to_convex, l_thresh, u_thresh, func_g_convex, func_h_convex, func_g_minus_l_tangent, left_range, right_range): rcParams['pdf.fonttype'] = 42 rcParams['ps.fonttype'] = 42 rcParams.update({'legend.fontsize': 5.4}) rcParams.update({'font.size': 5.8}) # textwidth is 506.295, columnwidth is 241.14749 fig = plt.figure(figsize=get_figsize(columnwidth=506.295, wf=0.32, hf=0.42)) ax = fig.gca() ax.set_xlim(xlim) ax.set_ylim(ylim) # Make data X = np.arange(xlim[0], xlim[1], 0.01) Y = func_to_convex(X) # Plot the sine in the domain ax.plot(X, Y, color="black", linewidth=0.9) ax.plot(X0, func_to_convex(X0), 'o', color="black", markersize=3) g_convex_val = func_g_convex(X) h_convex_val = func_h_convex(X) ax.plot(X, g_convex_val, label=r"$\breve{g}(x)$", color="tab:orange", linewidth=0.9) ax.plot(X, h_convex_val, label=r"$\breve{h}(x)$", color="tab:green", linewidth=0.9) g_minus_l_tangent_val = func_g_minus_l_tangent(X) ax.fill_between(X, g_convex_val, u_thresh, where=g_convex_val < u_thresh, color='orange', alpha=0.5, interpolate=True) ax.fill_between(X, h_convex_val, g_minus_l_tangent_val, where=h_convex_val < g_minus_l_tangent_val, color='green', alpha=0.3, interpolate=True) ax.axvline(x=left_range, ymin=-1, ymax=1, linestyle=":", color="grey", linewidth=0.8) ax.axvline(x=right_range, ymin=-1, ymax=1, linestyle=":", color="grey", linewidth=0.8) plt.xticks([left_range, right_range]) ax.hlines(y=u_thresh, xmin=xlim[0], xmax=xlim[1], colors='tab:blue', linestyles="--", linewidth=0.9) ax.hlines(y=l_thresh, xmin=xlim[0], xmax=xlim[1], colors='tab:red', linestyles="--", linewidth=0.9) ax.plot(X, g_minus_l_tangent_val, label=r"$f(x_0)+\nabla f(x_0)^T (x-x_0) - L$", color="grey", linestyle="-.", linewidth=0.9) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_linewidth(0.5) ax.spines['left'].set_linewidth(0.5) ax.tick_params(width=0.5) handles, labels = ax.get_legend_handles_labels() plt.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5, 1.36), ncol=3, columnspacing=0.8, handlelength=1.7, frameon=False, handletextpad=0.8) plt.subplots_adjust(top=0.82, bottom=0.18, left=0.09, right=0.96, hspace=0.08, wspace=0.2) fig_file_name = "sine_convex_diff.pdf" plt.savefig(fig_file_name) plt.close(fig) rcParams.update(rcParamsDefault) def plot_2d_concave_diff(X0, xlim, ylim, func_to_concave, l_thresh, u_thresh, func_g_concave, func_h_concave, func_g_minus_u_tangent, left_range, right_range): rcParams['pdf.fonttype'] = 42 rcParams['ps.fonttype'] = 42 rcParams.update({'legend.fontsize': 5.4}) rcParams.update({'font.size': 5.8}) # textwidth is 506.295, columnwidth is 241.14749 fig = plt.figure(figsize=get_figsize(columnwidth=506.295, wf=0.32, hf=0.42)) ax = fig.gca() ax.set_xlim(xlim) ax.set_ylim(ylim) # Make data X = np.arange(xlim[0], xlim[1], 0.01) Y = func_to_concave(X) # Plot the sine in the domain ax.plot(X, Y, color="black", linewidth=0.9) ax.plot(X0, func_to_concave(X0), 'o', color="black", markersize=3) g_concave_val = func_g_concave(X) h_concave_val = func_h_concave(X) ax.plot(X, g_concave_val, label="$\hat{g}(x)$", color="tab:green", linewidth=0.9) ax.plot(X, h_concave_val, label="$\hat{h}(x)$", color="tab:orange", linewidth=0.9) g_minus_u_tangent_val = func_g_minus_u_tangent(X) ax.fill_between(X, g_concave_val, l_thresh, where=g_concave_val > l_thresh, color='green', alpha=0.5, interpolate=True) ax.fill_between(X, h_concave_val, g_minus_u_tangent_val, where=h_concave_val > g_minus_u_tangent_val, color='orange', alpha=0.3, interpolate=True) ax.axvline(x=left_range, ymin=-1, ymax=1, linestyle=":", color="grey", linewidth=0.8) ax.axvline(x=right_range, ymin=-1, ymax=1, linestyle=":", color="grey", linewidth=0.8) plt.xticks([left_range, right_range]) ax.hlines(y=u_thresh, xmin=xlim[0], xmax=xlim[1], colors='tab:blue', linestyles="--", linewidth=0.9) ax.hlines(y=l_thresh, xmin=xlim[0], xmax=xlim[1], colors='tab:red', linestyles="--", linewidth=0.9) ax.plot(X, g_minus_u_tangent_val, label=r"$f(x_0) +\nabla f(x_0)^T (x-x_0) - U$", color="grey", linestyle="-.", linewidth=0.9) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_linewidth(0.5) ax.spines['left'].set_linewidth(0.5) ax.tick_params(width=0.5) handles, labels = ax.get_legend_handles_labels() plt.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5, 1.38), ncol=3, columnspacing=0.8, handlelength=1.7, frameon=False, handletextpad=0.8) plt.subplots_adjust(top=0.82, bottom=0.18, left=0.09, right=0.96, hspace=0.08, wspace=0.2) fig_file_name = "sine_concave_diff.pdf" plt.savefig(fig_file_name) plt.close(fig) rcParams.update(rcParamsDefault) # Minimize this function over x in a specific neighborhood around X0 def func_min_eigenvalue(x, args): hess = args eigenvalues, eigenvector = np.linalg.eig(hess(x)) min_eigenvalue = np.min(eigenvalues) return min_eigenvalue # Maximize this function over x in a specific neighborhood around X0 def func_max_eigenvalue(x, args): hess = args eigenvalues, eigenvector = np.linalg.eig(hess(x)) max_eigenvalue = np.max(eigenvalues) return -1.0 * max_eigenvalue def func_min_max_eigenvalues(func_to_convex, X0, domain): hess = hessian(func_to_convex) sol_min = minimize(func_min_eigenvalue, X0, args=hess, bounds=domain) sol_max = minimize(func_max_eigenvalue, X0, args=hess, bounds=domain) min_eigenvalue = sol_min.fun minimizing_point = sol_min.x max_eigenvalue = -1.0 * sol_max.fun maximizing_point = sol_max.x return min_eigenvalue, minimizing_point, max_eigenvalue, maximizing_point def find_min_and_max_eigenvalues(func_to_convex, domain): min_eigenvalue = np.inf max_eigenvalue = -np.inf # Start the optimization process from multiple points in the domain, then choose the max and min rand_start_points = np.random.uniform(domain[0][0], domain[0][1], (10, len(domain))) for start_point in rand_start_points: start_point = np.array(start_point, dtype=np.float32) min_eigenvalue_temp, minimizing_point, max_eigenvalue_temp, maximizing_point = func_min_max_eigenvalues(func_to_convex, start_point, domain) min_eigenvalue = np.minimum(min_eigenvalue, min_eigenvalue_temp) max_eigenvalue = np.maximum(max_eigenvalue, max_eigenvalue_temp) assert (min_eigenvalue <= max_eigenvalue) print("max_eigenvalue:", max_eigenvalue) print("min_eigenvalue:", min_eigenvalue) return min_eigenvalue, max_eigenvalue def admissible_region(X0, func_to_convex, xlim=None, ylim=None): l_thresh = func_to_convex(X0) - 0.2 u_thresh = func_to_convex(X0) + 0.2 func = lambda x: func_to_convex(x) - l_thresh lower_thresh_root_left, lower_thresh_root_right = brentq(func, X0 - 2, X0), brentq(func, X0, X0 + 2) plot_admissible_region(X0, xlim, ylim, func_to_convex, l_thresh, u_thresh, lower_thresh_root_left, lower_thresh_root_right) def convex_diff(X0, min_eigenvalue, func_to_convex, xlim=None, ylim=None): l_thresh = func_to_convex(X0) - 0.2 u_thresh = func_to_convex(X0) + 0.2 search_roots_distance = 10 eig = min_eigenvalue g_convex = lambda x: func_to_convex(x) + 0.5 * np.abs(eig) * (x - X0) * (x - X0) h_convex = lambda x: 0.5 * np.abs(eig) * (x - X0) * (x - X0) grad_func_to_convex = grad(func_to_convex) g_minus_l_tangent = lambda x: func_to_convex(X0) + grad_func_to_convex(X0) * (x - X0) - l_thresh # Condition 1: g(x) < U. # Check where g(x) = U and write in title func = lambda x: g_convex(x) - u_thresh upper_thresh_root_left, upper_thresh_root_right = brentq(func, X0 - search_roots_distance, X0), brentq(func, X0, X0 + search_roots_distance) assert upper_thresh_root_left <= upper_thresh_root_right, str(upper_thresh_root_left) + "," + str(upper_thresh_root_right) upper_safe_zone_size = upper_thresh_root_right - upper_thresh_root_left # Condition 2: Tangent g(x)-L bigger than h(x) # Check where Tangent g(x)-L = h(x) and write in figure title func = lambda x: g_minus_l_tangent(x) - h_convex(x) lower_thresh_root_left, lower_thresh_root_right = brentq(func, X0 - search_roots_distance, X0), brentq(func, X0, X0 + search_roots_distance) assert lower_thresh_root_left <= lower_thresh_root_right, str(lower_thresh_root_left) + "," + str(lower_thresh_root_right) lower_safe_zone_size = lower_thresh_root_right - lower_thresh_root_left if upper_safe_zone_size == 0 or lower_safe_zone_size == 0: safe_zone_size = 0 else: safe_zone_size = np.minimum(upper_thresh_root_right, lower_thresh_root_right) - np.maximum(upper_thresh_root_left, lower_thresh_root_left) assert safe_zone_size >= 0, str(safe_zone_size) plot_2d_convex_diff(X0, xlim, ylim, func_to_convex, l_thresh, u_thresh, g_convex, h_convex, g_minus_l_tangent, np.maximum(lower_thresh_root_left, upper_thresh_root_left), np.minimum(lower_thresh_root_right, upper_thresh_root_right)) return safe_zone_size, upper_safe_zone_size, lower_safe_zone_size def concave_diff(X0, max_eigenvalue, func_to_concave, xlim=None, ylim=None): l_thresh = func_to_concave(X0) - 0.2 u_thresh = func_to_concave(X0) + 0.2 search_roots_distance = 10 g_concave = lambda x: func_to_concave(x) - 0.5 * max_eigenvalue * (x - X0) * (x - X0) h_concave = lambda x: -0.5 * max_eigenvalue * (x - X0) * (x - X0) grad_func_to_convex = grad(func_to_concave) g_minus_u_tangent = lambda x: func_to_concave(X0) + grad_func_to_convex(X0) * (x - X0) - u_thresh # Condition 1: g(x) > L. # Check where g(x) = L and write in title func = lambda x: g_concave(x) - l_thresh lower_thresh_root_left, lower_thresh_root_right = brentq(func, X0 - search_roots_distance, X0), brentq(func, X0, X0 + search_roots_distance) assert lower_thresh_root_left <= lower_thresh_root_right, str(lower_thresh_root_left) + "," + str(lower_thresh_root_right) lower_safe_zone_size = lower_thresh_root_right - lower_thresh_root_left # Condition 2: Tangent g(x)-U smaller than h(x) # Check where Tangent g(x)-U = h(x) and write in figure title func = lambda x: g_minus_u_tangent(x) - h_concave(x) upper_thresh_root_left, upper_thresh_root_right = brentq(func, X0 - search_roots_distance, X0), brentq(func, X0, X0 + search_roots_distance) assert upper_thresh_root_left <= upper_thresh_root_right, str(upper_thresh_root_left) + "," + str(upper_thresh_root_right) upper_safe_zone_size = upper_thresh_root_right - upper_thresh_root_left if upper_safe_zone_size == 0 or lower_safe_zone_size == 0: safe_zone_size = 0 else: safe_zone_size = np.minimum(upper_thresh_root_right, lower_thresh_root_right) - np.maximum( upper_thresh_root_left, lower_thresh_root_left) assert safe_zone_size >= 0, str(safe_zone_size) plot_2d_concave_diff(X0, xlim, ylim, func_to_concave, l_thresh, u_thresh, g_concave, h_concave, g_minus_u_tangent, np.maximum(lower_thresh_root_left, upper_thresh_root_left), np.minimum(lower_thresh_root_right, upper_thresh_root_right)) return safe_zone_size, upper_safe_zone_size, lower_safe_zone_size if __name__ == "__main__": # Figure 1 X0 = 0.5 * np.pi domain = ((X0 - 3, X0 + 3),) xlim = [X0 - 2.1, X0 + 2.1] ylim = [-0.5, 1.5] X0 = np.array([X0]) min_eigenvalue, max_eigenvalue = find_min_and_max_eigenvalues(func_sine, domain) # Plot the concave and convex diffs convex_diff(X0, min_eigenvalue, func_sine, xlim=xlim, ylim=ylim) concave_diff(X0, max_eigenvalue, func_sine, xlim=xlim, ylim=ylim) admissible_region(X0, func_sine, xlim=xlim, ylim=ylim)
StarcoderdataPython
1675151
import tfm__unit_interval import tfm__2D_rows_sum_to_one__log import tfm__2D_rows_sum_to_one__stickbreak # Make a few functions easily available logistic_sigmoid = tfm__unit_interval.logistic_sigmoid inv_logistic_sigmoid = tfm__unit_interval.inv_logistic_sigmoid from log_logistic_sigmoid import log_logistic_sigmoid
StarcoderdataPython
4801894
<reponame>neugeeug/terraform-aws-ecr-scanner import os, boto3, json import urllib.request, urllib.parse from urllib.error import HTTPError import logging from botocore.exceptions import ClientError client = boto3.client('ecr') logger = logging.getLogger() def get_all_image_data(repository): """ Gets a list of dicts with Image tags and latest scan results. :param repository: :return: [{'imageTags': ['1.0.70'], 'imageScanStatus': {'HIGH': 21, 'MEDIUM': 127, 'INFORMATIONAL': 115, }}] """ images = [] levels = os.environ['RISK_LEVELS'] try: response = client.describe_images(repositoryName=repository, filter={ 'tagStatus': 'TAGGED' })['imageDetails'] except ClientError as c: logger.error("Failed to get result from describe images with, client error: {}".format(c)) return [] for image in response: image_data = {} try: image_data['imageTags'] = image['imageTags'] except KeyError: image_data['imageTags'] = 'IMAGE UNTAGGED' try: image_data['imageScanStatus'] = image['imageScanFindingsSummary']['findingSeverityCounts'] except KeyError: logger.error('FAILED TO RETRIEVE LATEST SCAN STATUS for image {}'.format(image_data['imageTags'])) continue if len(levels) > 0: image_data['imageScanStatus'] = {key: value for key, value in image_data['imageScanStatus'].items() if key in levels} if len(image_data['imageScanStatus']) > 0: images.append(image_data) return images def get_all_repositories(): """ Gets a list of ECR repository string names. :return: ['repository1', 'repository2', 'repository3'] """ repositories = [] response = client.describe_repositories()['repositories'] for repository in response: repositories.append(repository['repositoryName']) return repositories def get_scan_results(): repositories = get_all_repositories() all_images = {} for repository in repositories: all_images[repository] = get_all_image_data(repository) return all_images def convert_scan_dict_to_string(scan_dict): """ converts parsed ImageScanStatus dictionary to string. :param scan_dict: {'HIGH': 64, 'MEDIUM': 269, 'INFORMATIONAL': 157, 'LOW': 127, 'CRITICAL': 17, 'UNDEFINED': 6} :return: HIGH 64, MEDIUM 269, INFORMATIONAL 157, LOW 127, CRITICAL 17, UNDEFINED 6 """ result = '' if not scan_dict: return result try: for key, value in scan_dict.items(): result = result + key + " " + str(value) + ", " except AttributeError: return "Failed to retrieve repository scan results" return result[:len(result)-2] def convert_image_scan_status(repository_scan_results): repository_scan_block_list = [] for image in sorted(repository_scan_results, key=lambda imageScanResult: imageScanResult['imageTags'][0], reverse=True): image_block = dict() image_block["image"] = image['imageTags'][0] image_block["vulnerabilities"] = convert_scan_dict_to_string((image['imageScanStatus'])) repository_scan_block_list.append(image_block) return repository_scan_block_list def create_image_scan_slack_block(repository, repository_scan_block_list): blocks = [] # Generate slack messages for image scan results. for image in repository_scan_block_list: blocks.append( { "type": "section", "text": { "type": "mrkdwn", "text": "*`{}:{}`* vulnerabilities: {}".format(repository, image['image'], image['vulnerabilities']) } } ) return blocks # Send a message to a slack channel def notify_slack(slack_block): slack_url = os.environ['SLACK_WEBHOOK_URL'] slack_channel = os.environ['SLACK_CHANNEL'] slack_username = os.environ['SLACK_USERNAME'] slack_emoji = os.environ['SLACK_EMOJI'] payload = { "channel": slack_channel, "username": slack_username, "icon_emoji": slack_emoji, "blocks": slack_block } data = urllib.parse.urlencode({"payload": json.dumps(payload)}).encode("utf-8") req = urllib.request.Request(slack_url) try: result = urllib.request.urlopen(req, data) return json.dumps({"code": result.getcode(), "info": result.info().as_string()}) except HTTPError as e: logging.error("{}: result".format(e)) return json.dumps({"code": e.getcode(), "info": e.info().as_string()}) def lambda_handler(event, context): scan_results = get_scan_results() for repository, values in scan_results.items(): if len(values) > 0: repository_scan_results = convert_image_scan_status(values) slack_block = create_image_scan_slack_block(repository, repository_scan_results) else: continue if len(slack_block) > 0: try: response = notify_slack(slack_block=slack_block) if json.loads(response)["code"] != 200: logger.error("Error: received status {} for slack_block {}".format(json.loads(response)["info"], slack_block)) except Exception as e: logger.error(msg=e)
StarcoderdataPython
63354
""" Created on 19/06/2020 @author: <NAME> """ from Data_manager.Dataset import Dataset from Data_manager.IncrementalSparseMatrix import IncrementalSparseMatrix_FilterIDs from pandas.api.types import is_string_dtype import pandas as pd def _add_keys_to_mapper(key_to_value_mapper, new_key_list): for new_key in new_key_list: if new_key not in key_to_value_mapper: new_value = len(key_to_value_mapper) key_to_value_mapper[new_key] = new_value return key_to_value_mapper class DatasetMapperManager(object): """ This class is used to build a Dataset object The DatasetMapperManager object takes as input the original data in dataframes. The required columns are: - URM: "UserID", "ItemID", "Data" - ICM: "ItemID", "FeatureID", "Data" - UCM: "UserID", "FeatureID", "Data" The data type of the "Data" columns can be any, the "ItemID", "UserID", "FeatureID" data types MUST be strings. How to use it: - First add all the necessary data calling the add_URM, add_ICM, add_UCM functions - Then call the generate_Dataset function(dataset_name, is_implicit) to obtain the Dataset object. The generate_Dataset function will first transform all "ItemID", "UserID", "FeatureID" into unique numerical indices and represent all of them as sparse matrices: URM, ICM, UCM. """ URM_DICT = None URM_mapper_DICT = None ICM_DICT = None ICM_mapper_DICT = None UCM_DICT = None UCM_mapper_DICT = None user_original_ID_to_index = None item_original_ID_to_index = None __Dataset_finalized = False def __init__(self): super(DatasetMapperManager, self).__init__() self.URM_DICT = {} self.URM_mapper_DICT = {} self.ICM_DICT = {} self.ICM_mapper_DICT = {} self.UCM_DICT = {} self.UCM_mapper_DICT = {} self.__Dataset_finalized = False def generate_Dataset(self, dataset_name, is_implicit): assert not self.__Dataset_finalized, "Dataset mappers have already been generated, adding new data is forbidden" self.__Dataset_finalized = True # Generate ID to index mappers self._generate_global_mappers() self._generate_ICM_UCM_mappers() URM_DICT_sparse = {} ICM_DICT_sparse = {} UCM_DICT_sparse = {} on_new_ID = "ignore" for URM_name, URM_dataframe in self.URM_DICT.items(): URM_sparse_builder = IncrementalSparseMatrix_FilterIDs(preinitialized_col_mapper = self.item_original_ID_to_index, preinitialized_row_mapper = self.user_original_ID_to_index, on_new_col = on_new_ID, on_new_row = on_new_ID) URM_sparse_builder.add_data_lists(URM_dataframe["UserID"].values, URM_dataframe["ItemID"].values, URM_dataframe["Data"].values) URM_DICT_sparse[URM_name] = URM_sparse_builder.get_SparseMatrix() for ICM_name, ICM_dataframe in self.ICM_DICT.items(): feature_ID_to_index = self.ICM_mapper_DICT[ICM_name] ICM_sparse_builder = IncrementalSparseMatrix_FilterIDs(preinitialized_col_mapper = feature_ID_to_index, preinitialized_row_mapper = self.item_original_ID_to_index, on_new_col = on_new_ID, on_new_row = on_new_ID) ICM_sparse_builder.add_data_lists(ICM_dataframe["ItemID"].values, ICM_dataframe["FeatureID"].values, ICM_dataframe["Data"].values) ICM_DICT_sparse[ICM_name] = ICM_sparse_builder.get_SparseMatrix() for UCM_name, UCM_dataframe in self.UCM_DICT.items(): feature_ID_to_index = self.UCM_mapper_DICT[UCM_name] UCM_sparse_builder = IncrementalSparseMatrix_FilterIDs(preinitialized_col_mapper = feature_ID_to_index, preinitialized_row_mapper = self.user_original_ID_to_index, on_new_col = on_new_ID, on_new_row = on_new_ID) UCM_sparse_builder.add_data_lists(UCM_dataframe["UserID"].values, UCM_dataframe["FeatureID"].values, UCM_dataframe["Data"].values) UCM_DICT_sparse[UCM_name] = UCM_sparse_builder.get_SparseMatrix() loaded_dataset = Dataset(dataset_name=dataset_name, URM_dictionary=URM_DICT_sparse, ICM_dictionary=ICM_DICT_sparse, ICM_feature_mapper_dictionary=self.ICM_mapper_DICT, UCM_dictionary=UCM_DICT_sparse, UCM_feature_mapper_dictionary=self.UCM_mapper_DICT, user_original_ID_to_index=self.user_original_ID_to_index, item_original_ID_to_index=self.item_original_ID_to_index, is_implicit=is_implicit, ) return loaded_dataset def _generate_global_mappers(self): """ Generates the UserID and ItemID mapper including all data available: URM, ICM, UCM :return: """ self.user_original_ID_to_index = {} self.item_original_ID_to_index = {} for _, URM_dataframe in self.URM_DICT.items(): self.user_original_ID_to_index = _add_keys_to_mapper(self.user_original_ID_to_index, URM_dataframe["UserID"].values) self.item_original_ID_to_index = _add_keys_to_mapper(self.item_original_ID_to_index, URM_dataframe["ItemID"].values) for _, ICM_dataframe in self.ICM_DICT.items(): self.item_original_ID_to_index = _add_keys_to_mapper(self.item_original_ID_to_index, ICM_dataframe["ItemID"].values) for _, UCM_dataframe in self.UCM_DICT.items(): self.user_original_ID_to_index = _add_keys_to_mapper(self.user_original_ID_to_index, UCM_dataframe["UserID"].values) def _generate_ICM_UCM_mappers(self): """ Generates the FeatureID mapper of each ICM and UCM :return: """ for ICM_name, ICM_dataframe in self.ICM_DICT.items(): feature_ID_to_index = _add_keys_to_mapper({}, ICM_dataframe["FeatureID"].values) self.ICM_mapper_DICT[ICM_name] = feature_ID_to_index for UCM_name, UCM_dataframe in self.UCM_DICT.items(): feature_ID_to_index = _add_keys_to_mapper({}, UCM_dataframe["FeatureID"].values) self.UCM_mapper_DICT[UCM_name] = feature_ID_to_index def add_URM(self, URM_dataframe:pd.DataFrame, URM_name): """ Adds the URM_dataframe to the current dataset object :param URM_dataframe: Expected columns: UserID, ItemID, Data :param URM_name: String with the name of the URM :return: """ assert set(["UserID", "ItemID", "Data"]).issubset(set(URM_dataframe.columns)), "Dataframe columns not correct" assert all(is_string_dtype(URM_dataframe[ID_column]) for ID_column in ["UserID", "ItemID"]), "ID columns must be strings" assert not self.__Dataset_finalized, "Dataset mappers have already been generated, adding new data is forbidden" assert URM_name not in self.URM_DICT, "URM_name alredy exists" self.URM_DICT[URM_name] = URM_dataframe def add_ICM(self, ICM_dataframe:pd.DataFrame, ICM_name): """ Adds the ICM_dataframe to the current dataset object :param ICM_dataframe: Expected columns: ItemID, FeatureID, Data :param ICM_name: String with the name of the ICM :return: """ assert set(["ItemID", "FeatureID", "Data"]).issubset(set(ICM_dataframe.columns)), "Dataframe columns not correct" assert all(is_string_dtype(ICM_dataframe[ID_column]) for ID_column in ["ItemID", "FeatureID"]), "ID columns must be strings" assert not self.__Dataset_finalized, "Dataset mappers have already been generated, adding new data is forbidden" assert ICM_name not in self.ICM_DICT, "ICM_name alredy exists" self.ICM_DICT[ICM_name] = ICM_dataframe def add_UCM(self, UCM_dataframe:pd.DataFrame, UCM_name): """ Adds the UCM_dataframe to the current dataset object :param UCM_dataframe: Expected columns: UserID, FeatureID, Data :param UCM_name: String with the name of the UCM :return: """ assert set(["UserID", "FeatureID", "Data"]).issubset(set(UCM_dataframe.columns)), "Dataframe columns not correct" assert all(is_string_dtype(UCM_dataframe[ID_column]) for ID_column in ["UserID", "FeatureID"]), "ID columns must be strings" assert not self.__Dataset_finalized, "Dataset mappers have already been generated, adding new data is forbidden" assert UCM_name not in self.UCM_DICT, "UCM_name alredy exists" self.UCM_DICT[UCM_name] = UCM_dataframe
StarcoderdataPython
3215836
# Copyright 2017 The TensorFlow 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. # ============================================================================== """Builder function for image resizing operations.""" import functools import tensorflow.compat.v1 as tf from object_detection.core import preprocessor from object_detection.protos import image_resizer_pb2 def _tf_resize_method(resize_method): """Maps image resize method from enumeration type to TensorFlow. Args: resize_method: The resize_method attribute of keep_aspect_ratio_resizer or fixed_shape_resizer. Returns: method: The corresponding TensorFlow ResizeMethod. Raises: ValueError: if `resize_method` is of unknown type. """ dict_method = { image_resizer_pb2.BILINEAR: tf.image.ResizeMethod.BILINEAR, image_resizer_pb2.NEAREST_NEIGHBOR: tf.image.ResizeMethod.NEAREST_NEIGHBOR, image_resizer_pb2.BICUBIC: tf.image.ResizeMethod.BICUBIC, image_resizer_pb2.AREA: tf.image.ResizeMethod.AREA } if resize_method in dict_method: return dict_method[resize_method] else: raise ValueError('Unknown resize_method') def build(image_resizer_config): """Builds callable for image resizing operations. Args: image_resizer_config: image_resizer.proto object containing parameters for an image resizing operation. Returns: image_resizer_fn: Callable for image resizing. This callable always takes a rank-3 image tensor (corresponding to a single image) and returns a rank-3 image tensor, possibly with new spatial dimensions. Raises: ValueError: if `image_resizer_config` is of incorrect type. ValueError: if `image_resizer_config.image_resizer_oneof` is of expected type. ValueError: if min_dimension > max_dimension when keep_aspect_ratio_resizer is used. """ if not isinstance(image_resizer_config, image_resizer_pb2.ImageResizer): raise ValueError('image_resizer_config not of type ' 'image_resizer_pb2.ImageResizer.') image_resizer_oneof = image_resizer_config.WhichOneof('image_resizer_oneof') if image_resizer_oneof == 'keep_aspect_ratio_resizer': keep_aspect_ratio_config = image_resizer_config.keep_aspect_ratio_resizer if not (keep_aspect_ratio_config.min_dimension <= keep_aspect_ratio_config.max_dimension): raise ValueError('min_dimension > max_dimension') method = _tf_resize_method(keep_aspect_ratio_config.resize_method) image_resizer_fn = functools.partial( preprocessor.resize_to_range, min_dimension=keep_aspect_ratio_config.min_dimension, max_dimension=keep_aspect_ratio_config.max_dimension, method=method, pad_to_max_dimension=keep_aspect_ratio_config.pad_to_max_dimension) if not keep_aspect_ratio_config.convert_to_grayscale: return image_resizer_fn elif image_resizer_oneof == 'fixed_shape_resizer': fixed_shape_resizer_config = image_resizer_config.fixed_shape_resizer method = _tf_resize_method(fixed_shape_resizer_config.resize_method) image_resizer_fn = functools.partial( preprocessor.resize_image, new_height=fixed_shape_resizer_config.height, new_width=fixed_shape_resizer_config.width, method=method) if not fixed_shape_resizer_config.convert_to_grayscale: return image_resizer_fn else: raise ValueError( 'Invalid image resizer option: \'%s\'.' % image_resizer_oneof) def grayscale_image_resizer(image): [resized_image, resized_image_shape] = image_resizer_fn(image) grayscale_image = preprocessor.rgb_to_gray(resized_image) grayscale_image_shape = tf.concat([resized_image_shape[:-1], [1]], 0) return [grayscale_image, grayscale_image_shape] return functools.partial(grayscale_image_resizer)
StarcoderdataPython
59206
# import the necessary packages from imutils.video import VideoStream from imutils import face_utils import argparse import imutils import time import dlib import cv2 import tensorflow as tf from tensorflow.keras.models import load_model import numpy as np from matplotlib import pyplot as plt import os # construct the argument parser and parse the arguments #path to facial landmark predictor ap = argparse.ArgumentParser() ap.add_argument("-p", "--shape-predictor", required=True, help="path to facial landmark predictor") #path to video or use camera ap.add_argument("-i", "--input_method", required=True, help="path to video or use camera") args = vars(ap.parse_args()) # initialize dlib's face detector (HOG-based) and then load our trained shape predictor print("[INFO] loading facial landmark predictor...") detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(args["shape_predictor"]) camera_video=int(args["input_method"]) # 0 for video camera if camera_video is 0: # initialize the video stream and allow the cammera sensor to warmup print("[INFO] camera sensor warming up...") vs = cv2.VideoCapture(0) time.sleep(2.0) #1 for path to video on system elif camera_video is 1: vs = cv2.VideoCapture("NTHU_yAWNING/16-FemaleGlasses-Yawning.avi") #vs=cv2.VideoCapture("D:/sayus/Pictures/Camera Roll/WIN_20200716_18_36_16_Pro.mp4") else: print("Invalid Argument") d=0 e=0 #load our pre-trained feature extractotr and yawn detector feature_extractor=load_model('feature_extractor_1.h5') yawn_detector=load_model('GRU_best_1.h5') #set threshold values yawn_detection_sigmoid=0.70 yawn_detection_frames=0 yawn_detection=0 input_feature_extractor=[] count=0 start_time = time.perf_counter() is_yawn=False # loop over the frames from the video stream while True: # grab the frame from the video stream, resize it to have a # maximum width of 400 pixels, and convert it to grayscale grabbed,frame = vs.read() if grabbed==False: break count=count+1 frame = imutils.resize(frame, width=400) # detect faces in image rects = detector(frame, 0) # loop over the face detections for rect in rects: # convert the dlib rectangle into an OpenCV bounding box and draw a bounding box surrounding the face #use our custom dlib shape predictor to predict the location # of our landmark coordinates, then convert the prediction to # an easily parsable NumPy array shape = predictor(frame, rect) shape = face_utils.shape_to_np(shape) (x, y, w, h) = cv2.boundingRect(shape) #extract mouth region roi = frame[y-int(h/3):y + int(h), x:x + int(w)] #resize to 50x50 roi=cv2.resize(roi,(50,50)) cv2.rectangle(frame, (x, y-int(h/3)), (x + int(w), y + int(5*h/4)), (0, 255, 0), 2) input_feature_extractor.append(roi) #append 32 frames together and make prediction if len(input_feature_extractor)<32: continue input_feature_extractor=np.array(input_feature_extractor) out_feature_extractor=feature_extractor.predict(input_feature_extractor) out_feature_extractor=out_feature_extractor.reshape(1,32,256) out_yawn_detector=yawn_detector.predict(out_feature_extractor) #check for threshold if out_yawn_detector > yawn_detection_sigmoid: yawn_detection=yawn_detection+1 if yawn_detection>yawn_detection_frames: frame = cv2.putText(frame, 'Yawning', (275,25), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 1, cv2.LINE_AA) end_time = time.perf_counter() u1=float("{:.2f}".format(count/(end_time-start_time))) u="fps: "+str(u1) #put fps on frame cv2.putText(frame, u, (15,25), cv2.FONT_HERSHEY_SIMPLEX , 1, (255,0,0), 1, cv2.LINE_AA) is_yawn=True yawn_detection=0 else: yawn_detection=0 input_feature_extractor=[] # show the frame end_time = time.perf_counter() u1=float("{:.2f}".format(count/(end_time-start_time))) u="fps: "+str(u1) # if is_yawn==False: # frame = cv2.putText(frame, 'Not Yawning', (205,25), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 1, cv2.LINE_AA) # else: # is_yawn=False cv2.putText(frame, u, (15,25), cv2.FONT_HERSHEY_SIMPLEX , 1, (255,0,0), 1, cv2.LINE_AA) cv2.imshow("Frame", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows() vs.release()
StarcoderdataPython
3342482
<filename>decoder/xor/xor/xor.py # Copyright 2014-2015 PUNCH Cyber Analytics Group # # 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. """ Overview ======== Decode XOR encoded content """ from stoq.plugins import StoqDecoderPlugin class XorDecoder(StoqDecoderPlugin): def __init__(self): super().__init__() def activate(self, stoq): self.stoq = stoq super().activate() def decode(self, payload, **kwargs): """ XOR decode content from provided payload :param bytes payload: Payload to be decoded :param str key: String of space-separated XOR keys (i.e., "41 166 3") or list/tuple of xor values :returns: XOR decoded payload :rtype: list of tuples or None """ try: byte_content = self.to_bytearray(payload) content_length = len(byte_content) if 'key' in kwargs: if type(kwargs['key']) is not (list, tuple): xor_values = kwargs['key'].split(" ") else: self.log.error("No XOR key(s) provided.") return None last_rolling_index = len(xor_values) - 1 current_rolling_index = 0 for index in range(content_length): xor_value = xor_values[current_rolling_index] byte_content[index] ^= int(xor_value) if current_rolling_index < last_rolling_index: current_rolling_index += 1 else: current_rolling_index = 0 # Define the metadata we want to return meta = {} meta['size'] = content_length # Return the results as a list of tuples return [(meta, bytes(byte_content))] except Exception as err: self.log.warn("Unable to XOR payload: {}".format(str(err))) return None
StarcoderdataPython
1741183
# Twowaits Twowaits Problem # Python code to find second largest # element from a dictionary using sorted() method # creating a new Dictionary example_dict ={"a":13, "b":3, "c":6, "d":11} # now directly print the second largest # value in the dictionary print(list(sorted(example_dict.values()))[-2])
StarcoderdataPython
1782204
<filename>tests/test_adaptivecard.py from unittest import TestCase from adaptivecards.adaptivecard import AdaptiveCard class TestAdaptiveCard(TestCase): def test_generate_card(self): apt = AdaptiveCard() obj = apt.render() expected = { 'type': 'AdaptiveCard', 'version': '1.2', '$schema': 'http://adaptivecards.io/schemas/adaptive-card.json' } self.assertDictEqual(obj, expected)
StarcoderdataPython
3389298
<filename>app/views.py """The albumjet flask app viewss """ from flask import jsonify, render_template, request from . import app, db from .models import UserAlbum, UserLamina from .functions import toBoolean @app.route('/') def index(): """index view """ useralbum = UserAlbum.query.get(1) return render_template('albumjet.html', useralbum=useralbum) @app.route('/ajax/lamina/mark', methods=['GET', 'POST']) def mark_lamina(): """mark or unmark lamina """ id = request.args.get('iduserlamina', 0) mark = toBoolean(request.args.get('mark', False)) userlamina = UserLamina.query.get(id) userlamina.mark = mark db.session.commit() return jsonify(result="ok")
StarcoderdataPython
3321434
<gh_stars>1-10 class LaftelPyException(Exception): pass class HTTPException(LaftelPyException): pass
StarcoderdataPython
1622629
<gh_stars>1-10 # Importar as bibliotecas necessárias import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error import seaborn as sns from sklearn.linear_model import LinearRegression # Leitura do dataset df = pd.read_csv("dataset/consumo.csv") # Converter uma coluna para numerica df['Temperatura Maxima (C)'] = df['Temperatura Maxima (C)'].str.replace(',','.').astype(float) df['Temperatura Minima (C)'] = df['Temperatura Minima (C)'].str.replace(',','.').astype(float) df['Precipitacao (mm)'] = df['Precipitacao (mm)'].str.replace(',','.').astype(float) df['Temperatura Media (C)'] = df['Temperatura Media (C)'].str.replace(',','.').astype(float) # Análise descritiva df.describe() df.head() df.dtypes df.info() df.tail() df.shape # Verificar quais são os valores faltantes df.isnull().sum() # Remover todos os valores faltantes df.dropna(how = "all", inplace = True) # Copiando um data frame em uma nova variável df_feature = df.copy() # Criação de uma nova feature df_feature['variacao'] = (df_feature['Temperatura Maxima (C)']) - (df_feature['Temperatura Minima (C)']) df_feature # Plotando o gráfico da nova feature df_feature.plot(x='variacao', y = 'Consumo de cerveja (litros)') plt.xlabel('variacao', fontsize = 15) plt.ylabel('Consumo de cerveja (litros)',fontsize = 15) plt.grid() # Excluindo a coluna data df_feature = df_feature.drop(columns = 'Data') # Realizar a matriz de correlação df_feature.corr().round(3) # Gráficos plt.figure() sns.pairplot(df_feature,x_vars=['Temperatura Minima (C)','Temperatura Media (C)','Temperatura Maxima (C)','Precipitacao (mm)','variacao'], y_vars=['Consumo de cerveja (litros)'],hue='Final de Semana',diag_kind=None) # Realizar o gráfico de final de semana e consumo de cerveja plt.figure(2) sns.swarmplot(x='Final de Semana',y='Consumo de cerveja (litros)',data= df_feature) plt.grid() plt.xlabel('Final de semana') plt.ylabel('Consumo de cerveja [L]') # Realizar o gráfico de final de semana e variacao(nova feature criada) plt.figure(3) sns.swarmplot(x = 'Final de Semana', y = 'variacao', data = df_feature) plt.grid() plt.xlabel('Final de semana') plt.ylabel('variacao') # Utilizando o modelo de regressão linear modelo = LinearRegression() # Colocando a variável target y = df_feature['Consumo de cerveja (litros)'].values #target # colocando as variaveis independentes neste exemplo pega todos menos consumo de cerveja x = df_feature.drop(columns='Consumo de cerveja (litros)').values #fetures xColunas = df_feature.drop(columns='Consumo de cerveja (litros)').columns # Realizando o treinamento xTrain,xTest,yTrain,yTest = train_test_split(x,y, test_size = 0.3, random_state = 54564541) # Fitando o modelo modelo.fit(xTrain,yTrain) yPred = modelo.predict(xTest) # Calcular os resíduos res = yPred - yTest # Testes print('Valor de R2: {}'.format(modelo.score(xTest,yTest))) print('Valor MSE: {}' .format(mean_squared_error(yTest,yPred))) print('Coeficientes da regressão: {}'.format(modelo.coef_)) print('Intercept da regressão: {} \n'.format(modelo.intercept_))
StarcoderdataPython
3200558
<filename>sentinel/rest/http.py import asyncio import weakref import aiohttp import sys import json import traceback import logging from urllib.parse import quote as _uriquote from ..errors import HTTPException, Forbidden, NotFound, ServerError, SentinelError log = logging.getLogger(__name__) class Route: BASE = "https://discord.com/api/v9" def __init__(self, method, path, **kwargs): self.path = path self.method = method url = self.BASE + path if kwargs: self.url = url.format_map({x: _uriquote(y) if isinstance(y, str) else y for x, y in kwargs.items()}) else: self.url = url self.channel_id = kwargs.get("channel_id") self.guild_id = kwargs.get("guild_id") self.webhook_id = kwargs.get("webhook_id") self.webhook_token = kwargs.get("webhook_token") @property def bucket(self): return "{}:{}:{}".format(self.channel_id, self.guild_id, self.path) class MaybeUnlock: def __init__(self, lock): self.lock = lock self._unlock = True def __enter__(self): return self def defer(self): self._unlock = False def __exit__(self, type, value, traceback): if self._unlock: self.lock.release() async def json_or_text(res): t = await res.text(encoding="utf-8") try: if res.headers["content-type"] == "application/json": return json.loads(t) except KeyError: pass return t class HTTPClient: def __init__(self, ws, token): self.loop = asyncio.get_event_loop() self.ws = ws self.session = aiohttp.ClientSession() self._locks = weakref.WeakValueDictionary() self._token = token self.pool = None self._global_over = asyncio.Event() self._global_over.set() user_agent = 'DiscordBot ({0}) Python/{1[0]}.{1[1]} aiohttp/{2}' self.user_agent = user_agent.format("0.0.1", sys.version_info, aiohttp.__version__) async def request(self, route, *, files=None, form=None, **kwargs): bucket = route.bucket method = route.method url = route.url lock = self._locks.get(bucket) if lock is None: lock = asyncio.Lock() if bucket is not None: self._locks[bucket] = lock headers = { "User-Agent": self.user_agent, "Authorization": "Bot {}".format(self._token) } if "json" in kwargs: headers.update({ "Content-Type": "application/json", }) kwargs["data"] = json.dumps(kwargs.pop("json")) try: reason = kwargs.pop("reason") except KeyError: pass else: if reason: headers.update({ "X-Audit-Log-Reason": _uriquote(reason, safe="/ ") }) kwargs.update({ "headers": headers }) if not self._global_over.is_set(): await self._global_over.wait() await lock.acquire() with MaybeUnlock(lock) as maybe_lock: for t in range(5): if files: for f in files: f.reset(seek=t) if form: f_data = aiohttp.FormData() for p in form: f_data.add_field(**p) kwargs.update({ "data": f_data }) try: async with self.session.request(method, url, **kwargs) as res: data = await json_or_text(res) r = res.headers.get("X-Ratelimit-Remaining", 1) if int(r) == 0 and res.status != 429: delta = float(res.headers.get("X-Ratelimit-Reset-After")) maybe_lock.defer() self.loop.call_later(delta, lock.release) if 300 > res.status >= 200: return data if res.status == 429: if not res.headers.get("Via"): raise HTTPException(res, data) txt = "Ratelimited! Retrying in {0} seconds (Bucket {1})" retry_after = data["retry_after"] log.warn(txt.format(retry_after, bucket)) _global = data.get("global", False) if _global: log.warn("Global rate limit hit!") self._global_over.clear() await asyncio.sleep(retry_after) if _global: self._global_over.set() log.info("Global ratelimit over.") continue if res.status in (500, 502): await asyncio.sleep(1 + t * 2) continue if res.status == 403: raise Forbidden(res, data) elif res.status == 404: raise NotFound(res, data) elif res.status == 503: raise ServerError(res, data) else: raise HTTPException(res, data) except OSError as e: if t < 4 and e.errno in (54, 10054): await asyncio.sleep(1 + t * 2) continue raise if res.status >= 500: raise ServerError(res, data) raise HTTPException(res, data) def send_message(self, channel_id, content, embeds: list =None): try: r = Route("POST", f"/channels/{channel_id}/messages", channel_id=channel_id) payload = {} if content: payload.update({ "content": content }) final_embeds = [] if embeds: for e in embeds: final_embeds.append(e._to_json()) payload.update({ "embeds": final_embeds }) try: self.loop.run_until_complete(self.request(r, json=payload)) except TimeoutError: pass except SentinelError as ex: log.error(ex) def get_guild_member(self, guild_id, user_id): try: r = Route("GET", f"/guilds/{guild_id}/members/{user_id}") res = self.loop.run_until_complete(self.request(r)) return res except SentinelError as ex: log.error(ex) def get_guild_commands(self, guild_id, app_id): try: r = Route("GET", f"/applications/{app_id}/guilds/{guild_id}/commands") res = self.loop.run_until_complete(self.request(r)) return res except SentinelError as ex: log.error(ex) def register_guild_command(self, guild_id: int, app_id: int, name: str, description: str, params: list): description = description if description != None else "A cool command!" try: payload = { "name": name, "description": description, "options": [] } options = [] if len(params) > 0: for i, p in enumerate(params): options.append( { "name": p, "description": f"Parameter number {i+1}", "type": 3, "required": True } ) payload.update({ "options": options }) r = Route("POST", f"/applications/{app_id}/guilds/{guild_id}/commands") res = self.loop.run_until_complete(self.request(r, json=payload)) return res except SentinelError as ex: log.error(ex) def delete_guild_command(self, guild_id: int, app_id: int, command_id: int): try: r = Route("DELETE", f"/applications/{app_id}/guilds/{guild_id}/commands/{command_id}") res = self.loop.run_until_complete(self.request(r)) return res except SentinelError as ex: log.error(ex) def respond_to_command(self, interaction_id: int, interaction_token: str, _type: int, content: str, embeds: list = None, flags = None): try: payload = { "type": _type, "data": { "content": content, "flags": flags } } final_embeds = [] if embeds: for e in embeds: final_embeds.append(e._to_json()) payload["data"].update({ "embeds": final_embeds }) r = Route("POST", f"/interactions/{interaction_id}/{interaction_token}/callback") res = self.loop.run_until_complete(self.request(r, json=payload)) return res except SentinelError as ex: log.error(ex) def send_dm(self, user_id: int, content: str, embeds: list = None): try: dm_channel_payload = { "recipient_id": user_id } dm_req = Route("POST", f"/users/@me/channels") dm_channel = self.loop.run_until_complete(self.request(dm_req, json=dm_channel_payload)) return self.send_message(dm_channel["id"], content, embeds) except SentinelError as ex: log.error(ex) def _delete_old_commands(self, commands: list, app_id: int): try: r = Route("GET", "/users/@me/guilds") guilds = self.loop.run_until_complete(self.request(r)) for g in guilds: all_commands = self.get_guild_commands(g["id"], app_id) for cmd in all_commands: if not cmd["name"].lower() in commands: self.delete_guild_command(g["id"], app_id, cmd["id"]) except SentinelError as ex: log.error(ex)
StarcoderdataPython
1672803
<filename>pallindrome.py n=int(input("Enter number:")) temp=n rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 if(temp==rev): print("The number is a palindrome!") else: print("The number isn't a palindrome!")
StarcoderdataPython
1684852
import requests # For calculating the lat and long of places from geopy.geocoders import Nominatim geolocator = Nominatim() source = geolocator.geocode("tambaram") print(source.longitude, source.latitude) dest = geolocator.geocode("nungambakkam") print (dest.longitude , dest.latitude ) source_coordinates = str(source.latitude)+","+str(source.longitude) # if not using geopy replace with source_latitude dest_coordinates = str(dest.latitude)+","+str(dest.longitude) # IF NOT USING GEOPY # source_latitude = "" # source_longitude = "" # dest_latitude = "" # dest_longitude = "" #graph hopper api key api = "5eda2deb-7ac1-44d9-990d-8aac82e96def" # url for given loc url = "https://graphhopper.com/api/1/route?point="+ source_coordinates +"&point="+ dest_coordinates +"&vehicle=car&locale=de&key="+api response = requests.get(url) data = response.json() print (data)
StarcoderdataPython
24049
string_input = "amazing" vowels = "aeiou" answer = [char for char in string_input if char not in vowels] print(answer)
StarcoderdataPython
3200495
<filename>Scripts/Utils/board.py def check_args(r, c, d, i, player): if r > 2 or r < 0: raise ValueError('Unknown row: ' + str(r)) if c > 2 or c < 0: raise ValueError('Unknown column: ' + str(c)) if d > 1 or d < 0: raise ValueError('Unknown diag: ' + str(d)) if i > 8 or i < 0: raise ValueError('Unknown i: ' + str(i)) if player > 2 or player < 0: raise ValueError('Unknown player: ' + str(player)) def line_count_player(line, player): # Count how many times a player appears in a line (list) count = 0 for c in line: if c == player: count += 1 return count def line_get_empty_index(line): # Get the index of the first empty place in a line (list) for index, c in enumerate(line): if c == 0: return index raise ValueError("Line not empty!") def line_list_empty_index(line): # Get all indexes of empty places in a line (list) l = [] for index, c in enumerate(line): if c == 0: l.append(index) return l class board: def __init__(self, board=[0, 0, 0, 0, 0, 0, 0, 0, 0]) -> None: # The board: # 0 1 2 # 3 4 5 # 6 7 8 self.board = board # Player symbols: self.p_sym = [' ', 'O', 'X'] # The indexes corresponding to the two diagonals self.diag_index = [[0, 4, 8], [2, 4, 6]] # The rows, columns, indexes, diags over which we can iterate: self.rows = range(3) self.columns = range(3) self.positions = range(9) self.diags = range(2) def player_sym(self, p): # Get the symbol corresponding to a given player check_args(0, 0, 0, 0, p) return self.p_sym[p] def player_sym_i(self, i): # Get the symbol for current state of the board at a index check_args(0, 0, 0, i, 0) return self.player_sym(self.get_i(i)) def set_i(self, i, player): # Set the board at index i to a given player check_args(0, 0, 0, i, player) self.board[i] = player def get_i(self, i): # Get the board state at index i check_args(0, 0, 0, i, 0) return self.board[i] def set_rc(self, r, c, player): # Set the board at a given row/column location to a given player check_args(r, c, 0, 0, player) self.board[r*3+c] = player def get_rc(self, r, c): # Get the board at a given row/column check_args(r, c, 0, 0, 0) return self.board[r*3+c] def set_dr(self, d, r, player): # Set the board on a given diagonal in a given row to a given player check_args(r, 0, d, 0, player) self.set_i(self.diag_index[d][r], player) def get_dr(self, d, r): # Get the board on a given diagonal in a given row check_args(r, 0, d, 0, 0) return self.get_i(self.diag_index[d][r]) def get_r(self, r): # Return a give row (as a list) check_args(r, 0, 0, 0, 0) return [self.get_rc(r, 0), self.get_rc(r, 1), self.get_rc(r, 2)] def get_c(self, c): # Return a given column (as a list) check_args(0, c, 0, 0, 0) return [self.get_rc(0, c), self.get_rc(1, c), self.get_rc(2, c)] def get_d(self, d): # Return a given diagonal (as a list) check_args(0, 0, d, 0, 0) return [self.get_dr(d, 0), self.get_dr(d, 1), self.get_dr(d, 2)] def game_over(self): # Check if the game is over return self.game_state() != -1 def game_state(self): # Get the current game state # -1 : game in progress # 0 : draw # 1 : P1 won # 2 : P2 won for r in self.rows: if line_count_player(self.get_r(r), 1) == 3: return 1 if line_count_player(self.get_r(r), 2) == 3: return 2 for c in self.columns: if line_count_player(self.get_c(c), 1) == 3: return 1 if line_count_player(self.get_c(c), 2) == 3: return 2 for d in self.diags: if line_count_player(self.get_d(d), 1) == 3: return 1 if line_count_player(self.get_d(d), 2) == 3: return 2 if line_count_player(self.board, 0) == 0: return 0 return -1 def is_empty(self): # Check if the board is empty for c in self.board: if c != ' ': return False return True def __str__(self): # Printable board state v = "" v += self.player_sym_i(0) + "|" + self.player_sym_i(1) + \ "|" + self.player_sym_i(2) + "\n" v += "-+-+-\n" v += self.player_sym_i(3) + "|" + self.player_sym_i(4) + \ "|" + self.player_sym_i(5) + "\n" v += "-+-+-\n" v += self.player_sym_i(6) + "|" + self.player_sym_i(7) + \ "|" + self.player_sym_i(8) + "\n" return v
StarcoderdataPython
44492
<filename>digit-dataset/k-means.py import numpy as np from sklearn.cluster import KMeans num_classes = 10 dirr = "./" cat = np.load(dirr+"features_cat.npz") rev = np.load(dirr+"features_rev.npz") mstn = np.load(dirr+"features_mstn.npz") cat_pred = KMeans(n_clusters=num_classes, n_jobs=-1).fit_predict(np.concatenate([cat['x1'],cat['x2']] , 0)) cat_label = np.concatenate([cat['y1'],cat['y2']] , 0) components = {} labels = {} correct = 0 summ = 0 for i in range(num_classes): components[i] = np.nonzero(cat_pred == i)[0] #print(components[i].shape) tmp = [] for j in range(num_classes): tmp.append((cat_label[components[i]] == j).sum()) #print(tmp) labels[i] = np.argmax(np.array(tmp)) correct += np.max(np.array(tmp)) summ += np.sum(np.array(tmp)) #print(labels[i]) print(float(correct) / summ) cat_pred = KMeans(n_clusters=num_classes, n_jobs=-1).fit_predict(np.concatenate([rev['x1'],rev['x2']] , 0)) cat_label = np.concatenate([rev['y1'],rev['y2']] , 0) components = {} labels = {} correct = 0 summ = 0 for i in range(num_classes): components[i] = np.nonzero(cat_pred == i)[0] #print(components[i].shape) tmp = [] for j in range(num_classes): tmp.append((cat_label[components[i]] == j).sum()) #print(tmp) labels[i] = np.argmax(np.array(tmp)) correct += np.max(np.array(tmp)) summ += np.sum(np.array(tmp)) #print(labels[i]) print(float(correct) / summ) cat_pred = KMeans(n_clusters=num_classes, n_jobs=-1).fit_predict(np.concatenate([mstn['x1'],mstn['x2']] , 0)) cat_label = np.concatenate([mstn['y1'],mstn['y2']] , 0) components = {} labels = {} correct = 0 summ = 0 for i in range(num_classes): components[i] = np.nonzero(cat_pred == i)[0] #print(components[i].shape) tmp = [] for j in range(num_classes): tmp.append((cat_label[components[i]] == j).sum()) #print(tmp) labels[i] = np.argmax(np.array(tmp)) correct += np.max(np.array(tmp)) summ += np.sum(np.array(tmp)) #print(labels[i]) print(float(correct) / summ)
StarcoderdataPython
82293
import socket import sys from thread import start_new_thread from InstagramAPI import InstagramAPI import subprocess import flickrapi import requests import MySQLdb import urllib2 def getIDbyUsername(uname): target_link="http://instagram.com/"+uname+"/" response=urllib2.urlopen(target_link) page_source=response.read() string_start=page_source.find("profilePage_")+12 returnID=page_source[string_start:string_start+10] if returnID[len(returnID)-1]=='"': returnID=page_source[string_start:string_start+9] return returnID HOST = '' PORT = 6636 try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print("Could not create socket. Error Code: ", str(msg[0]), "Error: ", msg[1]) sys.exit(0) print("[+] Socket Created") try: s.bind((HOST, PORT)) print("[-] Socket Bound to port " + str(PORT)) except socket.error, msg: print("Bind Failed. Error Code: {} Error: {}".format(str(msg[0]), msg[1])) sys.exit() s.listen(10) print("[!] Listening...") def client_thread(conn,addr): loggedIn = False loggedInIG = False userInstagram= None username=None while True: try: data = conn.recv(1024) except Exception as disconnected: print("[-] Disconnected "+addr[0]+":"+str(addr[1])) q=disconnected break if not data: break arguments = data.split(" ") if arguments[0]=='--help' or arguments[0]=='-h': to_send="CoLiW\n\nCommands:\n\tlogin\n\tlogout\n\tregister\n\tweb module\n\thistory" elif arguments[0] == "login": if loggedIn==True: to_send="You are already logged in" else: if len(arguments)<3: to_send="Too few arguments!\nSyntax: login <username> <password>" elif len(arguments)>3: to_send="Too many arguments!\nSyntax: login <username> <password>" else: db = MySQLdb.connect(host="localhost", user="root", passwd="", db="aplicatiebd") cur = db.cursor() stringalau="SELECT password FROM USERS WHERE username ='"+arguments[1]+"'" cur.execute(stringalau) if arguments[2]==cur.fetchall()[0][0]: loggedIn=True username=arguments[1] to_send="Login sucessfull" else: to_send="Wrong creditals" #flag = subprocess.check_output([sys.executable, "login.py", arguments[1], arguments[2]]) #if flag == '1\n': # to_send = "Login sucessfull" # loggedIn = True #else: # to_send = "Error with login creditals. Check again your user/password" elif arguments[0]=='history': if loggedIn: if len(arguments)==2: if arguments[1]=='-h': to_send="Hystory\nBasicly, it prints command history of the user\n\n\t-h prints this message\n\t-o prints output also (rather not)\n\t-c clears the history" elif arguments[1]=='-o': db = MySQLdb.connect(host="localhost", user="root", passwd="", db="aplicatiebd") cur=db.cursor() stringalau="SELECT command,output from history where username='"+username+"'" cur.execute(stringalau) output=cur.fetchall() sortedOutput=list(set(output)) to_send="" for i in sortedOutput: to_send=to_send+i[0]+"\t\t"+i[1]+"\n" elif arguments[1]=='-c': flag=subprocess.check_output( [sys.executable, "clearHistory.py", username]) to_send="History cleared" else: to_send="Expected -o -h or -c and recieved"+arguments[1] elif len(arguments)==1: db = MySQLdb.connect(host="localhost", user="root", passwd="", db="aplicatiebd") cur=db.cursor() stringalau="SELECT command from history where username='"+username+"'" cur.execute(stringalau) output=cur.fetchall() sortedOutput=list(set(output)) to_send="" for i in sortedOutput: to_send=to_send+i[0]+"\n" else: to_send="Wrong syntax\nType in 'history -h' for more info" else: to_send="You cannot use this command if you`re not logged in" elif arguments[0] == "register": if loggedIn==True: to_send="You cannot register while you are logged in already" else: if len(arguments)<4: to_send="Too few arguments!\nSyntax: register <username> <password> <email>" elif len(arguments)>4: to_send="Too many arguments!\nSyntax: register <username> <password> <email>" else: db = MySQLdb.connect(host="localhost", user="root", passwd="", db="aplicatiebd") cur = db.cursor() stringalau="SELECT id FROM USERS WHERE username ='"+arguments[1]+"'" cur.execute(stringalau) if len(cur.fetchall())>0: to_send="There is already someone called "+arguments[1] else: stringalau="INSERT INTO users(username,password,email) VALUES('"+arguments[1]+"','"+arguments[2]+"','"+arguments[3]+"');" cur.execute(stringalau) db.commit() to_send="You`ve been registred and now you`re logged in" loggedIn=True username=arguments[1] elif arguments[0]=='logout': to_send="Logged out" loggedIn=False #flag = subprocess.check_output([sys.executable, "register.py", arguments[1], arguments[2], arguments[3]]) #if flag == "True\n": # to_send = "You have been registered!" #else: # to_send = "There is someone called " + arguments[1] elif arguments[0]=="web": if loggedIn==False: to_send="You have to be logged in to use web module." else: if len(arguments)>1: if arguments[1]=='-h': to_send="CoLiW Web Module\n\tinstagram API\n\tflickr API" elif arguments[1]=="instagram": if len(arguments)==2: to_send="Invalid syntax.\nType in web instagram -h" else: #web instagram login username passwd if arguments[2]=="login": if len(arguments)>5: to_send="Too many arguments\nSyntax: web instagram login <username> <password>" elif len(arguments)<5: to_send="Too few arguments\nSyntax: web instagram login <username> <password>" else: userInstagram=InstagramAPI(arguments[3],arguments[4]) if(userInstagram.login()): to_send="You`ve logged in through Instagram. Now you can use it as you desire" loggedInIG = True else: to_send="Wrong username/password. try again after you check them again" elif arguments[2]=='logout': if loggedInIG: loggedInIG=False userInstagram=None to_send="Logged out" else: to_send="You cannot log out if you`re not logged in" elif arguments[2]=="follow": if loggedInIG == True : #returnID = subprocess.check_output( [sys.executable, "getIDbyUsername.py", arguments[3]]) returnID=getIDbyUsername(arguments[3]) if returnID[len(returnID)-1]=='"': returnID=returnID[:-1] userInstagram.follow(returnID) to_send="Now following "+arguments[3] else: to_send="You have to be logged in with instagram\nUse web instagram -h for more info" elif arguments[2] == "unfollow": if loggedInIG==True: #returnID = subprocess.check_output( [sys.executable, "getIDbyUsername.py", arguments[3]]) returnID=getIDbyUsername(arguments[3]) if returnID[len(returnID)-1]=='"': returnID=returnID[:-1] userInstagram.unfollow(returnID) to_send="Now not following "+arguments[3]+" anymore" else: to_send="You have to be logged in with instagram\nUse web instagram -h for more info" elif arguments[2] == 'block': if loggedInIG==True: returnID=getIDbyUsername(arguments[3]) if returnID[len(returnID)-1]=='"': returnID=returnID[:-1] userInstagram.block(returnID) to_send=+arguments[3]+" been blocked" else: to_send="You have to be logged in with instagram\nUse web instagram -h for more info" elif arguments[2] == 'unblock': if loggedInIG==True: returnID=getIDbyUsername(arguments[3]) if returnID[len(returnID)-1]=='"': returnID=returnID[:-1] userInstagram.unblock(returnID) to_send=+arguments[3]+" been unblocked" else: to_send="You have to be logged in with instagram\nUse web instagram -h for more info" elif arguments[2]=="upload": if loggedInIG == True: if arguments[3]=="photo": caption="" for i in arguments[4:]: caption+=str(i)+" " uploadPhoto(arguments[4], caption) elif arguments[2]=='-h': to_send="Instagram API in Coliw\n\n\tsyntax: web instagram <follow/unfollow/login/block/unblock> <username>" elif arguments[1] == "flickr": continueT=True index_to_start=0 number_of_photos=0 #web flickr if len(arguments)==2: to_send="no arguments given!" #web flickr <tag> elif len(arguments)==3: if arguments[2]=='-h': to_send="\nFlickr api\nSyntax: web flickr <keyword> <options>\n\n\t-i start index ( 0 as default )\n\t-n number of photos ( 1 as default )" continueT=False else: index_to_start=1 number_of_photos=1 elif len(arguments)==5: if arguments[3]=='-i': if arguments[4].isdigit(): index_to_start=int(arguments[4]) else: continueT=False to_send=argument[4]+" is not a number" elif arguments[3]=='-n': if arguments[4].isdigit(): number_of_photos=int(arguments[4]) else: continueT=False to_send=argument[4]+" is not a number" elif len(arguments)==6: if arguments[3]=='-in': if arguments[4].isdigit(): index_to_start=int(arguments[4]) else: continueT=False to_send=arguments[4]+" is not a number" if arguments[5].isdigit(): number_of_photos=int(arguments[5]) else: continueT=False to_send=arguments[5]+" is not a number" elif arguments[3]=='-ni': if arguments[4].isdigit(): number_of_photos=int(arguments[4]) else: continueT=False to_send=arguments[4]+" is not a number" if arguments[5].isdigit(): index_to_start=int(arguments[5]) else: continueT=False to_send=arguments[5]+" is not a number" elif len(arguments)==7: if arguments[3]=='-i' and arguments[5]=='-n': if arguments[4].isdigit(): if arguments[6].isdigit(): index_to_start=int(arguments[4]) number_of_photos=int(arguments[6]) else: continueT=False to_send=arguments[6]+" is not a number" else: continueT=False to_send=arguments[4]+" is not a number" elif arguments[3]=='-n' and arguments[5]=='-i': if arguments[4].isdigit(): if arguments[6].isdigit(): number_of_photos=int(arguments[4]) index_to_start=int(arguments[6]) else: continueT=False to_send=arguments[6]+" is not a number" else: continueT=False to_send=arguments[4]+" is not a number" elif arguments[3]==arguments[5]: continueT=False to_send="3rd and 5th argument cannot be even" else: continueT=False to_send="Wrong syntax, expected -i or -n on the 3rd or 5th" else: to_send="Too many arguments given/wrong syntax" continueT=False if continueT: #to_send="Right syntax/ you wanna search "+arguments[2]+" index="+str(index_to_start)+" no="+str(number_of_photos) startUP=0 startDOWN=0 if number_of_photos==0: number_of_photos=1 if number_of_photos==1 and index_to_start==1: startUP=0 startDOWN=1 elif index_to_start==0 and number_of_photos>1: startUP=0 startDOWN=number_of_photos elif index_to_start>1 and number_of_photos==1: startUP=index_to_start startDOWN=index_to_start+1 elif index_to_start>1 and number_of_photos>1: startUP=index_to_start startDOWN=startUP+number_of_photos elif index_to_start==1 and number_of_photos>1: startUP=index_to_start startDOWN=number_of_photos+1 elif index_to_start==0 and number_of_photos==1: startUP=0 startDOWN=1 flickr = flickrapi.FlickrAPI('e57cfa37f00d7a9a5d7fac7e37ebcbb5', '00751b0c7b65ba7a',format='parsed-json') extras = 'url_sq,url_t,url_s,url_q,url_m,url_n,url_z,url_c,url_l,url_o' links = "" cats = flickr.photos.search(text=arguments[2], per_page=startDOWN+startUP, extras=extras) for i in range(startUP, startDOWN): photos = cats['photos']['photo'][i]['url_m'] links =links+photos + '\n' links=links[:-1] to_send=links else: to_send="unknown web command" else: to_send="too few arguments known" else: to_send=arguments[0]+" is not recognized" if loggedIn: print subprocess.check_output( [sys.executable, "addCMD.py", username,data, to_send]) reply = to_send conn.send(reply.encode('ascii')) conn.close() while True: conn, addr = s.accept() print("[+] Connected to " + addr[0] + ":" + str(addr[1])) start_new_thread(client_thread, (conn,addr)) s.close()
StarcoderdataPython
1724833
<filename>binp/service.py from asyncio import Task, get_event_loop, sleep, CancelledError from dataclasses import dataclass from enum import Enum from logging import getLogger from typing import Callable, Awaitable, Optional, Dict, List from pydantic import BaseModel from binp.events import Emitter class Status(str, Enum): """ Service life status """ #: service stopped and will not be restarted stopped = 'stopped' #: service scheduled to start starting = 'starting' #: service up and running running = 'running' #: service stopped, is waiting before restart restarting = 'restarting' class Info(BaseModel): """ Service information """ #: service name name: str #: service description description: str #: actual service status status: Status #: is service marked to be started automatically autostart: bool #: is service has to be restarted automatically restart: bool #: interval between restarts restart_delay: float @dataclass class Handler: info: Info events: Emitter[Info] handler: Callable[[], Awaitable] task: Optional[Task] = None async def __call__(self): logger = getLogger('service:' + self.info.name) try: while True: self.info.status = Status.running self.events.emit(self.info) try: await self.handler() except (CancelledError, KeyboardInterrupt): break except Exception as ex: logger.warning("service stopped: %v", ex, exc_info=ex) if not self.info.restart: break self.info.status = Status.restarting self.events.emit(self.info) await sleep(self.info.restart_delay) finally: self.info.status = Status.stopped self.events.emit(self.info) class Service: """ Annotate async function as service (background task). Supports automatic (default) and manual start, restarts, restarts delays. Useful to interact with environment in unpredictable schedule (ex: listen for low-level network requests). .. code-block:: python from binp import BINP from asyncio import sleep binp = BINP() @binp.service async def check_messages(): while True: await sleep(3) print("checks") For scheduling by time better use `aiocron` instead: .. code-block:: pip install aiocron .. highlight:: python .. code-block:: python from binp import BINP from aiocron import crontab binp = BINP() @crontab("*/5 * * * *") @binp.journal async def poll_something(): print("do something every 5 minutes....") :Conflicts: Services are indexed by name. If multiple services defined with the same name - the old one will be stopped and the latest one will be used. :Events: * ``service_changed`` - when service status changed. Emits Info """ def __init__(self): self.service_changed: Emitter[Info] = Emitter() self.__services: Dict[str, Handler] = {} def __call__(self, func: Optional[Callable[[], Awaitable]] = None, *, name: Optional[str] = None, description: Optional[str] = None, restart: bool = True, autostart: bool = True, restart_delay: float = 3): """ Mark async function as service """ def register_function(fn: Callable[[], Awaitable]): nonlocal name, description if name is None: name = fn.__qualname__ if description is None: description = "\n".join(line.strip() for line in (fn.__doc__ or '').splitlines()).strip() if name in self.__services: old = self.__services[name] getLogger(self.__class__.__qualname__).warning("redefining service %r: %s => %s", name, old.handler.__qualname__, fn.__qualname__) if old.task is not None: old.task.cancel() old.task = None handler = Handler( info=Info( name=name, description=description, status=Status.stopped, autostart=autostart, restart=restart, restart_delay=restart_delay ), events=self.service_changed, handler=fn ) self.__services[name] = handler if autostart: self.start(name) else: self.service_changed.emit(handler.info) return fn if func is None: return register_function return register_function(func) def start(self, name: str): """ Starts single service by name. Does nothing if no such service or service not yet stopped. """ service = self.__services.get(name) if service is None: return if service.info.status != Status.stopped: return service.info.status = Status.starting service.task = get_event_loop().create_task(service()) self.service_changed.emit(service.info) def stop(self, name: str): """ Stops service by name. Does nothing if no such service or service stopped. """ service = self.__services.get(name) if service is None or service.info.status == Status.stopped or service.task is None: return service.task.cancel() @property def services(self) -> List[Info]: """ List of all services """ return [v.info for v in self.__services.values()]
StarcoderdataPython
1747433
import unittest from app.models import Comment,User,Pitch from app import db class CommentModelTest(unittest.TestCase): def setUp(self): self.user_postgres = User(username = 'kayleen',password = 'password', email = '<EMAIL>') self.new_comment = Comment(comment='nice work',user = self.user_kayleen,pitch_id=1 )
StarcoderdataPython
15766
from unittest import TestCase, mock from modelgen import ModelGenerator, Base from os import getcwd, path class TestModelgen(TestCase): @classmethod def setUpClass(self): self.yaml = {'tables': {'userinfo':{'columns': [{'name': 'firstname', 'type': 'varchar'}, {'name': 'lastname', 'type': 'varchar'}, {'name': 'dob', 'type': 'date'}, {'name': 'contact', 'type': 'numeric'}, {'name': 'address', 'type': 'varchar'}]}}} self.logger = Base().logger @mock.patch('modelgen.modelgenerator.Validate') @mock.patch('modelgen.ModelGenerator.__init__') @mock.patch('modelgen.modelgenerator.Helper.write_to_file') @mock.patch('modelgen.modelgenerator.Path') @mock.patch('modelgen.modelgenerator.Parser') @mock.patch('modelgen.modelgenerator.Template') def test_create_model_wo_alembic(self, mock_templt, mock_prsr, mock_pth, mock_wrtf, mock_init, mock_validate): ''' Test create_model function without setting alembic support to True ''' mock_init.return_value = None mock_validate.validate.return_value = True mock_wrtf.return_value = True mock_prsr.data.return_value = self.yaml model_obj = ModelGenerator() response = model_obj._create_model('test') self.assertEqual(True, response) mock_prsr.assert_called_with(filepath=path.join(getcwd(), 'templates/test.yaml')) mock_wrtf.assert_called_with(path=path.join(getcwd(), 'models/test.py'), data=mock_templt().render()) @mock.patch('modelgen.modelgenerator.ModelGenerator._create_alembic_meta') @mock.patch('modelgen.modelgenerator.Validate') @mock.patch('modelgen.ModelGenerator.__init__') @mock.patch('modelgen.modelgenerator.Helper.write_to_file') @mock.patch('modelgen.modelgenerator.Path') @mock.patch('modelgen.modelgenerator.Parser') @mock.patch('modelgen.modelgenerator.Template') def test_create_model_w_alembic(self, mock_templt, mock_prsr, mock_pth, mock_wrtf, mock_init, mock_validate, mock_cam): ''' Test _create_model function with setting alembic support to True ''' mock_init.return_value = None mock_validate.validate.return_value = True mock_wrtf.return_value = True mock_prsr.data.return_value = self.yaml mock_cam.return_value = True model_obj = ModelGenerator() response = model_obj._create_model(datasource='./test', alembic=True) self.assertEqual(True, response) mock_prsr.assert_called_with(filepath=path.join(getcwd(), 'templates/./test.yaml')) mock_wrtf.assert_called_with(path=path.join(getcwd(), 'models/./test.py'), data=mock_templt().render()) @mock.patch('modelgen.modelgenerator.Validate') @mock.patch('modelgen.ModelGenerator.__init__') @mock.patch('modelgen.modelgenerator.Helper.write_to_file') @mock.patch('modelgen.modelgenerator.Path') @mock.patch('modelgen.modelgenerator.Parser') @mock.patch('modelgen.modelgenerator.Template') def test_create_alembic_meta(self, mock_templt, mock_prsr, mock_pth, mock_wrtf, mock_init, mock_validate): ''' Test _create_alembic_meta function. Function creates alembic support by a folder called metadata and a file __init__.py in the folder. This file contains sqlalchemy metadata imported from all the sqlalchemy model files ''' mock_init.return_value = None mock_validate.validate.return_value = True mock_wrtf.return_value = True mock_prsr.data.return_value = self.yaml model_obj = ModelGenerator() response = model_obj._create_alembic_meta() self.assertEqual(True, response) mock_wrtf.assert_called_with(path=path.join(getcwd(), 'metadata/__init__.py'), data=mock_templt().render()) @mock.patch('modelgen.modelgenerator.path') @mock.patch('modelgen.modelgenerator.Path') @mock.patch('modelgen.modelgenerator.copyfile') def test_create_template_folder(self, mock_cpyfile, mock_pth, mock_ospth): ''' Test _create_template_folder function. Function creates templates folder structure when modelgen is initialized ''' mock_ospth.join.side_effects = ['./test', './test', './test', './test'] mock_ospth.exists.return_value = False mock_pth.mkdir.return_value = True mock_cpyfile.return_value = True model_obj = ModelGenerator() response = model_obj._create_template_folder(init='./testfolder') self.assertEqual(response, True) mock_cpyfile.assert_called_with(mock_ospth.join(), mock_ospth.join()) @mock.patch('modelgen.ModelGenerator._create_alembic_folder') @mock.patch('modelgen.modelgenerator.Path') @mock.patch('modelgen.modelgenerator.path') @mock.patch('modelgen.modelgenerator.copyfile') def test_create_template_folder_exists(self, mock_cpyfile, mock_ospth, mock_pth, mock_caf): ''' Test _create_template_folder function when folder already exists Function throws FileExistsError. ''' mock_pth.mkdir.return_value = FileExistsError mock_caf.return_value = True mock_ospth.join.side_effects = ['./test', './test', './test', './test'] mock_ospth.exists.return_value = True mock_cpyfile.return_value = True model_obj = ModelGenerator() with self.assertRaises(FileExistsError) as err: model_obj._create_template_folder(init='./models') @mock.patch('modelgen.modelgenerator.copytree') @mock.patch('modelgen.modelgenerator.path') @mock.patch('modelgen.modelgenerator.Path') @mock.patch('modelgen.modelgenerator.copyfile') def test_create_alembic_folder(self, mock_cpyfile, mock_pth, mock_ospth, mock_cptr): ''' Test _create_alembic_folder function. Tests the creation of folders alembic/versions, alembic/alembic.ini, alembic/env.py. Relative path is passed in this test ''' mock_cptr.return_value = True mock_ospth.join.return_value = './testfolder' mock_ospth.isabs.return_value = False mock_ospth.exists.return_value = False mock_pth.mkdir.return_value = True mock_cpyfile.return_value = True model_obj = ModelGenerator() response = model_obj._create_alembic_folder(init='./testfolder') self.assertEqual(response, True) mock_cptr.assert_called_with(mock_ospth.join(), mock_ospth.join()) @mock.patch('modelgen.modelgenerator.copytree') @mock.patch('modelgen.modelgenerator.path') @mock.patch('modelgen.modelgenerator.Path') @mock.patch('modelgen.modelgenerator.copyfile') def test_create_alembic_folder_absolute_path(self, mock_cpyfile, mock_pth, mock_ospth, mock_cptr): ''' Test _create_alembic_folder function. Tests the creation of folders alembic/versions, alembic/alembic.ini, alembic/env.py. Absolute path is passed in this test. ''' mock_cptr.return_value = True mock_ospth.join.return_value = '/testfolder' mock_ospth.exists.return_value = False mock_pth.mkdir.return_value = True mock_cpyfile.return_value = True model_obj = ModelGenerator() response = model_obj._create_alembic_folder(init='/testfolder') self.assertEqual(response, True) mock_cptr.assert_called_with(mock_ospth.join(), mock_ospth.join()) @mock.patch('modelgen.ModelGenerator._create_template_folder') @mock.patch('modelgen.modelgenerator.path') @mock.patch('modelgen.modelgenerator.copytree') @mock.patch('modelgen.modelgenerator.copyfile') def test_create_alembic_folder_exists(self, mock_cpyfile, mock_cptr, mock_ospth, mock_ctf): ''' Test _create_alembic_folder function when folder already exists. The function raises FileExistsError ''' mock_ctf.return_value = True mock_cptr.return_value = True mock_ospth.join.side_effects = ['./test', './test', './test', './test'] mock_ospth.exists.return_value = True mock_cpyfile.return_value = True model_obj = ModelGenerator() with self.assertRaises(FileExistsError) as err: model_obj._create_alembic_folder(init='./docs') @mock.patch('modelgen.modelgenerator.ModelGenerator._create_alembic_folder') @mock.patch('modelgen.modelgenerator.ModelGenerator._create_template_folder') @mock.patch('modelgen.modelgenerator.ModelGenerator._create_checkpoint_file') def test_modelgenerator_init(self, mock_cafldr, mock_ctfldr, mock_cchk): obj = ModelGenerator(init='./test') mock_cafldr.assert_called_with(init='./test') mock_cchk.assert_called_with(init='./test') mock_ctfldr.assert_called_with(init='./test') @mock.patch('modelgen.modelgenerator.path') @mock.patch('modelgen.modelgenerator.ModelGenerator._create_model') @mock.patch('modelgen.modelgenerator.ModelGenerator._find_checkpoint_file') def test_modelgenerator_init_create_model_elif_w_yaml_extn(self, mock_fcf, mock_cm, mock_ospth): ''' Test modelgen/modelgenerator.py file's __init__ method when schema yaml file with extension .yaml is passed ''' mock_ospth.return_value = True mock_cm.return_value = True mock_fcf = True obj = ModelGenerator(createmodel=True, file='./test.yaml') @mock.patch('modelgen.modelgenerator.path') @mock.patch('modelgen.modelgenerator.ModelGenerator._create_model') @mock.patch('modelgen.modelgenerator.ModelGenerator._find_checkpoint_file') def test_modelgenerator_init_create_model_elif_w_yml_extn(self, mock_fcf, mock_cm, mock_ospth): ''' Test modelgen/modelgenerator.py file's __init__ method when schema yaml file with extension .yml is passed ''' mock_ospth.return_value = True mock_cm.return_value = True mock_fcf = True obj = ModelGenerator(createmodel=True, file='./test.yml') @mock.patch('modelgen.modelgenerator.path') @mock.patch('modelgen.modelgenerator.ModelGenerator._create_model') @mock.patch('modelgen.modelgenerator.ModelGenerator._find_checkpoint_file') def test_modelgenerator_init_create_model_elif_wo_yaml_extn(self, mock_fcf, mock_cm, mock_ospth): ''' Test modelgen/modelgenerator.py file's __init__ method when schema file without .yaml or .yml is passed. The function will throw NameError ''' mock_ospth.return_value = True mock_cm.return_value = True mock_fcf = True with self.assertRaises(NameError) as err: obj = ModelGenerator(createmodel=True, file='./test.txt') @mock.patch('modelgen.modelgenerator.path') @mock.patch('modelgen.modelgenerator.ModelGenerator._create_model') @mock.patch('modelgen.modelgenerator.ModelGenerator._find_checkpoint_file') def test_modelgenerator_createmodel_find_checkpoint_file_true(self, mock_fcf, mock_cm, mock_ospth): ''' Test _find_checkpoint_file_ when the checkpoint file, .modelgen, exists. ''' mock_ospth.return_value = True mock_cm.return_value = True mock_fcf = True obj = ModelGenerator(createmodel=True, file='./test.yaml') @mock.patch('modelgen.modelgenerator.path') @mock.patch('modelgen.modelgenerator.ModelGenerator._create_model') @mock.patch('modelgen.modelgenerator.ModelGenerator._find_checkpoint_file') def test_modelgenerator_createmodel_find_checkpoint_file_false(self, mock_fcf, mock_cm, mock_ospth): ''' Test _find_checkpoint_file_ when the checkpoint file, .modelgen, doesn't exists. ''' mock_ospth.return_value = True mock_cm.return_value = True mock_fcf.return_value = False obj = ModelGenerator(createmodel=True, file='./test.yaml') mock_fcf.assert_called_with() @mock.patch('modelgen.modelgenerator.Helper.write_to_file') def test_create_checkpoint_file(self, mock_wrtf): ''' Test _create_checkpoint_file. The checkpoint file is created when the modelgen is initialized for the first time ''' mock_wrtf.return_value = True obj = ModelGenerator() obj._create_checkpoint_file(init='./dummy') mock_wrtf.assert_called_with(path='./dummy/.modelgen', data='') @mock.patch('modelgen.modelgenerator.path') def test_find_checkpoint_file_exists(self, mock_ospth): mock_ospth.exists.return_value = True obj = ModelGenerator() response = obj._find_checkpoint_file() self.assertEqual(response, True) mock_ospth.exists.assert_called_with(mock_ospth.join()) @mock.patch('modelgen.modelgenerator.path') def test_find_checkpoint_file_not_found(self, mock_ospth): mock_ospth.exists.return_value = False obj = ModelGenerator() with self.assertRaises(FileNotFoundError) as err: obj._find_checkpoint_file() @classmethod def tearDownClass(self): pass
StarcoderdataPython
3293530
''' The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night. Determine the maximum amount of money the thief can rob tonight without alerting the police. Example 1: Input: [3,2,3,null,3,null,1] 3 / \ 2 3 \ \ 3 1 Output: 7 Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. Example 2: Input: [3,4,5,1,3,null,1] 3 / \ 4 5 / \ \ 1 3 1 Output: 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9. ''' # 2018-11-19 # 337. House Robber III # https://leetcode.com/problems/house-robber-iii/ # https://leetcode.com/problems/house-robber-iii/discuss/79330/Step-by-step-tackling-of-the-problem # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def rob(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 val = 0 if root.left != None: val += self.rob(root.left.left) + self.rob(root.left.right) if root.right != None: val += self.rob(root.right.left) + self.rob(root.right.right) return max(val + root.val, self.rob(root.left) + self.rob(root.right)) # https://leetcode.com/problems/house-robber-iii/discuss/79363/Easy-understanding-solution-with-dfs # use dfs class Solution: def rob(self, root): """ :type root: TreeNode :rtype: int """
StarcoderdataPython
72562
import copy from proxy import Proxy class ProxyList(list): """ A proxy wrapper for a normal Python list. A lot of functionality is being reproduced from Proxy. Inheriting Proxy would simplify things a lot but I get type errors when I try to do so. It is not exactly clear what a partial copy entails for a ProxyList so we will not consider this option for now. """ __slots__ = ["_obj", "__weakref__", "__slots__", "_is_copied", "_enable_partial_copy", "_attr_map"] _is_copied = False _special_names = [ '__add__', '__contains__', '__delitem__', '__delslice__', '__eq__', '__ge__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', '__xor__', 'next', ] def __init__(self, obj, _partial_copy=False): object.__setattr__(self, "_obj", obj) object.__setattr__(self, "_enable_partial_copy", _partial_copy) def append(self, obj): if not self._is_copied: self._obj = copy.deepcopy(self._obj) self._is_copied = True self._obj.append(obj) def count(self, obj): return self._obj.count(obj) def extend(self, iterable): if not self._is_copied: self._obj = copy.deepcopy(self._obj) self._is_copied = True self._obj.extend(iterable) def index(self, obj): return self._obj.index(obj) def insert(self, idx, obj): if not self._is_copied: self._obj = copy.deepcopy(self._obj) self._is_copied = True self._obj.insert(idx, obj) def pop(self): if not self._is_copied: self._obj = copy.deepcopy(self._obj) self._is_copied = True return self._obj.pop() def remove(self, obj): if not self._is_copied: self._obj = copy.deepcopy(self._obj) self._is_copied = True self._obj.remove(obj) def reverse(self): if not self._is_copied: self._obj = copy.deepcopy(self._obj) self._is_copied = True self._obj.reverse() def sort(self, cm='None', key='None', reverse='False'): if not self._is_copied: self._obj = copy.deepcopy(self._obj) self._is_copied = True self._obj.sort(cm, key, reverse) @classmethod def _create_class_proxy(cls, theclass): """creates a proxy for the given class""" def make_method(name): def method(self, *args, **kw): if name in cls._special_names and args is not (): args = map(lambda x: x._obj if isinstance(x, Proxy) or isinstance(x, ProxyList) else x, args) return getattr(object.__getattribute__(self, "_obj"), name)(*args, **kw) return method namespace = {} for name in cls._special_names: if hasattr(theclass, name): namespace[name] = make_method(name) return type("%s(%s)" % (cls.__name__, theclass.__name__), (cls,), namespace) def __new__(cls, obj, *args, **kwargs): """ creates an proxy instance referencing `obj`. (obj, *args, **kwargs) are passed to this class' __init__, so deriving classes can define an __init__ method of their own. note: _class_proxy_cache is unique per deriving class (each deriving class must hold its own cache) """ try: cache = cls.__dict__["_class_proxy_cache"] except KeyError: cls._class_proxy_cache = cache = {} try: theclass = cache[obj.__class__] except KeyError: cache[obj.__class__] = theclass = cls._create_class_proxy(obj.__class__) ins = list.__new__(theclass) theclass.__init__(ins, obj, *args, **kwargs) return ins
StarcoderdataPython
3322783
from rest_framework.test import APITestCase from main.models import FavoriteThing, Category class BaseViewTest(APITestCase): @staticmethod def create_category(category_name=''): category = Category.objects.create(category_name=category_name) return category @staticmethod def create_favorite_thing(**kwargs): favorite_thing = FavoriteThing.objects.create(**kwargs) return favorite_thing def setUp(self): self.category_one = self.create_category('phone') self.category_two = self.create_category('food') self.category_three = self.create_category('place') self.favourite_thing_one = self.create_favorite_thing( title='samsung', description='a good phone', ranking=1, metadata={"model": "A series"}, category=self.category_one, ) self.favourite_thing_two = self.create_favorite_thing( title='rice', description='a good food', ranking=1, category=self.category_two, ) self.favourite_thing_three = self.create_favorite_thing( title='erricson', description='a good phone', ranking=2, metadata={"model": "A series"}, category=self.category_one, ) self.favourite_thing_four = self.create_favorite_thing( title='beans', description='a good food', ranking=2, category=self.category_two, ) class Meta: model = FavoriteThing
StarcoderdataPython
3215465
<gh_stars>1-10 from setuptools import setup if __name__ == '__main__': setup(name='lakehouse', author='Elementl', license='Apache-2.0', install_requires=['dagster'])
StarcoderdataPython
122137
from unittest import TestCase, mock from unittest.mock import MagicMock import numpy as np from source.constants import Constants from source.preprocessing.epoch import Epoch from source.preprocessing.heart_rate.heart_rate_collection import HeartRateCollection from source.preprocessing.heart_rate.heart_rate_feature_service import HeartRateFeatureService class TestHeartRateFeatureService(TestCase): @mock.patch('source.preprocessing.heart_rate.heart_rate_feature_service.pd') def test_load(self, mock_pd): mock_pd.read_csv.return_value = mock_return = MagicMock() mock_return.values = expected_return = np.array([1, 2, 3, 4, 5]) actual_returned_value = HeartRateFeatureService.load("subjectA") self.assertListEqual(expected_return.tolist(), actual_returned_value.tolist()) mock_pd.read_csv.assert_called_once_with(str(HeartRateFeatureService.get_path("subjectA")), delimiter=' ') def test_get_path(self): expected_path = Constants.FEATURE_FILE_PATH.joinpath("subjectA" + '_hr_feature.out') self.assertEqual(expected_path, HeartRateFeatureService.get_path("subjectA")) @mock.patch('source.preprocessing.heart_rate.heart_rate_feature_service.np') def test_write(self, mock_np): feature_to_write = np.array([1, 2, 3, 4]) subject_id = "subjectA" HeartRateFeatureService.write(subject_id, feature_to_write) mock_np.savetxt.assert_called_once_with(HeartRateFeatureService.get_path(subject_id), feature_to_write, fmt='%f') def test_get_window(self): timestamps = np.array([-1000, -500, 32, 50, 60, 800, 1000]) epoch = Epoch(timestamp=55, index=120) expected_indices_in_range = np.array([2, 3, 4]) actual_indices_in_range = HeartRateFeatureService.get_window(timestamps, epoch) self.assertEqual(expected_indices_in_range.tolist(), actual_indices_in_range.tolist()) @mock.patch.object(HeartRateFeatureService, 'get_feature') @mock.patch('source.preprocessing.heart_rate.heart_rate_feature_service.HeartRateService') def test_build_feature_array(self, mock_heart_rate_service, mock_get_feature): subject_id = "subjectA" data = np.array( [[1, 10], [10, 220], [20, 0], [40, 500], [70, 200], [90, 0], [100, 0], [400, 4]]) motion_collection = HeartRateCollection(subject_id=subject_id, data=data) mock_heart_rate_service.load_cropped.return_value = motion_collection expected_features = [np.array([0.1]), np.array([0.2])] mock_get_feature.side_effect = expected_features expected_feature_array = np.array(expected_features) valid_epochs = [Epoch(timestamp=4, index=1), Epoch(timestamp=50, index=2)] returned_feature_array = HeartRateFeatureService.build(subject_id, valid_epochs) self.assertEqual(expected_feature_array.tolist(), returned_feature_array.tolist())
StarcoderdataPython
12404
<gh_stars>1-10 #!/usr/bin/env python # # Copyright (C) 2006 British Broadcasting Corporation and Kamaelia Contributors(1) # All Rights Reserved. # # You may only modify and redistribute this under the terms of any of the # following licenses(2): Mozilla Public License, V1.1, GNU General # Public License, V2.0, GNU Lesser General Public License, V2.1 # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://kamaelia.sourceforge.net/AUTHORS - please extend this file, # not this notice. # (2) Reproduced in the COPYING file, and at: # http://kamaelia.sourceforge.net/COPYING # Under section 3.5 of the MPL, we are using this text since we deem the MPL # notice inappropriate for this file. As per MPL/GPL/LGPL removal of this # notice is prohibited. # # Please contact us via: <EMAIL> # to discuss alternative licensing. # ------------------------------------------------------------------------- # Licensed to the BBC under a Contributor Agreement: RJL """(Bit)Torrent IPC messages""" from Kamaelia.BaseIPC import IPC # ====================== Messages to send to TorrentMaker ======================= class TIPCMakeTorrent(IPC): "Create a .torrent file" Parameters = [ "trackerurl", "log2piecesizebytes", "title", "comment", "srcfile" ] #Parameters: # trackerurl - the URL of the BitTorrent tracker that will be used # log2piecesizebytes - log base 2 of the hash-piece-size, sensible value: 18 # title - name of the torrent # comment - a field that can be read by users when they download the torrent # srcfile - the file that the .torrent file will have metainfo about # ========= Messages for TorrentPatron to send to TorrentService ================ # a message for TorrentClient (i.e. to be passed on by TorrentService) class TIPCServicePassOn(IPC): "Add a client to TorrentService" Parameters = [ "replyService", "message" ] #Parameters: replyService, message # request to add a TorrentPatron to a TorrentService's list of clients class TIPCServiceAdd(IPC): "Add a client to TorrentService" Parameters = [ "replyService" ] #Parameters: replyService # request to remove a TorrentPatron from a TorrentService's list of clients class TIPCServiceRemove(IPC): "Remove a client from TorrentService" Parameters = [ "replyService" ] #Parameters: replyService # ==================== Messages for TorrentClient to produce ==================== # a new torrent has been added with id torrentid class TIPCNewTorrentCreated(IPC): "New torrent %(torrentid)d created in %(savefolder)s" Parameters = [ "torrentid", "savefolder" ] #Parameters: torrentid, savefolder # the torrent you requested me to download is already being downloaded as torrentid class TIPCTorrentAlreadyDownloading(IPC): "That torrent is already downloading!" Parameters = [ "torrentid" ] #Parameters: torrentid # for some reason the torrent could not be started class TIPCTorrentStartFail(object): "Torrent failed to start!" Parameters = [] #Parameters: (none) # message containing the current status of a particular torrent class TIPCTorrentStatusUpdate(IPC): "Current status of a single torrent" def __init__(self, torrentid, statsdictionary): super(TIPCTorrentStatusUpdate, self).__init__() self.torrentid = torrentid self.statsdictionary = statsdictionary def __str__(self): return "Torrent %d status : %s" % (self.torrentid, str(int(self.statsdictionary.get("fractionDone",0) * 100)) + "%") # ====================== Messages to send to TorrentClient ====================== # create a new torrent (a new download session) from a .torrent file's binary contents class TIPCCreateNewTorrent(IPC): "Create a new torrent" Parameters = [ "rawmetainfo" ] #Parameters: rawmetainfo - the contents of a .torrent file # close a running torrent class TIPCCloseTorrent(IPC): "Close torrent %(torrentid)d" Parameters = [ "torrentid" ] #Parameters: torrentid
StarcoderdataPython
1624308
import collections import logging import pickle from typing import Any, Dict, Hashable, Iterable, Iterator, Mapping, Optional, Sequence, Union import warnings import numpy as np from smqtk_dataprovider import from_uri from smqtk_descriptors import DescriptorElement from smqtk_classifier.interfaces.classify_descriptor_supervised import ClassifyDescriptorSupervised LOG = logging.getLogger(__name__) try: # noinspection PyPackageRequirements import scipy.stats # type: ignore except ImportError: warnings.warn( "scipy.stats not importable: SkLearnSvmClassifier will not be usable." ) scipy = None try: from sklearn import svm except ImportError: warnings.warn( "svm not importable: SkLearnSvmClassifier will not be usable." ) svm = None class SkLearnSvmClassifier (ClassifyDescriptorSupervised): """ Classifier that wraps the SkLearn SVM (Support Vector Machine) SVC (C-Support Vector Classification) module. Model file paths are optional. If they are given and the file(s) exist, we will load them. If they do not, we treat the path(s) as the output path(s) for saving a model after calling ``train``. If this is None (default), no model is loaded nor output via training, thus any model trained will only exist in memory during the lifetime of this instance. :param svm_model_uri: Path to the model file. :param C: Regularization parameter passed to SkLearn SVM SVC model. :param kernel: Kernel type passed to SkLearn SVM SVC model. :param probability: Whether to enable probability estimates or not. :param calculate_class_weights: Whether to manually calculate the class weights to be passed to the SVM model or not. Defaults to true. If false, all classes will be given equal weight. :param normalize: Normalize input vectors to training and classification methods using ``numpy.linalg.norm``. This may either be ``None``, disabling normalization, or any valid value that could be passed to the ``ord`` parameter in ``numpy.linalg.norm`` for 1D arrays. This is ``None`` by default (no normalization). """ # noinspection PyDefaultArgument def __init__( self, svm_model_uri: Optional[str] = None, C: float = 2.0, # Regularization parameter kernel: str = 'linear', # Kernel type probability: bool = True, # Enable probabilty estimates calculate_class_weights: bool = True, # Enable calculation of class weights normalize: Optional[Union[int, float, str]] = None, ): super(SkLearnSvmClassifier, self).__init__() self.svm_model_uri = svm_model_uri # Elements will be None if input URI is None #: :type: None | smqtk.representation.DataElement self.svm_model_elem = \ svm_model_uri and from_uri(svm_model_uri) self.C = C self.kernel = kernel self.probability = probability self.calculate_class_weights = calculate_class_weights self.normalize = normalize # Validate normalization parameter by trying it on a random vector if normalize is not None: self._norm_vector(np.random.rand(8)) # generated parameters self.svm_model: Optional[svm.SVC] = None self._reload_model() @classmethod def is_usable(cls) -> bool: return None not in {scipy, svm} def get_config(self) -> Dict[str, Any]: return { "svm_model_uri": self.svm_model_uri, "C": self.C, "kernel": self.kernel, "probability": self.probability, "calculate_class_weights": self.calculate_class_weights, "normalize": self.normalize, } def _reload_model(self) -> None: """ Reload SVM model from configured file path. """ if self.svm_model_elem and not self.svm_model_elem.is_empty(): svm_model_tmp_fp = self.svm_model_elem.write_temp() with open(svm_model_tmp_fp, 'rb') as f: self.svm_model = pickle.load(f) self.svm_model_elem.clean_temp() def _norm_vector(self, v: np.ndarray) -> np.ndarray: """ Class standard array normalization. Normalized along max dimension (a=0 for a 1D array, a=1 for a 2D array, etc.). :param v: Vector to normalize :return: Returns the normalized version of input array ``v``. """ if self.normalize is not None: n = np.linalg.norm(v, self.normalize, v.ndim - 1, keepdims=True) # replace 0's with 1's, preventing div-by-zero n[n == 0.] = 1. return v / n # Normalization off return v def has_model(self) -> bool: """ :return: If this instance currently has a model loaded. If no model is present, classification of descriptors cannot happen. :rtype: bool """ return self.svm_model is not None def _train( self, class_examples: Mapping[Hashable, Iterable[DescriptorElement]] ) -> None: train_labels = [] train_vectors = [] train_group_sizes: Dict = {} # number of examples per class # Making SVM label assignment deterministic to lexicographical order # of the type repr. # -- Can't specifically guarantee that dict key types will all support # less-than operator, however we can always get some kind of repr # which is a string which does support less-than. In the common case # keys will be strings and ints, but this "should" handle more # exotic cases, at least for the purpose of ordering keys reasonably # deterministically. for i, l in enumerate(sorted(class_examples, key=lambda e: str(e))): # requires a sequence, so making the iterable ``g`` a tuple g = class_examples[l] if not isinstance(g, collections.abc.Sequence): LOG.debug(' (expanding iterable into sequence)') g = tuple(g) train_group_sizes[l] = float(len(g)) x = np.array(DescriptorElement.get_many_vectors(g)) x = self._norm_vector(x) train_labels.extend([l] * x.shape[0]) train_vectors.extend(x) del g, x assert len(train_labels) == len(train_vectors), \ "Count mismatch between parallel labels and descriptor vectors" \ "(%d != %d)" \ % (len(train_labels), len(train_vectors)) # Calculate class weights weights = None if self.calculate_class_weights: weights = {} # (john.moeller): The weighting should probably be the geometric # mean of the number of examples over the classes divided by the # number of examples for the current class. gmean = scipy.stats.gmean(list(train_group_sizes.values())) for i, g in enumerate(train_group_sizes): w = gmean / train_group_sizes[g] weights[g] = w self.svm_model = svm.SVC(C=self.C, kernel=self.kernel, probability=self.probability, class_weight=weights) LOG.debug("Training SVM model") self.svm_model.fit(train_vectors, train_labels) if self.svm_model_elem and self.svm_model_elem.writable(): LOG.debug("Saving model to element (%s)", self.svm_model_elem) self.svm_model_elem.set_bytes(pickle.dumps(self.svm_model)) def get_labels(self) -> Sequence[Hashable]: if self.svm_model is not None: return list(self.svm_model.classes_) else: raise RuntimeError("No model loaded") def _classify_arrays(self, array_iter: Union[np.ndarray, Iterable[np.ndarray]]) -> Iterator[Dict[Hashable, float]]: if self.svm_model is None: raise RuntimeError("No SVM model present for classification") # Dump descriptors into a matrix for normalization and use in # prediction. vec_mat = np.array(list(array_iter)) vec_mat = self._norm_vector(vec_mat) svm_model_labels = self.get_labels() if self.svm_model.probability: proba_mat = self.svm_model.predict_proba(vec_mat) for proba in proba_mat: yield dict(zip(svm_model_labels, proba)) else: c_base = {label: 0.0 for label in svm_model_labels} proba_mat = self.svm_model.predict(vec_mat) for p in proba_mat: c = dict(c_base) c[p] = 1.0 yield c
StarcoderdataPython
3280504
<filename>scripts/usage-report.py # Emails you a per-collector per-source usage report # # python usage-report.py <accessId> <accessKey> <orgId> <fromTime> <toTime> <timezone> <timeslice> <email> # # TODO per-source # TODO log hook # TODO delete jobs? from email.mime.text import MIMEText import json from smtplib import SMTP import sys from sumologic import SumoLogic args = sys.argv sumo = SumoLogic(args[1], args[2], "https://long-api.sumologic.net/api/v1") orgId = args[3] fromTime = args[4] toTime = args[5] timezone = args[6] timeslice = args[7] fromEmail = '<EMAIL>' toEmail = args[8] lookup = "lookup/collector_name" q = r""" _sourceCategory=config "Collector by name and ID" !GURR "%s" | parse "[logger=*]" as logger | where logger = "scala.config.LoggingVisitor" | parse "Collector by name and ID, id: '*', decimal: '*', name: '*', organization ID: '*', decimal: '*', organization name: '*', organization type: '*'" as collector_id, collector_id_decimal, collector_name, org_id, org_id_decimal, org_name, account_type | where org_id = "%s" | count by collector_id, collector_name | fields collector_id, collector_name | save %s """ q = q % (orgId, orgId, lookup) q = q.replace('\n', ' ') r = sumo.search_and_wait(q, fromTime, toTime, timezone) print r q = r""" (_sourceCategory=receiver or _sourceCategory=cloudcollector) "Message stats, combined" "by collector" "%s" | parse "customer: '*'" as customer_id | where customer_id = "%s" | parse "{\"collector\":*" as collector_json | parse regex field=collector_json "\"(?<collector_id>\S+?)\":\{\"sizeInBytes\":(?<size_in_bytes>\d+?),\"count\":(?<message_count>\d+?)" multi | fields - collector_json | lookup collector_name as collector_name from %s on collector_id = collector_id | sum(size_in_bytes) as size_in_bytes, sum(message_count) as message_count by collector_id, collector_name | sort size_in_bytes """ q = q % (orgId, orgId, lookup) q = q.replace('\n', ' ') r = sumo.search_and_wait(q, fromTime, toTime, timezone) print r msg = MIMEText(json.dumps(r)) msg['From'] = fromEmail msg['To'] = toEmail msg['Subject'] = 'Collector Usage Report' smtp = SMTP('localhost') smtp.sendmail(fromEmail, [toEmail], msg.as_string()) smtp.quit()
StarcoderdataPython
143532
<reponame>JosephVSN/cmus-scrobbler<gh_stars>0 """Config script for cmus_scrobbler.""" import os import json import lastfm CONFIG_DIR = os.path.join(os.path.expanduser("~"), ".config", "cmus-scrobbler") CONFIG_JSON = os.path.join(CONFIG_DIR, "cmus_scrobbler_config.json") def _setup_config() -> bool: """Creates the API config directory and file""" try: os.mkdir(CONFIG_DIR) except (IOError, PermissionError) as e: print(f"DEBUG: Failed to create config directory due to '{e}'") return False try: with open (CONFIG_JSON, "w") as cfg_f: json.dump({"api_key": "", "secret_key": "", "session_key": "", "api_token": ""}, cfg_f) except (IOError, PermissionError) as e: print(f"DEBUG: Failed to create config file due to '{e}'") return False return True def read_config() -> dict: """Wrapper for opening CONFIG_JSON and returning it as a dictionary""" try: with open (CONFIG_JSON) as cfg: cfg_json = json.load(cfg) except (json.decoder.JSONDecodeError, PermissionError, IOError) as e: print(f"DEBUG: Refusing to read config, encountered '{e}'") return None return cfg_json def update_config(api_key: str = None, secret_key: str = None, session_key: str = None, api_token: str = None) -> bool: """Updates the values in the API config file""" if not os.path.exists(CONFIG_JSON): if not _setup_config(): print("DEBUG: Refusing to update config, file/directory do not exist and were unable to be created") return False if not (cfg_json := read_config()): return False if api_key: cfg_json["api_key"] = api_key if secret_key: cfg_json["secret_key"] = secret_key if session_key: cfg_json["session_key"] = session_key if api_token: cfg_json["api_token"] = api_token try: with open(CONFIG_JSON, 'w') as cfg: json.dump(cfg_json, cfg) except PermissionError as e: print(f"DEBUG: Refusing to update config, encountered '{e}'") return False return True
StarcoderdataPython
43184
<filename>python_demo_v2/lxml_test.py import requests from lxml import etree def get_one_page(url): try: headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36', 'cookie': 'prov=75cc3cab-0ed5-5eb2-d18c-b312a24350db; _ga=GA1.2.1662857097.1537756289; __qca=P0-1944747911-1537756288975; __gads=ID=07b4138067dfdc8b:T=1537756486:S=ALNI_MZZ_k0v-XqE5eG_swFphVY1MMMqpQ; hero-dismissed=1537756342543!stk_a; _gid=GA1.2.968380875.1539586485' } res = requests.get(url, headers=headers) if res.status_code != 200: return res.status_code else: html = etree.parse(res.text, etree.HTMLParser()) results = html.xpath('//a/@href') return results except Exception as e: return e def main(): url = 'https://stackoverflow.com/questions/tagged/react-leaflet' html = get_one_page(url) print(html) main();
StarcoderdataPython
110649
<reponame>chrigl/docker-library<gh_stars>0 """Define interfaces for your add-on. """ from plone.theme.interfaces import IDefaultPloneLayer from zope.interface import Interface class IGeoFileLayer(IDefaultPloneLayer): """Marker interface that defines a Zope 3 browser layer. """ class IGisFile(Interface): """ Marker interface for files containing GIS data. Should just be used in the browser page definition!!! """
StarcoderdataPython
17117
<gh_stars>0 import sys from __init__ import Bot MESSAGE_USAGE = "Usage is python %s [name] [token]" if __name__ == "__main__": if len(sys.argv) == 3: Bot(sys.argv[1], sys.argv[2]) else: print(MESSAGE_USAGE.format(sys.argv[0]))
StarcoderdataPython
4819668
# TODO: FIX INDENTATION TO REMOVE THIS ERROR # PEP8-COMPLIANT MEANS 4 SPACES/TAB import logging import re import aiohttp import discord from bs4 import BeautifulSoup from discord.ext import commands from asyncTest import saveDict user_agent = """\ Mozilla/5.0 (Windows; U; Windows NT 10.0; rv:10.0) Gecko/20100101 Firefox/52.0\ """ sendHeader = {'User-Agent': user_agent, } class Pokemon: """Pokemon related commands.""" def __init__(self, bot): self.bot = bot self.pokedex = None def _getPokeCategory(self, tble, poke): """Get a Pokemon's category from its Bulbapedia page. Keyword arguments: tble -- the info table from the BeautifulSoup object of the page poke -- the name of the Pokemon """ try: pokeText = tble.find(name="a", title=re.compile("Pok.mon category")) # If the Pokemon category has an explanation # i.e. if you hover over it if (pokeText.string is None): pokeText = pokeText.find(name="span", attrs={"class": "explain"}) pokeText = pokeText.string # "é" = "\u00e9" if (" Pok\u00e9mon" not in pokeText): pokeText = "{} Pok\u00e9mon".format(pokeText) except Exception as e: logging.error(e) logging.error("Error getting Pokemon category for {}".format(poke)) return False return pokeText def _getPokeNatDexNo(self, tble, poke): """Get a Pokemon's National Dex number from its Bulbapedia page. Keyword arguments: tble -- the info table from the BeautifulSoup object of the page poke -- the name of the Pokemon """ dexRE = re.compile("List of Pok.mon by National Pok.dex number") try: natDexNo = tble.find(name="a", title=dexRE).string assert(natDexNo != "") except Exception as e: logging.error(e) logging.error("""\ Error getting National Pokedex number for {}\ """.format(poke)) return False return natDexNo def _getPokeEmbedImg(self, tble, poke): """Get a Pokemon's image URL from its Bulbapedia page. Keyword arguments: tble -- the info table from the BeautifulSoup object of the page poke -- the name of the Pokemon """ try: embedImg = tble.find(name="a", attrs={"class": "image"}) embedImg = embedImg.find(name="img") embedImg = embedImg.get("src") except Exception as e: logging.error(e) logging.error("Error getting embed image for {}".format(poke)) return False embedImg = "https:{}".format(embedImg) return embedImg # TODO: LOOK INTO USING COLLECTIONS.ORDEREDDICT INSTEAD OF DICT FOR TYPES, # ABILITIES, AND BASE STATSs def _getPokeTypes(self, tble, poke): """Get a Pokemon's types from its Bulbapedia page. Keyword arguments: tble -- the info table from the BeautifulSoup object of the page poke -- the name of the Pokemon """ pokeTypes = dict() typeRE = re.compile("(?<!Unknown )\(type\)") typeSet = [] try: types = tble.find_all(name="a", title=typeRE) for type in types: tempTable = type.find_parent("table") add = True for setTable in typeSet: # TODO: LOOK INTO THE POSSIBILITY OF OPTIMIZING W/ SETS if (tempTable is setTable): add = False if (add): typeSet += [tempTable] while(len(typeSet) > 0): typeTable = typeSet.pop() parent = typeTable.find_parent(name="td") key = parent.find(name="small") if (key is not None): key = key.string else: key = poke for type in typeTable.find_all(name="a", title=typeRE): if (key in pokeTypes): # pokeTypes[key] = pokeTypes[key] + ";" + type.string pokeTypes[key] = "{};{}".format(pokeTypes[key], type.string) else: pokeTypes[key] = type.string except Exception as e: logging.error(e) logging.error("Error getting types for {}".format(poke)) return False return pokeTypes def _getPokeAbilities(self, tble, poke): """Get a Pokemon's abilities from its Bulbapedia page. Keyword arguments: tble -- the info table from the BeautifulSoup object of the page poke -- the name of the Pokemon """ abilities = dict() try: # Find the link in the table for abilities abilityLink = tble.find(name="a", title="Ability") assert(abilityLink is not None) # Find the parent table abilitiesTable = abilityLink.find_parent(name="td") # Find all of the table cells that will have the abilities abilitiesCells = abilitiesTable.find_all(name="td") for ability in abilitiesCells: # Filter out abilities that aren't displayed # e.g. unused "Cacophony" ability if (("style" in ability.attrs) and ("display: none" in ability.attrs["style"])): continue else: try: # Subtitles # e.g. "Hidden Ability", "Mega Charizard X", etc. key = ability.small.string.strip() # No subtitle # Implies that it's a normal ability so use the Pokemon except Exception: key = poke # Pokemon may have multiple possible abilities # e.g. Snorlax may normally have Immunity or Thick Fat for link in ability.find_all(name="a"): if (key in abilities): abilities[key] = "{};{}".format(abilities[key], link.string) else: abilities[key] = link.string except Exception as e: logging.error(e) logging.error("Error getting abilities for {}".format(poke)) return False return abilities def _getPokeBaseStats(self, soup, poke): """Get a Pokemon's base stats from its Bulbapedia page. Keyword arguments: soup -- the BeautifulSoup object of the Pokemon's page poke -- the name of the Pokemon """ baseStats = dict() try: statTables = soup.find_all(name="table", align="left") for table in statTables: if (table.span.string != "Stat"): continue title = table.find_previous().string if (title == "Base stats"): title = poke tempDict = dict() # Get the tag with the numbers for a stat baseStat = table.find_next(name="td") # Get the tag with the stat range at level 50 range50 = baseStat.find_next(name="small") # Get the stat range at level 100 range100 = range50.find_next(name="small").string # Get the stat range at level 50 range50 = range50.string def getNextNext(tag, name, string=False): """Get the next next name element from the tag. Optional: return the element's string Keyword arguments: tag -- the Beautiful Soup object to work with name -- the element to get string -- whether or not to return the element's string """ temp = tag.find_next(name=name).find_next(name=name) if (string is True): try: temp = temp.string.strip() except Exception as e: logging.error(e) return temp key = baseStat.a.string tempDict[key] = """\ {};{};{}""".format(getNextNext(baseStat, "th", True), range50, range100) # Do this 5 more times (total of 6) to get all of the stats for i in range(0, 5): baseStat = getNextNext(baseStat, "td") range50 = baseStat.find_next(name="small") range100 = range50.find_next(name="small").string range50 = range50.string key = baseStat.a.string tempDict[key] = """\ {};{};{}""".format(getNextNext(baseStat, "th", True), range50, range100) baseStat = getNextNext(baseStat, "td") tempDict["Total"] = getNextNext(baseStat, "th", True) baseStats[title] = tempDict except Exception as e: logging.error(e) logging.error("Error getting base stats for {}".format(poke)) return False return baseStats def _getPokeData(self, soup, poke): """Get a Pokemon's data from its Bulbapedia page. Keyword arguments: soup -- the BeautifulSoup object of the Pokemon's page poke -- the name of the Pokemon """ # Dictionary with the Pokemon's info pokeDict = dict() infoTable = soup.find(name="table", style=re.compile("float:right*")) pokemon = self._titlecase(poke.replace("_", " ")) # Pokemon info in order of appearance on the Bulbapedia page pokeText = "" # Pokemon text e.g. "Seed Pokemon" for Bulbasaur natDexNo = "" # National Pokédex number embedImg = "" # Image of the Pokemon pokeTypes = dict() # Pokemon types abilities = dict() # Pokemon abilities baseStats = dict() # Pokemon base stats pokeText = self._getPokeCategory(tble=infoTable, poke=pokemon) natDexNo = self._getPokeNatDexNo(tble=infoTable, poke=pokemon) embedImg = self._getPokeEmbedImg(tble=infoTable, poke=pokemon) pokeTypes = self._getPokeTypes(tble=infoTable, poke=pokemon) abilities = self._getPokeAbilities(tble=infoTable, poke=pokemon) baseStats = self._getPokeBaseStats(soup=soup, poke=pokemon) pokeDict["category"] = pokeText pokeDict["natDexNo"] = natDexNo pokeDict["img"] = embedImg pokeDict["types"] = pokeTypes pokeDict["abilities"] = abilities pokeDict["baseStats"] = baseStats # Check that there were no problems getting the stats # The helper functions return False if there were any issues for key in pokeDict: if (not pokeDict[key]): return False return pokeDict def _createDiscordEmbed(self, info, poke): """Create a formatted Discord Embed object for a Pokemon. Keyword arguments: info -- the dictionary containing the Pokemon's information poke -- the name of the Pokemon """ pokeName = self._titlecase(poke.replace("_", " ")) def unicodeFix(str): """Replace certain substrings with Unicode characters. Return a copy of str with certain substrings replaced with Unicode characters. Keyword arguments: str -- the string to copy and modify """ temp = re.sub("[ _]\([fF]\)", "\u2640", str) temp = re.sub("[ _]\([mM]\)", "\u2642", temp) return temp pokeName = unicodeFix(pokeName) embed = discord.Embed(title=pokeName, description="{}: {}".format(info["natDexNo"], info["category"]), url=self.pokedex[poke]) types = info["types"] abilities = info["abilities"] baseStats = info["baseStats"] def addField(fieldDict: dict, name: str, inline: bool=False): """Add a field to the embed containing the items in the dict. Keyword arguments: fieldDict -- the dictionary to iterate over name -- the name of the embed field inline -- whether or not the embed field is inline """ strList = [] if (len(fieldDict) == 1): strList.append(list(fieldDict.values())[0].replace(";", ", ")) else: for item in sorted(fieldDict.items()): strList.append("{}: {}".format(item[0], item[1].replace(";", ", "))) embed.add_field(name=name, value="\n".join(strList), inline=inline) addField(types, "Types", inline=False) addField(abilities, "Abilities", inline=False) statStr = [] statStr.append("```{:^15}{:^24}".format("Stat", "Range")) statStr.append("{:15}{:^12}{:^12}".format("", "At Lv. 50", "At Lv. 100")) def getValues(poke, stat): """Return a list of values for a Pokemon's stat. Keyword arguments: poke -- the name of the Pokemon stat -- the stat to get """ return baseStats[poke][stat].split(";") def appendStat(poke, stat): """Append a formatted str of a Pokemon's stat to the stat list. Keyword arguments: poke -- the name of the Pokemon stat -- the stat to get """ tempStr = "{}:".format(stat) if (stat.lower() != "total"): formatStr = "{0:<9}{1[0]:<6}{1[1]:^12}{1[2]:^12}" else: formatStr = "{0:<9}{1[0]}" statStr.append(formatStr.format(tempStr, getValues(poke, stat))) return keys = sorted(baseStats.keys()) # Experienced errors with Deoxys probably because of the many forms # Limit the base stats to reduce the character count # Probably hitting the character limit # Limit to 3 tables of stats # TODO: REMOVE LIMIT IF THE CHARACTER LIMIT IS UPPED OR REMOVED count = 0 for key in keys: if (count == 3): break statStr.append(unicodeFix(key)) appendStat(key, "HP") appendStat(key, "Attack") appendStat(key, "Defense") appendStat(key, "Sp.Atk") appendStat(key, "Sp.Def") appendStat(key, "Speed") appendStat(key, "Total") count += 1 statStr.append("```") embed.add_field(name="Base Stats", value="\n".join(statStr), inline=False) embed.set_thumbnail(url=info["img"]) embed.set_footer(text="Source: https://bulbapedia.bulbagarden.net") return embed def _titlecase(self, string): """Titlecase workaround for a string with apostrophes. Keyword arguments: string -- the string to titlecase """ if (string.lower() == "ho-oh"): return "Ho-Oh" else: return " ".join(map(lambda s: s.capitalize(), string.split(" "))) async def _getPokeURLs(self, session): """Create a dictionary containing the Bulbapedia URLs for every Pokemon. Keyword arguments: session -- the aiohttp session to use """ baseURL = "http://bulbapedia.bulbagarden.net" page = "/wiki/List_of_Pok%C3%A9mon_by_National_Pok%C3%A9dex_number" pokeUrl = "{}{}".format(baseURL, page) pokedex = dict() async with session.get(pokeUrl) as response: try: assert(response.status == 200) data = await response.read() soup = BeautifulSoup(data, "html.parser") except Exception as e: logging.error(e) # Add more regions as needed regions = {"Kanto", "Johto", "Hoenn", "Sinnoh", "Unova", "Kalos", "Alola", } tables = soup.find_all("table") for tableBody in tables: # not isdisjoint checks if any of the regions is in the table titles # can check tables[i].th.a["title"] for Kanto-Kalos, but not Alola # regions.isdisjoint(str(tables[1].th).split(" ")) if ((tableBody is tables[7]) or (not regions.isdisjoint(str(tableBody.th).split(" ")))): rows = tableBody.find_all("tr") for row in rows: for link in row.find_all("a"): URL = link.get("href") if (("Pok%C3%A9mon" in URL) and ("list" not in URL)): URL = URL.replace("%27", "'") URLRE = re.compile("(/wiki/)|(_\(pok%c3%a9mon\))", re.IGNORECASE) pokemon = re.sub(URLRE, "", URL) # Farfetch'd pokemon = pokemon.replace("%27", "'") # Nidorans pokemon = pokemon.replace("%e2%99%80", "_(f)") pokemon = pokemon.replace("%e2%99%82", "_(m)") # Flabébé pokemon = pokemon.replace("%c3%a9", "é") pokemon = pokemon.lower() pokedex[pokemon] = "{}{}".format(baseURL, URL) self.pokedex = pokedex saveDict(pokedex, "asyncPokedex.json", "") return @commands.command() async def pokemon(self, ctx, *search: str): """Look up a Pokemon on Bulbapedia""" errorMsg = ["Invalid Pokemon '{}' specified.".format(" ".join(search)), "Please specify a valid Pokemon to look up."] if (len(search) < 1): await ctx.send("```{0[1]}```".format(errorMsg)) return # Share a client session so it will not open a new session for each request async with aiohttp.ClientSession() as session: # Setup the dictionary with all of the URL's first if (self.pokedex is None): await self._getPokeURLs(session) species = "_".join(search).lower() species = species.replace("mega_", "") URL = "" pokemon = "" # TODO: LOOK INTO MAKING THESE DICTIONARY ENTRIES INSTEAD OF CONDITIONALS if (species in self.pokedex): pokemon = species elif (species == "derpkip"): pokemon = "mudkip" elif (species == "farfetchd"): pokemon = "farfetch'd" elif (species == "flabebe"): pokemon = "flabébé" elif ((species == "hakamoo") or (species == "hakamo_o")): pokemon = "hakamo-o" elif ((species == "ho_oh") or (species == "hooh")): pokemon = "ho-oh" elif ((species == "jangmoo") or (species == "jangmo_o")): pokemon = "jangmo-o" elif ((species == "kommoo") or (species == "kommo_o")): pokemon = "kommo-o" elif (species == "mime_jr"): pokemon = "mime_jr." elif (species == "mr_mime"): pokemon = "mr._mime" elif ((species == "porygon_z") or (species == "porygonz")): pokemon = "porygon-z" elif (species == "type_null"): pokemon = "type:_null" elif (species == "nidoran"): await ctx.send("""```Please specify either Nidoran (F) or\ Nidoran (M).```""") return elif (species == "nidoran_f"): pokemon = "nidoran_(f)" elif (species == "nidoran_m"): pokemon = "nidoran_(m)" else: await ctx.send("```{0[0]} {0[1]}```".format(errorMsg)) return # Get the Bulbapedia URL URL = self.pokedex[pokemon] # Get the Bulbapedia page async with session.get(URL) as response: try: assert(response.status == 200) data = await response.read() except Exception as e: logging.error(e) return # Get a BeautifulSoup object try: soup = BeautifulSoup(data, "html.parser") except Exception as e: logging.error(e) return # Get the Pokemon's information from the BeautifulSoup object pokeDict = self._getPokeData(soup, pokemon) if (not pokeDict): logging.error("""Something went wrong while getting data from the \ BeautifulSoup object for the Pokemon '{}'.""".format(pokemon)) return pokeEmbed = self._createDiscordEmbed(pokeDict, pokemon) await ctx.send(embed=pokeEmbed) return
StarcoderdataPython
3384979
<reponame>BobBriksz/front-end """Initialize flask app""" from .app import create_app app=create_app()
StarcoderdataPython
3236220
# -*- coding: utf-8 -*- # Copyright 2018 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for chromite.lib.repo and helpers for testing that module.""" from __future__ import print_function import os import sys from chromite.lib import constants from chromite.lib import cros_build_lib from chromite.lib import cros_logging as logging from chromite.lib import cros_test_lib from chromite.lib import git from chromite.lib import osutils from chromite.lib import repo_util assert sys.version_info >= (3, 6), 'This module requires Python 3.6+' def RepoInitSideEffects(*_args, **kwargs): """Mimic side effects of `repo init` by creating .repo dir.""" os.mkdir(os.path.join(kwargs['cwd'], '.repo')) def CopySideEffects(dest): """Mimic side effects of Repository.Copy by creating .repo dir.""" os.mkdir(os.path.join(dest, '.repo')) def RepoCmdPath(repo_root): """Return the path to the repo command to use for the given repo root.""" return os.path.join(repo_root, '.repo', 'repo', 'repo') class RepositoryTest(cros_test_lib.RunCommandTempDirTestCase): """Tests for repo_util.Repository.""" MANIFEST_URL = 'https://example.com/manifest.xml' def setUp(self): self.empty_root = os.path.join(self.tempdir, 'empty') self.empty_root_subdir = os.path.join(self.empty_root, 'sub', 'dir') os.makedirs(self.empty_root_subdir) self.repo_root = os.path.join(self.tempdir, 'root') self.repo_root_subdir = os.path.join(self.repo_root, 'sub', 'dir') os.makedirs(self.repo_root_subdir) self.repo_dir = os.path.join(self.repo_root, '.repo') os.makedirs(self.repo_dir) def testInit(self): """Test Repository.__init__.""" repo = repo_util.Repository(self.repo_root) self.assertTrue(os.path.samefile(repo.root, self.repo_root)) def testInitNoRepoDir(self): """Test Repository.__init__ fails if not in repo.""" with self.assertRaises(repo_util.NotInRepoError): repo_util.Repository(self.empty_root) def testInitializeSimple(self): """Test Repository.Initialize simple call.""" expected_cmd = ['repo', 'init', '--manifest-url', self.MANIFEST_URL] self.rc.AddCmdResult(expected_cmd, side_effect=RepoInitSideEffects) repo = repo_util.Repository.Initialize(self.empty_root, self.MANIFEST_URL) self.assertCommandCalled(expected_cmd, cwd=self.empty_root) self.assertTrue(os.path.samefile(repo.root, self.empty_root)) def testInitializeComplex(self): """Test Repository.Initialize complex call.""" expected_cmd = [ 'repo', 'init', '--manifest-url', 'http://manifest.xyz/manifest', '--manifest-branch', 'test-branch', '--manifest-name', 'other.xml', '--mirror', '--reference', '/repo/reference', '--depth', '99', '--groups', 'abba,queen', '--repo-url', 'https://repo.xyz/repo', '--repo-branch', 'repo-branch' ] self.rc.AddCmdResult(expected_cmd, side_effect=RepoInitSideEffects) repo = repo_util.Repository.Initialize( self.empty_root, 'http://manifest.xyz/manifest', manifest_branch='test-branch', manifest_name='other.xml', mirror=True, reference='/repo/reference', depth=99, groups='abba,queen', repo_url='https://repo.xyz/repo', repo_branch='repo-branch' ) self.assertCommandCalled(expected_cmd, cwd=self.empty_root) self.assertTrue(os.path.samefile(repo.root, self.empty_root)) def testInitializeExistingRepoDir(self): """Test Repository.Initialize fails in existing repo dir.""" with self.assertRaisesRegex(repo_util.Error, 'cannot init in existing'): repo_util.Repository.Initialize(self.repo_root, self.MANIFEST_URL) def testInitializeExistingRepoSubdir(self): """Test Repository.Initialize fails in existing repo subdir.""" with self.assertRaisesRegex(repo_util.Error, 'cannot init in existing'): repo_util.Repository.Initialize(self.repo_root_subdir, self.MANIFEST_URL) def testInitializeFailCleanup(self): """Test Repository.Initialize failure deletes .repo.""" expected_cmd = ['repo', 'init', '--manifest-url', self.MANIFEST_URL] self.rc.AddCmdResult(expected_cmd, returncode=99, side_effect=RepoInitSideEffects) rmdir = self.PatchObject(osutils, 'RmDir') with self.assertRaises(cros_build_lib.RunCommandError): repo_util.Repository.Initialize(self.empty_root, self.MANIFEST_URL) repo_dir = os.path.join(self.empty_root, '.repo') rmdir.assert_any_call(repo_dir, ignore_missing=True) def testFind(self): """Test Repository.Find finds repo from subdir.""" repo = repo_util.Repository.Find(self.repo_root_subdir) self.assertEqual(repo.root, self.repo_root) def testFindNothing(self): """Test Repository.Find finds nothing from non-repo dir.""" self.assertIsNone(repo_util.Repository.Find(self.empty_root_subdir)) def testMustFind(self): """Test Repository.MustFind finds repo from subdir.""" repo = repo_util.Repository.MustFind(self.repo_root_subdir) self.assertEqual(repo.root, self.repo_root) def testMustFindNothing(self): """Test Repository.MustFind fails from non-repo dir.""" with self.assertRaises(repo_util.NotInRepoError): repo_util.Repository.MustFind(self.empty_root_subdir) class RepositoryCommandMethodTest(cros_test_lib.RunCommandTempDirTestCase): """Tests for repo_util.Repository command methods.""" # Testing _Run: pylint: disable=protected-access def setUp(self): self.root = os.path.join(self.tempdir, 'root') self.repo_dir = os.path.join(self.root, '.repo') self.subdir = os.path.join(self.root, 'sub', 'dir') os.makedirs(self.repo_dir) os.makedirs(self.subdir) self.repo = repo_util.Repository(self.root) def AssertRepoCalled(self, repo_args, **kwargs): kwargs.setdefault('cwd', self.root) kwargs.setdefault('capture_output', False) kwargs.setdefault('debug_level', logging.DEBUG) kwargs.setdefault('encoding', 'utf-8') self.assertCommandCalled([RepoCmdPath(self.root)] + repo_args, **kwargs) def AddRepoResult(self, repo_args, **kwargs): self.rc.AddCmdResult([RepoCmdPath(self.root)] + repo_args, **kwargs) def testAssertRepoCalled(self): """Test that AddRepoResult test helper works.""" self.repo._Run(['subcmd', 'arg1']) with self.assertRaises(AssertionError): self.AssertRepoCalled(['subcmd', 'arg2']) with self.assertRaises(AssertionError): self.AssertRepoCalled(['subcmd']) with self.assertRaises(AssertionError): self.AssertRepoCalled(['subcmd', 'arg1'], cwd='other_dir') self.AssertRepoCalled(['subcmd', 'arg1']) def testRun(self): """Test Repository._Run repo_cmd.""" self.repo._Run(['subcmd', 'arg']) self.AssertRepoCalled(['subcmd', 'arg']) def testRunSubDirCwd(self): """Test Repository._Run cwd.""" self.repo._Run(['subcmd'], cwd=self.subdir) self.AssertRepoCalled(['subcmd'], cwd=self.subdir) def testRunBadCwd(self): """Test Repository._Run fails on cwd outside of repo.""" with self.assertRaises(repo_util.NotInRepoError): self.repo._Run(['subcmd'], cwd=self.tempdir) def testSyncSimple(self): """Test Repository.Sync simple call.""" self.repo.Sync() self.AssertRepoCalled(['sync']) def testSyncComplex(self): """Test Repository.Sync complex call.""" manifest_path = os.path.join(self.tempdir, 'other', 'manifest.xml') osutils.Touch(manifest_path, makedirs=True) self.repo.Sync( projects=['p1', 'p2'], local_only=True, current_branch=True, jobs=9, manifest_path=manifest_path, cwd=self.subdir) self.AssertRepoCalled( ['sync', 'p1', 'p2', '--local-only', '--current-branch', '--jobs', '9', '--manifest-name', '../../../other/manifest.xml'], cwd=self.subdir) def testStartBranchSimple(self): """Test Repository.StartBranch simple call.""" self.repo.StartBranch('my-branch') self.AssertRepoCalled(['start', 'my-branch', '--all']) def testStartBranchComplex(self): """Test Repository.StartBranch complex call.""" self.repo.StartBranch( 'my-branch', projects=['foo', 'bar'], cwd=self.subdir) self.AssertRepoCalled( ['start', 'my-branch', 'foo', 'bar'], cwd=self.subdir) def testListSimple(self): """Test Repository.List simple call.""" output = 'src/project : my/project\nsrc/ugly : path : other/project\n' self.AddRepoResult(['list'], output=output) projects = self.repo.List() self.AssertRepoCalled(['list'], capture_output=True) self.assertListEqual(projects, [ repo_util.ProjectInfo(name='my/project', path='src/project'), repo_util.ProjectInfo(name='other/project', path='src/ugly : path'), ]) def testListComplex(self): """Test Repository.List complex call.""" self.repo.List(['project1', 'project2'], cwd=self.subdir) self.AssertRepoCalled(['list', 'project1', 'project2'], cwd=self.subdir, capture_output=True) def testListProjectNotFound(self): """Test Repository.List fails when given a nonexistant project.""" self.AddRepoResult(['list', 'foobar'], returncode=1, error='error: project foobar not found') with self.assertRaises(repo_util.ProjectNotFoundError): self.repo.List(['foobar']) def testManifest(self): """Test Repository.Manifest.""" output = '<manifest></manifest>' self.AddRepoResult(['manifest'], output=output) manifest = self.repo.Manifest() self.assertIsNotNone(manifest) def testCopy(self): """Test Repository.Copy.""" copy_root = os.path.join(self.tempdir, 'copy') os.mkdir(copy_root) def mkdirDestRepo(*_args, **_kwargs): os.mkdir(os.path.join(copy_root, '.repo')) output = 'src/p1 : p1\nother : other/project\n' self.AddRepoResult(['list'], output=output, side_effect=mkdirDestRepo) copy = self.repo.Copy(copy_root) self.assertEqual(copy.root, copy_root) kwargs = dict(debug_level=logging.DEBUG, capture_output=True, encoding='utf-8', extra_env={'LC_MESSAGES': 'C'}, cwd=self.root) self.assertCommandCalled([ 'cp', '--archive', '--link', '--parents', '.repo/project-objects/p1.git/objects', copy_root, ], **kwargs) self.assertCommandCalled([ 'cp', '--archive', '--link', '--parents', '.repo/project-objects/other/project.git/objects', copy_root, ], **kwargs) self.assertCommandCalled([ 'cp', '--archive', '--no-clobber', '.repo', copy_root, ], **kwargs) @cros_test_lib.NetworkTest() class RepositoryIntegrationTest(cros_test_lib.TempDirTestCase): """Tests for repo_util.Repository that actually call `repo`. Note that these test methods are *not* independent: they must run in definition order. """ MANIFEST_URL = constants.EXTERNAL_GOB_URL + '/chromiumos/manifest.git' PROJECT = 'chromiumos/chromite' PROJECT_DIR = 'chromite' root = None repo = None copy = None project_path = None tests = [] def runTest(self): for test in self.tests: test(self) @tests.append def testInitialize(self): """Test Repository.Initialize creates a .repo dir.""" self.root = os.path.join(self.tempdir, 'root') os.mkdir(self.root) # Try to use the current repo as a --reference. reference = repo_util.Repository.Find(constants.SOURCE_ROOT) self.repo = repo_util.Repository.Initialize( self.root, manifest_url=self.MANIFEST_URL, reference=reference, depth=1) self.assertExists(os.path.join(self.root, '.repo')) @tests.append def testSync(self): """Test Repository.Sync creates a project checkout dir.""" self.repo.Sync([self.PROJECT], current_branch=True) self.project_path = os.path.join(self.root, self.PROJECT_DIR) self.assertExists(self.project_path) @tests.append def testMustFind(self): """Test Repository.MustFind finds the Repository from a subdir.""" repo = repo_util.Repository.MustFind(self.project_path) self.assertEqual(repo.root, self.root) @tests.append def testList(self): """Test Repository.List returns correct ProjectInfo.""" projects = self.repo.List([self.PROJECT]) self.assertEqual(projects, [ repo_util.ProjectInfo(name=self.PROJECT, path=self.PROJECT_DIR)]) @tests.append def testStartBranch(self): """Test Repository.StartBranch creates a git branch.""" self.repo.StartBranch('my-branch') project_branch = git.GetCurrentBranch(self.project_path) self.assertEqual(project_branch, 'my-branch') @tests.append def testManifest(self): """Test Repository.Manifest includes project.""" manifest = self.repo.Manifest() project = manifest.GetUniqueProject(self.PROJECT) self.assertEqual(project.path, self.PROJECT_DIR) @tests.append def testCopy(self): """Test Repository.Copy creates a working copy.""" copy_root = os.path.join(self.tempdir, 'copy') os.mkdir(copy_root) copy = self.repo.Copy(copy_root) self.assertEqual(copy.root, copy_root) copy.Sync([self.PROJECT], local_only=True) self.assertExists(os.path.join(copy_root, self.PROJECT_DIR)) # Check for hardlinking; any object file will do. objects_path = repo_util.PROJECT_OBJECTS_PATH_FORMAT % self.PROJECT for dirname, _, files in os.walk(os.path.join(self.root, objects_path)): if files: object_file = os.path.join(dirname, files[0]) break else: self.fail('no object file found') self.assertTrue(os.path.samefile( os.path.join(self.root, object_file), os.path.join(copy_root, object_file)))
StarcoderdataPython
3399001
# Implements a list of unique numbers from cs50 import get_int # Memory for numbers numbers = [] # Prompt for numbers (until EOF) while True: # Prompt for number number = get_int("number: ") # Check for EOF if not number: break # Check whether number is already in list if number not in numbers: # Add number to list numbers.append(number) # Print numbers print() for number in numbers: print(number)
StarcoderdataPython
196445
#!/usr/bin/env python import os import re import sys import warnings from setuptools import setup, find_packages from setuptools import Command MAJOR = 0 MINOR = 10 MICRO = 0 ISRELEASED = False VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) QUALIFIER = 'rc2' DISTNAME = 'xarray' LICENSE = 'Apache' AUTHOR = 'xarray Developers' AUTHOR_EMAIL = '<EMAIL>' URL = 'https://github.com/pydata/xarray' CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Intended Audience :: Science/Research', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Scientific/Engineering', ] INSTALL_REQUIRES = ['numpy >= 1.11', 'pandas >= 0.18.0'] TESTS_REQUIRE = ['pytest >= 2.7.1'] if sys.version_info[0] < 3: TESTS_REQUIRE.append('mock') DESCRIPTION = "N-D labeled arrays and datasets in Python" LONG_DESCRIPTION = """ **xarray** (formerly **xray**) is an open source project and Python package that aims to bring the labeled data power of pandas_ to the physical sciences, by providing N-dimensional variants of the core pandas data structures. Our goal is to provide a pandas-like and pandas-compatible toolkit for analytics on multi-dimensional arrays, rather than the tabular data for which pandas excels. Our approach adopts the `Common Data Model`_ for self- describing scientific data in widespread use in the Earth sciences: ``xarray.Dataset`` is an in-memory representation of a netCDF file. .. _pandas: http://pandas.pydata.org .. _Common Data Model: http://www.unidata.ucar.edu/software/thredds/current/netcdf-java/CDM .. _netCDF: http://www.unidata.ucar.edu/software/netcdf .. _OPeNDAP: http://www.opendap.org/ Important links --------------- - HTML documentation: http://xarray.pydata.org - Issue tracker: http://github.com/pydata/xarray/issues - Source code: http://github.com/pydata/xarray - SciPy2015 talk: https://www.youtube.com/watch?v=X0pAhJgySxk """ # Code to extract and write the version copied from pandas. # Used under the terms of pandas's license, see licenses/PANDAS_LICENSE. FULLVERSION = VERSION write_version = True if not ISRELEASED: import subprocess FULLVERSION += '.dev' pipe = None for cmd in ['git', 'git.cmd']: try: pipe = subprocess.Popen( [cmd, "describe", "--always", "--match", "v[0-9]*"], stdout=subprocess.PIPE) (so, serr) = pipe.communicate() if pipe.returncode == 0: break except: pass if pipe is None or pipe.returncode != 0: # no git, or not in git dir if os.path.exists('xarray/version.py'): warnings.warn("WARNING: Couldn't get git revision, using existing xarray/version.py") write_version = False else: warnings.warn("WARNING: Couldn't get git revision, using generic version string") else: # have git, in git dir, but may have used a shallow clone (travis does this) rev = so.strip() # makes distutils blow up on Python 2.7 if sys.version_info[0] >= 3: rev = rev.decode('ascii') if not rev.startswith('v') and re.match("[a-zA-Z0-9]{7,9}", rev): # partial clone, manually construct version string # this is the format before we started using git-describe # to get an ordering on dev version strings. rev = "v%s.dev-%s" % (VERSION, rev) # Strip leading v from tags format "vx.y.z" to get th version string FULLVERSION = rev.lstrip('v') else: FULLVERSION += QUALIFIER def write_version_py(filename=None): cnt = """\ version = '%s' short_version = '%s' """ if not filename: filename = os.path.join( os.path.dirname(__file__), 'xarray', 'version.py') a = open(filename, 'w') try: a.write(cnt % (FULLVERSION, VERSION)) finally: a.close() if write_version: write_version_py() setup(name=DISTNAME, version=FULLVERSION, license=LICENSE, author=AUTHOR, author_email=AUTHOR_EMAIL, classifiers=CLASSIFIERS, description=DESCRIPTION, long_description=LONG_DESCRIPTION, install_requires=INSTALL_REQUIRES, tests_require=TESTS_REQUIRE, url=URL, packages=find_packages(), package_data={'xarray': ['tests/data/*', 'plot/default_colormap.csv']})
StarcoderdataPython
4826776
""" System tests. <NAME> <<EMAIL>> pytest tmpdir docs: http://doc.pytest.org/en/latest/tmpdir.html#the-tmpdir-fixture """ import copy import shutil import re from pathlib import Path import textwrap import click.testing from mailmerge.__main__ import main from . import utils def test_no_options(tmpdir): """Verify help message when called with no options. Run mailmerge at the CLI with no options. Do this in an empty temporary directory to ensure that mailmerge doesn't find any default input files. """ runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, []) assert result.exit_code == 1 assert 'Error: can\'t find template "mailmerge_template.txt"' in \ result.output assert "https://github.com/awdeorio/mailmerge" in result.output def test_sample(tmpdir): """Verify --sample creates sample input files.""" runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--sample"]) assert not result.exception assert result.exit_code == 0 assert Path(tmpdir/"mailmerge_template.txt").exists() assert Path(tmpdir/"mailmerge_database.csv").exists() assert Path(tmpdir/"mailmerge_server.conf").exists() assert "Created sample template" in result.output assert "Created sample database" in result.output assert "Created sample config" in result.output def test_sample_clobber_template(tmpdir): """Verify --sample won't clobber template if it already exists.""" runner = click.testing.CliRunner() with tmpdir.as_cwd(): Path("mailmerge_template.txt").touch() result = runner.invoke(main, ["--sample"]) assert result.exit_code == 1 assert "Error: file exists: mailmerge_template.txt" in result.output def test_sample_clobber_database(tmpdir): """Verify --sample won't clobber database if it already exists.""" runner = click.testing.CliRunner() with tmpdir.as_cwd(): Path("mailmerge_database.csv").touch() result = runner.invoke(main, ["--sample"]) assert result.exit_code == 1 assert "Error: file exists: mailmerge_database.csv" in result.output def test_sample_clobber_config(tmpdir): """Verify --sample won't clobber config if it already exists.""" runner = click.testing.CliRunner() with tmpdir.as_cwd(): Path("mailmerge_server.conf").touch() result = runner.invoke(main, ["--sample"]) assert result.exit_code == 1 assert "Error: file exists: mailmerge_server.conf" in result.output def test_defaults(tmpdir): """When no options are provided, use default input file names.""" runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--sample"]) assert not result.exception assert result.exit_code == 0 with tmpdir.as_cwd(): result = runner.invoke(main, []) assert not result.exception assert result.exit_code == 0 assert "message 1 sent" in result.output assert "Limit was 1 message" in result.output assert "This was a dry run" in result.output def test_bad_limit(tmpdir): """Verify --limit with bad value.""" # Simple template template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: {{email}} FROM: <EMAIL> Hello world """), encoding="utf8") # Simple database with two entries database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ email <EMAIL> <EMAIL> """), encoding="utf8") # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run mailmerge runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--dry-run", "--limit", "-1"]) assert result.exit_code == 2 assert "Error: Invalid value" in result.output def test_limit_combo(tmpdir): """Verify --limit 1 --no-limit results in no limit.""" # Simple template template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: {{email}} FROM: <EMAIL> Hello world """), encoding="utf8") # Simple database with two entries database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ email <EMAIL> <EMAIL> """), encoding="utf8") # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run mailmerge runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--no-limit", "--limit", "1"]) assert not result.exception assert result.exit_code == 0 assert "message 1 sent" in result.output assert "message 2 sent" in result.output assert "Limit was 1" not in result.output def test_template_not_found(tmpdir): """Verify error when template input file not found.""" runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--template", "notfound.txt"]) assert result.exit_code == 1 assert "Error: can't find template" in result.output def test_database_not_found(tmpdir): """Verify error when database input file not found.""" runner = click.testing.CliRunner() with tmpdir.as_cwd(): Path("mailmerge_template.txt").touch() result = runner.invoke(main, ["--database", "notfound.csv"]) assert result.exit_code == 1 assert "Error: can't find database" in result.output def test_config_not_found(tmpdir): """Verify error when config input file not found.""" runner = click.testing.CliRunner() with tmpdir.as_cwd(): Path("mailmerge_template.txt").touch() Path("mailmerge_database.csv").touch() result = runner.invoke(main, ["--config", "notfound.conf"]) assert result.exit_code == 1 assert "Error: can't find config" in result.output def test_help(): """Verify -h or --help produces a help message.""" runner = click.testing.CliRunner() result1 = runner.invoke(main, ["--help"]) assert result1.exit_code == 0 assert "Usage:" in result1.stdout assert "Options:" in result1.stdout result2 = runner.invoke(main, ["-h"]) # Short option is an alias assert result1.stdout == result2.stdout def test_version(): """Verify --version produces a version.""" runner = click.testing.CliRunner() result = runner.invoke(main, ["--version"]) assert not result.exception assert result.exit_code == 0 assert "version" in result.output def test_bad_template(tmpdir): """Template mismatch with database header should produce an error.""" # Template has a bad key template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: {{error_not_in_database}} SUBJECT: Testing mailmerge FROM: <EMAIL> Hello world """), encoding="utf8") # Normal database database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ email <EMAIL> """), encoding="utf8") # Normal, unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run mailmerge, which should exit 1 runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, []) assert result.exit_code == 1 # Verify output assert "template.txt: 'error_not_in_database' is undefined" in \ result.output def test_bad_database(tmpdir): """Database read error should produce a sane error.""" # Normal template template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: <EMAIL> FROM: <EMAIL> {{message}} """), encoding="utf8") # Database with unmatched quote database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ message "hello world """), encoding="utf8") # Normal, unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run mailmerge, which should exit 1 runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, []) assert result.exit_code == 1 # Verify output assert "database.csv:1: unexpected end of data" in result.output def test_bad_config(tmpdir): """Config containing an error should produce an error.""" # Normal template template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: <EMAIL> FROM: <EMAIL> """), encoding="utf8") # Normal database database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ dummy asdf """), encoding="utf8") # Server config is missing host config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] port = 25 """), encoding="utf8") # Run mailmerge, which should exit 1 runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, []) assert result.exit_code == 1 # Verify output assert "server.conf: No option 'host' in section: 'smtp_server'" in \ result.output def test_attachment(tmpdir): """Verify attachments feature output.""" # First attachment attachment1_path = Path(tmpdir/"attachment1.txt") attachment1_path.write_text("Hello world\n", encoding="utf8") # Second attachment attachment2_path = Path(tmpdir/"attachment2.txt") attachment2_path.write_text("Hello mailmerge\n", encoding="utf8") # Template with attachment header template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: {{email}} FROM: <EMAIL> ATTACHMENT: attachment1.txt ATTACHMENT: attachment2.txt Hello world """), encoding="utf8") # Simple database database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ email <EMAIL> """), encoding="utf8") # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run mailmerge runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--output-format", "text"]) assert not result.exception assert result.exit_code == 0 # Verify output assert ">>> message part: text/plain" in result.output assert "Hello world" in result.output # message assert ">>> message part: attachment attachment1.txt" in result.output assert ">>> message part: attachment attachment2.txt" in result.output def test_utf8_template(tmpdir): """Message is utf-8 encoded when only the template contains utf-8 chars.""" # Template with UTF-8 characters and emoji template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: {{email}} FROM: <EMAIL> Laȝamon 😀 klâwen """), encoding="utf8") # Simple database without utf-8 characters database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ email <EMAIL> """), encoding="utf8") # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run mailmerge runner = click.testing.CliRunner() result = runner.invoke(main, [ "--template", template_path, "--database", database_path, "--config", config_path, "--dry-run", "--output-format", "text", ]) assert not result.exception assert result.exit_code == 0 # Remove the Date string, which will be different each time stdout = copy.deepcopy(result.output) stdout = re.sub(r"Date:.+", "Date: REDACTED", stdout, re.MULTILINE) # Verify output assert stdout == textwrap.dedent("""\ >>> message 1 TO: <EMAIL> FROM: <EMAIL> MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 Date: REDACTED Laȝamon 😀 klâwen >>> message 1 sent >>> Limit was 1 message. To remove the limit, use the --no-limit option. >>> This was a dry run. To send messages, use the --no-dry-run option. """) # noqa: E501 def test_utf8_database(tmpdir): """Message is utf-8 encoded when only the databse contains utf-8 chars.""" # Simple template without UTF-8 characters template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: <EMAIL> FROM: <EMAIL> {{message}} """), encoding="utf8") # Database with utf-8 characters and emoji database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ message Laȝamon 😀 klâwen """), encoding="utf8") # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run mailmerge runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--output-format", "text"]) assert not result.exception assert result.exit_code == 0 # Remove the Date string, which will be different each time stdout = copy.deepcopy(result.output) stdout = re.sub(r"Date:.+", "Date: REDACTED", stdout, re.MULTILINE) # Verify output assert stdout == textwrap.dedent("""\ >>> message 1 TO: <EMAIL> FROM: <EMAIL> MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 Date: REDACTED Laȝamon 😀 klâwen >>> message 1 sent >>> Limit was 1 message. To remove the limit, use the --no-limit option. >>> This was a dry run. To send messages, use the --no-dry-run option. """) # noqa: E501 def test_utf8_headers(tmpdir): """Message is utf-8 encoded when headers contain utf-8 chars.""" # Template with UTF-8 characters and emoji in headers template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: Laȝamon <<EMAIL>> FROM: klâwen <<EMAIL>> SUBJECT: Laȝamon 😀 klâwen {{message}} """), encoding="utf8") # Simple database without utf-8 characters database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ message hello """), encoding="utf8") # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run mailmerge runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, [ "--template", template_path, "--database", database_path, "--config", config_path, "--dry-run", "--output-format", "raw", ]) assert not result.exception assert result.exit_code == 0 # Remove the Date string, which will be different each time stdout = copy.deepcopy(result.output) stdout = re.sub(r"Date:.+", "Date: REDACTED", stdout, re.MULTILINE) # Verify output assert stdout == textwrap.dedent("""\ >>> message 1 TO: =?utf-8?b?TGHInWFtb24gPHRvQHRlc3QuY29tPg==?= FROM: =?utf-8?b?a2zDondlbiA8ZnJvbUB0ZXN0LmNvbT4=?= SUBJECT: =?utf-8?b?TGHInWFtb24g8J+YgCBrbMOid2Vu?= MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 Date: REDACTED aGVsbG8= >>> message 1 sent >>> Limit was 1 message. To remove the limit, use the --no-limit option. >>> This was a dry run. To send messages, use the --no-dry-run option. """) # noqa: E501 def test_resume(tmpdir): """Verify --resume option starts "in the middle" of the database.""" # Simple template template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: <EMAIL> FROM: <EMAIL> {{message}} """), encoding="utf8") # Database with two entries database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ message hello world """), encoding="utf8") # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run mailmerge runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--resume", "2", "--no-limit"]) assert not result.exception assert result.exit_code == 0 # Verify only second message was sent assert "hello" not in result.output assert "message 1 sent" not in result.output assert "world" in result.output assert "message 2 sent" in result.output def test_resume_too_small(tmpdir): """Verify --resume <= 0 prints an error message.""" # Simple template template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: <EMAIL> FROM: <EMAIL> {{message}} """), encoding="utf8") # Database with two entries database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ message hello world """), encoding="utf8") # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run "mailmerge --resume 0" and check output runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--resume", "0"]) assert result.exit_code == 2 assert "Invalid value" in result.output # Run "mailmerge --resume -1" and check output with tmpdir.as_cwd(): result = runner.invoke(main, ["--resume", "-1"]) assert result.exit_code == 2 assert "Invalid value" in result.output def test_resume_too_big(tmpdir): """Verify --resume > database does nothing.""" # Simple template template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: <EMAIL> FROM: <EMAIL> {{message}} """), encoding="utf8") # Database with two entries database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ message hello world """), encoding="utf8") # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run and check output runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--resume", "3", "--no-limit"]) assert not result.exception assert result.exit_code == 0 assert "sent message" not in result.output def test_resume_hint_on_config_error(tmpdir): """Verify *no* --resume hint when error is after first message.""" # Simple template template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: <EMAIL> FROM: <EMAIL> {{message}} """), encoding="utf8") # Database with error on second entry database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ message hello "world """), encoding="utf8") # Server config missing port config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com """), encoding="utf8") # Run and check output runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, []) assert result.exit_code == 1 assert "--resume 1" not in result.output def test_resume_hint_on_csv_error(tmpdir): """Verify --resume hint after CSV error.""" # Simple template template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: <EMAIL> FROM: <EMAIL> {{message}} """), encoding="utf8") # Database with unmatched quote on second entry database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ message hello "world """), encoding="utf8") # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run and check output runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--resume", "2", "--no-limit"]) assert result.exit_code == 1 assert "--resume 2" in result.output def test_other_mime_type(tmpdir): """Verify output with a MIME type that's not text or an attachment.""" # Template containing a pdf template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: {{email}} FROM: <EMAIL> MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="boundary" --boundary Content-Type: text/plain; charset=us-ascii Hello world --boundary Content-Type: application/pdf DUMMY """), encoding="utf8") # Simple database with two entries database_path = Path(tmpdir/"mailmerge_database.csv") database_path.write_text(textwrap.dedent("""\ email <EMAIL> """), encoding="utf8") # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run mailmerge runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, []) assert not result.exception assert result.exit_code == 0 # Verify output stdout = copy.deepcopy(result.output) stdout = re.sub(r"Date:.+", "Date: REDACTED", stdout, re.MULTILINE) assert stdout == textwrap.dedent("""\ \x1b[7m\x1b[1m\x1b[36m>>> message 1\x1b(B\x1b[m TO: <EMAIL> FROM: <EMAIL> MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="boundary" Date: REDACTED \x1b[36m>>> message part: text/plain\x1b(B\x1b[m Hello world \x1b[36m>>> message part: application/pdf\x1b(B\x1b[m \x1b[7m\x1b[1m\x1b[36m>>> message 1 sent\x1b(B\x1b[m >>> Limit was 1 message. To remove the limit, use the --no-limit option. >>> This was a dry run. To send messages, use the --no-dry-run option. """) # noqa: E501 def test_database_bom(tmpdir): """Bug fix CSV with a byte order mark (BOM). It looks like Excel will sometimes save a file with Byte Order Mark (BOM). When the mailmerge database contains a BOM, it can't seem to find the first header key. https://github.com/awdeorio/mailmerge/issues/93 """ # Simple template template_path = Path(tmpdir/"mailmerge_template.txt") template_path.write_text(textwrap.dedent("""\ TO: {{email}} FROM: My Self <<EMAIL>> Hello {{name}} """), encoding="utf8") # Copy database containing a BOM database_path = Path(tmpdir/"mailmerge_database.csv") database_with_bom = utils.TESTDATA/"mailmerge_database_with_BOM.csv" shutil.copyfile(database_with_bom, database_path) # Simple unsecure server config config_path = Path(tmpdir/"mailmerge_server.conf") config_path.write_text(textwrap.dedent("""\ [smtp_server] host = open-smtp.example.com port = 25 """), encoding="utf8") # Run mailmerge runner = click.testing.CliRunner() with tmpdir.as_cwd(): result = runner.invoke(main, ["--output-format", "text"]) assert not result.exception assert result.exit_code == 0 # Verify output stdout = copy.deepcopy(result.output) stdout = re.sub(r"Date:.+", "Date: REDACTED", stdout, re.MULTILINE) assert stdout == textwrap.dedent("""\ >>> message 1 TO: <EMAIL> FROM: <NAME> <<EMAIL>> MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Date: REDACTED Hello <NAME> >>> message 1 sent >>> Limit was 1 message. To remove the limit, use the --no-limit option. >>> This was a dry run. To send messages, use the --no-dry-run option. """) # noqa: E501
StarcoderdataPython
145267
<gh_stars>0 # # Class for quick plotting of variables from models # import numpy as np import pybamm import warnings from collections import defaultdict def ax_min(data): "Calculate appropriate minimum axis value for plotting" data_min = np.nanmin(data) if data_min <= 0: return 1.04 * data_min else: return 0.96 * data_min def ax_max(data): "Calculate appropriate maximum axis value for plotting" data_max = np.nanmax(data) if data_max <= 0: return 0.96 * data_max else: return 1.04 * data_max def split_long_string(title, max_words=4): "Get title in a nice format" words = title.split() # Don't split if fits on one line, don't split just for units if len(words) <= max_words or words[max_words].startswith("["): return title else: first_line = (" ").join(words[:max_words]) second_line = (" ").join(words[max_words:]) return first_line + "\n" + second_line class QuickPlot(object): """ Generates a quick plot of a subset of key outputs of the model so that the model outputs can be easily assessed. The axis limits can be set using: self.axis["Variable name"] = [x_min, x_max, y_min, y_max] They can be reset to the default values by using self.reset_axis. Parameters ---------- models: (iter of) :class:`pybamm.BaseModel` The model(s) to plot the outputs of. meshes: (iter of) :class:`pybamm.Mesh` The mesh(es) on which the model(s) were solved. solutions: (iter of) :class:`pybamm.Solver` The numerical solution(s) for the model(s) which contained the solution to the model(s). output_variables : list of str, optional List of variables to plot labels : list of str, optional Labels for the different models. Defaults to model names colors : list of str, optional The colors to loop over when plotting. Defaults to ["r", "b", "k", "g", "m", "c"] linestyles : list of str, optional The linestyles to loop over when plotting. Defaults to ["-", ":", "--", "-."] """ def __init__( self, solutions, output_variables=None, labels=None, colors=None, linestyles=None, ): if isinstance(solutions, pybamm.Solution): solutions = [solutions] elif not isinstance(solutions, list): raise TypeError("'solutions' must be 'pybamm.Solution' or list") models = [solution.model for solution in solutions] # Set labels self.labels = labels or [model.name for model in models] # Set colors and linestyles self.colors = colors self.linestyles = linestyles # Time scale in hours self.time_scale = models[0].timescale_eval / 3600 # Spatial scales (default to 1 if information not in model) variables = models[0].variables self.spatial_scales = {"x": 1, "y": 1, "z": 1, "r_n": 1, "r_p": 1} if "x [m]" and "x" in variables: self.spatial_scales["x"] = (variables["x [m]"] / variables["x"]).evaluate()[ -1 ] if "y [m]" and "y" in variables: self.spatial_scales["y"] = (variables["y [m]"] / variables["y"]).evaluate()[ -1 ] if "z [m]" and "z" in variables: self.spatial_scales["z"] = (variables["z [m]"] / variables["z"]).evaluate()[ -1 ] if "r_n [m]" and "r_n" in variables: self.spatial_scales["r_n"] = ( variables["r_n [m]"] / variables["r_n"] ).evaluate()[-1] if "r_p [m]" and "r_p" in variables: self.spatial_scales["r_p"] = ( variables["r_p [m]"] / variables["r_p"] ).evaluate()[-1] # Time parameters self.ts = [solution.t for solution in solutions] self.min_t = np.min([t[0] for t in self.ts]) * self.time_scale self.max_t = np.max([t[-1] for t in self.ts]) * self.time_scale # Default output variables for lead-acid and lithium-ion if output_variables is None: if isinstance(models[0], pybamm.lithium_ion.BaseModel): output_variables = [ "Negative particle surface concentration", "Electrolyte concentration", "Positive particle surface concentration", "Current [A]", "Negative electrode potential [V]", "Electrolyte potential [V]", "Positive electrode potential [V]", "Terminal voltage [V]", ] elif isinstance(models[0], pybamm.lead_acid.BaseModel): output_variables = [ "Interfacial current density [A.m-2]", "Electrolyte concentration [mol.m-3]", "Current [A]", "Porosity", "Electrolyte potential [V]", "Terminal voltage [V]", ] # else plot all variables in first model else: output_variables = models[0].variables self.set_output_variables(output_variables, solutions) self.reset_axis() def set_output_variables(self, output_variables, solutions): # Set up output variables self.variables = {} self.spatial_variable = {} # Calculate subplot positions based on number of variables supplied self.subplot_positions = {} self.n_rows = int(len(output_variables) // np.sqrt(len(output_variables))) self.n_cols = int(np.ceil(len(output_variables) / self.n_rows)) # Process output variables into a form that can be plotted processed_variables = {} for solution in solutions: processed_variables[solution] = {} for variable_list in output_variables: # Make sure we always have a list of lists of variables if isinstance(variable_list, str): variable_list = [variable_list] # Add all variables to the list of variables that should be processed processed_variables[solution].update( {var: solution[var] for var in variable_list} ) # Prepare dictionary of variables for k, variable_list in enumerate(output_variables): # Make sure we always have a list of lists of variables if isinstance(variable_list, str): variable_list = [variable_list] # Prepare list of variables key = tuple(variable_list) self.variables[key] = [None] * len(solutions) # process each variable in variable_list for each model for i, solution in enumerate(solutions): # self.variables is a dictionary of lists of lists self.variables[key][i] = [ processed_variables[solution][var] for var in variable_list ] # Make sure variables have the same dimensions and domain first_variable = self.variables[key][0][0] domain = first_variable.domain for variable in self.variables[key][0]: if variable.domain != domain: raise ValueError("mismatching variable domains") # Set the x variable for any two-dimensional variables if first_variable.dimensions == 2: spatial_variable_key = first_variable.spatial_var_name spatial_variable_value = first_variable.mesh[0].edges self.spatial_variable[key] = ( spatial_variable_key, spatial_variable_value, ) # Don't allow 3D variables elif any(var.dimensions == 3 for var in self.variables[key][0]): raise NotImplementedError("cannot plot 3D variables") # Define subplot position self.subplot_positions[key] = (self.n_rows, self.n_cols, k + 1) def reset_axis(self): """ Reset the axis limits to the default values. These are calculated to fit around the minimum and maximum values of all the variables in each subplot """ self.axis = {} for key, variable_lists in self.variables.items(): if variable_lists[0][0].dimensions == 1: spatial_var_name, spatial_var_value = "x", None x_min = self.min_t x_max = self.max_t elif variable_lists[0][0].dimensions == 2: spatial_var_name, spatial_var_value = self.spatial_variable[key] if spatial_var_name == "r": if "negative" in key[0].lower(): spatial_var_scaled = ( spatial_var_value * self.spatial_scales["r_n"] ) elif "positive" in key[0].lower(): spatial_var_scaled = ( spatial_var_value * self.spatial_scales["r_p"] ) else: spatial_var_scaled = ( spatial_var_value * self.spatial_scales[spatial_var_name] ) x_min = spatial_var_scaled[0] x_max = spatial_var_scaled[-1] # Get min and max y values y_min = np.min( [ ax_min( var( self.ts[i], **{spatial_var_name: spatial_var_value}, warn=False ) ) for i, variable_list in enumerate(variable_lists) for var in variable_list ] ) y_max = np.max( [ ax_max( var( self.ts[i], **{spatial_var_name: spatial_var_value}, warn=False ) ) for i, variable_list in enumerate(variable_lists) for var in variable_list ] ) if y_min == y_max: y_min -= 1 y_max += 1 self.axis[key] = [x_min, x_max, y_min, y_max] def plot(self, t): """Produces a quick plot with the internal states at time t. Parameters ---------- t : float Dimensional time (in hours) at which to plot. """ import matplotlib.pyplot as plt t /= self.time_scale self.fig, self.ax = plt.subplots(self.n_rows, self.n_cols, figsize=(15, 8)) plt.tight_layout() plt.subplots_adjust(left=-0.1) self.plots = {} self.time_lines = {} colors = self.colors or ["r", "b", "k", "g", "m", "c"] linestyles = self.linestyles or ["-", ":", "--", "-."] fontsize = 42 // self.n_cols for k, (key, variable_lists) in enumerate(self.variables.items()): if len(self.variables) == 1: ax = self.ax else: ax = self.ax.flat[k] ax.set_xlim(self.axis[key][:2]) ax.set_ylim(self.axis[key][2:]) ax.xaxis.set_major_locator(plt.MaxNLocator(3)) self.plots[key] = defaultdict(dict) # Set labels for the first subplot only (avoid repetition) if variable_lists[0][0].dimensions == 2: # 2D plot: plot as a function of x at time t spatial_var_name, spatial_var_value = self.spatial_variable[key] ax.set_xlabel(spatial_var_name + " [m]", fontsize=fontsize) for i, variable_list in enumerate(variable_lists): for j, variable in enumerate(variable_list): if spatial_var_name == "r": if "negative" in key[0].lower(): spatial_scale = self.spatial_scales["r_n"] elif "positive" in key[0].lower(): spatial_scale = self.spatial_scales["r_p"] else: spatial_scale = self.spatial_scales[spatial_var_name] (self.plots[key][i][j],) = ax.plot( spatial_var_value * spatial_scale, variable( t, **{spatial_var_name: spatial_var_value}, warn=False ), lw=2, color=colors[i], linestyle=linestyles[j], ) else: # 1D plot: plot as a function of time, indicating time t with a line ax.set_xlabel("Time [h]", fontsize=fontsize) for i, variable_list in enumerate(variable_lists): for j, variable in enumerate(variable_list): full_t = self.ts[i] (self.plots[key][i][j],) = ax.plot( full_t * self.time_scale, variable(full_t, warn=False), lw=2, color=colors[i], linestyle=linestyles[j], ) y_min, y_max = self.axis[key][2:] (self.time_lines[key],) = ax.plot( [t * self.time_scale, t * self.time_scale], [y_min, y_max], "k--" ) # Set either y label or legend entries if len(key) == 1: title = split_long_string(key[0]) ax.set_title(title, fontsize=fontsize) else: ax.legend( [split_long_string(s, 6) for s in key], bbox_to_anchor=(0.5, 1), fontsize=8, loc="lower center", ) if k == len(self.variables) - 1: ax.legend(self.labels, loc="upper right", bbox_to_anchor=(1, -0.2)) def dynamic_plot(self, testing=False): """ Generate a dynamic plot with a slider to control the time. We recommend using ipywidgets instead of this function if you are using jupyter notebooks """ import matplotlib.pyplot as plt from matplotlib.widgets import Slider # create an initial plot at time 0 self.plot(0) axcolor = "lightgoldenrodyellow" axfreq = plt.axes([0.315, 0.02, 0.37, 0.03], facecolor=axcolor) self.sfreq = Slider(axfreq, "Time", 0, self.max_t, valinit=0) self.sfreq.on_changed(self.update) # ignore the warning about tight layout warnings.simplefilter("ignore") self.fig.tight_layout() warnings.simplefilter("always") if not testing: # pragma: no cover plt.show() def update(self, val): """ Update the plot in self.plot() with values at new time """ t = self.sfreq.val t_dimensionless = t / self.time_scale for key, plot in self.plots.items(): if self.variables[key][0][0].dimensions == 2: spatial_var_name, spatial_var_value = self.spatial_variable[key] for i, variable_lists in enumerate(self.variables[key]): for j, variable in enumerate(variable_lists): plot[i][j].set_ydata( variable( t_dimensionless, **{spatial_var_name: spatial_var_value}, warn=False ) ) else: self.time_lines[key].set_xdata([t]) self.fig.canvas.draw_idle()
StarcoderdataPython
1761015
__source__ = 'https://leetcode.com/problems/hand-of-straights/' # Time: O(N * (N/W)) # Space: O(N) # # Description: Leetcode # 846. Hand of Straights # # Alice has a hand of cards, given as an array of integers. # # Now she wants to rearrange the cards into groups so that each group is size W, # and consists of W consecutive cards. # # Return true if and only if she can. # # Example 1: # # Input: hand = [1,2,3,6,2,3,4,7,8], W = 3 # Output: true # Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]. # Example 2: # # Input: hand = [1,2,3,4,5], W = 4 # Output: false # Explanation: Alice's hand can't be rearranged into groups of 4. # # # Note: # # 1 <= hand.length <= 10000 # 0 <= hand[i] <= 10^9 # 1 <= W <= hand.length # import unittest import collections # 784ms 15.47% class Solution(object): def isNStraightHand(self, hand, W): """ :type hand: List[int] :type W: int :rtype: bool """ count = collections.Counter(hand) while count: m = min(count) for k in xrange(m, m+W): v = count[k] if not v: return False if v == 1: del count[k] else: count[k] = v - 1 return True class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java = ''' # Thought: https://leetcode.com/problems/hand-of-straights/solution/ Approach #1: Brute Force [Accepted] Complexity Analysis Time Complexity: O(N * (N/W)), where N is the length of hand. The (N / W) factor comes from min(count). In Java, the (N / W) factor becomes logN due to the complexity of TreeMap. Space Complexity: O(N) # 61ms 52.04% class Solution { public boolean isNStraightHand(int[] hand, int W) { TreeMap<Integer, Integer> count = new TreeMap(); for (int card : hand) { if (!count.containsKey(card)) { count.put(card, 1); } else { count.replace(card, count.get(card) + 1); } } while (count.size() > 0) { int first = count.firstKey(); for (int card = first; card < first + W; ++card) { if (!count.containsKey(card)) return false; int c = count.get(card); if (c == 1) count.remove(card); else count.replace(card, c - 1); } } return true; } } # 6ms 97.71% class Solution { public boolean isNStraightHand(int[] hand, int W) { int n = hand.length; if (n < W || n % W != 0) return false; int[] arr = new int[W]; for (int i = 0; i < n; i++) { arr[hand[i] % W]++; } for (int i = 0; i < W - 1; i++) { if (arr[i] != arr[i + 1]) return false; } return true; } } '''
StarcoderdataPython
54516
<reponame>hnarasimhan/constrained-classification import numpy as np from time import time from sklearn.preprocessing import MinMaxScaler from sklearn.linear_model import LogisticRegressionCV from models.constrained import COCOClassifier, FRACOClassifier from models.unconstrained import FrankWolfeClassifier, BisectionClassifier """ This module contains functions for running experiments with constrained and unconstrained classification, over multiple train-test splits """ # Define constants for COCO and FRACO ALGO_COCO = 0 ALGO_FRACO = 1 def run_expt(loss_name, cons_name, data_name, expt_param, solver_param, eps=1): """ Runs an experiment optimizing given loss function s.t. constraint over multiple random train-test splits, and returns the average loss, constraint function, and runtime values across trials This function supports optimizing the following loss functions without constraints: 0-1 classification error (loss_name = 'err', cons_name = None) H-mean (loss_name = 'hmean', cons_name = None) Q-mean (loss_name = 'qmean', cons_name = None) F-measure (loss_name = 'fmeasure', cons_name = None) Micro F1 (loss_name = 'microF1', cons_name = None) This function supports the following binary constrained learning problems: 0-1 classification error s.t. Demographic Parity constraint (loss_name = 'err', cons_name = 'dp') H-mean s.t. Coverage constraint (loss_name = 'hmean', cons_name = 'cov') Q-mean s.t. Demographic Parity constraint (loss_name = 'qmean', cons_name = 'dp') F-measure s.t. KLD constraint (loss_name = 'fmeasure', cons_name = 'kld') and the following multiclass constrained learning problems: Q-mean s.t. NAE constraint (loss_name = 'qmean', cons_name = 'nae') micro F1 s.t. Coverage constraint (loss_name = 'microF1', cons_name = 'cov') Args: loss_name (string): Name of loss function ('er', 'hmean', 'qmean', 'fmeasure', 'microF1') cons_name (string): Name of constraint function ('cov', 'dp', 'kld', 'nae' or None if unconstrained) data_name (string): Name of data set expt_param (dict): Dictionary of parameters for the experiment: 'training_frac' (float): Fraction of data set for training 'num_trials' (int): Number of trials with random train-test splits 'verbosity' (bool): Should the output be printed? solver_param (dict): Dictionary of parameters for the experiment: 'eta_list' (list): List of step-sizes eta to consider 'num_outer_iter': Number of outer gradient ascent iterations in COCO 'num_inner_iter': Number of inner Frank-Wolfe iterations in COCO eps (float): Constraint limit (g(h) <= eps) (default = 1) Returns: avg_loss (float): Average loss value of learned classifier across different trials avg_cons (float): Average constraint value of learned classifier across different trials avg_runtime (float): Average runtime of the algorithm across different trials """ if (loss_name == 'fmeasure') or (loss_name == 'microF1'): solver_param['algo'] = ALGO_FRACO if expt_param['verbosity']: print('Running FRACO for optimizing ' + loss_name + (' s.t. ' + cons_name + ' constraint' if cons_name != '' else '') + ' on ' + data_name + ' dataset\n') else: solver_param['algo'] = ALGO_COCO if expt_param['verbosity']: print('Running COCO for optimizing ' + loss_name + (' s.t. ' + cons_name + ' constraint ' if cons_name != '' else '') + ' on ' + data_name + ' dataset\n') # Load data set data = np.loadtxt('data/' + data_name + '.data', delimiter=',') # Run either constrained or unconstrained solver if cons_name != '': return run_expt_con(data, loss_name, cons_name, eps, expt_param, solver_param) else: return run_expt_unc(data, loss_name, expt_param, solver_param) def run_expt_con(data, loss_name, cons_name, eps, expt_param, solver_param): """ Runs experiment for constrained learning Args: data (array-like, shape=(m,d+1)): Data set with first column containing labels, followed by features (in case of a protected attribute, it must be placed as the first feature) loss_name (string): Name of loss function ('er', 'hmean', 'qmean', 'fmeasure', 'microF1') cons_name (string): Name of constraint function ('cov', 'dp', 'kld', 'nae' or None if unconstrained) eps (float): Constraint limit (g(h) <= eps) expt_param (dict): Dictionary of parameters for the experiment (see docstring for run_expt()) solver_param (dict): Dictionary of parameters for the experiment (see docstring for run_expt()) Returns: avg_loss (float): Average loss value of learned classifier across different trials avg_cons (float): Average constraint value of learned classifier across different trials avg_runtime (float): Average runtime of the algorithm across different trials """ np.random.seed(1) # Set random seed training_frac = expt_param['training_frac'] num_trials = expt_param['num_trials'] is_protected = expt_param['is_protected'] verbosity = expt_param['verbosity'] eta_list = solver_param['eta_list'] algo = solver_param['algo'] num_outer_iter = solver_param['num_outer_iter'] max_inner_ter = solver_param['num_inner_iter'] num_class = len(np.unique(data[:, 0])) num_eta = len(eta_list) # Calculate number of training points n = data.shape[0] n_tr = int(np.round(n * training_frac)) if verbosity: print('\n' + 'eps = ' + str(eps) + '\n') avg_loss = 0 avg_cons = 0 avg_runtime = 0 # Run for specified number of trials for ii in range(num_trials): # Permute data, and split into train and test sets perm = np.random.permutation(n) if verbosity: print('Trial ' + str(ii+1)) y = data[perm[0:n_tr], 0] x = data[perm[0:n_tr], 1:] if is_protected: z = data[perm[0:n_tr], 1] else: z = None y_ts = data[perm[n_tr:], 0] x_ts = data[perm[n_tr:], 1:] if is_protected: z_ts = data[perm[n_tr:], 1] else: z_ts = None # Scale train set and apply same transformation to test set scaler = MinMaxScaler(copy=False) scaler.fit_transform(x) scaler.transform(x_ts) # Train base class probability estimation model cpe_model = LogisticRegressionCV(solver='liblinear') cpe_model.fit(x, y) eta_classifier = [None] * num_eta eta_loss = [0] * num_eta eta_cons = [0] * num_eta eta_run_time = [0] * num_eta # Try different values of eta, and record the loss, constraint values and the classifier for kk in range(num_eta): # Choose between COCO and FRACO models if algo == ALGO_COCO: eta_classifier[kk] = COCOClassifier(loss_name, cons_name, is_protected, num_class) elif algo == ALGO_FRACO: eta_classifier[kk] = FRACOClassifier(loss_name, cons_name, is_protected, num_class) # Fit classifier using given eta value, keep track of the run time start_time = time() eta_classifier[kk].fit(x, y, eps, eta_list[kk], num_outer_iter, max_inner_ter, cpe_model, z) eta_run_time[kk] = time() - start_time eta_loss[kk] = eta_classifier[kk].evaluate_loss(x, y, z) eta_cons[kk] = eta_classifier[kk].evaluate_cons(x, y, z) if verbosity: print('eta = ' + str(eta_list[kk]) + ' : ' + str(eta_loss[kk]) + ' / ' + str(eta_cons[kk]) + ' (' + str(eta_run_time[kk]) + 's)') # Choose the best eta based stats recorded best_eta_ind = choose_best_eta(eta_loss, eta_cons, eps) best_classifier = eta_classifier[best_eta_ind] # Evaluate the classifier at the best eta best_loss = best_classifier.evaluate_loss(x_ts, y_ts, z_ts) best_cons = best_classifier.evaluate_cons(x_ts, y_ts, z_ts) if verbosity: print('best eta = ' + str(eta_list[best_eta_ind]) + ' : ' + str(best_loss) + ' / ' + str(best_cons) + '\n') avg_loss += best_loss * 1.0 / num_trials avg_cons += best_cons * 1.0 / num_trials avg_runtime += eta_run_time[best_eta_ind] * 1.0 / num_trials if verbosity: print('eps = ' + str(eps) + ' : ' + str(avg_loss) + ' / ' + str(avg_cons) + ' (' + str(avg_runtime) + 's)') return avg_loss, avg_cons, avg_runtime def run_expt_unc(data, loss_name, expt_param, solver_param): """ Runs experiment for unconstrained learning Args: data (array-like, shape=(m,d+1)): Data set with first column containing labels, followed by features (in case of a protected attribute, it must be placed as the first feature) loss_name (string): Name of loss function ('er', 'hmean', 'qmean', 'fmeasure', 'microF1') expt_param (dict): Dictionary of parameters for the experiment (see docstring for run_expt()) solver_param (dict): Dictionary of parameters for the experiment: 'num_inner_iter' (int): Number of iterations in Frank-Wolfe, specify None for Bisection algorithm Returns: avg_loss (float): Average loss value of learned classifier across different trials avg_runtime (float): Average runtime of the algorithm across different trials """ np.random.seed(1) # Set random seed training_frac = expt_param['training_frac'] num_trials = expt_param['num_trials'] is_protected = expt_param['is_protected'] verbosity = expt_param['verbosity'] algo = solver_param['algo'] num_iter = solver_param['num_inner_iter'] num_class = len(np.unique(data[:, 0])) # Calculate number of training points n = data.shape[0] n_tr = int(np.round(n * training_frac)) avg_loss = 0.0 avg_runtime = 0.0 # Run for specified number of trials for ii in range(num_trials): perm = np.random.permutation(n) y = data[perm[0:n_tr], 0] x = data[perm[0:n_tr], 1:] if is_protected: z = data[perm[0:n_tr], 1] else: z = None y_ts = data[perm[n_tr:], 0] x_ts = data[perm[n_tr:], 1:] if is_protected: z_ts = data[perm[n_tr:], 1] else: z_ts = None # Scale train set and apply same transformation to test set scaler = MinMaxScaler(copy=False) scaler.fit_transform(x) scaler.transform(x_ts) # Train a base class-probability estimation model cpe_model = LogisticRegressionCV(solver='liblinear') cpe_model.fit(x, y) # Fit classifier using either Frank-Wolfe or Bisection algorithm, keep track of run-time if algo == ALGO_COCO: classifier = FrankWolfeClassifier(loss_name, protected_present=is_protected, num_class=num_class) else: classifier = BisectionClassifier(loss_name, protected_present=is_protected, num_class=num_class) start_time = time() classifier.fit(x, y, num_iter, cpe_model, z) run_time = time() - start_time # loss = classifier.evaluate_loss(x_ts, y_ts, z_ts) if verbosity: print('Trial' + str(ii+1) + ' : ' + str(loss)) avg_loss += loss * 1.0 / num_trials avg_runtime += run_time * 1.0 / num_trials if verbosity: print('unconstrained: ' + str(avg_loss) + ' (' + str(avg_runtime) + 's)') return avg_loss, avg_runtime def choose_best_eta(loss_list, cons_list, eps): """ Heuristic to choose index of the best eta param given their loss, constraint values and eps: If there is an eta for which constraint value <= 1.05 * eps Among all such eta, choose the one with minimum loss Else: Choose eta that minimizes |constraint value - eps| Args: loss_list (list, dtype = float): List of loss function values for different eta values cons_list (list, dtype = float): List of corresponding constraint function values eps (float): Constraint limit (g(h) <= eps) Returns: eta_ind (int): Index of chosen value of eta """ valid_loss = [loss_list[ind] for ind in range(len(loss_list))\ if cons_list[ind] <= 1.05*eps] if len(valid_loss) > 0: return loss_list.index(min(valid_loss)) return np.argmin([abs(x - eps) for x in cons_list])
StarcoderdataPython
3299639
import copy import os from typing import Optional, Text, List, Dict, Union, Tuple, Any, TYPE_CHECKING from rasa.shared.exceptions import FileNotFoundException import rasa.shared.utils.io import rasa.shared.utils.cli from rasa.core.constants import ( DEFAULT_NLU_FALLBACK_THRESHOLD, DEFAULT_CORE_FALLBACK_THRESHOLD, DEFAULT_NLU_FALLBACK_AMBIGUITY_THRESHOLD, ) from rasa.shared.core.constants import ( ACTION_DEFAULT_FALLBACK_NAME, ACTION_TWO_STAGE_FALLBACK_NAME, ) import rasa.utils.io from rasa.shared.constants import ( DEFAULT_NLU_FALLBACK_INTENT_NAME, LATEST_TRAINING_DATA_FORMAT_VERSION, ) from rasa.shared.core.training_data.story_reader.yaml_story_reader import ( YAMLStoryReader, ) import rasa.shared.utils.io import rasa.utils.io from rasa.core.policies.mapping_policy import MappingPolicy from rasa.core.policies.rule_policy import RulePolicy from rasa.core.policies.fallback import FallbackPolicy from rasa.core.policies.two_stage_fallback import TwoStageFallbackPolicy from rasa.nlu.classifiers.fallback_classifier import FallbackClassifier if TYPE_CHECKING: from rasa.core.policies.policy import Policy from rasa.shared.core.domain import Domain from rasa.shared.core.training_data.structures import StoryStep def load(config_file: Optional[Union[Text, Dict]]) -> List["Policy"]: """Load policy data stored in the specified file.""" from rasa.core.policies.ensemble import PolicyEnsemble if not config_file: raise FileNotFoundException( f"The provided configuration file path does not seem to be valid. " f"The file '{os.path.abspath(config_file)}' could not be found." ) config_data = {} if isinstance(config_file, str) and os.path.isfile(config_file): config_data = rasa.shared.utils.io.read_model_configuration(config_file) elif isinstance(config_file, Dict): config_data = config_file return PolicyEnsemble.from_dict(config_data) def migrate_fallback_policies(config: Dict) -> Tuple[Dict, Optional["StoryStep"]]: """Migrate the deprecated fallback policies to their `RulePolicy` counterpart. Args: config: The model configuration containing deprecated policies. Returns: The updated configuration and the required fallback rules. """ new_config = copy.deepcopy(config) policies = new_config.get("policies", []) fallback_config = _get_config_for_name( FallbackPolicy.__name__, policies ) or _get_config_for_name(TwoStageFallbackPolicy.__name__, policies) if not fallback_config: return config, None rasa.shared.utils.cli.print_info(f"Migrating the '{fallback_config.get('name')}'.") _update_rule_policy_config_for_fallback(policies, fallback_config) _update_fallback_config(new_config, fallback_config) new_config["policies"] = _drop_policy(fallback_config.get("name"), policies) # The triggered action is hardcoded for the Two-Stage Fallback` fallback_action_name = ACTION_TWO_STAGE_FALLBACK_NAME if fallback_config.get("name") == FallbackPolicy.__name__: fallback_action_name = fallback_config.get( "fallback_action_name", ACTION_DEFAULT_FALLBACK_NAME ) fallback_rule = _get_faq_rule( f"Rule to handle messages with low NLU confidence " f"(automated conversion from '{fallback_config.get('name')}')", DEFAULT_NLU_FALLBACK_INTENT_NAME, fallback_action_name, ) return new_config, fallback_rule def _get_config_for_name(component_name: Text, config_part: List[Dict]) -> Dict: return next( (config for config in config_part if config.get("name") == component_name), {} ) def _update_rule_policy_config_for_fallback( policies: List[Dict], fallback_config: Dict ) -> None: """Update the `RulePolicy` configuration with the parameters for the fallback. Args: policies: The current list of configured policies. fallback_config: The configuration of the deprecated fallback configuration. """ rule_policy_config = _get_config_for_name(RulePolicy.__name__, policies) if not rule_policy_config: rule_policy_config = {"name": RulePolicy.__name__} policies.append(rule_policy_config) core_threshold = fallback_config.get( "core_threshold", DEFAULT_CORE_FALLBACK_THRESHOLD ) fallback_action_name = fallback_config.get( "fallback_core_action_name" ) or fallback_config.get("fallback_action_name", ACTION_DEFAULT_FALLBACK_NAME) rule_policy_config.setdefault("core_fallback_threshold", core_threshold) rule_policy_config.setdefault("core_fallback_action_name", fallback_action_name) def _update_fallback_config(config: Dict, fallback_config: Dict) -> None: fallback_classifier_config = _get_config_for_name( FallbackClassifier.__name__, config.get("pipeline", []) ) if not fallback_classifier_config: fallback_classifier_config = {"name": FallbackClassifier.__name__} config["pipeline"].append(fallback_classifier_config) nlu_threshold = fallback_config.get("nlu_threshold", DEFAULT_NLU_FALLBACK_THRESHOLD) ambiguity_threshold = fallback_config.get( "ambiguity_threshold", DEFAULT_NLU_FALLBACK_AMBIGUITY_THRESHOLD ) fallback_classifier_config.setdefault("threshold", nlu_threshold) fallback_classifier_config.setdefault("ambiguity_threshold", ambiguity_threshold) def _get_faq_rule(rule_name: Text, intent: Text, action_name: Text) -> "StoryStep": faq_rule = f""" version: "{LATEST_TRAINING_DATA_FORMAT_VERSION}" rules: - rule: {rule_name} steps: - intent: {intent} - action: {action_name} """ story_reader = YAMLStoryReader() return story_reader.read_from_string(faq_rule)[0] def _drop_policy(policy_to_drop: Text, policies: List[Dict]) -> List[Dict]: return [policy for policy in policies if policy.get("name") != policy_to_drop] def migrate_mapping_policy_to_rules( config: Dict[Text, Any], domain: "Domain" ) -> Tuple[Dict[Text, Any], "Domain", List["StoryStep"]]: """Migrate `MappingPolicy` to its `RulePolicy` counterparts. This migration will update the config, domain and generate the required rules. Args: config: The model configuration containing deprecated policies. domain: The domain which potentially includes intents with the `triggers` property. Returns: The updated model configuration, the domain without trigger intents, and the generated rules. """ policies = config.get("policies", []) has_mapping_policy = False has_rule_policy = False for policy in policies: if policy.get("name") == MappingPolicy.__name__: has_mapping_policy = True if policy.get("name") == RulePolicy.__name__: has_rule_policy = True if not has_mapping_policy: return config, domain, [] rasa.shared.utils.cli.print_info(f"Migrating the '{MappingPolicy.__name__}'.") new_config = copy.deepcopy(config) new_domain = copy.deepcopy(domain) new_rules = [] for intent, properties in new_domain.intent_properties.items(): # remove triggers from intents, if any triggered_action = properties.pop("triggers", None) if triggered_action: trigger_rule = _get_faq_rule( f"Rule to map `{intent}` intent to " f"`{triggered_action}` (automatic conversion)", intent, triggered_action, ) new_rules.append(trigger_rule) # finally update the policies policies = _drop_policy(MappingPolicy.__name__, policies) if new_rules and not has_rule_policy: policies.append({"name": RulePolicy.__name__}) new_config["policies"] = policies return new_config, new_domain, new_rules
StarcoderdataPython
1762723
<gh_stars>1-10 #!usr/bin/env python3 # # Copyright 2017 Petuum, 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 unittest from jsonapi_framework.response import Response class ResponseTestCase(unittest.TestCase): def test_init(self): resp = Response(body={}, status=400, headers=None) self.assertEqual( Response(body={}, status=400, headers=None).body, resp.body) self.assertEqual( Response(body={}, status=400, headers=None).status, resp.status) self.assertEqual( Response(body={}, status=400, headers=None).headers, resp.headers)
StarcoderdataPython
3302826
# Copyright 2016-2020 The <NAME> at the California Institute of # Technology (Caltech), with support from the Paul Allen Family Foundation, # Google, & National Institutes of Health (NIH) under Grant U24CA224309-01. # All rights reserved. # # Licensed under a modified 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.github.com/vanvalenlab/deepcell-tf/LICENSE # # The Work provided may be used for non-commercial academic purposes only. # For any other use of the Work, including commercial use, please contact: # <EMAIL> # # Neither the name of Caltech nor the names of its contributors may be used # to endorse or promote products derived from this software without specific # prior written permission. # # 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. # ============================================================================== """Tests for padding layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from absl.testing import parameterized from tensorflow.python import keras # from tensorflow.python.eager import context from tensorflow.python.keras import keras_parameterized from tensorflow.python.keras import testing_utils from tensorflow.python.platform import test from deepcell import layers def _get_random_padding(dim): R = lambda: np.random.randint(low=0, high=9) return tuple([(R(), R()) for _ in range(dim)]) @keras_parameterized.run_all_keras_modes class ReflectionPaddingTest(keras_parameterized.TestCase): def test_reflection_padding_2d(self): num_samples = 2 stack_size = 2 input_num_row = 4 input_num_col = 5 custom_objects = {'ReflectionPadding2D': layers.ReflectionPadding2D} ins1 = np.ones((num_samples, input_num_row, input_num_col, stack_size)) ins2 = np.ones((num_samples, stack_size, input_num_row, input_num_col)) data_formats = ['channels_first', 'channels_last'] with tf.keras.utils.custom_object_scope(custom_objects): for data_format, inputs in zip(data_formats, [ins2, ins1]): # basic test testing_utils.layer_test( layers.ReflectionPadding2D, kwargs={'padding': (2, 2), 'data_format': data_format}, input_shape=inputs.shape) testing_utils.layer_test( layers.ReflectionPadding2D, kwargs={'padding': ((1, 2), (3, 4)), 'data_format': data_format}, input_shape=inputs.shape) # correctness test # with self.cached_session(): # layer = layers.ReflectionPadding2D( # padding=(2, 2), data_format=data_format) # layer.build(inputs.shape) # output = layer(tf.keras.backend.variable(inputs)) # if context.executing_eagerly(): # np_output = output.numpy() # else: # np_output = tf.keras.backend.eval(output) # if data_format == 'channels_last': # for offset in [0, 1, -1, -2]: # np.testing.assert_allclose(np_output[:, offset, :, :], 0.) # np.testing.assert_allclose(np_output[:, :, offset, :], 0.) # np.testing.assert_allclose(np_output[:, 2:-2, 2:-2, :], 1.) # elif data_format == 'channels_first': # for offset in [0, 1, -1, -2]: # np.testing.assert_allclose(np_output[:, :, offset, :], 0.) # np.testing.assert_allclose(np_output[:, :, :, offset], 0.) # np.testing.assert_allclose(np_output[:, 2:-2, 2:-2, :], 1.) # layer = layers.ReflectionPadding2D( # padding=((1, 2), (3, 4)), data_format=data_format) # layer.build(inputs.shape) # output = layer(tf.keras.backend.variable(inputs)) # if context.executing_eagerly(): # np_output = output.numpy() # else: # np_output = tf.keras.backend.eval(output) # if data_format == 'channels_last': # for top_offset in [0]: # np.testing.assert_allclose(np_output[:, top_offset, :, :], 0.) # for bottom_offset in [-1, -2]: # np.testing.assert_allclose(np_output[:, bottom_offset, :, :], 0.) # for left_offset in [0, 1, 2]: # np.testing.assert_allclose(np_output[:, :, left_offset, :], 0.) # for right_offset in [-1, -2, -3, -4]: # np.testing.assert_allclose(np_output[:, :, right_offset, :], 0.) # np.testing.assert_allclose(np_output[:, 1:-2, 3:-4, :], 1.) # elif data_format == 'channels_first': # for top_offset in [0]: # np.testing.assert_allclose(np_output[:, :, top_offset, :], 0.) # for bottom_offset in [-1, -2]: # np.testing.assert_allclose(np_output[:, :, bottom_offset, :], 0.) # for left_offset in [0, 1, 2]: # np.testing.assert_allclose(np_output[:, :, :, left_offset], 0.) # for right_offset in [-1, -2, -3, -4]: # np.testing.assert_allclose(np_output[:, :, :, right_offset], 0.) # np.testing.assert_allclose(np_output[:, :, 1:-2, 3:-4], 1.) # test incorrect use with self.assertRaises(ValueError): layers.ReflectionPadding2D(padding=(1, 1, 1)) with self.assertRaises(ValueError): layers.ReflectionPadding2D(padding=None) def test_reflection_padding_3d(self): num_samples = 2 stack_size = 2 input_len_dim1 = 4 input_len_dim2 = 5 input_len_dim3 = 3 custom_objects = {'ReflectionPadding3D': layers.ReflectionPadding3D} inputs1 = np.ones((num_samples, input_len_dim1, input_len_dim2, input_len_dim3, stack_size)) inputs2 = np.ones((num_samples, stack_size, input_len_dim1, input_len_dim2, input_len_dim3)) data_formats = ['channels_first', 'channels_last'] with tf.keras.utils.custom_object_scope(custom_objects): for data_format, inputs in zip(data_formats, [inputs2, inputs1]): # basic test testing_utils.layer_test( layers.ReflectionPadding3D, kwargs={'padding': (2, 2, 2), 'data_format': data_format}, input_shape=inputs.shape) # correctness test # with self.cached_session(): # layer = layers.ReflectionPadding3D(padding=(2, 2, 2)) # layer.build(inputs.shape) # output = layer(tf.keras.backend.variable(inputs)) # if context.executing_eagerly(): # np_output = output.numpy() # else: # np_output = tf.keras.backend.eval(output) # for offset in [0, 1, -1, -2]: # np.testing.assert_allclose(np_output[:, offset, :, :, :], 0.) # np.testing.assert_allclose(np_output[:, :, offset, :, :], 0.) # np.testing.assert_allclose(np_output[:, :, :, offset, :], 0.) # np.testing.assert_allclose(np_output[:, 2:-2, 2:-2, 2:-2, :], 1.) # test incorrect use with self.assertRaises(ValueError): layers.ReflectionPadding3D(padding=(1, 1)) with self.assertRaises(ValueError): layers.ReflectionPadding3D(padding=None) if __name__ == '__main__': test.main()
StarcoderdataPython
3294920
from django.db import models from django.template.defaultfilters import slugify from django.conf import settings from datetime import datetime class Category(models.Model): id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100, unique=True, verbose_name='What is the category name ?') category_slug = models.SlugField(unique=True, max_length=150, blank=True) def __str__(self): return self.category_name def save(self, *args, **kwargs): self.category_slug = slugify(self.category_name) return super().save(*args, **kwargs) class Post(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100, unique=True, verbose_name='Title of the Post') body = models.TextField(verbose_name='Blog content') picture_location = models.ImageField(upload_to='images/', max_length=200) author = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) timestamp = models.DateTimeField(default=datetime.now()) category = models.ForeignKey(to=Category, on_delete=models.CASCADE) blog_slug = models.SlugField(blank=True, ) published = models.BooleanField(default=False) def __str__(self): return self.title def save(self, *args, **kwargs): self.blog_slug = slugify(self.title) return super().save(*args, **kwargs) class Comment(models.Model): name = models.CharField(max_length=50, verbose_name='Fullname') comment = models.TextField(verbose_name='Comment') timestamp = models.DateTimeField(default=datetime.now()) blog_post = models.ForeignKey(to=Post, on_delete=models.CASCADE) def __str__(self): return self.name
StarcoderdataPython
3213276
class BoolNode: def __init__(self,token): self.token = token self.position = token.position def __repr__(self): return f'{self.token}' class NumberNode: def __init__(self,token): self.token = token self.position = token.position def __repr__(self): return f'{self.token}' class StringNode: def __init__(self,token): self.token = token self.position = token.position def __repr__(self): return f'{self.token}' class ListNode: def __init__(self,elementNodes, position): self.elementNodes = elementNodes self.position = position class BinaryOperationNode: def __init__(self,leftNode,operationToken,rightNode): self.leftNode = leftNode self.operationToken = operationToken self.rightNode = rightNode self.position = leftNode.position def __repr__(self): return f'({self.leftNode},{self.operationToken},{self.rightNode})' class UnaryOperationNode: def __init__(self,operationToken,rightNode): self.operationToken = operationToken self.rightNode = rightNode self.position = operationToken.position def __repr__(self): return f'({self.operationToken},{self.rightNode})' class VarAccessNode: def __init__(self,varToken): self.varToken = varToken self.position = varToken.position class VarAssignNode: def __init__(self,varToken,expressionNode): self.varToken = varToken self.expressionNode = expressionNode self.position = varToken.position class IfNode: def __init__(self,baseCase,elseCase): self.baseCase = baseCase self.elseCase = elseCase self.position = baseCase[0].position class ForNode: def __init__(self,varName,startValueNode,endValueNode,stepValueNode ,bodyNode): self.varName = varName self.startValueNode = startValueNode self.endValueNode = endValueNode self.stepValueNode = stepValueNode self.bodyNode = bodyNode self.position = varName.position class WhileNode: def __init__(self,conditionNode,bodyNode): self.conditionNode = conditionNode self.bodyNode = bodyNode self.position = conditionNode.position class PrintNode: def __init__(self,bodyNode): self.bodyNode = bodyNode self.position = bodyNode.position class SumNode: def __init__(self,listNode): self.listNode = listNode self.position = listNode.position class StringifyNode: def __init__(self,bodyNode): self.bodyNode = bodyNode self.position = bodyNode.position
StarcoderdataPython
1653319
from __future__ import unicode_literals from django.apps import AppConfig class SignalControlConfig(AppConfig): name = 'signalcontrol' verbose_name = 'Signal Control'
StarcoderdataPython
3229755
<gh_stars>0 #!/usr/bin/env python3 # author: d.koch # coding: utf-8 # naming: pep-0008 # typing: pep-0484 # docstring: pep-0257 # indentation: tabulation (4 spc) """ enamlx-api.py API list in copy/paste friendly format """ # How to use this file # This file is *not* runnable # This file is *not* an exhaustive documentation # This file briefly describes the topology of the module # This file briefly describes the different classes # This file briefly describes the relationship between classes # Check the 'Dependencies and relationship' part below # Copy and paste the 'from ... import ...' and 'xxx:' parts into the enaml file # Ensure relationship is preserved, indent as needed, adapt members and methods # Check often using 'enaml-run file.enaml' # Hierarchy and inheritance # (atom) Atom # widgets +-- Brush # | color = ColorMember() # | image = Instance(Image) # | style = Enum('solid', 'dense1', 'dense2', 'dense3', 'dense4', 'dense5', 'dense6', 'dense7', 'horizontal', 'vertical', 'cross', 'diag', 'bdiag', 'fdiag', 'linear', 'radial', 'conical', 'texture', 'none') # (enaml) +-- Object # (enaml) | +-- Declarative # (enaml) | +-- ToolkitObject # widgets | +-- GraphicsItem # | | | <GraphicsView # | | | proxy = Typed(ProxyGraphicsItem) # | | | position = PointMember() # | | | rotation = Float(strict=False) # | | | scale = Float(1.0, strict=False) # | | | opacity = Float(1.0, strict=False) # | | | selected = Bool() # | | | enabled = Bool(True) # | | | visible = Bool(True) # | | | tool_tip = Str() # | | | status_tip = Str() # | | | features = Coerced(Feature.Flags) # | | | extra_features = Coerced(GraphicFeature.Flags) # | | | request_update = Event() # | | | selectable = Bool() # | | | movable = Bool() # | | | # # | | | self.show() # | | | self.hide() # | | | # # | | | focus_gained => (): # | | | focus_lost => (): # | | | drag_start => (): # | | | drag_end => (drag_data, result): # | | | drag_enter => (event): # | | | drag_move => (event): # | | | drag_leave => (): # | | | drop => (event): # | | | mouse_press_event => (event): # | | | mouse_move_event => (event): # | | | mouse_release_event => (event): # | | | wheel_event => (event): # | | | draw => (painter, options, widget): # | | +-- AbstractGraphicsShapeItem # | | | | proxy = Typed(ProxyAbstractGraphicsShapeItem) # | | | | pen = Instance(Pen) # | | | | brush = Instance(Brush) # widgets | | | +-- GraphicsEllipseItem # | | | | proxy = Typed(ProxyGraphicsEllipseItem) # | | | | width = Float(10.0, strict=False) # | | | | height = Float(10.0, strict=False) # | | | | span_angle = Float(360.0, strict=False) # | | | | start_angle = Float(0.0, strict=False) # widgets | | | +-- GraphicsLineItem # | | | | proxy = Typed(ProxyGraphicsLineItem) # | | | | point = List(PointMember()) # widgets | | | +-- GraphicsPathItem # | | | | proxy = Typed(ProxyGraphicsPathItem) # | | | | path = Value() # widgets | | | +-- GraphicsPolygonItem # | | | | proxy = Typed(ProxyGraphicsPolygonItem) # | | | | points = List(PointMember()) # widgets | | | +-- GraphicsRectItem # | | | | proxy = Typed(ProxyGraphicsRectItem) # | | | | width = Float(10.0, strict=False) # | | | | height = Float(10.0, strict=False) # widgets | | | +-- GraphicsTextItem # | | | proxy = Typed(ProxyGraphicsTextItem) # | | | text = Str() # | | | font = FontMember() # widgets | | +-- GraphicsImageItem # | | | proxy = Typed(ProxyGraphicsImageItem) # | | | image = Instance(Image) # widgets | | +-- GraphicsItemGroup # | | | proxy = Typed(ProxyGraphicsItemGroup) # widgets | | +-- GraphicsWidget # | | proxy = Typed(ProxyGraphicsWidget) # (enaml) | +-- Widget # (enaml) | +-- ConstraintsWidget # (enaml) | +-- Control # | | +-- AbstractItemView # | | | | hug_width = set_default('ignore') # | | | | hug_height = set_default('ignore') # | | | | items = ContainerList(default=[]) # | | | | selection_mode = Enum('extended', 'none', 'multi', 'single', 'contiguous') # | | | | selection_behavior = Enum('items', 'rows', 'columns') # | | | | selection = ContainerList(default=[]) # | | | | scroll_to_bottom = Bool(False) # | | | | alternating_row_colors = Bool(False) # | | | | cell_padding = Int(0) # | | | | auto_resize = Bool(True) # | | | | resize_mode = Enum('interactive', 'fixed', 'stretch', 'resize_to_contents', 'custom') # | | | | word_wrap = Bool(False) # | | | | show_vertical_header = Bool(True) # | | | | vertical_headers = ContainerList() # | | | | vertical_stretch = Bool(False) # | | | | vertical_minimum_section_size = Int(0) # | | | | show_horizontal_header = Bool(True) # | | | | horizontal_headers << ContainerList() # | | | | horizontal_stretch = Bool(False) # | | | | horizontal_minimum_section_size = Int(0) # | | | | sortable = Bool(True) # | | | | current_row = Int(0) # | | | | current_column = Int(0) # | | | | visible_row = Int(0) # | | | | visible_rows = Int(100) # | | | | visible_column = Int(0) # | | | | visible_columns = Int(1) # widgets | | | +-- TableView # | | | | proxy = Typed(ProxyTableView) # | | | | show_grid = Bool(True) # widgets | | | +-- TreeView # | | | proxy = Typed(ProxyTreeView) # | | | show_root = Bool(True) # | | +-- AbstractWidgetItemGroup # | | | | >AbstractWidgetItem # | | | | clicked = d_(Event(), writable=False) # | | | | double_clicked = d_(Event(), writable=False) # | | | | entered = d_(Event(), writable=False) # | | | | pressed = d_(Event(), writable=False) # | | | | selection_changed = d_(Event(bool), writable=False) # | | | +-- AbstractWidgetItem # | | | | | row = d_(Int(), writable=False) # | | | | | column = d_(Int(), writable=False) # | | | | | text = d_(Str()) # | | | | | text_alignment = d_(Enum(*[(h, v) for h in ('left', 'right', 'center', 'justify') for v in ('center', 'top', 'bottom')])) # | | | | | icon = d_(Typed(Icon)) # | | | | | icon_size = d_(Coerced(Size, (-1, -1))) # | | | | | selectable = d_(Bool(True)) # | | | | | selected = d_(Bool()) # | | | | | checkable = d_(Bool()) # | | | | | checked = d_(Bool()) # | | | | | editable = d_(Bool()) # | | | | | changed = d_(Event(), writable=False) # | | | | | toggled = d_(Event(bool), writable=False) # widgets | | | | +-- TableViewItem # | | | | | proxy = Typed(ProxyTableViewItem) # widgets | | | | +-- TreeViewItem # | | | | | <TreeViewItem # | | | | | >TreeViewItem # | | | | | proxy = Typed(ProxyTreeViewItem) # | | | | | items = ContainerList(default=[]) # | | | | | visible_row = Int(0) # | | | | | visible_rows = Int(100) # | | | | | visible_column = Int(0) # | | | | | visible_columns = Int(1) # widgets | | | | +-- TreeViewColumn # | | | | proxy = Typed(ProxyTreeViewColumn) # widgets | | | +-- TableViewRow # | | | | proxy = Typed(ProxyTableViewRow) # | | | | row = Int() # widgets | | | +-- TableViewColumn # | | | proxy = Typed(ProxyTableViewColumn) # | | | column = Int() # widgets | | +-- GraphicsView # | | | >GraphicsItem # | | | proxy = Typed(ProxyGraphicsView) # | | | hug_width = set_default('ignore') # | | | hug_height = set_default('ignore') # | | | renderer = Enum('default', 'opengl', 'qwidget') # | | | antialiasing = Bool(True) # | | | selected_items = List(GraphicsItem) # | | | drag_mode = Enum('none', 'scroll', 'selection') # | | | min_zoom = Float(0.007, strict=False) # | | | max_zoom = Float(100.0, strict=False) # | | | auto_range = Bool(False) # | | | lock_aspect_ratio = Bool(True) # | | | extra_features = Coerced(GraphicFeature.Flags) # | | | # # | | | self.get_item_at(*args, **kwargs) # | | | self.fit_in_view(item) # | | | self.center_on(item) # | | | self.translate_view(x=0, y=0) # | | | self.scale_view(x=1, y=1) # | | | self.rotate_view(angle=0) # | | | self.reset_view() # | | | self.map_from_scene(point) # | | | self.map_to_scene(point) # | | | self.pixel_density(self) # | | | # # | | | wheel_event => (event): # | | | mouse_press_event => (event): # | | | mouse_move_event => (event): # | | | mouse_release_event => (event): # | | | draw_background => (painter, rect): # widgets | | +-- KeyEvent # | | | proxy = Typed(ProxyKeyEvent)) # | | | keys = List(str) # | | | enabled = Bool(True) # | | | repeats = Bool(True) # widgets | | +-- OccViewer # | | | proxy = Typed(ProxyOccViewer) # | | | position = Tuple(Int(strict=False),default=(0,0)) # | | | display_mode = Enum('shaded','hlr','wireframe') # | | | selection_mode = Enum('shape','neutral','face','edge','vertex') # | | | selection = List() # | | | view_mode = Enum('iso','top','bottom','left','right','front','rear') # | | | trihedron_mode = Enum('right-lower','disabled') # | | | background_gradient = Tuple(Int(),default=(206, 215, 222, 128, 128, 128)) # | | | double_buffer = Bool(True) # | | | shadows = Bool(False) # | | | reflections = Bool(True) # | | | antialiasing = Bool(True) # | | | hug_width = set_default('ignore') # | | | hug_height = set_default('ignore') # | | | # # | | | on_key_press :: Event() # | | | on_mouse_press :: Event() # | | | on_mouse_release :: Event() # | | | on_mouse_wheel :: Event() # | | | on_mouse_move :: Event() # | | +-- PlotItem # | | | | title = Str() # | | | | name = Str() # | | | | row = Int(0) # | | | | column = Int(0) # | | | | line_pen = Instance(PEN_ARGTYPES) # | | | | shadow_pen = Instance(PEN_ARGTYPES) # | | | | fill_level = Float(strict=False) # | | | | fill_brush = Instance(BRUSH_ARGTYPES) # | | | | symbol = Enum(None, 'o', 's', 't', 'd', '+') # | | | | symbol_size = Float(10, strict=False) # | | | | symbol_pen = Instance(PEN_ARGTYPES) # | | | | symbol_brush = Instance(BRUSH_ARGTYPES) # | | | | show_legend = ContainerList() # | | | | label_left = Str() # | | | | label_right = Str() # | | | | label_top = Str() # | | | | label_bottom = Str() # | | | | grid = Tuple(bool, default=(False, False)) # | | | | grid_alpha = FloatRange(low=0.0, high=1.0, value=0.5) # | | | | multi_axis = Bool(True) # | | | | axis_left_ticks = Callable() # | | | | axis_bottom_ticks = Callable() # | | | | log_mode = Tuple(bool, default=(False, False)) # | | | | antialias = Bool(False) # | | | | auto_range = Enum(True, False) # | | | | range_x = ContainerList(default=[0, 100]) # | | | | range_y = ContainerList(default=[0, 100]) # | | | | auto_downsample = Bool(False) # | | | | clip_to_view = Bool(False) # | | | | step_mode = Bool(False) # | | | | aspect_locked = Bool(False) # | | | | refresh_time = Int(100) # widgets | | | +-- PlotItem2D # | | | | | x = ContainerList() # | | | | | y = ContainerList() # widgets | | | | +-- PlotItem3D # | | | | | | z = ContainerList() # widgets | | | | | +-- PlotItemArray3D # | | | | | type = Enum('line') # | | | | | x = numpy_ndarray # | | | | | y = numpy_ndarray # | | | | | z = numpy_ndarray # widgets | | | | +-- PlotItemArray # | | | | x = numpy_ndarray # | | | | y = numpy_ndarray # | | | +-- AbstractDataPlotItem # widgets | | | +-- PlotItemDict # | | | | data = Dict(default={'x': [], 'y': []}) # widgets | | | +-- PlotItemList # | | | data = ContainerList() # (enaml) | | +-- SpinBox # widgets | | +-- DoubleSpinBox # | | decimals = Int(2) # | | minimum = Float(0, strict=False) # | | maximum = Float(100, strict=False) # | | single_step = Float(1.0, strict=False) # | | value = Float(0, strict=False) # (enaml) | +-- Frame # (enaml) | +-- Container # widgets | +-- Console # | | proxy = Typed(ProxyConsole) # | | font_family = Str() # | | font_size = Int(0) # | | console_size = Coerced(Size,(81,25)) # | | buffer_size = Int(0) # | | display_banner = Bool(False) # | | completion = Enum('ncurses','plain', 'droplist') # | | execute = Instance(object) # widgets | +-- PlotArea # | hug_width = set_default('ignore') # | hug_height = set_default('ignore') # | proxy = Typed(ProxyPlotArea) # | setup = Callable(lambda graph: None) # widgets +-- Pen # | color = ColorMember() # | width = Float(1.0, strict=False) # | line_style = Enum('solid', 'dash', 'dot', 'dash_dot', 'dash_dot_dot', 'custom', 'none') # | cap_style = Enum('square', 'flat', 'round') # | join_style = Enum('bevel', 'miter', 'round') # | dash_pattern = List(Float(strict=False)) # widgets +-- Point # | x = Float(0, strict=False) # | y = Float(0, strict=False) # | z = Float(0, strict=False) # widgets +-- Rect # x = Float(0, strict=False) # y = Float(0, strict=False) # width = Float(0, strict=False) # height = Float(0, strict=False) # Dependencies and relationship # (enaml) # +-- (Container) # +-- GraphicsView # | | >Point # | | >Rect # | | background = # | | drag_mode = # | | minimum_size = # | +-- (AbstractGraphicsShapeItem) # | | >Brush # | | >Pen # | +-- (Menu) # | +-- (Pattern) # | | | iterable = range(...) # | | | loop.index # | | +-- GraphicsEllipseItem # | | | height = # | | | opacity = # | | | pen = # | | | position = # | | | width = # | | +-- GraphicsLineItem # | | | point = # | | | position = # | | +-- GraphicsPathItem # | | | pen = # | | | movable = # | | | path << # | | | scale = # | | +-- GraphicsPolygonItem # | | | points = # | | | scale = # | | +-- GraphicsRectItem # | | | brush = # | | | position = # | | | opacity = # | | | width = # | | +-- GraphicsTextItem # | | activated :: # | | drag_start => (): # | | drag_end => (drag_data, result): # | | features = # | | pen = # | | position = # | | rotation = # | | selectable = # | | text << # | +-- GraphicsImageItem # | +-- GraphicsItemGroup # | | +-- (Pattern) # | | | iterable = range(...) # | | | loop.index # | | +-- (Graphics...Item) # | +-- GraphicsWidget # | | position = # | | rotation = # | +-- (Widget) # +-- PlotArea # | +-- PlotItemArray # | | auto_range = # | | background = # | | label_left = # | | label_right = # | | line_pen = # | | multi_axis = # | | y << # | +-- (PlotItem...) # | +-- (PlotItem...) # +-- TableView: table: # | | horizontal_headers << # | | horizontal_stretch = True # | | items << # | | minimum_size = # | +-- (Pattern) # | | iterable << # | | loop.index # | | loop.item # | +-- TableViewRow # | | row << table.items[self.row] # | | clicked := # | +-- (Menu) # | +-- TableViewItem # | | checkable = # | | checked := # | | clicked := # | | double_clicked := # | | selected := # | | icon << # | | text << # | +-- (Control) # | +-- (Menu) # | +-- (Action) # | text << # | triggered :: # +-- TreeView: tree: # | horizontal_headers << # | items << # +-- (Pattern) # | iterable << tree.items # | loop.index # | loop.item # +-- TreeViewItem # | icon << # | items << # | text << # +-- (TreeViewItem) # +-- (TreeViewColumn) # | checkable = # | checked := # | icon << # | text << # +-- (Control) # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # EnamlX : AbstractItemView from enamlx.widgets.abstract_item_view import AbstractItemView AbstractItemView: hug_width = set_default('ignore') hug_height = set_default('ignore') items = ContainerList(default=[]) selection_mode = Enum('extended', 'none', 'multi', 'single', 'contiguous') selection_behavior = Enum('items', 'rows', 'columns') selection = ContainerList(default=[]) scroll_to_bottom = Bool(False) alternating_row_colors = Bool(False) cell_padding = Int(0) auto_resize = Bool(True) resize_mode = Enum('interactive', 'fixed', 'stretch', 'resize_to_contents', 'custom') word_wrap = Bool(False) show_vertical_header = Bool(True) vertical_headers = ContainerList() vertical_stretch = Bool(False) vertical_minimum_section_size = Int(0) show_horizontal_header = Bool(True) horizontal_headers << ContainerList() horizontal_stretch = Bool(False) horizontal_minimum_section_size = Int(0) sortable = Bool(True) current_row = Int(0) current_column = Int(0) visible_row = Int(0) visible_rows = Int(100) visible_column = Int(0) visible_columns = Int(1) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (Control) : aiview = AbstractItemView() # <-> (set_default('ignore')) : Table should expand by default hug_width = aiview.hug_width = hug_width # <-> (set_default('ignore')) : Table should expand by default hug_height = aiview.hug_height = hug_height # <-> (ContainerList(default=[])) : The items to display in the view items = aiview.items = items # <-> (Enum('extended', 'none', 'multi', 'single', 'contiguous')) : Selection mode of the view selection_mode = aiview.selection_mode = selection_mode # <-> (Enum('items', 'rows', 'columns')) : Selection behavior of the view selection_behavior = aiview.selection_behavior = selection_behavior # <-> (ContainerList(default=[])) : Selection selection = aiview.selection = selection # <-> (Bool(False)) : Automatically scroll to bottm when new items are added scroll_to_bottom = aiview.scroll_to_bottom = scroll_to_bottom # <-> (Bool(False)) : Set alternating row colors alternating_row_colors = aiview.alternating_row_colors = alternating_row_colors # <-> (Int(0)) : Cell padding cell_padding = aiview.cell_padding = cell_padding # <-> (Bool(True)) : Automatically resize columns to fit contents auto_resize = aiview.auto_resize = auto_resize # <-> (Enum('interactive', 'fixed', 'stretch', 'resize_to_contents', 'custom')) : Resize mode of columns and rows resize_mode = aiview.resize_mode = resize_mode # <-> (Bool(False)) : Word wrap word_wrap = aiview.word_wrap = word_wrap # <-> (Bool(True)) : Show vertical header bar show_vertical_header = aiview.show_vertical_header = show_vertical_header # <-> (ContainerList()) : Row headers vertical_headers = aiview.vertical_headers = vertical_headers # <-> (Bool(False)) : Stretch last row vertical_stretch = aiview.vertical_stretch = vertical_stretch # <-> (Int(0)) : Minimum row size vertical_minimum_section_size = aiview.vertical_minimum_section_size = vertical_minimum_section_size # <-> (Bool(True)) : Show horizontal hearder bar show_horizontal_header = aiview.show_horizontal_header = show_horizontal_header # <-> (ContainerList()) : Column headers horizontal_headers = aiview.horizontal_headers = horizontal_headers # <-> (Bool(False)) : Stretch last column horizontal_stretch = aiview.horizontal_stretch = horizontal_stretch # <-> (Int(0)) : Minimum column size horizontal_minimum_section_size = aiview.horizontal_minimum_section_size = horizontal_minimum_section_size # <-> (Bool(True)) : Table is sortable sortable = aiview.sortable = sortable # <-> (Int(0)) : Current row index current_row = aiview.current_row = current_row # <-> (Int(0)) : Current column index current_column = aiview.current_column = current_column # <-> (Int(0)) : First visible row visible_row = aiview.visible_row = visible_row # <-> (Int(100)) : Number of rows visible visible_rows = aiview.visible_rows = visible_rows # <-> (Int(0)) : First visible column visible_column = aiview.visible_column = visible_column # <-> (Int(1)) : Number of columns visible visible_columns = aiview.visible_columns = visible_columns # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . from enamlx.widgets.abstract_item import AbstractWidgetItemGroup AbstractWidgetItemGroup: clicked :: Event() double_clicked :: Event() entered :: Event() pressed :: Event() selection_changed :: Event(bool) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (Control) : awigroup = AbstractWidgetItemGroup() # <-> (Event()) : Triggered when clicked clicked = awigroup.clicked = clicked # <-> (Event()) : Triggered when double clicked double_clicked = awigroup.double_clicked = double_clicked # <-> (Event()) : Triggered when the row, column, or item is entered entered = awigroup.entered = entered # <-> (Event()) : Triggered when the row, column, or item is pressed pressed = awigroup.pressed = pressed # <-> (Event(bool)) : Triggered when the row, column, or item's selection changes selection_changed = awigroup.selection_changed = selection_changed # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . from enamlx.widgets.abstract_item import AbstractWidgetItem AbstractWidgetItem: row = Int() column = Int() text = Str() text_alignment = Enum(*[(h, v) for h in ('left', 'right', 'center', 'justify') for v in ('center', 'top', 'bottom')]) icon = Typed(Icon) icon_size = Coerced(Size, (-1, -1)) selectable = Bool(True) selected = Bool() checkable = Bool() checked = Bool() editable = Bool() changed :: Event() toggled :: Event(bool) #AbstractWidgetItemGroup: clicked :: Event() double_clicked :: Event() entered :: Event() pressed :: Event() selection_changed :: Event(bool) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractWidgetItemGroup) : awitem = AbstractWidgetItem() # <-> (Int()) : Model index or row within the view row = awitem.row = row # <-> (Int()) : Column within the view column = awitem.column = column # <-> (Str()) : Text to display within the cell text = awitem.text = text # <-> (Enum(*[(h, v) for h in ('left', 'right', 'center', 'justify') for v in ('center', 'top', 'bottom')])) : Text alignment within the cell text_alignment = awitem.text_alignment = text_alignment # <-> (Typed(Icon)) : Icon to display in the cell icon = awitem.icon = icon # <-> (Coerced(Size, (-1, -1))) : The size to use for the icon icon_size = awitem.icon_size = icon_size # <-> (Bool(True)) : Whether the item or group can be selected selectable = awitem.selectable = selectable # <-> (Bool()) : Selection state of the item or group selected = awitem.selected = selected # <-> (Bool()) : Whether the item or group can be checked checkable = awitem.checkable = checkable # <-> (Bool()) : Checked state of the item or group checked = awitem.checked = checked # <-> (Bool()) : Whether the item or group can be edited editable = awitem.editable = editable # <-> (Event()) : Triggered when the item's contents change changed = awitem.changed = changed # <-> (Event(bool)) : Triggered when the checkbox state changes toggled = awitem.toggled = toggled # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # EnamlX : TableView from enamlx.widgets.api import TableView TableView: proxy = Typed(ProxyTableView) show_grid = Bool(True) #AbstractItemView: hug_width = set_default('ignore') hug_height = set_default('ignore') items = ContainerList(default=[]) selection_mode = Enum('extended', 'none', 'multi', 'single', 'contiguous') selection_behavior = Enum('items', 'rows', 'columns') selection = ContainerList(default=[]) scroll_to_bottom = Bool(False) alternating_row_colors = Bool(False) cell_padding = Int(0) auto_resize = Bool(True) resize_mode = Enum('interactive', 'fixed', 'stretch', 'resize_to_contents', 'custom') word_wrap = Bool(False) show_vertical_header = Bool(True) vertical_headers = ContainerList() vertical_stretch = Bool(False) vertical_minimum_section_size = Int(0) show_horizontal_header = Bool(True) horizontal_headers << ContainerList() horizontal_stretch = Bool(False) horizontal_minimum_section_size = Int(0) sortable = Bool(True) current_row = Int(0) current_column = Int(0) visible_row = Int(0) visible_rows = Int(100) visible_column = Int(0) visible_columns = Int(1) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractItemView) : tview = TableView() # <-> (Typed(ProxyTableView)) : Proxy reference proxy = tview.proxy = proxy # <-> (Bool(True)) : Show grid of cells show_grid = tview.show_grid = show_grid # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : TableViewItem from enamlx.widgets.api import TableViewItem TableViewItem: proxy = Typed(ProxyTableViewItem) #AbstractWidgetItem: row = Int() column = Int() text = Str() text_alignment = Enum(*[(h, v) for h in ('left', 'right', 'center', 'justify') for v in ('center', 'top', 'bottom')]) icon = Typed(Icon) icon_size = Coerced(Size, (-1, -1)) selectable = Bool(True) selected = Bool() checkable = Bool() checked = Bool() editable = Bool() changed :: Event() toggled :: Event(bool) #AbstractWidgetItemGroup: clicked :: Event() double_clicked :: Event() entered :: Event() pressed :: Event() selection_changed :: Event(bool) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractWidgetItem) : tvitem = TableViewItem() # <-> (Typed(ProxyTableViewItem)) : Proxy reference proxy = tvitem.proxy = proxy # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : TableViewRow from enamlx.widgets.api import TableViewRow TableViewRow: proxy = Typed(ProxyTableViewRow) row = Int() #AbstractWidgetItemGroup: clicked :: Event() double_clicked :: Event() entered :: Event() pressed :: Event() selection_changed :: Event(bool) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractWidgetItemGroup) : tvrow = TableViewRow() # <-> (Typed(ProxyTableViewRow)) : Proxy reference proxy = tvrow.proxy = proxy # <-> (Int()) : Row within the table row = tvrow.row = row # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : TableViewColumn from enamlx.widgets.api import TableViewColumn TableViewColumn: proxy = Typed(ProxyTableViewColumn) column = Int() #AbstractWidgetItemGroup: clicked :: Event() double_clicked :: Event() entered :: Event() pressed :: Event() selection_changed :: Event(bool) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractWidgetItemGroup) : tvcol = TableViewColumn() # <-> (Typed(ProxyTableViewColumn)) : Proxy reference proxy = tvcol.proxy = proxy # <-> (Int()) : Column within the table column = tvcol.column = column # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # EnamlX : TreeView from enamlx.widgets.api import TreeView TreeView: proxy = Typed(ProxyTreeView) show_root = Bool(True) #AbstractItemView: hug_width = set_default('ignore') hug_height = set_default('ignore') items = ContainerList(default=[]) selection_mode = Enum('extended', 'none', 'multi', 'single', 'contiguous') selection_behavior = Enum('items', 'rows', 'columns') selection = ContainerList(default=[]) scroll_to_bottom = Bool(False) alternating_row_colors = Bool(False) cell_padding = Int(0) auto_resize = Bool(True) resize_mode = Enum('interactive', 'fixed', 'stretch', 'resize_to_contents', 'custom') word_wrap = Bool(False) show_vertical_header = Bool(True) vertical_headers = ContainerList() vertical_stretch = Bool(False) vertical_minimum_section_size = Int(0) show_horizontal_header = Bool(True) horizontal_headers << ContainerList() horizontal_stretch = Bool(False) horizontal_minimum_section_size = Int(0) sortable = Bool(True) current_row = Int(0) current_column = Int(0) visible_row = Int(0) visible_rows = Int(100) visible_column = Int(0) visible_columns = Int(1) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractItemView) : tview = TreeView() # <-> (Typed(ProxyTreeView)) : Proxy reference proxy = tview.proxy = proxy # <-> (Bool(True)) : Show root node show_root = tview.show_root = show_root # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : TreeViewItem from enamlx.widgets.api import TreeViewItem TreeViewItem: proxy = Typed(ProxyTreeViewItem) items = ContainerList(default=[]) visible_row = Int(0) visible_rows = Int(100) visible_column = Int(0) visible_columns = Int(1) #AbstractWidgetItem: row = Int() column = Int() text = Str() text_alignment = Enum(*[(h, v) for h in ('left', 'right', 'center', 'justify') for v in ('center', 'top', 'bottom')]) icon = Typed(Icon) icon_size = Coerced(Size, (-1, -1)) selectable = Bool(True) selected = Bool() checkable = Bool() checked = Bool() editable = Bool() changed :: Event() toggled :: Event(bool) #AbstractWidgetItemGroup: clicked :: Event() double_clicked :: Event() entered :: Event() pressed :: Event() selection_changed :: Event(bool) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractWidgetItem) : tvitem = TreeViewItem() # <-> (Typed(ProxyTreeViewItem)) : Proxy reference proxy = tvitem.proxy = proxy # <-> (ContainerList(default=[])) : The child items items = tvitem.items = items # <-> (Int(0)) : First visible row visible_row = tvitem.visible_row = visible_row # <-> (Int(100)) : Number of rows visible visible_rows = tvitem.visible_rows = visible_rows # <-> (Int(0)) : First visible column visible_column = tvitem.visible_column = visible_column # <-> (Int(1)) : Number of columns visible visible_columns = tvitem.visible_columns = visible_columns # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : TreeViewColumn from enamlx.widgets.api import TreeViewColumn TreeViewColumn: proxy = Typed(ProxyTreeViewColumn) #AbstractWidgetItem: row = Int() column = Int() text = Str() text_alignment = Enum(*[(h, v) for h in ('left', 'right', 'center', 'justify') for v in ('center', 'top', 'bottom')]) icon = Typed(Icon) icon_size = Coerced(Size, (-1, -1)) selectable = Bool(True) selected = Bool() checkable = Bool() checked = Bool() editable = Bool() changed :: Event() toggled :: Event(bool) #AbstractWidgetItemGroup: clicked :: Event() double_clicked :: Event() entered :: Event() pressed :: Event() selection_changed :: Event(bool) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractWidgetItem) : tvcol = TreeViewColumn() # <-> (Typed(ProxyTreeViewColumn)) : Proxy reference proxy = tvcol.proxy = proxy # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # EnamlX : PlotArea from enamlx.widgets.api import PlotArea PlotArea: hug_width = set_default('ignore') hug_height = set_default('ignore') proxy = Typed(ProxyPlotArea) setup = Callable(lambda graph: None) #Container: share_layout = Bool(False) padding = Coerced(Box, (10, 10, 10, 10)) resist_width = set_default('ignore') resist_height = set_default('ignore') hug_width = set_default('ignore') hug_height = set_default('ignore') proxy = Typed(ProxyContainer) # self.widgets() self.visible_widgets() self.child_added(child) self.child_moved(child) self.child_removed(child) self.layout_constraints(child) #Frame: border = Typed(Border) proxy = Typed(ProxyFrame) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (Container) : parea = PlotArea() # <-> (set_default('ignore')) : hug_width = parea.hug_width = hug_width # <-> (set_default('ignore')) : hug_height = parea.hug_height = hug_height # <-> (Typed(ProxyPlotArea)) : proxy = parea.proxy = proxy # <-> (Callable(lambda graph: None)) : setup = parea.setup = setup # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : PlotItem from enamlx.widgets.plot_area import PlotItem PlotItem: title = Str() name = Str() row = Int(0) column = Int(0) line_pen = Instance(PEN_ARGTYPES) shadow_pen = Instance(PEN_ARGTYPES) fill_level = Float(strict=False) fill_brush = Instance(BRUSH_ARGTYPES) symbol = Enum(None, 'o', 's', 't', 'd', '+') symbol_size = Float(10, strict=False) symbol_pen = Instance(PEN_ARGTYPES) symbol_brush = Instance(BRUSH_ARGTYPES) show_legend = ContainerList() label_left = Str() label_right = Str() label_top = Str() label_bottom = Str() grid = Tuple(bool, default=(False, False)) grid_alpha = FloatRange(low=0.0, high=1.0, value=0.5) multi_axis = Bool(True) axis_left_ticks = Callable() axis_bottom_ticks = Callable() log_mode = Tuple(bool, default=(False, False)) antialias = Bool(False) auto_range = Enum(True, False) range_x = ContainerList(default=[0, 100]) range_y = ContainerList(default=[0, 100]) auto_downsample = Bool(False) clip_to_view = Bool(False) step_mode = Bool(False) aspect_locked = Bool(False) refresh_time = Int(100) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (Control) : pitem = PlotItem() # <-> (Str()) : Title of data series title = pitem.title = title # <-> (Str()) : Name name = pitem.name = name # <-> (Int(0)) : Row in plot area row = pitem.row = row # <-> (Int(0)) : Column in plot area column = pitem.column = column # <-> (Instance(PEN_ARGTYPES)) : Pen type to use for line line_pen = pitem.line_pen = line_pen # <-> (Instance(PEN_ARGTYPES)) : Pen type to use for shadow shadow_pen = pitem.shadow_pen = shadow_pen # <-> (Float(strict=False)) : Fill level fill_level = pitem.fill_level = fill_level # <-> (Instance(BRUSH_ARGTYPES)) : Brush fill type fill_brush = pitem.fill_brush = fill_brush # <-> (Enum(None, 'o', 's', 't', 'd', '+')) : Symbol to use for points symbol = pitem.symbol = symbol # <-> (Float(10, strict=False)) : Symbol sizes for points symbol_size = pitem.symbol_size = symbol_size # <-> (Instance(PEN_ARGTYPES)) : Symbol pen to use symbol_pen = pitem.symbol_pen = symbol_pen # <-> (Instance(BRUSH_ARGTYPES)) : Symbol brush symbol_brush = pitem.symbol_brush = symbol_brush # <-> (ContainerList()) : Show legend show_legend = pitem.show_legend = show_legend # <-> (Str()) : label_left = pitem.label_left = label_left # <-> (Str()) : label_right = pitem.label_right = label_right # <-> (Str()) : label_top = pitem.label_top = label_top # <-> (Str()) : label_bottom = pitem.label_bottom = label_bottom # <-> (Tuple(bool, default=(False, False))) : H, V grid = pitem.grid = grid # <-> (FloatRange(low=0.0, high=1.0, value=0.5)) : H, V grid_alpha = pitem.grid_alpha = grid_alpha # <-> (Bool(True)) : Display a separate axis for each nested plot multi_axis = pitem.multi_axis = multi_axis # <-> (Callable()) : axis_left_ticks = pitem.axis_left_ticks = axis_left_ticks # <-> (Callable()) : axis_bottom_ticks = pitem.axis_bottom_ticks = axis_bottom_ticks # <-> (Tuple(bool, default=(False, False))) : Display the axis on log scale log_mode = pitem.log_mode = log_mode # <-> (Bool(False)) : Enable antialiasing antialias = pitem.antialias = antialias # <-> (Enum(True, False)) : Set auto range for each axis auto_range = pitem.auto_range = auto_range # <-> (ContainerList(default=[0, 100])) : x-range to use if auto_range is disabled range_x = pitem.range_x = range_x # <-> (ContainerList(default=[0, 100])) : y-range to use if auto_range is disabled range_y = pitem.range_y = range_y # <-> (Bool(False)) : Automatically downsaple auto_downsample = pitem.auto_downsample = auto_downsample # <-> (Bool(False)) : Clip data points to view clip_to_view = pitem.clip_to_view = clip_to_view # <-> (Bool(False)) : Step mode to use step_mode = pitem.step_mode = step_mode # <-> (Bool(False)) : Keep aspect ratio locked when resizing aspect_locked = pitem.aspect_locked = aspect_locked # <-> (Int(100)) : Time between updates refresh_time = pitem.refresh_time = refresh_time # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : PlotItem2D from enamlx.widgets.api import PlotItem2D PlotItem2D: x = ContainerList() y = ContainerList() #PlotItem: title = Str() name = Str() row = Int(0) column = Int(0) line_pen = Instance(PEN_ARGTYPES) shadow_pen = Instance(PEN_ARGTYPES) fill_level = Float(strict=False) fill_brush = Instance(BRUSH_ARGTYPES) symbol = Enum(None, 'o', 's', 't', 'd', '+') symbol_size = Float(10, strict=False) symbol_pen = Instance(PEN_ARGTYPES) symbol_brush = Instance(BRUSH_ARGTYPES) show_legend = ContainerList() label_left = Str() label_right = Str() label_top = Str() label_bottom = Str() grid = Tuple(bool, default=(False, False)) grid_alpha = FloatRange(low=0.0, high=1.0, value=0.5) multi_axis = Bool(True) axis_left_ticks = Callable() axis_bottom_ticks = Callable() log_mode = Tuple(bool, default=(False, False)) antialias = Bool(False) auto_range = Enum(True, False) range_x = ContainerList(default=[0, 100]) range_y = ContainerList(default=[0, 100]) auto_downsample = Bool(False) clip_to_view = Bool(False) step_mode = Bool(False) aspect_locked = Bool(False) refresh_time = Int(100) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (PlotItem) : pi2d = PlotItem2D() # <-> (ContainerList()) : x-axis values, as a list x = pi3d.x = x # <-> (ContainerList()) : y-axis values, as a list y = pi3d.y = y # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : PlotItem3D from enamlx.widgets.api import PlotItem3D PlotItem3D: z = ContainerList() #PlotItem2D: x = ContainerList() y = ContainerList() #PlotItem: title = Str() name = Str() row = Int(0) column = Int(0) line_pen = Instance(PEN_ARGTYPES) shadow_pen = Instance(PEN_ARGTYPES) fill_level = Float(strict=False) fill_brush = Instance(BRUSH_ARGTYPES) symbol = Enum(None, 'o', 's', 't', 'd', '+') symbol_size = Float(10, strict=False) symbol_pen = Instance(PEN_ARGTYPES) symbol_brush = Instance(BRUSH_ARGTYPES) show_legend = ContainerList() label_left = Str() label_right = Str() label_top = Str() label_bottom = Str() grid = Tuple(bool, default=(False, False)) grid_alpha = FloatRange(low=0.0, high=1.0, value=0.5) multi_axis = Bool(True) axis_left_ticks = Callable() axis_bottom_ticks = Callable() log_mode = Tuple(bool, default=(False, False)) antialias = Bool(False) auto_range = Enum(True, False) range_x = ContainerList(default=[0, 100]) range_y = ContainerList(default=[0, 100]) auto_downsample = Bool(False) clip_to_view = Bool(False) step_mode = Bool(False) aspect_locked = Bool(False) refresh_time = Int(100) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (PlotItem2D) : pi3d = PlotItem3D() # <-> (ContainerList()) : z-axis values, as a list z = pi3d.z = z # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : PlotItemArray from enamlx.widgets.api import PlotItemArray PlotItemArray: x << numpy_ndarray y << numpy_ndarray #PlotItem2D: x = ContainerList() y = ContainerList() #PlotItem: title = Str() name = Str() row = Int(0) column = Int(0) line_pen = Instance(PEN_ARGTYPES) shadow_pen = Instance(PEN_ARGTYPES) fill_level = Float(strict=False) fill_brush = Instance(BRUSH_ARGTYPES) symbol = Enum(None, 'o', 's', 't', 'd', '+') symbol_size = Float(10, strict=False) symbol_pen = Instance(PEN_ARGTYPES) symbol_brush = Instance(BRUSH_ARGTYPES) show_legend = ContainerList() label_left = Str() label_right = Str() label_top = Str() label_bottom = Str() grid = Tuple(bool, default=(False, False)) grid_alpha = FloatRange(low=0.0, high=1.0, value=0.5) multi_axis = Bool(True) axis_left_ticks = Callable() axis_bottom_ticks = Callable() log_mode = Tuple(bool, default=(False, False)) antialias = Bool(False) auto_range = Enum(True, False) range_x = ContainerList(default=[0, 100]) range_y = ContainerList(default=[0, 100]) auto_downsample = Bool(False) clip_to_view = Bool(False) step_mode = Bool(False) aspect_locked = Bool(False) refresh_time = Int(100) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # Numpy array item # << (PlotItem2D) : piarr2d = PlotItemArray() # <-> (numpy_ndarray) : x-axis values, as a numpy array x = piarr2d.x = x # <-> (numpy_ndarray) : y-axis values, as a numpy array y = piarr2d.y = y # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : PlotItemArray3D from enamlx.widgets.api import PlotItemArray3D PlotItemArray3D: type = Enum('line') x << numpy_ndarray y << numpy_ndarray z << numpy_ndarray #PlotItem3D: z = ContainerList() #PlotItem2D: x = ContainerList() y = ContainerList() #PlotItem: title = Str() name = Str() row = Int(0) column = Int(0) line_pen = Instance(PEN_ARGTYPES) shadow_pen = Instance(PEN_ARGTYPES) fill_level = Float(strict=False) fill_brush = Instance(BRUSH_ARGTYPES) symbol = Enum(None, 'o', 's', 't', 'd', '+') symbol_size = Float(10, strict=False) symbol_pen = Instance(PEN_ARGTYPES) symbol_brush = Instance(BRUSH_ARGTYPES) show_legend = ContainerList() label_left = Str() label_right = Str() label_top = Str() label_bottom = Str() grid = Tuple(bool, default=(False, False)) grid_alpha = FloatRange(low=0.0, high=1.0, value=0.5) multi_axis = Bool(True) axis_left_ticks = Callable() axis_bottom_ticks = Callable() log_mode = Tuple(bool, default=(False, False)) antialias = Bool(False) auto_range = Enum(True, False) range_x = ContainerList(default=[0, 100]) range_y = ContainerList(default=[0, 100]) auto_downsample = Bool(False) clip_to_view = Bool(False) step_mode = Bool(False) aspect_locked = Bool(False) refresh_time = Int(100) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # Numpy array item # << (PlotItem3D) : piarr3d = PlotItemArray3D() # <-> (Enum('line')) : Plot type type = piarr3d.type = type # <-> (numpy_ndarray) : x-axis values, as a numpy array x = piarr3d.x = x # <-> (numpy_ndarray) : y-axis values, as a numpy array y = piarr3d.y = y # <-> (numpy_ndarray) : z-axis values, as a numpy array z = piarr3d.z = z # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : PlotItemDict from enamlx.widgets.api import PlotItemDict PlotItemDict: data = Dict(default={'x': [], 'y': []}) #AbstractDataPlotItem: #PlotItem: title = Str() name = Str() row = Int(0) column = Int(0) line_pen = Instance(PEN_ARGTYPES) shadow_pen = Instance(PEN_ARGTYPES) fill_level = Float(strict=False) fill_brush = Instance(BRUSH_ARGTYPES) symbol = Enum(None, 'o', 's', 't', 'd', '+') symbol_size = Float(10, strict=False) symbol_pen = Instance(PEN_ARGTYPES) symbol_brush = Instance(BRUSH_ARGTYPES) show_legend = ContainerList() label_left = Str() label_right = Str() label_top = Str() label_bottom = Str() grid = Tuple(bool, default=(False, False)) grid_alpha = FloatRange(low=0.0, high=1.0, value=0.5) multi_axis = Bool(True) axis_left_ticks = Callable() axis_bottom_ticks = Callable() log_mode = Tuple(bool, default=(False, False)) antialias = Bool(False) auto_range = Enum(True, False) range_x = ContainerList(default=[0, 100]) range_y = ContainerList(default=[0, 100]) auto_downsample = Bool(False) clip_to_view = Bool(False) step_mode = Bool(False) aspect_locked = Bool(False) refresh_time = Int(100) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractDataPlotItem) : pidict = PlotItemDict() # <-> (Dict(default={'x': [], 'y': []})) : data = pidict.data = data # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : PlotItemList from enamlx.widgets.api import PlotItemList PlotItemList: data = ContainerList() #AbstractDataPlotItem: #PlotItem: title = Str() name = Str() row = Int(0) column = Int(0) line_pen = Instance(PEN_ARGTYPES) shadow_pen = Instance(PEN_ARGTYPES) fill_level = Float(strict=False) fill_brush = Instance(BRUSH_ARGTYPES) symbol = Enum(None, 'o', 's', 't', 'd', '+') symbol_size = Float(10, strict=False) symbol_pen = Instance(PEN_ARGTYPES) symbol_brush = Instance(BRUSH_ARGTYPES) show_legend = ContainerList() label_left = Str() label_right = Str() label_top = Str() label_bottom = Str() grid = Tuple(bool, default=(False, False)) grid_alpha = FloatRange(low=0.0, high=1.0, value=0.5) multi_axis = Bool(True) axis_left_ticks = Callable() axis_bottom_ticks = Callable() log_mode = Tuple(bool, default=(False, False)) antialias = Bool(False) auto_range = Enum(True, False) range_x = ContainerList(default=[0, 100]) range_y = ContainerList(default=[0, 100]) auto_downsample = Bool(False) clip_to_view = Bool(False) step_mode = Bool(False) aspect_locked = Bool(False) refresh_time = Int(100) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractDataPlotItem) : pilist = PlotItemList() # <-> (ContainerList()) : data = pilist.data = data # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # EnamlX : OccViewer from enamlx.widgets.api import OccViewer OccViewer: proxy = Typed(ProxyOccViewer) position = Tuple(Int(strict=False),default=(0,0)) display_mode = Enum('shaded','hlr','wireframe') selection_mode = Enum('shape','neutral','face','edge','vertex') selection = List() view_mode = Enum('iso','top','bottom','left','right','front','rear') trihedron_mode = Enum('right-lower','disabled') background_gradient = Tuple(Int(),default=(206, 215, 222, 128, 128, 128)) double_buffer = Bool(True) shadows = Bool(False) reflections = Bool(True) antialiasing = Bool(True) hug_width = set_default('ignore') hug_height = set_default('ignore') # on_key_press :: Event() on_mouse_press :: Event() on_mouse_release :: Event() on_mouse_wheel :: Event() on_mouse_move :: Event() #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # A spin box widget which manipulates integer values # << (Control) : occview = OccViewer() # <-> (Typed(ProxyOccViewer)) : A reference to the ProxySpinBox object proxy = occview.proxy = proxy # <-> (Tuple(Int(strict=False),default=(0,0))) : The minimum value for the spin box position = occview.position = position # <-> (Enum('shaded','hlr','wireframe')) : Display mode display_mode = occview.display_mode = display_mode # <-> (Enum('shape','neutral','face','edge','vertex')) : Selection mode selection_mode = occview.selection_mode = selection_mode # -> (List()) : Selected items selection = occview.selection # <-> (Enum('iso','top','bottom','left','right','front','rear')) : View direction view_mode = occview.view_mode = view_mode # <-> (Enum('right-lower','disabled')) : Show tahedron trihedron_mode = occview.trihedron_mode = trihedron_mode # <-> (Tuple(Int(),default=(206, 215, 222, 128, 128, 128))) : Background gradient background_gradient = occview.background_gradient = background_gradient # <-> (Bool(True)) : Use double buffering double_buffer = occview.double_buffer = double_buffer # <-> (Bool(False)) : Display shadows shadows = occview.shadows = shadows # <-> (Bool(True)) : Display reflections reflections = occview.reflections = reflections # <-> (Bool(True)) : Enable antialiasing antialiasing = occview.antialiasing = antialiasing # <-> (set_default('ignore')) : View expands freely in width by default hug_width = occview.hug_width = hug_width # <-> (set_default('ignore')) : View expands freely in height by default hug_height = occview.hug_height = hug_height # -> (Event()) : Raise StopIteration to indicate handling should stop on_key_press = occview.on_key_press # -> (Event()) : Raise StopIteration to indicate handling should stop on_mouse_press = occview.on_mouse_press # -> (Event()) : Raise StopIteration to indicate handling should stop on_mouse_release = occview.on_mouse_release # -> (Event()) : Raise StopIteration to indicate handling should stop on_mouse_wheel = occview.on_mouse_wheel # -> (Event()) : Raise StopIteration to indicate handling should stop on_mouse_move = occview.on_mouse_move # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # EnamlX : DoubleSpinBox from enamlx.widgets.api import DoubleSpinBox DoubleSpinBox: decimals = Int(2) minimum = Float(0, strict=False) maximum = Float(100, strict=False) single_step = Float(1.0, strict=False) value = Float(0, strict=False) #SpinBox: minimum = Int(0) maximum = Int(100) value = Int(0) prefix = Str() suffix = Str() special_value_text = Str() single_step = Range(low=1) read_only = Bool(False) wrapping = Bool(False) hug_width = set_default('ignore') proxy = Typed(ProxySpinBox) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # A spin box widget which manipulates float values # << (SpinBox) : dsbox = DoubleSpinBox() # <-> (Int(2)) : The number of decmial places to be shown decimals = dsbox.decimals = decimals # <-> (Float(0, strict=False)) : The minimum value for the spin box minimum = dsbox.minimum = minimum # <-> (Float(100, strict=False)) : The maximum value for the spin box maximum = dsbox.maximum = maximum # <-> (Float(1.0, strict=False)) : The maximum value for the spin box single_step = dsbox.single_step = single_step # <-> (Float(0, strict=False)) : The position value of the spin box value = dsbox.value = value # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # EnamlX : Console from enamlx.widgets.api import Console Console: proxy = Typed(ProxyConsole) font_family = Str() font_size = Int(0) console_size = Coerced(Size,(81,25)) buffer_size = Int(0) display_banner = Bool(False) completion = Enum('ncurses','plain', 'droplist') execute = Instance(object) #Frame: border = Typed(Border) proxy = Typed(ProxyFrame) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # Console widget # << (Container) : cli = Console() # <-> (Typed(ProxyConsole)) : proxy = cli.proxy = proxy # <-> (Str()) : Font family, leave blank for default font_family = cli.font_family = font_family # <-> (Int(0)) : Font size, leave 0 for default font_size = cli.font_size = font_size # <-> (Coerced(Size,(81,25))) : Default console size in characters console_size = cli.console_size = console_size # <-> (Int(0)) : Buffer size, leave 0 for default buffer_size = cli.buffer_size = buffer_size # <-> (Bool(False)) : Display banner like version, etc.. display_banner = cli.display_banner = display_banner # <-> (Enum('ncurses','plain', 'droplist')) : Code completion type completion = cli.completion = completion # <-> (Instance(object)) : Run the line or callabla execute = cli.execute = execute # <- (Dict()) : Push variables to the console scope = cli.scope # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # EnamlX : KeyEvent from enamlx.widgets.api import KeyEvent KeyEvent: proxy = Typed(ProxyKeyEvent)) keys = List(str) enabled = Bool(True) repeats = Bool(True) #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (Control) : kevnt = KeyEvent() # <-> (Typed(ProxyKeyEvent))) : Proxy reference proxy = kevnt.proxy = proxy # <-> (List(str)) : List of keys that or codes to filter keys = kevnt.keys = keys # <-> (Bool(True)) : Listen for events enabled = kevnt.enabled = enabled # <-> (Bool(True)) : Fire multiple times when the key is held repeats = kevnt.repeats = repeats # -> (Event(dict)) : Pressed event pressed = kevnt.pressed # -> (Event(dict)) : Released event released = kevnt.released # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # EnamlX : GraphicsView from enamlx.widgets.api import GraphicsView GraphicsView: proxy = Typed(ProxyGraphicsView) hug_width = set_default('ignore') hug_height = set_default('ignore') renderer = Enum('default', 'opengl', 'qwidget') antialiasing = Bool(True) selected_items = List(GraphicsItem) drag_mode = Enum('none', 'scroll', 'selection') min_zoom = Float(0.007, strict=False) max_zoom = Float(100.0, strict=False) auto_range = Bool(False) lock_aspect_ratio = Bool(True) extra_features = Coerced(GraphicFeature.Flags) # self.get_item_at(*args, **kwargs) self.fit_in_view(item) self.center_on(item) self.translate_view(x=0, y=0) self.scale_view(x=1, y=1) self.rotate_view(angle=0) self.reset_view() self.map_from_scene(point) self.map_to_scene(point) self.pixel_density(self) # wheel_event => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): draw_background => (painter, rect): #Control: proxy = Typed(ProxyControl) #ConstraintsWidget: hug_width = PolicyEnum('strong') hug_height = PolicyEnum('strong') resist_width = PolicyEnum('strong') resist_height = PolicyEnum('strong') limit_width = PolicyEnum('ignore') limit_height = PolicyEnum('ignore') proxy = Typed(ProxyConstraintsWidget) # self.request_relayout() self.when(switch) self.layout_constraints() #Widget: enabled = Bool(True) visible = Bool(True) background = ColorMember() foreground = ColorMember() font = FontMember() minimum_size = Coerced(Size, (-1, -1)) maximum_size = Coerced(Size, (-1, -1)) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) proxy = Typed(ProxyWidget) # self.restyle() self.show(s) self.hide() # next_focus_child => (current): previous_focus_child => (current): focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (Control) : gview = GraphicsView() # <-> (Typed(ProxyGraphicsView)) : Proxy reference proxy = gview.proxy = proxy # <-> (set_default('ignore')) : An graphicsview widget expands freely in height and width by default hug_width = gview.hug_width = hug_width # <-> (set_default('ignore')) : An graphicsview widget expands freely in height and width by default hug_height = gview.hug_height = hug_height # <-> (Enum('default', 'opengl', 'qwidget')) : Select backend for rendering. OpenGL is used by default if available renderer = gview.renderer = renderer # <-> (Bool(True)) : Antialiasing is enabled by default antialiasing = gview.antialiasing = antialiasing # <-> (List(GraphicsItem)) : Items currently selected selected_items = gview.selected_items = selected_items # <-> (Enum('none', 'scroll', 'selection')) : Defines the behavior when dragging drag_mode = gview.drag_mode = drag_mode # <-> (Float(0.007, strict=False)) : Range of allowed zoom factors min_zoom = gview.min_zoom = min_zoom # <-> (Float(100.0, strict=False)) : Range of allowed zoom factors max_zoom = gview.max_zoom = max_zoom # <-> (Bool(False)) : Automatically resize view to fit the scene contents auto_range = gview.auto_range = auto_range # <-> (Bool(True)) : Keep the aspect ratio locked when resizing the view range lock_aspect_ratio = gview.lock_aspect_ratio = lock_aspect_ratio # <-> (Coerced(GraphicFeature.Flags)) : Set the extra features to enable for this widget extra_features = gview.extra_features = extra_features # A method invoked when a wheel event occurs in the widget (to be reimplemented) # event (WheelEvent) : The event representing the wheel operation gview.wheel_event(event) # A method invoked when a mouse press event occurs in the widget (to be reimplemented) # event (MouseEvent) : The event representing the press operation gview.mouse_press_event(event) # A method invoked when a mouse move event occurs in the widget (to be reimplemented) # event (MouseEvent) : The event representing the press operation gview.mouse_move_event(event) # A method invoked when a mouse release event occurs in the widget (to be reimplemented) # event (MouseEvent) : The event representing the press operation gview.mouse_release_event(event) # A method invoked when a background draw is requested (to be reimplemented) # painter (Painter) : A the toolkit dependent handle drawing # rect (Rect) : A rect showing the area of interest gview.draw_background(painter, rect) # Return the items at the given position # args () : # kwargs () : # -> () : item = gview.get_item_at(*args, **kwargs) # Fit this item into the view # item () : gview.fit_in_view(item) # Center on the given item or point # item () : item = gview.center_on(item) # Translate the view by the given x and y pixels # x () : # y () : # -> () : item = gview.translate_view(x=0, y=0) # Scale the view by the given x and y factors # x () : # y () : # -> () : item = gview.scale_view(x=1, y=1) # Roteate the view by the given x and y factors. # angle () : # -> () : igview.rotate_view(angle=0) # Reset all view transformations gview.reset_view() # Returns the scene coordinate point mapped to viewport coordinates # point () : # -> () : item = gview.map_from_scene(point) # Returns the viewport coordinate point mapped to scene coordinates # point () : # -> () : item = gview.map_to_scene(point) # Returns the size of a pixel in sceen coordinates # -> () : item = gview.pixel_density() # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : GraphicsItem from enamlx.widgets.api import GraphicsItem GraphicsItem: proxy = Typed(ProxyGraphicsItem) position = PointMember() rotation = Float(strict=False) scale = Float(1.0, strict=False) opacity = Float(1.0, strict=False) selected = Bool() enabled = Bool(True) visible = Bool(True) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) extra_features = Coerced(GraphicFeature.Flags) request_update :: Event() selectable = Bool() movable = Bool() # self.show() self.hide() # focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): wheel_event => (event): draw => (painter, options, widget): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (ToolkitObject) : gitem = GraphicsItem() # <-> (Typed(ProxyGraphicsItem)) : Proxy reference proxy = gitem.proxy = proxy # <-> (PointMember()) : Position position = gitem.position = position # <-> (Float(strict=False)) : Item rotation rotation = gitem.rotation = rotation # <-> (Float(1.0, strict=False)) : Item scale scale = gitem.scale = scale # <-> (Float(1.0, strict=False)) : Item opacity opacity = gitem.opacity = opacity # <-> (Bool()) : Item selected selected = gitem.selected = selected # <-> (Bool(True)) : Item is enabled enabled = gitem.enabled = enabled # <-> (Bool(True)) : Item is visible visible = gitem.visible = visible # <-> (Str()) : Tool tip tool_tip = gitem.tool_tip = tool_tip # <-> (Str()) : Status tip status_tip = gitem.status_tip = status_tip # <-> (Coerced(Feature.Flags)) : Set the extra features to enable for this widget features = gitem.features = features # <-> (Coerced(GraphicFeature.Flags)) : Set the extra features to enable for this widget extra_features = gitem.extra_features = extra_features # <-> (Event()) : Update request_update = gitem.request_update = request_update # <-> (Bool()) : Set whether this item can be selected selectable = gitem.selectable = selectable # <-> (Bool()) : Set whether this item can be moved movable = gitem.movable = movable # Ensure the widget is shown gitem.show() # Ensure the widget is hidden gitem.hide() # Set the keyboard input focus to this widget (DON'T) gitem.set_focus() # Clear the keyboard input focus from this widget (DON'T) gitem.clear_focus() # Test whether this widget has input focus (DON'T) # -> (bool) : # True : if this widget has input focus # False : otherwise focused = gitem.has_focus() # A method invoked when the widget gains input focus (to be reimplemented) gitem.focus_gained() # A method invoked when the widget loses input focus (to be reimplemented) gitem.focus_lost() # A method called at the start of a drag-drop operation (to be reimplemented) # -> (DragData) : An Enaml DragData object which holds the drag data gitem.drag_start() # A method called at the end of a drag-drop operation (to be reimplemented) # drag_data (DragData) : The drag data created by the `drag_start` method # result (DropAction) : The requested drop action when the drop completed gitem.drag_end(drag_data, result) # A method invoked when a drag operation enters the widget (to be reimplemented) # event (DropEvent) : The event representing the drag-drop operation gitem.drag_enter(event) # A method invoked when a drag operation moves in the widget (to be reimplemented) # event (DropEvent) : The event representing the drag-drop operation gitem.drag_move(event) # A method invoked when a drag operation leaves the widget (to be reimplemented) gitem.drag_leave() # A method invoked when the user drops the data on the widget (to be reimplemented) # event (DropEvent) : The event representing the drag-drop operation gitem.drop(event) # A method invoked when a mouse press event occurs in the widget (to be reimplemented) # event (MouseEvent) : The event representing the press operation gitem.mouse_press_event(event) # A method invoked when a mouse move event occurs in the widget (to be reimplemented) # event (MouseEvent) : The event representing the press operation gitem.mouse_move_event(event) # A method invoked when a mouse release event occurs in the widget (to be reimplemented) # event (MouseEvent) : The event representing the press operation gitem.mouse_release_event(event) # A method invoked when a wheel event occurs in the widget (to be reimplemented) # event (WheelEvent) : The event representing the wheel operation gitem.wheel_event(event) # A method invoked when this widget needs to be drawn (to be reimplemented) # painter (Object) : The toolkit dependent painter object # options (Object) : The toolkit dependent options object # widget (Widget) : The underlying widget gitem.draw(painter, options, widget) # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : AbstractGraphicsShapeItem from enamlx.widgets.graphics_view import AbstractGraphicsShapeItem AbstractGraphicsShapeItem: proxy = Typed(ProxyAbstractGraphicsShapeItem) pen = Instance(Pen) brush = Instance(Brush) #GraphicsItem: proxy = Typed(ProxyGraphicsItem) position = PointMember() rotation = Float(strict=False) scale = Float(1.0, strict=False) opacity = Float(1.0, strict=False) selected = Bool() enabled = Bool(True) visible = Bool(True) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) extra_features = Coerced(GraphicFeature.Flags) request_update :: Event() selectable = Bool() movable = Bool() # self.show() self.hide() # focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): wheel_event => (event): draw => (painter, options, widget): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # A common base for all path items # << (GraphicsItem) : agsitem = AbstractGraphicsShapeItem() # <-> (Typed(ProxyAbstractGraphicsShapeItem)) : Proxy reference proxy = agsitem.proxy = proxy # <-> (Instance(Pen)) : Set the pen or "line" style pen = agsitem.pen = pen # <-> (Instance(Brush)) : Set the brush or "fill" style brush = agsitem.brush = brush # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : GraphicsRectItem from enamlx.widgets.api import GraphicsRectItem GraphicsRectItem: proxy = Typed(ProxyGraphicsRectItem) width = Float(10.0, strict=False) height = Float(10.0, strict=False) #AbstractGraphicsShapeItem: proxy = Typed(ProxyAbstractGraphicsShapeItem) pen = Instance(Pen) brush = Instance(Brush) #GraphicsItem: proxy = Typed(ProxyGraphicsItem) position = PointMember() rotation = Float(strict=False) scale = Float(1.0, strict=False) opacity = Float(1.0, strict=False) selected = Bool() enabled = Bool(True) visible = Bool(True) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) extra_features = Coerced(GraphicFeature.Flags) request_update :: Event() selectable = Bool() movable = Bool() # self.show() self.hide() # focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): wheel_event => (event): draw => (painter, options, widget): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractGraphicsShapeItem) : grectitem = GraphicsRectItem() # <-> (Typed(ProxyGraphicsRectItem)) : Proxy reference proxy = grectitem.proxy = proxy # <-> (Float(10.0, strict=False)) : Width width = grectitem.width = width # <-> (Float(10.0, strict=False)) : Height height = grectitem.height = height # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : GraphicsEllipseItem from enamlx.widgets.api import GraphicsEllipseItem GraphicsEllipseItem: proxy = Typed(ProxyGraphicsEllipseItem) width = Float(10.0, strict=False) height = Float(10.0, strict=False) span_angle = Float(360.0, strict=False) start_angle = Float(0.0, strict=False) #AbstractGraphicsShapeItem: proxy = Typed(ProxyAbstractGraphicsShapeItem) pen = Instance(Pen) brush = Instance(Brush) #GraphicsItem: proxy = Typed(ProxyGraphicsItem) position = PointMember() rotation = Float(strict=False) scale = Float(1.0, strict=False) opacity = Float(1.0, strict=False) selected = Bool() enabled = Bool(True) visible = Bool(True) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) extra_features = Coerced(GraphicFeature.Flags) request_update :: Event() selectable = Bool() movable = Bool() # self.show() self.hide() # focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): wheel_event => (event): draw => (painter, options, widget): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractGraphicsShapeItem) : gelpsitem = GraphicsEllipseItem() # <-> (Typed(ProxyGraphicsEllipseItem)) : Proxy reference proxy = gelpsitem.proxy = proxy # <-> (Float(10.0, strict=False)) : Width width = gelpsitem.width = width # <-> (Float(10.0, strict=False)) : Height height = gelpsitem.height = height # <-> (Float(360.0, strict=False)) : Sets the span angle for an ellipse segment to angle span_angle = gelpsitem.span_angle = span_angle # <-> (Float(0.0, strict=False)) : Sets the start angle for an ellipse segment to angle start_angle = gelpsitem.start_angle = start_angle # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : GraphicsPathItem from enamlx.widgets.api import GraphicsPathItem GraphicsPathItem: proxy = Typed(ProxyGraphicsPathItem) path = Value() #AbstractGraphicsShapeItem: proxy = Typed(ProxyAbstractGraphicsShapeItem) pen = Instance(Pen) brush = Instance(Brush) #GraphicsItem: proxy = Typed(ProxyGraphicsItem) position = PointMember() rotation = Float(strict=False) scale = Float(1.0, strict=False) opacity = Float(1.0, strict=False) selected = Bool() enabled = Bool(True) visible = Bool(True) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) extra_features = Coerced(GraphicFeature.Flags) request_update :: Event() selectable = Bool() movable = Bool() # self.show() self.hide() # focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): wheel_event => (event): draw => (painter, options, widget): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractGraphicsShapeItem) : gpitem = GraphicsPathItem() # <-> (Typed(ProxyGraphicsPathItem)) : Proxy reference proxy = gpitem.proxy = proxy # <-> (Value()) : Path path = gpitem.path = path # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : GraphicsLineItem from enamlx.widgets.api import GraphicsLineItem GraphicsLineItem: proxy = Typed(ProxyGraphicsLineItem) point = List(PointMember()) #AbstractGraphicsShapeItem: proxy = Typed(ProxyAbstractGraphicsShapeItem) pen = Instance(Pen) brush = Instance(Brush) #GraphicsItem: proxy = Typed(ProxyGraphicsItem) position = PointMember() rotation = Float(strict=False) scale = Float(1.0, strict=False) opacity = Float(1.0, strict=False) selected = Bool() enabled = Bool(True) visible = Bool(True) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) extra_features = Coerced(GraphicFeature.Flags) request_update :: Event() selectable = Bool() movable = Bool() # self.show() self.hide() # focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): wheel_event => (event): draw => (painter, options, widget): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractGraphicsShapeItem) : glinitem = GraphicsLineItem() # <-> (Typed(ProxyGraphicsLineItem)) : Proxy reference proxy = glinitem.proxy = proxy # <-> (List(PointMember())) : An x,y or x,y,z point point = glinitem.point = point # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : GraphicsTextItem from enamlx.widgets.api import GraphicsTextItem GraphicsTextItem: proxy = Typed(ProxyGraphicsTextItem) text = Str() font = FontMember() #AbstractGraphicsShapeItem: proxy = Typed(ProxyAbstractGraphicsShapeItem) pen = Instance(Pen) brush = Instance(Brush) #GraphicsItem: proxy = Typed(ProxyGraphicsItem) position = PointMember() rotation = Float(strict=False) scale = Float(1.0, strict=False) opacity = Float(1.0, strict=False) selected = Bool() enabled = Bool(True) visible = Bool(True) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) extra_features = Coerced(GraphicFeature.Flags) request_update :: Event() selectable = Bool() movable = Bool() # self.show() self.hide() # focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): wheel_event => (event): draw => (painter, options, widget): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractGraphicsShapeItem) : gtextitem = GraphicsTextItem() # <-> (Typed(ProxyGraphicsTextItem)) : Proxy reference proxy = gtextitem.proxy = proxy # <-> (Str()) : Text text = gtextitem.text = text # <-> (FontMember()) : Font font = gtextitem.font = font # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : GraphicsPolygonItem from enamlx.widgets.api import GraphicsPolygonItem GraphicsPolygonItem: proxy = Typed(ProxyGraphicsPolygonItem) points = List(PointMember()) #AbstractGraphicsShapeItem: proxy = Typed(ProxyAbstractGraphicsShapeItem) pen = Instance(Pen) brush = Instance(Brush) #GraphicsItem: proxy = Typed(ProxyGraphicsItem) position = PointMember() rotation = Float(strict=False) scale = Float(1.0, strict=False) opacity = Float(1.0, strict=False) selected = Bool() enabled = Bool(True) visible = Bool(True) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) extra_features = Coerced(GraphicFeature.Flags) request_update :: Event() selectable = Bool() movable = Bool() # self.show() self.hide() # focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): wheel_event => (event): draw => (painter, options, widget): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (AbstractGraphicsShapeItem) : gpolitem = GraphicsPolygonItem() # <-> (Typed(ProxyGraphicsPolygonItem)) : Proxy reference proxy = gpolitem.proxy = proxy # <-> (List(PointMember())) : A list of (x,y) or (x,y,z) points points = gpolitem.points = points # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : GraphicsImageItem from enamlx.widgets.api import GraphicsImageItem GraphicsImageItem: proxy = Typed(ProxyGraphicsImageItem) image = Instance(Image) #GraphicsItem: proxy = Typed(ProxyGraphicsItem) position = PointMember() rotation = Float(strict=False) scale = Float(1.0, strict=False) opacity = Float(1.0, strict=False) selected = Bool() enabled = Bool(True) visible = Bool(True) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) extra_features = Coerced(GraphicFeature.Flags) request_update :: Event() selectable = Bool() movable = Bool() # self.show() self.hide() # focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): wheel_event => (event): draw => (painter, options, widget): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (GraphicsItem) : giitem = GraphicsImageItem() # <-> (Typed(ProxyGraphicsImageItem)) : Proxy reference proxy = giitem.proxy = proxy # <-> (Instance(Image)) : Image image = giitem.image = image # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : GraphicsItemGroup from enamlx.widgets.api import GraphicsItemGroup GraphicsItemGroup: proxy = Typed(ProxyGraphicsItemGroup) #GraphicsItem: proxy = Typed(ProxyGraphicsItem) position = PointMember() rotation = Float(strict=False) scale = Float(1.0, strict=False) opacity = Float(1.0, strict=False) selected = Bool() enabled = Bool(True) visible = Bool(True) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) extra_features = Coerced(GraphicFeature.Flags) request_update :: Event() selectable = Bool() movable = Bool() # self.show() self.hide() # focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): wheel_event => (event): draw => (painter, options, widget): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # A common base for all path items # << (GraphicsItem) : gigroup = GraphicsItemGroup() # <-> (Typed(ProxyGraphicsItemGroup)) : Proxy reference proxy = gigroup.proxy = proxy # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : GraphicsWidget from enamlx.widgets.api import GraphicsWidget GraphicsWidget: proxy = Typed(ProxyGraphicsWidget) #GraphicsItem: proxy = Typed(ProxyGraphicsItem) position = PointMember() rotation = Float(strict=False) scale = Float(1.0, strict=False) opacity = Float(1.0, strict=False) selected = Bool() enabled = Bool(True) visible = Bool(True) tool_tip = Str() status_tip = Str() features = Coerced(Feature.Flags) extra_features = Coerced(GraphicFeature.Flags) request_update :: Event() selectable = Bool() movable = Bool() # self.show() self.hide() # focus_gained => (): focus_lost => (): drag_start => (): drag_end => (drag_data, result): drag_enter => (event): drag_move => (event): drag_leave => (): drop => (event): mouse_press_event => (event): mouse_move_event => (event): mouse_release_event => (event): wheel_event => (event): draw => (painter, options, widget): #ToolkitObject: activated :: Event() proxy = Typed(ProxyToolkitObject) proxy_is_active = flag_property(ACTIVE_PROXY_FLAG) # self.initialize() self.destroy() self.child_added(child) self.child_removed(child) self.activate_proxy() self.activate_top_down() self.activate_bottom_up() #Declarative: name = Str() initialized :: Event() is_initialized = flag_property() # self.initialize() self.destroy() self.child_added(child) #Object: name = Str() parent = Object() children = List(Object()) is_destroyed = flag_property(DESTROYED_FLAG) destroyed :: Event() # parent_changed => (old, new): child_added => (child): child_moved => (child): child_removed => (child): # self.destroy() self.set_parent(parent) self.insert_children(before, insert) self.root_object() self.traverse(depth_first=False) self.traverse_ancestors(root=None) self.find(name, regex=False) self.find_all(name, regex=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # Use this to embed a widget within a graphics scene # << (GraphicsItem) : gwidget = GraphicsWidget() # <-> (Typed(ProxyGraphicsWidget)) : Proxy reference proxy = gwidget.proxy = proxy # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : Pen from enamlx.widgets.api import Pen Pen: color = ColorMember() width = Float(1.0, strict=False) line_style = Enum('solid', 'dash', 'dot', 'dash_dot', 'dash_dot_dot', 'custom', 'none') cap_style = Enum('square', 'flat', 'round') join_style = Enum('bevel', 'miter', 'round') dash_pattern = List(Float(strict=False)) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (Atom) : pen = Pen() # <-> (ColorMember()) : Color color = pen.color = color # <-> (Float(1.0, strict=False)) : Width width = pen.width = width # <-> (Enum('solid', 'dash', 'dot', 'dash_dot', 'dash_dot_dot', 'custom', 'none')) : Line Style line_style = pen.line_style = line_style # <-> (Enum('square', 'flat', 'round')) : Cap Style cap_style = pen.cap_style = cap_style # <-> (Enum('bevel', 'miter', 'round')) : Join Style join_style = pen.join_style = join_style # <-> (List(Float(strict=False))) : Dash pattern used when line_style is 'custom' dash_pattern = pen.dash_pattern = dash_pattern # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : Brush from enamlx.widgets.api import Brush Brush: color = ColorMember() image = Instance(Image) style = Enum('solid', 'dense1', 'dense2', 'dense3', 'dense4', 'dense5', 'dense6', 'dense7', 'horizontal', 'vertical', 'cross', 'diag', 'bdiag', 'fdiag', 'linear', 'radial', 'conical', 'texture', 'none') #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (Atom) : brsh = Brush() # <-> (ColorMember()) : Color color = brsh.color = color # <-> (Instance(Image)) : image image = brsh.image = image # <-> (Enum('solid', 'dense1', 'dense2', 'dense3', 'dense4', 'dense5', 'dense6', 'dense7', 'horizontal', 'vertical', 'cross', 'diag', 'bdiag', 'fdiag', 'linear', 'radial', 'conical', 'texture', 'none')) : Style style = brsh.style = style # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : Point from enamlx.widgets.api import Point Point: x = Float(0, strict=False) y = Float(0, strict=False) z = Float(0, strict=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (Atom) : pt = Point() # <-> (Float(0, strict=False)) : x position x = pt.x = x # <-> (Float(0, strict=False)) : y position y = pt.y = y # <-> (Float(0, strict=False)) : z position z = pt.z = z pt.__init__ pt.__iter__ pt.__len__ pt.__eq__ pt.__add__ pt.__radd__ pt.__sub__ pt.__rsub__ pt.__mul__ pt.__rmul__ pt.__div__ pt.__rdiv__ pt.__neg__ pt.__hash__ pt.__getitem__ pt.__repr__ # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # EnamlX : Rect from enamlx.widgets.api import Rect Rect: x = Float(0, strict=False) y = Float(0, strict=False) width = Float(0, strict=False) height = Float(0, strict=False) #Atom: self.__init__(**kwargs) self.freeze() self.get_member(member: str) self.has_observer(member: str, func: Callable[[Dict[str, Any]], None]) self.has_observers(member: str) self.notifications_enabled() self.notify(member_name: str, *args, **kwargs) self.observe(member: str, func: Callable[[Dict[str, Any]], None]) self.set_notifications_enabled(enabled: bool) self.unobserve(member: str, func: Callable[[Dict[str, Any]], None]) self.__sizeof__() # # << (Atom) : rct = Rect() # <-> (Float(0, strict=False)) : x = rct.x = x # <-> (Float(0, strict=False)) : y = rct.y = y # <-> (Float(0, strict=False)) : width = rct.width = width # <-> (Float(0, strict=False)) : height = rct.height = height # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
StarcoderdataPython
3239423
<gh_stars>0 from keras.models import Sequential from keras.layers import Dense, Flatten, Conv2D, MaxPool2D, Dropout, ZeroPadding2D def create_mnist_model(xshape): model = Sequential() model.add(ZeroPadding2D(padding=((2, 2), (2, 2)), input_shape=xshape)) model.add(Conv2D(10, 5, activation='relu')) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Conv2D(25, 5, activation='relu')) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Conv2D(100, 4, activation='relu')) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(10, activation='softmax')) return model def create_cifar_model(xshape): model = Sequential() model.add(Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=xshape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(128, (3, 3), activation='relu', padding='same')) model.add(Conv2D(128, (3, 3), activation='relu')) model.add(MaxPool2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) return model
StarcoderdataPython
78060
{ 'variables': { 'target_arch%': 'ia32', 'naclversion': '0.4.5' }, 'targets': [ { 'target_name': 'sodium', 'sources': [ 'sodium.cc', ], "dependencies": [ "<(module_root_dir)/deps/libsodium.gyp:libsodium" ], 'include_dirs': [ './deps/libsodium-<(naclversion)/src/libsodium/include' ], 'cflags!': [ '-fno-exceptions' ], } ] }
StarcoderdataPython
160295
from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render from django.utils.decorators import method_decorator from django.conf.urls import url from ..core.app import ShopKitApp class OrderApp(ShopKitApp): app_name = 'order' namespace = 'order' Order = None DeliveryGroup = None OrderLine = None order_list_templates = [ 'shopkit/order/list.html', ] order_details_templates = [ 'shopkit/order/view.html', ] def __init__(self, **kwargs): super(OrderApp, self).__init__(**kwargs) assert self.Order and self.DeliveryGroup and self.OrderLine, ( 'You need to subclass OrderApp and provide Order,' ' DeliveryGroup and OrderLine.' ) def get_order(self, request, order_token): orders = self.Order.objects.filter( user=request.user if request.user.is_authenticated else None) return get_object_or_404(orders, token=order_token) # Views methods section # --------------------- def get_urls(self): return [ url(r'^$', self.index, name='index'), url(r'^(?P<order_token>[\w-]+)/$', self.details, name='details'), ] @method_decorator(login_required) def index(self, request, **kwargs): orders = self.Order.objects.filter(user=request.user) context = self.get_context_data(request, orders=orders) return render(request, self.order_list_templates, context) def details(self, request, order_token, **kwargs): order = self.get_order(request, order_token=order_token) context = self.get_context_data(request, order=order) return render(request, self.order_details_templates, context)
StarcoderdataPython
141081
DATABASE_NAME = 'telepebble' DATABASE_ALIAS = 'default'
StarcoderdataPython
54778
<filename>extreme_feedback_tts/build_status_enum.py<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- from enum import Enum class BuildStatus( Enum ): Success = 1 Failed = 2 Running = 3 Unavailable = 4 @classmethod def has_value( cls, value ): return any( BuildStatus( value ) == BuildStatus( e.value ) for e in cls )
StarcoderdataPython
1668743
# coding=utf-8 from OTLMOW.OTLModel.BaseClasses.OTLAttribuut import OTLAttribuut from OTLMOW.OTLModel.Classes.Verlichtingstoestel import Verlichtingstoestel from OTLMOW.OTLModel.Datatypes.KwantWrdInMeter import KwantWrdInMeter # Generated with OTLClassCreator. To modify: extend, do not edit class VerlichtingstoestelTL(Verlichtingstoestel): """Het geheel van de TL-lamp en de behuizing die werden samengesteld met als doel:* de lichtstroom van de lichtbronnen hoofdzakelijk op het te verlichten oppervlak (doorlopende wegsectie, conflictgebied,...) te richten, teneinde de zichtbaarheid te verhogen;* de lichtstroom te beheersen zodat de weggebruikers niet verblind worden en de lichthinder beperkt wordt;* het optisch systeem, de lichtbronnen en de hulpapparatuur tegen uitwendige invloeden te beschermen""" typeURI = 'https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#VerlichtingstoestelTL' """De URI van het object volgens https://www.w3.org/2001/XMLSchema#anyURI.""" def __init__(self): super().__init__() self._lichtpuntHoogte = OTLAttribuut(field=KwantWrdInMeter, naam='lichtpuntHoogte', label='lichtpunt hoogte', objectUri='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#VerlichtingstoestelTL.lichtpuntHoogte', definition='Hoogte van het lichtpunt ten opzichte van de rijweg.', owner=self) @property def lichtpuntHoogte(self): """Hoogte van het lichtpunt ten opzichte van de rijweg.""" return self._lichtpuntHoogte.get_waarde() @lichtpuntHoogte.setter def lichtpuntHoogte(self, value): self._lichtpuntHoogte.set_waarde(value, owner=self)
StarcoderdataPython
1663984
<gh_stars>1000+ __author__ = "<NAME>" import numpy as np from theano import config from theano import function from theano import tensor as T from pylearn2.sandbox.lisa_rl.bandit.environment import Environment from pylearn2.utils import sharedX from pylearn2.utils.rng import make_np_rng, make_theano_rng class GaussianBandit(Environment): """ An n-armed bandit whose rewards are drawn from a different Gaussian distribution for each arm. The mean and standard deviation of the reward for each arm is drawn at initialization time from N(0, <corresponding std arg>). (For the standard deviation we use the absolute value of the Gaussian sample) .. todo:: WRITEME : parameter list """ def __init__(self, num_arms, mean_std = 1.0, std_std = 1.0): self.rng = make_np_rng(None, [2013, 11, 12], which_method="randn") self.means = sharedX(self.rng.randn(num_arms) * mean_std) self.stds = sharedX(np.abs(self.rng.randn(num_arms) * std_std)) self.theano_rng = make_theano_rng(None, self.rng.randint(2 ** 16), which_method="normal") def get_action_func(self): """ Returns a theano function that takes an action and returns a reward. """ action = T.iscalar() reward_mean = self.means[action] reward_std = self.stds[action] reward = self.theano_rng.normal(avg=reward_mean, std=reward_std, dtype=config.floatX, size=reward_mean.shape) rval = function([action], reward) return rval
StarcoderdataPython
3275638
<reponame>SLieng/vim_snippets from snp.src.ᗰ͈ import ᗰ͈
StarcoderdataPython
3238551
<filename>reporting/models.py from django.db import models from django.urls import reverse class Product(models.Model): """ Model representing a vendors product """ asin = models.CharField('ASIN',max_length=50, help_text="ASIN for the product", primary_key=True) product_name = models.CharField('Product Name',max_length=200, help_text="ASIN Name for the product", null=True, blank=True) warehouse_units = models.IntegerField(help_text='Units stored at Amazon Warehouse', null=True, blank=True) external_id = models.CharField(max_length=200, help_text='External ID', null=True, blank=True) released = models.DateField(help_text='Date Released',null=True, blank=True) list_price = models.FloatField(help_text='List Price',null=True, blank=True) product_group = models.CharField(max_length=200, help_text='Product Group', null=True, blank=True) category = models.CharField(max_length=100, help_text='Category', null=True, blank=True) sub_category = models.CharField(max_length=150, help_text='Sub Category', null=True, blank=True) model_number = models.CharField(max_length=150, help_text='Model Number', null=True, blank=True) catalog_number = models.CharField(max_length=150, help_text='Catalog Number', null=True, blank=True) replenishment_code = models.CharField(max_length=150, help_text='Replenishment Code', null=True, blank=True) page_view_rank = models.IntegerField(help_text='Page View Rank', null=True, blank=True) brand_code = models.CharField(max_length=50, help_text='Brand Code', null=True, blank=True) vendor = models.CharField(max_length=50, help_text='Vendor') def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.asin class Meta: permissions = (('can_input_data', "Able to Input Data"),) class SalesDiagnostic(models.Model): """ Model representing a sales Diagnostic entry """ asin = models.CharField('ASIN',max_length=50, help_text="ASIN for the product") date = models.DateField(help_text='Date Released') asin_date = models.CharField('ASIN_Date Combined',max_length=50, help_text="ASIN_Date Combo for the entry", primary_key=True) product_name = models.CharField('Product Name',max_length=200, help_text="ASIN Name for the product", null=True, blank=True) shipped_cogs = models.DecimalField(help_text='Shipped Cost of Goods Sold',max_digits=14, decimal_places=2,null=True, blank=True) shipped_cogs_perc = models.DecimalField(help_text='Shipped Cost of Goods Sold Percentage of Total',max_digits=8, decimal_places=5,null=True, blank=True) shipped_cogs_prior_period = models.DecimalField(help_text='Shipped Cost of Goods Sold Change From Prior Period',max_digits=14, decimal_places=2,null=True, blank=True) shipped_cogs_last_year = models.DecimalField(help_text='Shipped Cost of Goods Sold Change From Last Year',max_digits=8, decimal_places=5,null=True, blank=True) shipped_units = models.IntegerField(help_text='Shipped Units', null=True, blank=True) shipped_units_perc = models.DecimalField(help_text='Shipped Units Percentage of Total',max_digits=8, decimal_places=5,null=True, blank=True) shipped_units_prior_period = models.DecimalField(help_text='Shipped Units Change From Prior Period',max_digits=14, decimal_places=2,null=True, blank=True) shipped_units_last_year = models.DecimalField(help_text='Shipped Units Change From Last Year',max_digits=8, decimal_places=5,null=True, blank=True) customer_returns = models.IntegerField(help_text='Customer Returns', null=True, blank=True) free_replacements = models.IntegerField(help_text='Free Replacements', null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.DO_NOTHING, default="") def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.asin class Meta: permissions = (('can_input_data', "Able to Input Data"),) class InventoryHealth(models.Model): """ Model representing an Inventry Health entry """ asin = models.CharField('ASIN',max_length=50, help_text="ASIN for the product") date = models.DateField(help_text='Date Released') asin_date = models.CharField('ASIN_Date Combined',max_length=50, help_text="ASIN_Date Combo for the entry", primary_key=True) product_name = models.CharField('Product Name',max_length=200, help_text="ASIN Name for the product", null=True, blank=True) net_received = models.DecimalField(help_text='Net Received Money',max_digits=14, decimal_places=2,null=True, blank=True) net_received_units = models.IntegerField(help_text='Net Received Units', null=True, blank=True) sell_through_rate = models.DecimalField(help_text='Sell-Through Rate',max_digits=8, decimal_places=5,null=True, blank=True) open_purchase_oq = models.IntegerField(help_text='Open Purchase Order Quantity', null=True, blank=True) sellable_oh_inven = models.DecimalField(help_text='Sellable On Hand Inventory',max_digits=14, decimal_places=2,null=True, blank=True) sellable_oh_inven_trail = models.DecimalField(help_text='Sellable On Hand Inventory - Trailing 30-day Average',max_digits=14, decimal_places=2,null=True, blank=True) sellable_oh_units = models.IntegerField(help_text='Sellable On Hand Units', null=True, blank=True) unsellable_oh_inven = models.DecimalField(help_text='Unsellable On Hand Inventory',max_digits=14, decimal_places=2,null=True, blank=True) unsellable_oh_inven_trail = models.DecimalField(help_text='Unsellable On Hand Inventory - Trailing 30-day Average',max_digits=14, decimal_places=2,null=True, blank=True) unsellable_oh_units = models.IntegerField(help_text='Unsellable On Hand Units', null=True, blank=True) aged_90_sellable = models.DecimalField(help_text='Aged 90+ Days Sellable Inventory',max_digits=14, decimal_places=2,null=True, blank=True) aged_90_sellable_trail = models.DecimalField(help_text='Aged 90+ Days Sellable Inventory - Trailing 30-day Average',max_digits=14, decimal_places=2,null=True, blank=True) aged_90_sellable_units = models.IntegerField(help_text='Aged 90+ Days Sellable Units', null=True, blank=True) repl_category = models.CharField(max_length=70, help_text="Replenishment Category") def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.asin class Meta: permissions = (('can_input_data', "Able to Input Data"),) class SponsoredProduct(models.Model): """ Model representing a Sponsored Product entry """ start_date = models.DateField(help_text='Start Date of Campaign') end_date = models.DateField(help_text='End Date of Campaign') currency = models.CharField(max_length=10, help_text="Currency", null=True, blank=True) campaign_name = models.CharField(max_length=150, help_text="Campaign Name", null=True, blank=True) asin = models.CharField(max_length=150, help_text="Campaign Name") impressions = models.IntegerField(help_text='Impressions', null=True, blank=True) clicks = models.IntegerField(help_text='Clicks', null=True, blank=True) ctr = models.DecimalField(help_text='Click-Thru Rate (CTR)',max_digits=8, decimal_places=5, null=True, blank=True) cpc = models.DecimalField(help_text='Cost Per Click (CPC)',max_digits=8, decimal_places=5, null=True, blank=True) spend = models.DecimalField(help_text='Spend',max_digits=8, decimal_places=5, null=True, blank=True) f_day_sales = models.DecimalField(help_text='Spend',max_digits=11, decimal_places=2, null=True, blank=True) acos = models.DecimalField(help_text='Total Advertising Cost of Sales (ACoS)',max_digits=8, decimal_places=5, null=True, blank=True) raos = models.DecimalField(help_text='Total Return on Advertising Spend (RoAS)',max_digits=8, decimal_places=2, null=True, blank=True) f_day_orders = models.IntegerField(help_text='14 Day Total Orders (#)', null=True, blank=True) f_day_units = models.IntegerField(help_text='14 Day Total Units (#)', null=True, blank=True) f_day_conv_rate = models.DecimalField(help_text='14 Day Conversion Rate',max_digits=8, decimal_places=2, null=True, blank=True) campasin = models.CharField(max_length=150, help_text="Campaign Name ASIN Combo", primary_key=True) def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.campasin class Meta: permissions = (('can_input_data', "Able to Input Data"),) class InventoryForecast(models.Model): """ Model representing a Sponsored Product entry """ asin = models.CharField('ASIN',max_length=50, help_text="ASIN for the product") date = models.DateField(help_text='Date Released') asin_date = models.CharField('ASIN_Date Combined',max_length=50, help_text="ASIN_Date Combo for the entry", primary_key=True) week_forecast = models.IntegerField(help_text='Weekly Inventory Forecast', null=True, blank=True) week2_forecast = models.IntegerField(help_text='Next Weeks Inventory Forecast', null=True, blank=True) week3_forecast = models.IntegerField(help_text='3 Weeks Out Inventory Forecast', null=True, blank=True) week4_forecast = models.IntegerField(help_text='4 Weeks Out Inventory Forecast', null=True, blank=True) week5_forecast = models.IntegerField(help_text='5 Weeks Out Inventory Forecast', null=True, blank=True) def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.asin class Meta: permissions = (('can_input_data', "Able to Input Data"),) class Headers(models.Model): """ Model representing the header dictionary """ amazon_header = models.CharField('Amazon Header', max_length=200, help_text='Amazon CSV Header', primary_key=True) database_header = models.CharField('Database Header', max_length=200, help_text='Database Header') def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.amazon_header class Meta: permissions = (('can_add_new_headers', "Able to Amend Amazon Database Headers"),) class Checks(models.Model): """ Model representing the checks dictionary """ amazon_header = models.CharField('Amazon Header', max_length=200, help_text='Amazon CSV Header', primary_key=True) file_type = models.CharField('File Type', max_length=200, help_text='File') def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.amazon_header class Meta: permissions = (('can_add_new_checks', "Able to Amend Amazon Database Checks"),) class VendorASIN(models.Model): """ Model representing ASIN checks to determine vendor """ asin = models.CharField('ASIN',max_length=50, help_text="ASIN for the product", primary_key=True) vendor = models.CharField('Vendor',max_length=50, help_text="Vendor for the ASIN") def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.asin class Meta: permissions = (('can_add_new_vendors', "Able to add Vendor ASIN Checks"),)
StarcoderdataPython
76676
<filename>weather/services/sun.py import datetime import time from typing import Dict import aiohttp def _utc_to_local(date: str) -> datetime.datetime: """Converts utl to local datetime.""" now_timestamp = time.time() return datetime.datetime.strptime(date, "%I:%M:%S %p") + ( datetime.datetime.fromtimestamp(now_timestamp) - datetime.datetime.utcfromtimestamp(now_timestamp) ) async def today(latitude: float, longitude: float) -> Dict[str, str]: """Returns sunrise/sunset for today.""" async with aiohttp.ClientSession() as session: async with session.get( f"https://api.sunrise-sunset.org/json?lat={latitude}&lng={longitude}" ) as response: response.raise_for_status() data = await response.json() sun_data = data.get("results", {}) for key, value in tuple(sun_data.items()): # type: str, str if "AM" not in value and "PM" not in value: continue sun_data[key] = datetime.datetime.strftime( _utc_to_local(value), "%I:%M:%S %p" ) return sun_data
StarcoderdataPython
1656833
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from metascrape import utils import mock import unittest class UtilsTestCase(unittest.TestCase): def test_extract_headers(self): mock_response = mock.Mock() mock_response.headers = { "Accept-Ranges": "none", "Connection": "close", "Content-Length": "230", "Content-Type": "text/plain", "Date": "Mon, 15 Jul 2019 19:43:30 GMT", "Etag": "abcdefg", "Last-Modified": "Thu, 11 Jul 2019 23:18:47 GMT", "Server": "EC2ws", } result = utils.extract_headers(mock_response) self.assertNotIn('Content-Length', result.keys()) self.assertNotIn('Date', result.keys()) self.assertNotIn('Etag', result.keys()) self.assertNotIn('Last-Modified', result.keys()) self.assertIn('Server', result.keys())
StarcoderdataPython
17636
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup setup(name='starsearch', version='0.3', description='Package to dig into the ESO archives', author='<NAME>', author_email='<EMAIL>', license='MIT', url='https://github.com/jdavidrcamacho/starsearch', packages=['starsearch'], install_requires=[ 'numpy', 'astroquery', "astropy", ], )
StarcoderdataPython
77544
# make sure configure registrations are executed from . import deserialize_content # noqa from . import deserialize_value # noqa from . import serialize_content # noqa from . import serialize_schema # noqa from . import serialize_schema_field # noqa from . import serialize_value # noqa
StarcoderdataPython
30730
<reponame>gexahedron/pytti from pytti.LossAug import MSELoss, LatentLoss import sys, os, gc import argparse import os import cv2 import glob import math, copy import numpy as np import torch from torch import nn from torch.nn import functional as F from PIL import Image import imageio import matplotlib.pyplot as plt from pytti.Notebook import Rotoscoper from torchvision.transforms import functional as TF os.chdir('GMA') try: sys.path.append('core') from network import RAFTGMA from utils import flow_viz from utils.utils import InputPadder finally: os.chdir('..') from pytti.Transforms import apply_flow from pytti import fetch, to_pil, DEVICE, vram_usage_mode from pytti.Image.RGBImage import RGBImage GMA = None def init_GMA(checkpoint_path): global GMA if GMA is None: with vram_usage_mode('GMA'): parser = argparse.ArgumentParser() parser.add_argument('--model', help="restore checkpoint", default=checkpoint_path) parser.add_argument('--model_name', help="define model name", default="GMA") parser.add_argument('--path', help="dataset for evaluation") parser.add_argument('--num_heads', default=1, type=int, help='number of heads in attention and aggregation') parser.add_argument('--position_only', default=False, action='store_true', help='only use position-wise attention') parser.add_argument('--position_and_content', default=False, action='store_true', help='use position and content-wise attention') parser.add_argument('--mixed_precision', action='store_true', help='use mixed precision') args = parser.parse_args([]) GMA = torch.nn.DataParallel(RAFTGMA(args)) GMA.load_state_dict(torch.load(checkpoint_path)) GMA.to(DEVICE) GMA.eval() def sample(tensor, uv, device=DEVICE): height, width = tensor.shape[-2:] max_pos = torch.tensor([width-1,height-1], device=device).view(2,1,1) grid = uv.div(max_pos/2).sub(1).movedim(0,-1).unsqueeze(0) return F.grid_sample(tensor.unsqueeze(0), grid, align_corners = True).squeeze(0) class TargetFlowLoss(MSELoss): def __init__(self, comp, weight = 0.5, stop = -math.inf, name = "direct target loss", image_shape = None): super().__init__(comp, weight, stop, name, image_shape) with torch.no_grad(): self.register_buffer('last_step', comp.clone()) self.mag = 1 @torch.no_grad() def set_target_flow(self, flow, device=DEVICE): self.comp.set_(flow.movedim(-1,1).to(device, memory_format = torch.channels_last)) self.mag = float(torch.linalg.norm(self.comp, dim = 1).square().mean()) @torch.no_grad() def set_last_step(self, last_step_pil, device = DEVICE): last_step = TF.to_tensor(last_step_pil).unsqueeze(0).to(device, memory_format = torch.channels_last) self.last_step.set_(last_step) def get_loss(self, input, img, device=DEVICE): os.chdir('GMA') try: init_GMA('checkpoints/gma-sintel.pth') image1 = self.last_step image2 = input padder = InputPadder(image1.shape) image1, image2 = padder.pad(image1, image2) _, flow = GMA(image1, image2, iters=3, test_mode=True) flow = flow.to(device, memory_format = torch.channels_last) finally: os.chdir('..') return super().get_loss(TF.resize(flow, self.comp.shape[-2:]), img)/self.mag class OpticalFlowLoss(MSELoss): @staticmethod @torch.no_grad() def motion_edge_map(flow_forward, flow_backward, img, border_mode = 'smear', sampling_mode = 'bilinear',device=DEVICE): # algorithm based on https://github.com/manuelruder/artistic-videos/blob/master/consistencyChecker/consistencyChecker.cpp # reimplemented in pytorch by <NAME> # // consistencyChecker # // Check consistency of forward flow via backward flow. # // # // (c) <NAME>, <NAME>, <NAME> 2016 dx_ker = torch.tensor([[[[0,0,0],[1,0,-1],[0, 0,0]]]], device = device).float().div(2).repeat(2,2,1,1) dy_ker = torch.tensor([[[[0,1,0],[0,0, 0],[0,-1,0]]]], device = device).float().div(2).repeat(2,2,1,1) f_x = nn.functional.conv2d(flow_backward, dx_ker, padding='same') f_y = nn.functional.conv2d(flow_backward, dy_ker, padding='same') motionedge = torch.cat([f_x,f_y]).square().sum(dim=(0,1)) height, width = flow_forward.shape[-2:] y,x = torch.meshgrid([torch.arange(0,height), torch.arange(0,width)]) x = x.to(device) y = y.to(device) p1 = torch.stack([x,y]) v1 = flow_forward.squeeze(0) p0 = p1 + flow_backward.squeeze() v0 = sample(v1, p0) p1_back = p0 + v0 v1_back = flow_backward.squeeze(0) r1 = torch.floor(p0) r2 = r1 + 1 max_pos = torch.tensor([width-1,height-1], device=device).view(2,1,1) min_pos = torch.tensor([0, 0], device=device).view(2,1,1) overshoot = torch.logical_or(r1.lt(min_pos),r2.gt(max_pos)) overshoot = torch.logical_or(overshoot[0],overshoot[1]) missed = (p1_back - p1).square().sum(dim=0).ge(torch.stack([v1_back,v0]).square().sum(dim=(0,1)).mul(0.01).add(0.5)) motion_boundary = motionedge.ge(v1_back.square().sum(dim=0).mul(0.01).add(0.002)) reliable = torch.ones((height, width), device=device) reliable[motion_boundary] = 0 reliable[missed] = -1 reliable[overshoot] = 0 mask = TF.gaussian_blur(reliable.unsqueeze(0), 3).clip(0,1) return mask @staticmethod @torch.no_grad() def get_flow(image1, image2, device=DEVICE): os.chdir('GMA') try: init_GMA('checkpoints/gma-sintel.pth') if isinstance(image1, Image.Image): image1 = TF.to_tensor(image1).unsqueeze(0).to(device) if isinstance(image2, Image.Image): image2 = TF.to_tensor(image2).unsqueeze(0).to(device) padder = InputPadder(image1.shape) image1, image2 = padder.pad(image1, image2) flow_low, flow_up = GMA(image1, image2, iters=12, test_mode=True) finally: os.chdir('..') return flow_up def __init__(self, comp, weight = 0.5, stop = -math.inf, name = "direct target loss", image_shape = None): super().__init__(comp, weight, stop, name, image_shape) with torch.no_grad(): self.latent_loss = MSELoss(comp.new_zeros((1,1,1,1)), weight, stop, name, image_shape) self.register_buffer('bg_mask',comp.new_zeros((1,1,1,1))) @torch.no_grad() def set_flow(self, frame_prev, frame_next, img, path, border_mode = 'smear', sampling_mode = 'bilinear', device = DEVICE): if path is not None: img = img.clone() state_dict = torch.load(path) img.load_state_dict(state_dict) gc.collect() torch.cuda.empty_cache() image1 = TF.to_tensor(frame_prev).unsqueeze(0).to(device) image2 = TF.to_tensor(frame_next).unsqueeze(0).to(device) if self.bg_mask.shape[-2:] != image1.shape[-2:]: bg_mask = TF.resize(self.bg_mask, image1.shape[-2:]) self.bg_mask.set_(bg_mask) noise = torch.empty_like(image2) noise.normal_(mean = 0, std = 0.05) noise.mul_(self.bg_mask) #adding the same noise vectors to both images forces #the flow model to match those parts of the frame, effectively #disabling the flow in those areas. image1.add_(noise) image2.add_(noise) # bdy = image2.clone().squeeze(0).mean(dim = 0) # h, w = bdy.shape # s = 4 # bdy[s:-s,s:-s] = 0 # mean = bdy.sum().div(w*h - (w-2*s)*(h-s*2)) # overlay = image2.gt(0.5) if mean > 0.5 else image2.lt(0.5) # noise = torch.empty_like(image2) # noise.normal_(mean = 0, std = 0.05) # noise[torch.logical_not(overlay)] = 0 # image1.add_(noise) # image2.add_(noise) flow_forward = OpticalFlowLoss.get_flow(image1, image2) flow_backward = OpticalFlowLoss.get_flow(image2, image1) unwarped_target_direct = img.decode_tensor() flow_target_direct = apply_flow(img, -flow_backward, border_mode = border_mode, sampling_mode = sampling_mode) fancy_mask = OpticalFlowLoss.motion_edge_map(flow_forward, flow_backward, img, border_mode, sampling_mode) target_direct = flow_target_direct target_latent = img.get_latent_tensor(detach = True) mask = fancy_mask.unsqueeze(0) self.comp.set_(target_direct) self.latent_loss.comp.set_(target_latent) self.set_flow_mask(mask) array = flow_target_direct.squeeze(0).movedim(0,-1).mul(255).clamp(0, 255).cpu().detach().numpy().astype(np.uint8)[:,:,:] return Image.fromarray(array), fancy_mask @torch.no_grad() def set_flow_mask(self,mask): super().set_mask(TF.resize(mask, self.comp.shape[-2:])) if mask is not None: self.latent_loss.set_mask(TF.resize(mask, self.latent_loss.comp.shape[-2:])) else: self.latent_loss.set_mask(None) @torch.no_grad() def set_mask(self, mask, inverted = False, device = DEVICE): if isinstance(mask, str) and mask != '': if mask[0] == '-': mask = mask[1:] inverted = True if mask.strip()[-4:] == '.mp4': r = Rotoscoper(mask,self) r.update(0) return mask = Image.open(fetch(mask)).convert('L') if isinstance(mask, Image.Image): with vram_usage_mode('Masks'): mask = TF.to_tensor(mask).unsqueeze(0).to(device, memory_format = torch.channels_last) if mask not in ['',None]: #this is where the inversion is. This mask is naturally inverted :) #since it selects the background self.bg_mask.set_(mask if inverted else (1-mask)) def get_loss(self, input, img): l1 = super().get_loss(input, img) l2 = self.latent_loss.get_loss(img.get_latent_tensor(), img) #print(float(l1),float(l2)) return l1+l2*img.latent_strength
StarcoderdataPython
3276081
""" This is the PyTurbSim python advanced programming interface (API). This module provides a fully-customizable high-level object-oriented interface to the PyTurbSim program. The four components of this API are: 1) The :class:`tsrun <pyts.main.tsrun>` class, which is the controller/run object for PyTurbSim simulations. 2) The :class:`tsGrid <pyts.base.tsGrid>` class, which is used to define the TurbSim grid. 3) The 'model' classes, which include: a) :mod:`profModels <pyts.profModels>` (aliased here as 'pm'), contains the mean velocity profile models. b) :mod:`.specModels` (aliased here as 'sm'), contains the TKE spectral models. c) :mod:`.stressModels` (aliased here as 'rm'), contains the Reynold's stress profile models. d) :mod:`.cohereModels` (aliased here as 'cm'), contains the spatial coherence models. 4) The :mod:`io` module, which supports reading and writing of TurbSim input (.inp) and output files (e.g. .bl, .wnd, etc.) Example usage of this API can be found in the <pyts_root>/Examples/api.py file. .. literalinclude:: ../../../examples/api.py """ from main import tsrun from base import tsGrid import profModels.api as profModels import specModels.api as specModels import cohereModels.api as cohereModels import stressModels.api as stressModels import io # Set aliases to the model modules: pm=profModels sm=specModels cm=cohereModels rm=stressModels
StarcoderdataPython
1794099
<reponame>sundarsrst/pytablewriter<filename>pytablewriter/error.py # encoding: utf-8 """ .. codeauthor:: <NAME> <<EMAIL>> """ from __future__ import absolute_import class NotSupportedError(Exception): pass class EmptyTableNameError(Exception): """ Exception raised when a table writer class of the |table_name| attribute is null and the class is not accepted null |table_name|. """ class EmptyHeaderError(Exception): """ Exception raised when a table writer class of the |headers| attribute is null, and the class is not accepted null |headers|. """ class EmptyValueError(Exception): """ Exception raised when a table writer class of the |value_matrix| attribute is null, and the class is not accepted null |value_matrix|. """ class EmptyTableDataError(Exception): """ Exception raised when a table writer class of the |headers| and |value_matrix| attributes are null. """ class WriterNotFoundError(Exception): """ Exception raised when appropriate loader writer found. """
StarcoderdataPython
1750598
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Authors: dr-prodigy <<EMAIL>> (c) 2017-2022 # ryanss <<EMAIL>> (c) 2014-2017 # Website: https://github.com/dr-prodigy/python-holidays # License: MIT (see LICENSE file) import unittest import warnings from datetime import date import holidays class TestCZ(unittest.TestCase): def setUp(self): self.holidays = holidays.CZ() def test_2017(self): # http://www.officeholidays.com/countries/czech_republic/2017.php self.assertIn(date(2017, 1, 1), self.holidays) self.assertIn(date(2017, 4, 14), self.holidays) self.assertIn(date(2017, 4, 17), self.holidays) self.assertIn(date(2017, 5, 1), self.holidays) self.assertIn(date(2017, 5, 8), self.holidays) self.assertIn(date(2017, 7, 5), self.holidays) self.assertIn(date(2017, 7, 6), self.holidays) self.assertIn(date(2017, 9, 28), self.holidays) self.assertIn(date(2017, 10, 28), self.holidays) self.assertIn(date(2017, 11, 17), self.holidays) self.assertIn(date(2017, 12, 24), self.holidays) self.assertIn(date(2017, 12, 25), self.holidays) self.assertIn(date(2017, 12, 26), self.holidays) def test_others(self): self.assertIn(date(1991, 5, 9), self.holidays) def test_older_years(self): self.assertNotIn(date(1950, 5, 1), self.holidays) self.assertNotIn(date(1991, 5, 8), self.holidays) self.assertIn(date(1990, 5, 9), self.holidays) self.assertNotIn(date(1946, 5, 9), self.holidays) self.assertNotIn(date(1950, 7, 5), self.holidays) self.assertNotIn(date(1950, 10, 28), self.holidays) self.assertNotIn(date(1989, 11, 17), self.holidays) self.assertNotIn(date(1989, 12, 24), self.holidays) self.assertNotIn(date(1950, 12, 25), self.holidays) self.assertNotIn(date(1950, 12, 26), self.holidays)
StarcoderdataPython
1732673
<reponame>voussoir/voussoirk import math import re import sys from voussoirkit import pipeable def hms_to_seconds(hms) -> float: ''' Convert hh:mm:ss string to an integer or float of seconds. ''' parts = hms.split(':') seconds = 0 if len(parts) > 3: raise ValueError(f'{hms} doesn\'t match the HH:MM:SS format.') if len(parts) == 3: seconds += int(parts[0]) * 3600 parts.pop(0) if len(parts) == 2: seconds += int(parts[0]) * 60 parts.pop(0) if len(parts) == 1: seconds += float(parts[0]) return seconds def hms_letters_to_seconds(hms) -> float: match = re.match(r'(?:(\d+)h)?(?:(\d+)m)?(\d+)s?', hms.strip()) if not match: raise ValueError(f'{hms} does not match 00h00m00s pattern') (hours, minutes, seconds) = match.groups() seconds = int(seconds) if hours: seconds += int(hours) * 3600 if minutes: seconds += int(minutes) * 60 return seconds def seconds_to_hms(seconds, force_minutes=False, force_hours=False) -> str: ''' Convert integer number of seconds to an hh:mm:ss string. Only the necessary fields are used. ''' seconds = math.ceil(seconds) (minutes, seconds) = divmod(seconds, 60) (hours, minutes) = divmod(minutes, 60) parts = [] if hours or force_hours: parts.append(hours) if hours or minutes or force_hours or force_minutes: parts.append(minutes) parts.append(seconds) hms = ':'.join(f'{part:02d}' for part in parts) return hms def seconds_to_hms_letters(seconds, force_minutes=False, force_hours=False) -> str: seconds = math.ceil(seconds) (minutes, seconds) = divmod(seconds, 60) (hours, minutes) = divmod(minutes, 60) parts = [] if hours or force_hours: parts.append(f'{hours:02d}h') if hours or minutes or force_hours or force_minutes: parts.append(f'{minutes:02d}m') parts.append(f'{seconds:02d}s') hms = ''.join(parts) return hms def main(args): lines = pipeable.input_many(args, strip=True, skip_blank=True) for line in lines: if ':' in line: line = hms_to_seconds(line) if 's' in line: line = hms_letters_to_seconds(line) else: line = float(line) if line > 60: line = seconds_to_hms(line) pipeable.stdout(line) if __name__ == '__main__': raise SystemExit(main(sys.argv[1:]))
StarcoderdataPython
1676224
import tensorflow as tf from tensorflow_probability import edward2 as ed N = 10000 car_door = ed.Categorical(probs=tf.constant([1. / 3., 1. / 3., 1. / 3.]), sample_shape = N, name = 'car_door') picked_door = ed.Categorical(probs=tf.constant([1. / 3., 1. / 3., 1. / 3.]), sample_shape = N, name = 'picked_door') preference = ed.Bernoulli(probs=tf.constant(0.5), sample_shape = N, name = 'preference') host_choice = tf.where(tf.not_equal(car_door, picked_door), 3 - car_door - picked_door, tf.where(tf.equal(car_door, 2 * tf.ones(N, dtype=tf.int32)), preference, tf.where(tf.equal(car_door, tf.ones(N, dtype=tf.int32)), 2 * preference, 1 + preference)), name = 'host_choice') #changed_door = 3 - host_choice - picked_door changed_door = tf.subtract(tf.subtract(3, host_choice), picked_door, name = 'changed_door') writer = tf.summary.FileWriter('./graphs_tfp', tf.get_default_graph()) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) car_door_samples, picked_door_samples, changed_door_samples = sess.run([car_door, picked_door, changed_door]) writer.close() print("probability to win of a player who stays with the initial choice:", (car_door_samples == picked_door_samples).mean()) print("probability to win of a player who switches:", (car_door_samples == changed_door_samples).mean())
StarcoderdataPython
163873
<filename>test/common/test_group_by.py<gh_stars>1-10 from inspect import isgenerator from stograde.common.group_by import group_by def test_group_by(): assert isgenerator(group_by([1, 2, 3], lambda s: s % 2 == 0)) assert dict(group_by(['1', '2', '3'], lambda s: s.isdigit())) == {True: ['1', '2', '3']} assert dict(group_by( [{'a': 1}, {'a': 2}, {'a': 1}], lambda i: i['a'])) == {1: [{'a': 1}, {'a': 1}], 2: [{'a': 2}]}
StarcoderdataPython
199095
from CyberSource import * import os import json from importlib.machinery import SourceFileLoader config_file = os.path.join(os.getcwd(), "data", "Configuration.py") configuration = SourceFileLoader("module.name", config_file).load_module() # To delete None values in Input Request Json body def del_none(d): for key, value in list(d.items()): if value is None: del d[key] elif isinstance(value, dict): del_none(value) return d def create_customer_payment_instrument_pinless_debit(): customerTokenId = "AB695DA801DD1BB6E05341588E0A3BDC" cardExpirationMonth = "12" cardExpirationYear = "2031" cardType = "001" cardIssueNumber = "01" cardStartMonth = "01" cardStartYear = "2020" cardUseAs = "pinless debit" card = Tmsv2customersEmbeddedDefaultPaymentInstrumentCard( expiration_month = cardExpirationMonth, expiration_year = cardExpirationYear, type = cardType, issue_number = cardIssueNumber, start_month = cardStartMonth, start_year = cardStartYear, use_as = cardUseAs ) billToFirstName = "John" billToLastName = "Doe" billToCompany = "CyberSource" billToAddress1 = "1 Market St" billToLocality = "San Francisco" billToAdministrativeArea = "CA" billToPostalCode = "94105" billToCountry = "US" billToEmail = "<EMAIL>" billToPhoneNumber = "4158880000" billTo = Tmsv2customersEmbeddedDefaultPaymentInstrumentBillTo( first_name = billToFirstName, last_name = billToLastName, company = billToCompany, address1 = billToAddress1, locality = billToLocality, administrative_area = billToAdministrativeArea, postal_code = billToPostalCode, country = billToCountry, email = billToEmail, phone_number = billToPhoneNumber ) instrumentIdentifierId = "7010000000016241111" instrumentIdentifier = Tmsv2customersEmbeddedDefaultPaymentInstrumentInstrumentIdentifier( id = instrumentIdentifierId ) requestObj = PostCustomerPaymentInstrumentRequest( card = card.__dict__, bill_to = billTo.__dict__, instrument_identifier = instrumentIdentifier.__dict__ ) requestObj = del_none(requestObj.__dict__) requestObj = json.dumps(requestObj) try: config_obj = configuration.Configuration() client_config = config_obj.get_configuration() api_instance = CustomerPaymentInstrumentApi(client_config) return_data, status, body = api_instance.post_customer_payment_instrument(customerTokenId, requestObj) print("\nAPI RESPONSE CODE : ", status) print("\nAPI RESPONSE BODY : ", body) return return_data except Exception as e: print("\nException when calling CustomerPaymentInstrumentApi->post_customer_payment_instrument: %s\n" % e) if __name__ == "__main__": create_customer_payment_instrument_pinless_debit()
StarcoderdataPython
188552
<reponame>bnels/manimtda<gh_stars>0 from setuptools import * LONG_DESC = """ An extension of `manim` for topological data analysis """ setup(name='manimtda', version='0.0.0', description='Topological Data Analysis in `manim`', long_description=LONG_DESC, author='<NAME> & <NAME>', url='https://github.com/bnels/manimtdy', install_requires=['manimlib'], author_email='<EMAIL>', license='MIT', packages=find_packages(), zip_safe=False)
StarcoderdataPython
3266566
from django.db import models class Report(models.Model): name = models.CharField(max_length = 50, null = True) phone = models.CharField(max_length = 20, null = True) lat = models.DecimalField(max_digits = 9, decimal_places = 6, null = True) lng = models.DecimalField(max_digits = 9, decimal_places = 6, null = True) address = models.CharField(max_length = 200, null = True) situation = models.TextField(null = True) details = models.CharField(max_length = 200, null = True) time = models.DateTimeField(auto_now = True) status = models.IntegerField(default = 0) image = models.CharField(max_length = 200, null = True)
StarcoderdataPython
1718349
<filename>1/solve.py with open('input') as fh: print('Part 1:', sum(int(x) // 3 - 2 for x in fh.readlines())) import itertools as it with open('input') as fh: print('Part 2:', sum( sum(it.takewhile((0).__lt__, it.accumulate(it.repeat(None), lambda a, b: a // 3 - 2, initial=int(x)//3 - 2))) for x in fh.readlines() ))
StarcoderdataPython
3253160
<gh_stars>0 import asyncio import bilibiliCilent class Rafflehandler: instance = None def __new__(cls, *args, **kw): if not cls.instance: cls.instance = super(Rafflehandler, cls).__new__(cls, *args, **kw) cls.instance.list_activity = [] cls.instance.list_TV = [] return cls.instance async def run(self): while True: len_list_activity = len(self.list_activity) len_list_TV = len(self.list_TV) set_activity = [] for i in self.list_activity: if i not in set_activity: set_activity.append(i) set_TV = set(self.list_TV) tasklist = [] for i in set_TV: task = asyncio.ensure_future(bilibiliCilent.handle_1_room_TV(i)) tasklist.append(task) for i in set_activity: task = asyncio.ensure_future(bilibiliCilent.handle_1_room_activity(i[0], i[1])) tasklist.append(task) if tasklist: await asyncio.wait(tasklist, return_when=asyncio.ALL_COMPLETED) else: pass del self.list_activity[:len_list_activity] del self.list_TV[:len_list_TV] if len_list_activity == 0 and len_list_TV == 0: await asyncio.sleep(5) else: await asyncio.sleep(1) def append2list_TV(self, real_roomid): self.list_TV.append(real_roomid) return def append2list_activity(self, text1, text2): self.list_activity.append([text1, text2]) return
StarcoderdataPython
99884
fig, ax = create_map_background() # Contour 1 - Temperature, dotted cs2 = ax.contour(lon, lat, tmpk_850.to('degC'), range(-50, 50, 2), colors='grey', linestyles='dotted', transform=dataproj) plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=10, fmt='%i', rightside_up=True, use_clabeltext=True) # Contour 2 clev850 = np.arange(0, 4000, 30) cs = ax.contour(lon, lat, hght_850, clev850, colors='k', linewidths=1.0, linestyles='solid', transform=dataproj) plt.clabel(cs, fontsize=10, inline=1, inline_spacing=10, fmt='%i', rightside_up=True, use_clabeltext=True) # Filled contours - Temperature advection contours = [-3, -2.2, -2, -1.5, -1, -0.5, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0] cf = ax.contourf(lon, lat, tmpc_adv_850*3600, contours, cmap='bwr', extend='both', transform=dataproj) plt.colorbar(cf, orientation='horizontal', pad=0, aspect=50, extendrect=True, ticks=contours) # Vector ax.barbs(lon, lat, uwnd_850.to('kts').m, vwnd_850.to('kts').m, regrid_shape=15, transform=dataproj) # Titles plt.title('850-hPa Geopotential Heights, Temperature (C), \ Temp Adv (C/h), and Wind Barbs (kts)', loc='left') plt.title('VALID: {}'.format(vtime), loc='right') plt.tight_layout() plt.show()
StarcoderdataPython
32975
from django.utils import timezone from django.utils.translation import ugettext from mediane.algorithms.enumeration import get_name_from from mediane.algorithms.lri.BioConsert import BioConsert from mediane.algorithms.lri.ExactAlgorithm import ExactAlgorithm from mediane.algorithms.misc.borda_count import BordaCount from mediane.distances.KendallTauGeneralizedNlogN import KendallTauGeneralizedNlogN from mediane.distances.enumeration import GENERALIZED_KENDALL_TAU_DISTANCE_WITH_UNIFICATION from mediane.median_ranking_tools import parse_ranking_with_ties_of_str, dump_ranking_with_ties_to_str from mediane.normalizations.enumeration import NONE, UNIFICATION, PROJECTION from mediane.normalizations.unification import Unification from mediane.normalizations.projection import Projection MIN_MEASURE_DURATION = 3 def execute_median_rankings_computation_from_rankings( rankings, algorithm, normalization, distance, precise_time_measurement, dataset=None, algorithms=None, ): if str(normalization) == "Unification": rankings_real = Unification.rankings_to_rankings(rankings) elif str(normalization) == "Projection": rankings_real = Projection.rankings_to_rankings(rankings) else: rankings_real = rankings if algorithms: return [execute_median_rankings_computation_from_rankings( rankings=rankings_real, algorithm=a, normalization=normalization, distance=distance, precise_time_measurement=precise_time_measurement, dataset=dataset, ) for a in algorithms] iteration = 1 start_timezone = timezone.now() c = algorithm.compute_median_rankings(rankings=rankings_real, distance=distance) duration = (timezone.now() - start_timezone).total_seconds() while precise_time_measurement and duration < MIN_MEASURE_DURATION: # print(iteration, duration) iteration = int((iteration / duration) * MIN_MEASURE_DURATION * 1.1) rang_iter = range(2, iteration) start_timezone = timezone.now() for k in rang_iter: algorithm.compute_median_rankings(rankings=rankings_real, distance=distance) duration = (timezone.now() - start_timezone).total_seconds() return dict( dataset=dict( id=-1, name=ugettext('typed'), ) if dataset is None else dict( id=dataset.id, name=str(dataset), ), consensus=c, distance=KendallTauGeneralizedNlogN(distance).get_distance_to_a_set_of_rankings( c[0], rankings=rankings, )[distance.id_order], duration=(int(duration / iteration * 1000.0 * 1000.0 * 1000.0)) / 1000.0 / 1000.0, algo=dict( id=algorithm.get_full_name(), name=str(get_name_from(algorithm.get_full_name())), ), ) def execute_median_rankings_computation_from_datasets( datasets, algorithm, normalization, distance, precise_time_measurement, algorithms=None, ): submission_results = [] algorithms = algorithms or [] if algorithm is not None: algorithms.append(algorithm) for d in datasets: if not d.complete: if str(normalization) == "Unification": rankings_real = Unification.rankings_to_rankings(d.rankings) elif str(normalization) == "Projection": rankings_real = Projection.rankings_to_rankings(d.rankings) else: rankings_real = d.rankings else: rankings_real = d.rankings for a in algorithms: submission_results.append( execute_median_rankings_computation_from_rankings( rankings=rankings_real, algorithm=a, normalization=normalization, distance=distance, precise_time_measurement=precise_time_measurement, dataset=d, ) ) return submission_results def create_computation_job( datasets, normalization, distance, precise_time_measurement, algorithms, owner, ): from mediane import models job = models.Job.objects.create( owner=owner, dist=distance, norm=normalization, creation=timezone.now(), bench=precise_time_measurement, identifier=None, ) for d in datasets: for a in algorithms: r = models.Result.objects.create( algo=a, dataset=d, job=job, ) r.mark_as_todo() job.update_task_count() return job def execute_median_rankings_computation_of_result( result, ): submission_result = execute_median_rankings_computation_from_rankings( rankings=result.dataset.rankings, algorithm=result.algo.get_instance(), normalization=result.job.norm, distance=result.job.dist, precise_time_measurement=result.job.bench, dataset=result.dataset, ) result.consensuses = '\n'.join([dump_ranking_with_ties_to_str(c) for c in submission_result["consensus"]]) result.distance_value = submission_result["distance"] result.duration = submission_result["duration"] result.save() def cleanup_dataset(rankings_as_one_str): if rankings_as_one_str is None: return "" rankings_as_one_str = rankings_as_one_str.replace("\r", "") rankings_as_one_str = rankings_as_one_str.replace("\\\n", "") rankings_as_one_str = rankings_as_one_str.replace(":\n", "") if rankings_as_one_str[-1] == ':': rankings_as_one_str = rankings_as_one_str[:-1] return rankings_as_one_str def evaluate_dataset_and_provide_stats(rankings_str): evaluation = {} elements = None rankings = [] complete = True invalid_rankings = {} cpt = -1 for ranking_str in rankings_str: cpt += 1 try: ranking = parse_ranking_with_ties_of_str(ranking_str) except ValueError as e: invalid_rankings[cpt] = e.args if len(e.args) > 1 else e.args[0] ranking = [] rankings.append(ranking) ranking_elements = set() for bucket in ranking: for element in bucket: if element in ranking_elements: invalid_rankings[cpt] = "Duplicated element '%s'" % element ranking_elements.add(element) if elements is None: elements = ranking_elements if ranking_elements != elements: complete = False elements.update(ranking_elements) evaluation["complete"] = complete evaluation["n"] = len(elements) evaluation["m"] = len(rankings) evaluation["invalid"] = len(invalid_rankings) > 0 evaluation["invalid_rankings_id"] = invalid_rankings evaluation["rankings"] = rankings return evaluation def compute_consensus_settings_based_on_datasets( n, m, complete, rankings, user, dbdatasets=None, algos=None, ): """ :param n: :param m: :param complete: :param rankings: :param user: the user for which we are find the best settings, should be used to not select an algorithm/distance/norm that is not visible by the user :param dbdatasets: :param algos: :return: """ dbdatasets = [] if dbdatasets is None else dbdatasets algos = [] if algos is None else algos from mediane.models import Distance, Normalization, Algorithm consensus_settings = {} consensus_settings["algo"] = Algorithm.objects.get(key_name=str(BioConsert().get_full_name())).pk consensus_settings["dist"] = Distance.objects.get(key_name=GENERALIZED_KENDALL_TAU_DISTANCE_WITH_UNIFICATION).pk # consensus_settings["norm"] = Normalization.objects.get(key_name=NONE if complete else UNIFICATION).pk consensus_settings["norm"] = Normalization.objects.get(key_name=NONE).pk if n < 70 and ExactAlgorithm().can_be_executed(): consensus_settings["algo"] = Algorithm.objects.get(key_name=str(ExactAlgorithm().get_full_name())).pk elif n > 100 or len(dbdatasets) * len(algos) > 20: consensus_settings["algo"] = Algorithm.objects.get(key_name=str(BordaCount().get_full_name())).pk # consensus_settings["auto_compute"] = n < 50 and len(dbdatasets) * len(algos) < 50 consensus_settings["auto_compute"] = False consensus_settings["bench"] = False consensus_settings["extended_analysis"] = len(dbdatasets) * len(algos) > 50 # print(consensus_settings) return consensus_settings
StarcoderdataPython
3341706
<filename>backend/scout_service/ScoutRepository.py import IQRRepository as rep from qrookDB.data import QRTable from datetime import datetime import json from abc import abstractmethod users = QRTable() class IScoutRepository(): @abstractmethod def register_event(self, user_id, time, event: str, data: dict): """register event""" class ScoutRepository(IScoutRepository, rep.QRRepository): def __init__(self): super().__init__() def register_event(self, user_id, time, event: str, data: dict): if self.db is None: raise Exception('DBAdapter not connected to database') data = data.copy() data['user_id'] = user_id str_data = json.dumps(data) time = datetime.fromtimestamp(time) i = self.db.intelligence ok = self.db.insert(i, i.time, i.event, i.data, auto_commit=True) \ .values([time, event, str_data]).exec() return ok
StarcoderdataPython
59485
<filename>django/api/tests/ftp.py from ftplib import FTP from io import StringIO import re import sys # Connect to local ftp server ftp = FTP(host='localhost', user='user',passwd='<PASSWORD>') ###################### Download ########################### # Store output for later old_stdout = sys.stdout # Redirect output result = StringIO() sys.stdout = result # Print listing of files ftp.dir() # Reset standard output sys.stdout = old_stdout # Grab the string and create array of files listing = result.getvalue().splitlines() # Download all files for line in listing: file = re.findall('.* (.*)',line)[0] localfile = open(file, 'wb') ftp.retrbinary('RETR ' + file,localfile.write, 1024) ######################################################### ###################### Upload ########################### # Upload a file filename = 'uploadme.txt' ftp.storbinary('STOR '+filename, open(filename,'rb')) ######################################################### # Close connection ftp.close()
StarcoderdataPython
1795557
import cv2 import numpy as np src = np.array( [[164, 215], [128, 8], [480, 72]] ) dst = np.array( [(175, 237), (146, 44), (486, 99)] ).reshape(-1,2) m = cv2.estimateAffine2D(dst,src) print(m) # m = cv2.estimateRigidTransform(_prev_pts, _curr_pts, fullAffine=False) tr = np.array([[ 1.03016009, 3.17376025e-02, -2.37998282e+01], [ 1.51034752e-02, 1.07026943e+00, -4.12969621e+01]]) dst2 = np.matmul(src,tr) print(dst2)
StarcoderdataPython
1697556
# -*- coding: utf-8 -*- #Completa Si import sip # switch on QVariant in Python3 sip.setapi('QVariant', 2) sip.setapi('QString', 1) from PyQt4.QtCore import QtCore, QString, QVariant from PyQt4.QtGui import QtGui from PyQt4.Qt import Qt from pineboolib.fllegacy.FLFormDB import FLFormDB from pineboolib.fllegacy.FLSqlCursor import FLSqlCursor from pineboolib.fllegacy.FLUtil import FLUtil from pineboolib.fllegacy.FLSqlConnections import FLSqlConnections from pineboolib.fllegacy.aqApp import aqApp class FLFormSearchDB(FLFormDB): """ Subclase de la clase FLFormDB, pensada para buscar un registro en una tabla. El comportamiento de elegir un registro se modifica para solamente cerrar el formulario y así el objeto que lo invoca pueda obtener del cursor dicho registro. También añade botones Aceptar y Cancelar. Aceptar indica que se ha elegido el registro activo (igual que hacer doble clic sobre él o pulsar la tecla Intro) y Cancelar aborta la operación. @author InfoSiAL S.L. """ """ Uso interno """ acceptingRejecting_ = False inExec_ = False """ Boton Aceptar """ pushButtonAccept = None """ Almacena si se ha abierto el formulario con el método FLFormSearchDB::exec() """ loop = None def __init__(self,*args, **kwargs): if isinstance(args[0],QString): super(FLFormSearchDB,self).__init(args[0], args[1],(Qt.WStyle_Customize, Qt.WStyle_Maximize, Qt.WStyle_Title, Qt.WStyle_NormalBorder, Qt.WType_Dialog, Qt.WShowModal, Qt.WStyle_SysMenu)) self.init1(args[0],args[1]) else: super(FLFormSearchDB,self).__init(args[1], args[2],(Qt.WStyle_Customize, Qt.WStyle_Maximize, Qt.WStyle_Title, Qt.WStyle_NormalBorder, Qt.WType_Dialog, Qt.WShowModal, Qt.WStyle_SysMenu)) self.init2(args[0],args[1],args[2]) """ constructor. @param actionName Nombre de la acción asociada al formulario """ def init1(self, actionName, parent = None): self.setFocusPolicy(QtGui.QWidget.NoFocus) if actionName.isEmpty(): self.action_ = False print(FLUtil.translate("app","FLFormSearchDB : Nombre de acción vacío")) return else: self.action_ = FLSqlConnections.database().manager().action(actionName) if not self.action_: print(FLUtil.translate("app","FLFormSearchDB : No existe la acción %s" % actionName)) return self.cursor_ = FLSqlCursor(self.action_.table(), True,"default", 0, 0, self) self.name_ = self.action_.name() self.initForm() """ constructor sobrecargado. @param cursor Objeto FLSqlCursor para asignar a este formulario @param actionName Nombre de la acción asociada al formulario """ def init2(self, cursor,actionName = QString.null, parent = None): self.setFocusPolicy(QtGui.QWidget.NoFocus) if actionName.isEmpty(): self.action_ = False elif cursor: self.action_ = FLSqlConnections.database().manager().action(actionName) self.cursor_ = cursor if self.action_: self.name_ = self.action_.name() else: self.name_ = QString.null """ destructor """ def __del__(self): if self.cursor_ and not self.cursor_.aqWasDeleted(): self.cursor_.restoreEditionFlag(self) self.cursor_.restoreBrowseFlag(self) """ Establece el cursor que debe utilizar el formulario. @param c Cursor con el que trabajar """ def setCursor(self, c): if not c == self.cursor_ and self.cursor_ and self.oldCursorCtxt: self.cursor_.setContext(self.oldCursorCtxt) if not c: return if self.cursor_: self.cursor_.recordChoosed.disconnect(self.accept()) self.cursor_.destroyed.disconnect(self.cursorDestroyed()) if self.cursor_ and not c == self.cursor_: self.cursor_.restoreEditionFlag(self) self.cursor_.restoreBrowseFlag(self) self.cursor_ = c self.cursor_.setEdition(False, self) self.cursor_.setBrowse(False, self) self.cursor_.recordChoosed.connect(self.accept()) self.cursor_.destroyed.connect(self.cursorDestroyed()) if self.iface and self.cursor_: self.oldCursorCtxt = self.cursor_.context() self.cursor_.setContext(self.iface) """ Sobrecargado de setMainWidget. Aqui toma el nombre de un formulario de la acción asociada y construye el Widget principal, a partir de él. """ """ Reimplementado, añade un widget como principal del formulario """ def setMainWidget(self, *args, **kwargs): if len(args) == 0: super(FLFormSearchDB,self).setMainWidget() else: self.setMainWidgetFLFormSearhDB(args[0]) def setMainWidgetFLFormSearchDB(self, w): if not self.cursor_ or not w: return if self.showed: if self.mainWidget_ and not self.mainWidget_ == w: self.initMainWidget(w) else: w.hide() if self.layoutButtons: del self.layoutButtons if self.layout: del self.layout w.setFont(QtGui.qApp.font()) desk = QtGui.QApplication.desktop.availableGeometry(self) geo = w.geometry() tooLarge = False if geo.width() > desk.width() or geo.height() > desk.heigh(): sv = QtGui.QScrollArea(self) #sv->setResizePolicy(QScrollView::AutoOneFit) FIXME sv.hide() sv.addChild(w) self.layout = QtGui.QVBoxLayout(self, 5,5,"vlay" + self.name_) self.Layout.add(sv) sv.resize(self.size().expand(desk.size())) self.layoutButtons = QtGui.QHBoxLayout(self.layout, 3, "hlay" + self.name_) self.formReady.connect(sv.show()) tooLarge = True else: self.layout = QtGui.QVBoxLayout(self, 2, 3, "vlay" + self.name_) self.layout.add(w) self.layoutButtons = QtGui.QHBoxLayout(self.layout, 3, "hlay" + self.name_) pbSize = Qt.qsize(22,22) """ QToolButton *wt = QWhatsThis::whatsThisButton(this); wt->setIconSet(QPixmap::fromMimeSource("about.png")); layoutButtons->addWidget(wt); wt->show() """ self.layoutButtons.addItem(QtGui.QSpacerItem(20,20, Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Minimum)) self.pushButtonAccept = QtGui.QPushButton(self,"pushButtonAccept") self.pushButtonAccept.sizePolicy(Qt.QSizePolicy(0,0,0,0, self.pushButtonAccept.sizePolicy().hasHeightForWidth())) self.pushButtonAccept.setMinimumSize(pbSize) self.pushButtonAccept.setMaximumSize(pbSize) ok = QtGui.QIcon(FLUtil.filedir("icons","button_ok.png")) self.pushButtonAccept.setIcon(ok) self.pushButtonAccept.setFocusPolicy(QtGui.QWidget.NoFocus) #pushButtonAccept->setAccel(QKeySequence(Qt::Key_F10)); FIXME self.pushButtonAccept.setDefault(True) #QToolTip::add(pushButtonAccept, tr("Seleccionar registro actual y cerrar formulario (F10)")); FIXME #QWhatsThis::add(pushButtonAccept, tr("Seleccionar registro actual y cerrar formulario (F10)")); FIXME self.layoutButtons.addWidget(self.pushButtonAccept) self.pushButtonAccept.clicked.connect(self.accept()) self.pushButtonCancel = QtGui.QPushButton(self, "pushButtonCancel") self.pushButtonCancel.sizePolicy(Qt.QSizePolicy(0,0,0,0, self.pushButtonAccept.sizePolicy().hasHeightForWidth())) self.pushButtonCancel.setMinimumSize(pbSize) self.pushButtonCancel.setMaximumSize(pbSize) cancel = QtGui.QIcon(FLUtil.filedir("icons","button_cancel.png")) self.pushButtonAccept.setIcon(cancel) self.pushButtonCancel.setFocusPolicy(QtGui.QWidget.NoFocus) #pushButtonCancel->setAccel(QKeySequence(tr("Esc"))); #FIXME #QToolTip::add(pushButtonCancel, tr("Cerrar formulario sin seleccionar registro (Esc)")); #FIXME #QWhatsThis::add(pushButtonCancel, tr("Cerrar formulario sin seleccionar registro (Esc)")); #FIXME self.layoutButtons.addItem(QtGui.QSpacerItem(20,20, Qt.QSizePolicy.Fixed, Qt.QSizePolicy.Fixed)) self.layoutButtons.addWidget(self.pushButtonCancel) self.pushButtonCancel.clicked.connect(self.reject()) self.mainWidget_ = w self.cursor_.setEdition(False) self.cursor_.setBrowse(False) self.cursor_.recordChoosed.connect(self.accept()) if not tooLarge: mWidth = self.mainWidget_.width() mHeight = self.mainWidget_.height() actWin = QtGui.qApp.activeWindow() if actWin: screen = actWin.geometry() else: screen = QtGui.qApp.mainWidget().geometry() p = screen.center() - Qt.QPoint(mWidth / 2, mHeight / 2) if p.x() + mWidth > desk.width(): p.setx(desk.width() - mWidth) if p.y() + mHeight > desk.height(): p.sety(desk.height() - mHeight) if p.x() < 0: p.setx(0) if p.y() < 0: p.sety(0) self.move(p) """ Muestra el formulario y entra en un nuevo bucle de eventos para esperar, a seleccionar registro. Se espera el nombre de un campo del cursor devolviendo el valor de dicho campo si se acepta el formulario y un QVariant::Invalid si se cancela. @param n Nombre del un campo del cursor del formulario @return El valor del campo si se acepta, o QVariant::Invalid si se cancela """ def exec(self, n = QString.null): if not self.cursor_: return QVariant() if self.loop and self.inExec_: print(FLUtil.translate("app","FLFormSearchDB::exec(): Se ha detectado una llamada recursiva")) self.QWidget.show() if self.initFocusWidget_: self.initFocusWidget_.setFocus() return QVariant() self.inExec_ = True self.acceptingRejecting_ = False self.QWidget.show() if self.initFocusWidget_: self.initFocusWidget_.setFocus() if self.iface: aqApp.call("init", self.QSArgumentList(), self.iface) #if (!isClosing_ && !aqApp->project()->interpreter()->hadError()) #FIXME # QTimer::singleShot(0, this, SLOT(emitFormReady())); #FIXME self.accepted_ = False self.loop = True if not self.isClosing_ and not self.acceptingRejecting_: QtGui.QApplication.eventLoop().enterLoop() self.loop = False self.clearWFlags(Qt.WShowModal) v = None if self.accepted_ and not n.isEmpty(): v = self.cursor_.valueBuffer(n) else: v = QVariant() self.inExec_ = False return v """ Aplica un filtro al cursor """ def setFilter(self, f): if not self.cursor_: return previousF = QString(self.cursor_.mainFilter()) newF = QString(None) if previousF.isEmpty(): newF = f elif previousF.contains(f): return else: newF = previousF + " AND " + f self.cursor_.setMainFilter(newF) """ Devuelve el nombre de la clase del formulario en tiempo de ejecución """ def formClassName(self): return "FormSearhDB" """ Establece el título de la ventana. @param text Texto a establecer como título de la ventana @author Silix """ def setCaptionWidget(self, text): if text.isEmpty(): return self.setCaption(text) """ Nombre interno del formulario """ def geoName(self): return QString("formSearch") + self.idMDI_ """ Captura evento cerrar """ def closeEvent(self, e): self.frameGeometry() if self.focusWidget(): fdb = self.focusWidget().parentWidget() if fdb and fdb.autoComFrame_ and fdb.autoComFrame_.isvisible(): fdb.autoComFrame_.hide() return if self.cursor_ and self.pushButtonCancel: if not self.pushButtonCancel.isEnabled(): return self.isClosing_ = True self.setCursor(None) else: self.isClosing_ = True if self.isShown(): self.reject() if self.isHidden(): self.closed() self.QWidget.closeEvent(e) self.deleteLater() """ Invoca a la función "init()" del script asociado al formulario """ @QtCore.pyqtSlot() def initScript(self): return False """ Redefinida por conveniencia """ @QtCore.pyqtSlot() def hide(self): if self.isHidden(): return self.QWidget.hide() if self.loop: self.loop = False QtGui.QApplication.eventLoop().exitLoop() """ Se activa al pulsar el boton aceptar """ @QtCore.pyqtSlot() def accept(self): if self.acceptingRejecting_: return self.frameGeometry() if self.cursor_: self.cursor_.recordChoosed.disconnect(self.accept()) self.accepted_ = True self.acceptingRejecting_ = True self.hide() """ Se activa al pulsar el botón cancelar """ @QtCore.pyqtSlot() def reject(self): if self.acceptingRejecting_: return self.frameGeometry() if self.cursor_: self.cursor_.recordChoosed.disconnect(self.accept()) self.acceptingRejecting_ = True self.hide() """ Redefinida por conveniencia """ @QtCore.pyqtSlot() def show(self): self.exec()
StarcoderdataPython
185315
<reponame>Kpaubert/onlineweb4 # Generated by Django 3.0.6 on 2020-05-25 12:40 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("events", "0027_auto_20200420_1143"), ] operations = [ migrations.AlterModelOptions( name="attendanceevent", options={ "default_permissions": ("add", "change", "delete"), "ordering": ("pk",), "permissions": (("view_attendanceevent", "View AttendanceEvent"),), "verbose_name": "påmelding", "verbose_name_plural": "påmeldinger", }, ), migrations.AlterModelOptions( name="rule", options={ "default_permissions": ("add", "change", "delete"), "ordering": ("id",), "permissions": (("view_rule", "View Rule"),), }, ), migrations.AlterModelOptions( name="rulebundle", options={ "default_permissions": ("add", "change", "delete"), "ordering": ("id",), "permissions": (("view_rulebundle", "View RuleBundle"),), }, ), ]
StarcoderdataPython
3392848
<filename>ExerciciosPYTHON/PythonCeV/038.py print('='*8,'Comparando Numeros','='*8) n1 = int(input('Digite um numero inteiro qualquer: ')) n2 = int(input('Digite outro numero inteiro qualquer: ')) if n1 > n2 : print('O primeiro valor e o {}MAIOR{}.'.format('\033[36m','\033[m')) elif n2 > n1 : print('O segundo valor e o {}MAIOR{}.'.format('\033[36m','\033[m')) else: print('Os dois valores sao {}IGUAIS{}.'.format('\033[33m','\033[m'))
StarcoderdataPython