max_stars_repo_path
stringlengths 3
269
| max_stars_repo_name
stringlengths 4
119
| max_stars_count
int64 0
191k
| id
stringlengths 1
7
| content
stringlengths 6
1.05M
| score
float64 0.23
5.13
| int_score
int64 0
5
|
|---|---|---|---|---|---|---|
pytype/tests/py3/test_pickle.py
|
adamcataldo/pytype
| 2
|
12778651
|
"""Tests for loading and saving pickled files."""
from pytype import file_utils
from pytype.tests import test_base
class PickleTest(test_base.TargetPython3BasicTest):
"""Tests for loading and saving pickled files."""
def testContainer(self):
pickled = self.Infer("""
import collections, json
def f() -> collections.OrderedDict[int, int]:
return collections.OrderedDict({1: 1})
def g() -> json.JSONDecoder:
return json.JSONDecoder()
""", pickle=True, module_name="foo")
with file_utils.Tempdir() as d:
u = d.create_file("u.pickled", pickled)
ty = self.Infer("""
import u
r = u.f()
""", deep=False, pythonpath=[""], imports_map={"u": u})
self.assertTypesMatchPytd(ty, """
import collections
u = ... # type: module
r = ... # type: collections.OrderedDict[int, int]
""")
test_base.main(globals(), __name__ == "__main__")
| 2.640625
| 3
|
search.py
|
nik-sm/gan-compression
| 2
|
12778652
|
import argparse
from datetime import datetime
import torch
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from torch_model import SizedGenerator
import os
from tqdm import trange
from torchvision.utils import save_image, make_grid
import params as P
from utils import save_img_tensorboard, load_trained_generator, load_target_image, psnr
def output_to_imshow(v):
return v.squeeze(0).detach().to('cpu').numpy().transpose(1, 2, 0)
def main(args):
logdir = f'tensorboard_logs/search/{args.run_name}'
os.makedirs(logdir,
exist_ok=True) # TODO - decide whether to clobber or what?
writer = SummaryWriter(logdir)
device = 'cuda:0'
x = load_target_image(args.image).to(device)
save_img_tensorboard(x.squeeze(0).detach().cpu(), writer, f'original')
g = load_trained_generator(SizedGenerator,
args.generator_checkpoint,
latent_dim=64,
num_filters=P.num_filters,
image_size=P.size,
num_ups=P.num_ups).to(device)
g.eval()
if args.latent_dim != g.latent_dim:
args.skip_linear_layer = True
else:
args.skip_linear_layer = False
if args.skip_linear_layer and args.latent_dim < 8192:
# Then we need a new linear layer to map to dimension 8192
linear_layer = torch.nn.Linear(args.latent_dim, 8192).to(device)
else:
linear_layer = lambda x: x
save_every_n = 50
for i in trange(args.n_restarts):
seed = i
torch.manual_seed(seed)
np.random.seed(seed)
# NOTE - based on quick experiments:
# - std=1.0 better than std=0.1 or std=0.01
# - uniform and normal performed nearly identical
if args.initialization == 'uniform':
z = (2 * args.std) * torch.rand(args.latent_dim,
device=device) - args.std
elif args.initialization == 'normal':
z = torch.randn(args.latent_dim, device=device) * args.std
elif args.initialization == 'ones':
mask = torch.rand(args.latent_dim) < 0.5
z = torch.ones(args.latent_dim, device=device)
z[mask] = -1
else:
raise NotImplementedError(args.initialization)
# network only saw [-1, 1] during training
z = torch.nn.Parameter(torch.clamp(z, -1, 1))
z_initial = z.data.clone()
optimizer = torch.optim.Adam([z], lr=0.05, betas=(0.5, 0.999))
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer, args.n_steps)
with torch.no_grad():
model_input = linear_layer(z_initial)
save_img_tensorboard(
g(model_input,
skip_linear_layer=args.skip_linear_layer).squeeze(
0).detach().cpu(), writer, f'restart_{i}/beginning')
for j in trange(args.n_steps, leave=False):
optimizer.zero_grad()
model_input = linear_layer(z)
x_hat = g(model_input,
skip_linear_layer=args.skip_linear_layer).squeeze(0)
mse = F.mse_loss(x_hat, x)
mse.backward()
optimizer.step()
scheduler.step()
writer.add_scalar(f'MSE/{i}', mse, j)
writer.add_scalar(f'PSNR/{i}', psnr(x, x_hat), j)
if j % save_every_n == 0:
save_img_tensorboard(
x_hat.squeeze(0).detach().cpu(), writer,
f'restart_{i}/reconstruction', j)
save_img_tensorboard(
x_hat.squeeze(0).detach().cpu(), writer, f'restart_{i}/final')
save_image(make_grid([x, x_hat.squeeze(0)], nrow=2),
f'{args.run_name}.png')
def get_latent_dims(x):
x = int(x)
if x > 8192:
raise ValueError('give a latent_dim between [1, 8192]')
return x
if __name__ == '__main__':
p = argparse.ArgumentParser()
p.add_argument('--generator_checkpoint',
default='./checkpoints/celeba_cropped/gen_ckpt.49.pt',
help="Path to generator checkpoint")
p.add_argument('--image', required=True)
p.add_argument('--run_name', default=datetime.now().isoformat())
p.add_argument('--n_restarts', type=int, default=3)
p.add_argument('--n_steps', type=int, default=3000)
p.add_argument('--initialization',
choices=['uniform', 'normal', 'ones'],
default='normal')
p.add_argument(
'--std',
type=float,
default=1.0,
help='for normal dist, the std. for uniform, the min and max val')
p.add_argument('--latent_dim',
type=get_latent_dims,
default=4096,
help='int between [1, 8192]')
args = p.parse_args()
# TODO - if model used latent_dim=64 and you also wanan reconstruct from 64,
# does it hurt to just skip linear layer?
main(args)
| 2.359375
| 2
|
app/utils/kafka.py
|
junpengxu/MyFlask
| 0
|
12778653
|
# -*- coding: utf-8 -*-
# @Time : 2021/11/13 1:47 下午
# @Author : xujunpeng
from app import app
from confluent_kafka import Producer
KafkaProducer = Producer({'bootstrap.servers': app.config["KAFKA_SERVERS"]})
| 1.328125
| 1
|
django/pokemongo/migrations/0033_auto_20200829_1259.py
|
TrainerDex/trainerdex.co.uk
| 1
|
12778654
|
import django.core.validators
from django.db import migrations, models
def clear_gen8(apps, schema_editor):
Update = apps.get_model("pokemongo", "Update")
Update.objects.update(badge_pokedex_entries_gen8=None)
class Migration(migrations.Migration):
dependencies = [
("pokemongo", "0032_remove_trainer_leaderboard_region"),
]
operations = [
migrations.RenameField(
model_name="update",
old_name="badge_photobombadge_rocket_grunts_defeated",
new_name="badge_rocket_grunts_defeated",
),
migrations.AlterField(
model_name="update",
name="badge_pokedex_entries_gen8",
field=models.PositiveIntegerField(
blank=True,
help_text="Register x Pokémon first discovered in the Alola region to the Pokédex.",
null=True,
validators=[django.core.validators.MaxValueValidator(2)],
verbose_name="Galar",
),
),
migrations.RunPython(clear_gen8, migrations.RunPython.noop),
]
| 1.789063
| 2
|
tests/test_platforms_apscheduler.py
|
collectiveacuity/labPack
| 2
|
12778655
|
__author__ = 'rcj1492'
__created__ = '2016.11'
__license__ = 'MIT'
from labpack.platforms.apscheduler import apschedulerClient
if __name__ == '__main__':
from labpack.records.settings import load_settings
system_config = load_settings('../../cred/system.yaml')
scheduler_url = 'http://%s:%s' % (system_config['system_ip_address'], system_config['scheduler_system_port'])
scheduler_client = apschedulerClient(scheduler_url)
scheduler_info = scheduler_client.get_info()
assert scheduler_info['running']
from time import time, sleep
job_function = 'init:app.logger.debug'
date_kwargs = {
'id': '%s.%s' % (job_function, str(time())),
'function': job_function,
'dt': time() + 2,
'kwargs': { 'msg': 'Add date job is working.'}
}
date_job = scheduler_client.add_date_job(**date_kwargs)
interval_kwargs = {
'id': '%s.%s' % (job_function, str(time())),
'function': job_function,
'interval': 1,
'kwargs': {'msg': 'Add interval job is working.'},
'start': time() + 0.5,
'end': time() + 10.5
}
interval_job = scheduler_client.add_interval_job(**interval_kwargs)
cron_a_kwargs = {
'id': '%s.%s' % (job_function, str(time())),
'function': job_function,
'kwargs': {'msg': 'Add nye cron job is working.'},
'month': 12,
'day': 31,
'hour': 23,
'minute': 59,
'second': 59
}
cron_job_a = scheduler_client.add_cron_job(**cron_a_kwargs)
cron_b_kwargs = {
'id': '%s.%s' % (job_function, str(time())),
'function': job_function,
'kwargs': {'msg': 'Add ny cron job is working.'},
'month': 1,
'day': 1,
'hour': 0,
'minute': 0,
'second': 0
}
cron_job_b = scheduler_client.add_cron_job(**cron_b_kwargs)
cron_c_kwargs = {
'id': '%s.%s' % (job_function, str(time())),
'function': job_function,
'kwargs': {'msg': 'Add weekday cron job is working.'},
'weekday': 5,
'hour': 5,
'minute': 5,
'second': 5
}
cron_job_c = scheduler_client.add_cron_job(**cron_c_kwargs)
try:
interval_filter = [{'.id': {'must_contain': [ 'app\\.logger']}, '.function': {'must_contain': [ 'debug' ]}, '.interval': { 'discrete_values': [1] }}]
interval_list = scheduler_client.list_jobs(argument_filters=interval_filter)
dt_filter = [{'.dt': { 'min_value': time() }}]
dt_list = scheduler_client.list_jobs(argument_filters=dt_filter)
cron_filter = [{'.weekday': { 'discrete_values': [ 5 ]}}]
cron_list = scheduler_client.list_jobs(argument_filters=cron_filter)
print(interval_list)
print(dt_list)
print(cron_list)
except:
pass
sleep(2)
job_list = scheduler_client.list_jobs()
assert job_list
id_list = [ interval_kwargs['id'], date_kwargs['id'], cron_a_kwargs['id'], cron_b_kwargs['id'], cron_c_kwargs['id'] ]
for job in job_list:
if job['id'] in id_list:
assert scheduler_client.delete_job(job['id']) == 204
| 2.0625
| 2
|
tests/django/test_django.py
|
ecarrara/connexion-faker
| 2
|
12778656
|
<gh_stars>1-10
import pytest
def test_settings(settings):
assert settings.ROOT_URLCONF == "tests.django.testapp.urls"
assert settings.INSTALLED_APPS == ['tests.django.testapp']
def test_hello_name(client):
resp = client.get("/hello")
assert resp.status_code == 200
assert resp.json() == {"name": any_string(), "last_name": 'Andreas' }
def test_wrong_path(client):
resp = client.get("/dark")
assert resp.status_code == 404
assert 'Not Found' in resp.content.decode("utf-8")
def test_201_path(client):
resp = client.get("/different_responses_2")
assert resp.status_code == 204
assert resp.content.decode('UTF-8') == ''
class any_string:
def __eq__(self, other):
return isinstance(other, str) and other
| 2.5
| 2
|
altymeter/api/exchange.py
|
juharris/altymeter
| 0
|
12778657
|
<reponame>juharris/altymeter<filename>altymeter/api/exchange.py
from abc import ABCMeta, abstractmethod
from collections import namedtuple
from typing import List, Optional
class ExchangeOpenOrder(namedtuple('Order', [
'name',
'exchange',
'price',
'volume',
'order_type',
])):
"""
An open order on an exchange.
:param name: The name of the pair traded (e.g. ETHCAD).
:param exchange: The name of the exchange (e.g. Kraken).
:param price: The price.
:param volume: The quantity.
:param order_type: The type of order, e.g. 'ask' or 'bid'.
"""
class ExchangeOrder(namedtuple('Order', [
'name',
'exchange',
'price',
'volume',
'status',
'action_type',
'order_type',
])):
"""
An order made on an exchange.
:param name: The name of the pair traded (e.g. ETHCAD).
:param exchange: The name of the exchange (e.g. Kraken).
:param price: The executed price.
:param volume: The quantity exchanged.
:param status: The order's status.
:param action_type: The action taken, e.g. buy or sell.
:param order_type: The type of order, e.g. market or limit.
"""
class ExchangeTransfer(namedtuple('ExchangeTransfer', [
'name',
'exchange',
'amount',
'transfer_cost',
'date',
'type',
'destination',
'origin',
])):
"""
A transfer into or out of an exchange.
:param name: The name of the asset.
:param type: 'DEPOSIT' into the exchange or 'WITHDRAW' from the exchange.
"""
class PairRecentStats(namedtuple('PairRecentStats', [
'name',
'exchange',
'weighted_avg_price',
'last_price',
])):
"""
Recent stats for a pair on an exchange.
:param name: The name of the pair traded (e.g. ETHCAD).
:param exchange: The name of the exchange (e.g. Kraken).
:param weighted_avg_price: The weighted price over the period of time.
:param last_price: The last traded price.
"""
class TradedPair(namedtuple('TradedPair', [
'name',
'exchange',
'base',
'base_full_name',
'to',
'to_full_name',
])):
"""
A pair that is traded on an exchange.
The price displayed in markets is a ratio where the `base` is used to buy the `to` asset.
The following documentation will use CAD to ETH in Kraken as an example.
:param name: The name of the pair traded (e.g. ETHCAD).
:param exchange: The name of the exchange (e.g. Kraken).
:param base: The asset used to buy and the asset obtained after selling.
(e.g. CAD)
(quote in the Kraken API and BaseCurrency in the Bittrex API).
:param base_full_name: The full name of the `base` asset.
:param to: The asset obtained after buying and the asset used to sell.
(e.g. ETH)
(base in the Kraken API and MarketCurrency in the Bittrex API).
:param to_full_name: The full name of the `to` asset.
"""
class TradingExchange(metaclass=ABCMeta):
@property
@abstractmethod
def name(self):
raise NotImplementedError
@abstractmethod
def collect_data(self, pair: str, since=None, sleep_time=90, stop_event=None):
raise NotImplementedError
@abstractmethod
def create_order(self, pair: str,
action_type: str,
order_type: str,
volume: float,
price: Optional[float] = None,
**kwargs) -> ExchangeOrder:
raise NotImplementedError
@abstractmethod
def get_deposit_history(self) -> List[ExchangeTransfer]:
raise NotImplementedError
@abstractmethod
def get_order_book(self, pair: Optional[str] = None,
base: Optional[str] = None, to: Optional[str] = None,
order_type: Optional[str] = 'all') \
-> List[ExchangeOpenOrder]:
raise NotImplementedError
@abstractmethod
def get_pair(self, pair: Optional[str] = None,
base: Optional[str] = None, to: Optional[str] = None) -> str:
raise NotImplementedError
@abstractmethod
def get_recent_stats(self, pair: str) -> PairRecentStats:
raise NotImplementedError
@abstractmethod
def get_traded_pairs(self) -> List[TradedPair]:
raise NotImplementedError
@abstractmethod
def get_withdrawal_history(self) -> List[ExchangeTransfer]:
raise NotImplementedError
| 2.96875
| 3
|
py/segment.py
|
weiwang2330/MultiGraph_MultiLabel_Learning
| 11
|
12778658
|
<filename>py/segment.py
"""
Segment image
usage: segment.py [-h] -i IMAGE -n NODE [-o OUTPUT]
optional arguments:
-h, --help show this help message and exit
-i IMAGE, --image IMAGE
(Required) Image file path
-n NODE, --node NODE (Required) Number of nodes which each image will have
approximately
-o OUTPUT, --output OUTPUT
Output subgraph file path
"""
import argparse
import numpy as np
from skimage import color
from skimage.future import graph
from skimage.io import imread
from skimage.segmentation import slic
from model.graph import *
def segment(img_path, node_num):
"""
Segment an image to multiple graphs.
Parameters
---
img_path: `str`
node_num: `int`
Returns
---
graphs: `MultiGraph`
"""
img = imread(img_path)
# Segment the image to node_num picese (approximately).
nodes = slic(img, sigma=1, n_segments=node_num)
# true_node_num = len(np.unique(nodes))
nodes_colors = color.label2rgb(
nodes, img, kind='avg') # avg color for each node
# Segment nodes to regions (graphs) based on Normalized Cut.
regions = graph.cut_normalized(
nodes, graph.rag_mean_color(img, nodes, mode='similarity'))
# region_num = len(np.unique(regions))
region_set = np.unique(regions)
# Build multi-graphs
graphs = MultiGraph()
for i in region_set:
region_graph = Graph()
x_len = len(regions)
for x in range(x_len):
y_len = len(regions[x])
for y in range(y_len):
if regions[x][y] == i:
node_id = nodes[x][y]
# Add nodes
# 4-bit (16 colors)
r = int(nodes_colors[x][y][0] / 256 * 16)
g = int(nodes_colors[x][y][1] / 256 * 16)
b = int(nodes_colors[x][y][2] / 256 * 16)
label = r + (g << 4) + (b << 8)
region_graph.add_node(node_id, label)
# Add edges
for xx, yy in [(x, y + 1), (x, y - 1), (x + 1, y), (x - 1, y)]:
if xx < x_len and xx > 0 and yy < y_len and yy > 0 and regions[xx][yy] == i:
region_graph.add_edge(node_id, nodes[xx][yy])
graphs.add_graph(region_graph)
return graphs
def segment_region(img_path, node_num):
"""
Segment an image to one graph.
Parameters
---
img_path: `str`
node_num: `int`
Returns
---
graph_: `Graph`
"""
img = imread(img_path)
# Segment the image to node_num picese (approximately).
nodes = slic(img, sigma=1, n_segments=node_num)
# true_node_num = len(np.unique(nodes))
# Segment nodes to regions (graphs) based on Normalized Cut.
regions = graph.cut_normalized(
nodes, graph.rag_mean_color(img, nodes, mode='similarity'))
regions_colors = color.label2rgb(
regions, img, kind='avg') # avg color for each region
# region_num = len(np.unique(regions))
# Build graph
graph_ = Graph()
x_len = len(regions)
for x in range(x_len):
y_len = len(regions[x])
for y in range(y_len):
node_id = regions[x][y]
# Add nodes
# 4-bit (16 colors)
r = int(regions_colors[x][y][0] / 256 * 16)
g = int(regions_colors[x][y][1] / 256 * 16)
b = int(regions_colors[x][y][2] / 256 * 16)
label = r + (g << 4) + (b << 8)
graph_.add_node(node_id, label)
# Add edges
for xx, yy in [(x, y + 1), (x, y - 1), (x + 1, y), (x - 1, y)]:
if xx < x_len and xx > 0 and yy < y_len and yy > 0:
graph_.add_edge(node_id, regions[xx][yy])
return graph_
def main(args):
img_path = args.image
node_num = args.node
output_file_path = args.output
graph_ = segment_region(img_path, node_num)
graphs = MultiGraph()
graphs.add_graph(graph_)
graphs.write(output_file_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--image', required=True,
type=str, help='(Required) Image file path')
parser.add_argument('-n', '--node', required=True, type=int,
help='(Required) Number of nodes which each image will have approximately')
parser.add_argument('-o', '--output', default='subgraph',
type=str, help='Output subgraph file path')
args = parser.parse_args()
main(args)
| 2.9375
| 3
|
restaurant/admin.py
|
shankarj67/Django-RESTAPI
| 0
|
12778659
|
<filename>restaurant/admin.py<gh_stars>0
from django.contrib import admin
from .models import FoodDetail, OrderDetail
from import_export.admin import ImportExportActionModelAdmin
@admin.register(FoodDetail)
class StartupAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
@admin.register(OrderDetail)
class StartupAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("restaurant_name",)}
| 1.664063
| 2
|
mbdata/api/data.py
|
markweaversonos/mbdata
| 51
|
12778660
|
from sqlalchemy import sql
from sqlalchemy.orm import joinedload, subqueryload
from sqlalchemy.inspection import inspect
from mbdata.utils.models import get_entity_type_model, get_link_model, ENTITY_TYPES
from mbdata.models import (
Area,
Artist,
Label,
Link,
LinkAreaArea,
LinkType,
Place,
Release,
Recording,
ReleaseGroup,
Work,
)
def load_areas(session, objs, include):
attrs = []
ids = set()
for obj in objs:
mapper = inspect(obj).mapper
for relationship in mapper.relationships:
if not issubclass(relationship.mapper.class_, Area):
continue
attr = relationship.key
for column in relationship.local_columns:
id = getattr(obj, mapper.get_property_by_column(column).key)
if id is not None:
attrs.append((obj, id, attr))
ids.add(id)
areas = fetch_areas(session, ids, include)
for obj, id, attr in attrs:
setattr(obj, attr, areas[id])
def fetch_areas(session, ids, include):
areas = {}
if not ids:
return areas
options = []
if include.iso_3166:
options.append(joinedload('iso_3166_1_codes'))
options.append(joinedload('iso_3166_2_codes'))
options.append(joinedload('iso_3166_3_codes'))
if include.type:
options.append(joinedload('type'))
query = session.query(Area).filter(Area.id.in_(ids)).options(*options)
for area in query:
areas[area.id] = area
if include.part_of and areas:
_fetch_parent_areas(session, areas, options)
return areas
def _fetch_parent_areas(session, areas, options):
for area in areas.values():
area.part_of = None
link_type_id_query = session.query(LinkType.id).\
filter_by(gid='de7cc874-8b1b-3a05-8272-f3834c968fb7').\
as_scalar()
area_parent_query = session.query(
LinkAreaArea.entity1_id.label('child_id'),
LinkAreaArea.entity0_id.label('parent_id'),
).\
select_from(LinkAreaArea).\
join(Link, LinkAreaArea.link_id == Link.id).\
filter(Link.link_type_id == link_type_id_query).\
subquery()
if session.bind.dialect.name == 'postgresql':
_fetch_parent_areas_cte(session, area_parent_query, areas, options)
else:
_fetch_parent_areas_iterate(session, area_parent_query, areas, options)
def _fetch_parent_areas_iterate(session, area_parent_query, areas, options):
while True:
area_ids = [area.id for area in areas.values() if area.part_of is None]
query = session.query(Area, area_parent_query.c.child_id).\
filter(Area.id == area_parent_query.c.parent_id).\
filter(area_parent_query.c.child_id.in_(area_ids)).\
options(*options)
found = False
for area, child_id in query:
area.part_of = None
areas[area.id] = area
areas[child_id].part_of = area
found = True
if not found:
break
def _fetch_parent_areas_cte(session, area_parent_query, areas, options):
area_ids = [area.id for area in areas.values() if area.part_of is None]
area_ancestors_cte = session.query(
area_parent_query.c.child_id,
area_parent_query.c.parent_id,
sql.literal(1).label('depth')
).\
select_from(area_parent_query).\
filter(area_parent_query.c.child_id.in_(area_ids)).\
cte(name='area_ancestors', recursive=True)
area_ancestors_cte = area_ancestors_cte.union_all(
session.query(
area_parent_query.c.child_id,
area_parent_query.c.parent_id,
area_ancestors_cte.c.depth + 1
).
select_from(area_ancestors_cte).
join(area_parent_query, area_ancestors_cte.c.parent_id == area_parent_query.c.child_id)
)
query = session.query(Area, area_ancestors_cte.c.child_id, area_ancestors_cte.c.depth).\
filter(Area.id == area_ancestors_cte.c.parent_id).\
order_by(area_ancestors_cte.c.depth).options(*options)
for area, child_id, depth in query:
area.part_of = None
areas[area.id] = area
areas[child_id].part_of = area
def query_artist(db, include):
return prepare_artist_query(db.query(Artist), include)
def query_label(db, include):
return prepare_label_query(db.query(Label), include)
def query_place(db, include):
return prepare_place_query(db.query(Place), include)
def query_recording(db, include):
return prepare_recording_query(db.query(Recording), include)
def query_release(db, include):
return prepare_release_query(db.query(Release), include)
def query_release_group(db, include):
return prepare_release_group_query(db.query(ReleaseGroup), include)
def query_work(db, include):
return prepare_work_query(db.query(Work), include)
def prepare_artist_query(query, include, prefix=""):
query = query.\
options(joinedload(prefix + "gender")).\
options(joinedload(prefix + "type"))
if include.ipi:
query = query.options(subqueryload(prefix + "ipis"))
if include.isni:
query = query.options(subqueryload(prefix + "isnis"))
return query
def prepare_label_query(query, include, prefix=""):
query = query.options(joinedload(prefix + "type"))
if include.ipi:
query = query.options(subqueryload(prefix + "ipis"))
if include.isni:
query = query.options(subqueryload(prefix + "isnis"))
return query
def prepare_place_query(query, include, prefix=""):
return query.options(joinedload(prefix + "type"))
def prepare_recording_query(query, include, prefix=""):
return prepare_artist_credits_subquery(query, include, prefix)
def prepare_release_query(query, include, prefix=""):
query = query.\
options(joinedload(prefix + "status")).\
options(joinedload(prefix + "packaging")).\
options(joinedload(prefix + "language")).\
options(joinedload(prefix + "script"))
query = prepare_artist_credits_subquery(query, include, prefix)
if include.release_group:
query = prepare_release_group_query(query, include.release_group, prefix + "release_group.")
if include.mediums:
query = query.options(subqueryload(prefix + "mediums"))
query = prepare_medium_query(query, include.mediums, prefix + "mediums.")
return query
def prepare_medium_query(query, include, prefix=""):
query = query.options(joinedload(prefix + "format"))
if include.tracks:
query = query.options(subqueryload(prefix + "tracks"))
query = prepare_track_query(query, include.tracks, prefix + "tracks.")
return query
def prepare_track_query(query, include, prefix=""):
query = prepare_artist_credits_subquery(query, include, prefix)
if include.recording:
query = query.options(subqueryload(prefix + "recording"))
query = prepare_recording_query(query, include, prefix + "recording.")
return query
def prepare_release_group_query(query, include, prefix=""):
query = query.\
options(joinedload(prefix + "type")).\
options(subqueryload(prefix + "secondary_types")).\
options(joinedload(prefix + "secondary_types.secondary_type", innerjoin=True))
query = prepare_artist_credits_subquery(query, include, prefix)
return query
def prepare_artist_credits_subquery(query, include, prefix):
if include.artist or include.artists:
query = query.options(joinedload(prefix + "artist_credit", innerjoin=True))
if include.artists:
query = query.\
options(subqueryload(prefix + "artist_credit.artists")).\
options(joinedload(prefix + "artist_credit.artists.artist", innerjoin=True))
return query
def prepare_url_query(query, include, prefix=""):
return query
def prepare_work_query(query, include, prefix=""):
return query.options(joinedload(prefix + "type"))
def load_links(db, all_objs, include):
for type in ENTITY_TYPES:
type_include = include.check(type)
if type_include:
load_links_by_target_type(db, all_objs, type, type_include)
ENTITY_TYPE_PREPARE_FUNCS = {
'artist': prepare_artist_query,
'label': prepare_label_query,
'place': prepare_place_query,
'recording': prepare_recording_query,
'release': prepare_release_query,
'release_group': prepare_release_group_query,
'url': prepare_url_query,
'work': prepare_work_query,
}
def load_links_by_target_type(db, all_objs, target_type, include):
attr = '{0}_links'.format(target_type)
grouped_objs = {}
for obj in all_objs:
setattr(obj, attr, [])
model = inspect(obj).mapper.class_
grouped_objs.setdefault(model, {})[obj.id] = obj
for model, objs in grouped_objs.items():
_load_links_by_types(db, objs, attr, model, target_type, include)
def _load_links_by_types(db, objs, attr, source_model, target_type, include):
target_model = get_entity_type_model(target_type)
model = get_link_model(source_model, target_model)
query = db.query(model).\
options(joinedload("link", innerjoin=True)).\
options(joinedload("link.link_type", innerjoin=True))
if model.entity0.property.mapper.class_ == model.entity1.property.mapper.class_:
_load_links_by_types_one_side(model, query, objs, attr, include, "entity0", "entity1", target_type)
_load_links_by_types_one_side(model, query, objs, attr, include, "entity1", "entity0", target_type)
else:
if source_model == model.entity0.property.mapper.class_:
_load_links_by_types_one_side(model, query, objs, attr, include, "entity0", "entity1", target_type)
else:
_load_links_by_types_one_side(model, query, objs, attr, include, "entity1", "entity0", target_type)
def _load_links_by_types_one_side(model, query, objs, attr, include, source_attr, target_attr, target_type):
source_id_attr = source_attr + "_id"
query = query.filter(getattr(model, source_id_attr).in_(objs))
query = query.options(joinedload(target_attr, innerjoin=True))
query = ENTITY_TYPE_PREPARE_FUNCS[target_type](query, include, target_attr + ".")
for link in query:
obj = objs.get(getattr(link, source_id_attr))
if obj is not None:
getattr(obj, attr).append(link)
| 2.265625
| 2
|
scripts/doubletiny_umap_visualize.py
|
langmead-lab/reference_flow-experiments
| 0
|
12778661
|
<reponame>langmead-lab/reference_flow-experiments
import seaborn as sns
import pandas as pd
import json
import glob, os, sys, subprocess
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_iris, load_digits
from sklearn.model_selection import train_test_split
jsonPrefix=sys.argv[1] #/net/langmead-bigmem-ib.bluecrab.cluster/storage/bsolomo9/json_vcf/reduced_min02_chr21_hg38 (Leave off suffix)
# CSV has same order as json (json and csv both read line by line from vcf file)
csv_file=sys.argv[2] #~/1kgenomes_sampleinfo_parsed.csv
outFig=sys.argv[3]
print("Loading jsons")
with open(jsonPrefix+"_hapA.json") as myFile:
matrixHapA=json.load(myFile)
#with open(jsonPrefix+"_hapB.json") as myFile:
# matrixHapB=json.load(myFile)
print("Loaded jsons")
# int conversion from bool / reduce matrix
tiny=100
tinyMatrix=[]
for i in range(tiny):
temp=[]
for si in range(tiny): #its all the same but why not
if matrixHapA[i][si]:
temp.append(1)
else:
temp.append(0)
tinyMatrix.append(temp)
# change matrix so that samples have arrays of variants rather then variants have arrays of samples
corrTinyMatrix=np.swapaxes(tinyMatrix,0,1)
print(len(corrTinyMatrix))
print(len(corrTinyMatrix[0]))
# Build tissue dictionary
count=0
popDic={}
superPop_labels=["EAS","EUR","AFR","AMR","SAS"]
superPop=[]
print("Building superpop array")
with open(csv_file) as myFile:
for line in myFile:
line=line.strip()
spline=line.split(',')
sample=spline[1]
k=spline[3]
if k=="CHB" or k=="JPT" or k=="CHS" or k=="CDX" or k=="KHV":
superPop.append(0)
elif k=="CEU" or k=="TSI" or k=="FIN" or k=="GBR" or k=="IBS":
superPop.append(1)
elif k=="YRI" or k=="LWK" or k=="GWD" or k=="MSL" or k=="ESN" or k=="ASW" or k=="ACB":
superPop.append(2)
elif k=="MXL" or k=="PUR" or k=="CLM" or k=="PEL":
superPop.append(3)
elif k=="GIH" or k=="PJL" or k=="BEB" or k=="STU" or k=="ITU":
superPop.append(4)
print("Built superpop array")
print("Building data array lebels")
dataArray_labels=[]
for i in range(len(corrTinyMatrix[0])):
dataArray_labels.append("var{}".format(i))
print("Built data array labels")
#print(len(matrixHapA))
#print(len(matrixHapB[0]))
print(len(dataArray_labels))
print(superPop)
print(superPop_labels)
print("pandas dataframing")
onek_df = pd.DataFrame(corrTinyMatrix, columns=dataArray_labels)
print("Adding data labels")
onek_df['superpop'] = pd.Series(superPop).map(dict(zip(range(len(superPop_labels)),superPop_labels)))
print("Plotting")
sns_plot = sns.pairplot(onek_df, hue='superpop')
print("Saving figure")
sns_plot.savefig(outFig)
#print(iris.data)
#print(iris.feature_names)
#print(iris.target)
#print(iris.target_names)
#iris_df = pd.DataFrame(iris.data, columns=iris.feature_names)
#iris_df['species'] = pd.Series(iris.target).map(dict(zip(range(3),iris.target_names)))
#sns.pairplot(iris_df, hue='species');
| 2.234375
| 2
|
contrib/tests/runtests.py
|
ryr/django-social-auth
| 1
|
12778662
|
<reponame>ryr/django-social-auth
#!/usr/bin/env python
import os, sys
from os.path import dirname, abspath
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
parent = dirname(dirname(dirname(abspath(__file__))))
sys.path.insert(0, parent)
from django.test.simple import DjangoTestSuiteRunner
if __name__ == '__main__':
DjangoTestSuiteRunner(failfast=False).run_tests(
['contrib.BackendsTest'], verbosity=1, interactive=True)
| 1.492188
| 1
|
services/_api_service_template/src/main.py
|
amthorn/qutex
| 0
|
12778663
|
<gh_stars>0
import flask
import os
import json
import marshmallow
import pprint
import requests
import werkzeug
import traceback
from app import app
from typing import Union
from bson.objectid import ObjectId
app.config['SERVICE_PREFIX'] = os.environ.get('SERVICE_PREFIX')
app.config['AUTH_SERVICE_TOKEN_CHECK_ROUTE'] = os.environ['AUTH_SERVICE_TOKEN_CHECK_ROUTE']
app.config['AUTH_SERVICE_HOST'] = os.environ['AUTH_SERVICE_HOST']
app.config['SUPER_ADMINS'] = json.loads(os.environ['SUPER_ADMINS'])
app.config['TOKEN_COOKIE_NAME'] = 'qutexToken'
app.config['FQDN'] = os.environ.get('FQDN', 'http://localhost')
app.config['DEFAULT_PAGE_LENGTH'] = 50
# Otherwise we get an error "Response" has no attribute 'get' from flask restx
app.config['ERROR_INCLUDE_MESSAGE'] = False
class CustomJSONEncoder(flask.json.JSONEncoder):
def default(self, o: object) -> str:
if isinstance(o, ObjectId):
return str(o)
return super().default(o)
app.config["RESTX_JSON"] = {"cls": CustomJSONEncoder}
########################
# SERVICE CONFIG SETUP #
########################
try:
with open('/run/secrets/privateKey') as f:
app.secret_key = f.read()
except Exception:
print("WARNING: No privateKey secret provided for Flask application")
try:
with open('/run/secrets/token') as f:
app.config['WEBEX_TEAMS_ACCESS_TOKEN'] = f.read().strip()
except Exception:
print("WARNING: No webex teams access token provided for Flask application")
try:
with open('/run/secrets/mongoPassword') as f:
app.config['MONGO_PASSWORD'] = f.read()
except Exception:
print("WARNING: No mongo password provided for Flask application")
##########
# MODELS #
##########
import setup_db # noqa
##########
# APIS #
##########
from setup_api import v1 # noqa
import documents # noqa
import api # noqa
@v1.errorhandler(Exception)
@app.errorhandler(Exception)
def handle_exception(e: Exception) -> flask.Response:
# Flask rest x bugs cause this to catch all errors
if isinstance(e, marshmallow.exceptions.ValidationError):
return dump_data(e, flask.make_response(), e.messages, 422)
elif isinstance(e, werkzeug.exceptions.Unauthorized):
response = dump_data(e, e.get_response(), {e.name: e.description}, e.code)
return response[0], response[1], {
**response[2],
'Set-Cookie': app.config.get("TOKEN_COOKIE_NAME") +
'=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT'
}
elif isinstance(e, werkzeug.exceptions.HTTPException):
return dump_data(e, e.get_response(), {e.name: e.description}, e.code)
return dump_data(e, flask.make_response(), {str(e.__class__.__name__): str(e)}, 500)
@app.before_request
def authenticate() -> None:
# if its not an unauthenticated route
unauthenticated = [
'/api/v1/auth/',
'healthcheck'
]
if not any([flask.request.path.startswith(i) for i in unauthenticated]):
# Will throw 401 if not authenticated
result = requests.get(
f"{app.config['AUTH_SERVICE_HOST']}/api/v1/auth/token/check",
cookies=flask.request.cookies
)
# It's not a very nice error, make it nicer looking
if result.status_code == 401:
raise werkzeug.exceptions.Unauthorized(result.json()['data']['description'])
result.raise_for_status()
def dump_data(
e: Exception,
response: flask.Response,
data: Union[list, dict],
code: int
) -> flask.Response:
message = dump_messages(data)
data = {
"data": {
"name": e.name if hasattr(e, 'name') else str(e.__class__.__name__),
"description": e.description if hasattr(e, 'description') else '',
},
"message": {
"raw": data,
"text": message,
"priority": "error"
}
}
app.logger.debug(pprint.pformat(response.data))
app.logger.debug(traceback.format_exc())
app.logger.debug(app.url_map)
return data, code, {'Content-Type': 'application/json'}
def dump_messages(data: dict) -> str:
messages = []
for k, v in data.items():
if isinstance(v, (tuple, list)) and len(v) > 0:
messages += [f'{k}: {i}' for i in v]
else:
messages.append(f'{k}: {v}')
return '\n'.join(messages)
| 1.960938
| 2
|
examples/resnest50.py
|
NodLabs/SHARK-Samples
| 11
|
12778664
|
import torch
import numpy as np
import os
import sys
from shark_runner import shark_inference
class ResNest50(torch.nn.Module):
def __init__(self):
super().__init__()
self.model = torch.hub.load(
"zhanghang1989/ResNeSt", "resnest50", pretrained=True
)
self.train(False)
def forward(self, input):
return self.model.forward(input)
input = torch.randn(1, 3, 224, 224)
results = shark_inference(
ResNest50(),
input,
device="cpu",
dynamic=False,
jit_trace=True,
)
| 2.671875
| 3
|
As_util.py
|
a2gs/AsWallet
| 1
|
12778665
|
<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# <NAME> (https://sites.google.com/view/a2gs/)
VERSION = float(0.1)
BTCLIB_DB_PATH = str('')
HOME_DIR = str('')
SCREENBAR = str('')
MSGBAR = str('')
| 1.640625
| 2
|
travel/docs/Amadeus-master/pactravel-master/swagger_client/models/car_reservation.py
|
shopglobal/api
| 0
|
12778666
|
<filename>travel/docs/Amadeus-master/pactravel-master/swagger_client/models/car_reservation.py
# coding: utf-8
"""
Amadeus Travel Innovation Sandbox
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class CarReservation(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'id': 'str',
'pick_up': 'str',
'drop_off': 'str',
'provider': 'Company',
'origin': 'str',
'car': 'Vehicle',
'traveler_ids': 'list[str]',
'booking_info': 'CarReservationBookingInfo'
}
attribute_map = {
'id': 'id',
'pick_up': 'pick_up',
'drop_off': 'drop_off',
'provider': 'provider',
'origin': 'origin',
'car': 'car',
'traveler_ids': 'traveler_ids',
'booking_info': 'booking_info'
}
def __init__(self, id=None, pick_up=None, drop_off=None, provider=None, origin=None, car=None, traveler_ids=None, booking_info=None):
"""
CarReservation - a model defined in Swagger
"""
self._id = None
self._pick_up = None
self._drop_off = None
self._provider = None
self._origin = None
self._car = None
self._traveler_ids = None
self._booking_info = None
self.id = id
self.pick_up = pick_up
self.drop_off = drop_off
self.provider = provider
self.origin = origin
self.car = car
if traveler_ids is not None:
self.traveler_ids = traveler_ids
if booking_info is not None:
self.booking_info = booking_info
@property
def id(self):
"""
Gets the id of this CarReservation.
Uniquely identifies this car rental reservation in this travel record. This ID is persistent, and remains the same for the lifetime of the travel record.
:return: The id of this CarReservation.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""
Sets the id of this CarReservation.
Uniquely identifies this car rental reservation in this travel record. This ID is persistent, and remains the same for the lifetime of the travel record.
:param id: The id of this CarReservation.
:type: str
"""
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`")
self._id = id
@property
def pick_up(self):
"""
Gets the pick_up of this CarReservation.
Date on which the car rental will be collected from the car rental location. <a href=\"https://en.wikipedia.org/wiki/ISO_8601\">ISO 8601</a> date format yyyy-MM-ddTHH.
:return: The pick_up of this CarReservation.
:rtype: str
"""
return self._pick_up
@pick_up.setter
def pick_up(self, pick_up):
"""
Sets the pick_up of this CarReservation.
Date on which the car rental will be collected from the car rental location. <a href=\"https://en.wikipedia.org/wiki/ISO_8601\">ISO 8601</a> date format yyyy-MM-ddTHH.
:param pick_up: The pick_up of this CarReservation.
:type: str
"""
if pick_up is None:
raise ValueError("Invalid value for `pick_up`, must not be `None`")
self._pick_up = pick_up
@property
def drop_off(self):
"""
Gets the drop_off of this CarReservation.
Date at which the car rental will end and the car will be returned to the rental location. <a href=\"https://en.wikipedia.org/wiki/ISO_8601\">ISO 8601</a> date format yyyy-MM-ddTHH.
:return: The drop_off of this CarReservation.
:rtype: str
"""
return self._drop_off
@drop_off.setter
def drop_off(self, drop_off):
"""
Sets the drop_off of this CarReservation.
Date at which the car rental will end and the car will be returned to the rental location. <a href=\"https://en.wikipedia.org/wiki/ISO_8601\">ISO 8601</a> date format yyyy-MM-ddTHH.
:param drop_off: The drop_off of this CarReservation.
:type: str
"""
if drop_off is None:
raise ValueError("Invalid value for `drop_off`, must not be `None`")
self._drop_off = drop_off
@property
def provider(self):
"""
Gets the provider of this CarReservation.
Details of the car company offering this rental.
:return: The provider of this CarReservation.
:rtype: Company
"""
return self._provider
@provider.setter
def provider(self, provider):
"""
Sets the provider of this CarReservation.
Details of the car company offering this rental.
:param provider: The provider of this CarReservation.
:type: Company
"""
if provider is None:
raise ValueError("Invalid value for `provider`, must not be `None`")
self._provider = provider
@property
def origin(self):
"""
Gets the origin of this CarReservation.
This car rental company office location ID. If this is an airport location, this will be the airport's <a href=\"https://en.wikipedia.org/wiki/International_Air_Transport_Association_airport_code\">IATA code</a>. Otherwise, this is a custom value provided by the car rental provider.
:return: The origin of this CarReservation.
:rtype: str
"""
return self._origin
@origin.setter
def origin(self, origin):
"""
Sets the origin of this CarReservation.
This car rental company office location ID. If this is an airport location, this will be the airport's <a href=\"https://en.wikipedia.org/wiki/International_Air_Transport_Association_airport_code\">IATA code</a>. Otherwise, this is a custom value provided by the car rental provider.
:param origin: The origin of this CarReservation.
:type: str
"""
if origin is None:
raise ValueError("Invalid value for `origin`, must not be `None`")
self._origin = origin
@property
def car(self):
"""
Gets the car of this CarReservation.
A car information object giving further details about the vehicle provided for rental.
:return: The car of this CarReservation.
:rtype: Vehicle
"""
return self._car
@car.setter
def car(self, car):
"""
Sets the car of this CarReservation.
A car information object giving further details about the vehicle provided for rental.
:param car: The car of this CarReservation.
:type: Vehicle
"""
if car is None:
raise ValueError("Invalid value for `car`, must not be `None`")
self._car = car
@property
def traveler_ids(self):
"""
Gets the traveler_ids of this CarReservation.
Traveler identifiers to indicate the travelers to whom this car rental applies. Generally, only drivers of the vehicle will be marked in this array.
:return: The traveler_ids of this CarReservation.
:rtype: list[str]
"""
return self._traveler_ids
@traveler_ids.setter
def traveler_ids(self, traveler_ids):
"""
Sets the traveler_ids of this CarReservation.
Traveler identifiers to indicate the travelers to whom this car rental applies. Generally, only drivers of the vehicle will be marked in this array.
:param traveler_ids: The traveler_ids of this CarReservation.
:type: list[str]
"""
self._traveler_ids = traveler_ids
@property
def booking_info(self):
"""
Gets the booking_info of this CarReservation.
Additional details the status of this car rental reservation.
:return: The booking_info of this CarReservation.
:rtype: CarReservationBookingInfo
"""
return self._booking_info
@booking_info.setter
def booking_info(self, booking_info):
"""
Sets the booking_info of this CarReservation.
Additional details the status of this car rental reservation.
:param booking_info: The booking_info of this CarReservation.
:type: CarReservationBookingInfo
"""
self._booking_info = booking_info
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, CarReservation):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| 1.953125
| 2
|
nesdis_aws/nesdis_aws.py
|
hagne/nesdis_aws
| 0
|
12778667
|
# -*- coding: utf-8 -*-
import pathlib as _pl
import pandas as _pd
import s3fs as _s3fs
# import urllib as _urllib
# import html2text as _html2text
import psutil as _psutil
import numpy as _np
# import xarray as _xr
def readme():
url = 'https://docs.opendata.aws/noaa-goes16/cics-readme.html'
# html = _urllib.request.urlopen(url).read().decode("utf-8")
# out = _html2text.html2text(html)
# print(out)
print(f'follow link for readme: {url}')
def available_products():
aws = _s3fs.S3FileSystem(anon=True)
df = _pd.DataFrame()
for satellite in [16,17]:
# satellite = 16#16 (east) or 17(west)
base_folder = _pl.Path(f'noaa-goes{satellite}')
products_available = aws.glob(base_folder.joinpath('*').as_posix())
df[satellite] = [p.split('/')[-1] for p in products_available if '.pdf' not in p]
if _np.all(df[16] == df[17]):
ins = ''
else:
ins = ' !!_NOT_!!'
print(f'goes 16 and 17 products are{ins} identical')
return df
class AwsQuery(object):
def __init__(self,
path2folder_local = '/mnt/telg/tmp/aws_tmp/',
satellite = '16',
product = 'ABI-L2-AOD',
scan_sector = 'C',
start = '2020-08-08 20:00:00',
end = '2020-08-09 18:00:00',
process = None,
keep_files = None,
# check_if_file_exist = True,
# no_of_days = None,
# last_x_days = None,
# max_no_of_files = 100,#10*24*7,
):
"""
This will initialize a search on AWS.
Parameters
----------
path2folder_local : TYPE, optional
DESCRIPTION. The default is '/mnt/telg/tmp/aws_tmp/'.
satellite : TYPE, optional
DESCRIPTION. The default is '16'.
product : str, optional
Note this is the product name described at
https://docs.opendata.aws/noaa-goes16/cics-readme.html
but without the scan sector. The default is 'ABI-L2-AOD'.
scan_sector : str, optional
(C)onus, (F)ull_disk, (M)eso. The default is 'C'.
start : TYPE, optional
DESCRIPTION. The default is '2020-08-08 20:00:00'.
end : TYPE, optional
DESCRIPTION. The default is '2020-08-09 18:00:00'.
process: dict,
This is still in development and might be buggy.
Example:
dict(concatenate = 'daily',
function = lambda row: some_function(row, *args, **kwargs),
prefix = 'ABI_L2_AOD_processed',
path2processed = '/path2processed/')
keep_files: bool, optional
Default is True unless process is given which changes the default
False.
Returns
-------
None.
"""
self.satellite = satellite
self.path2folder_aws = _pl.Path(f'noaa-goes{self.satellite}')
self.scan_sector = scan_sector
self.product = product
self.start = _pd.to_datetime(start)
self.end = _pd.to_datetime(end)
self.path2folder_local = _pl.Path(path2folder_local)
if isinstance(process, dict):
self._process = True
# self._process_concatenate = process['concatenate']
self._process_function = process['function']
self._process_name_prefix = process['prefix']
self._process_path2processed = _pl.Path(process['path2processed'])
# self._process_path2processed_tmp = self._process_path2processed.joinpath('tmp')
# self._process_path2processed_tmp.mkdir(exist_ok=True)
self.keep_files = False
# self.check_if_file_exist = False
else:
self._process = False
self.aws = _s3fs.S3FileSystem(anon=True)
self.aws.clear_instance_cache() # strange things happen if the is not the only query one is doing during a session
# properties
self._workplan = None
@property
def product(self):
return self._product
@product.setter
def product(self, value):
if value[-1] == self.scan_sector:
value = value[:-1]
self._product = value
return
def info_on_current_query(self):
nooffiles = self.workplan.shape[0]
if nooffiles == 0:
info = 'no file found or all files already on disk.'
else:
du = self.estimate_disk_usage()
disk_space_needed = du['disk_space_needed'] * 1e-6
disk_space_free_after_download = du['disk_space_free_after_download']
info = (f'no of files: {nooffiles}\n'
f'estimated disk usage: {disk_space_needed:0.0f} mb\n'
f'remaining disk space after download: {disk_space_free_after_download:0.0f} %\n')
return info
# def print_readme(self):
# url = 'https://docs.opendata.aws/noaa-goes16/cics-readme.html'
# html = _urllib.request.urlopen(url).read().decode("utf-8")
# out = _html2text.html2text(html)
# print(out)
def estimate_disk_usage(self, sample_size = 10): #mega bites
step_size = int(self.workplan.shape[0]/sample_size)
if step_size < 1:
step_size = 1
sizes = self.workplan.iloc[::step_size].apply(lambda row: self.aws.disk_usage(row.path2file_aws), axis = 1)
# sizes = self.workplan.iloc[::int(self.workplan.shape[0]/sample_size)].apply(lambda row: self.aws.disk_usage(row.path2file_aws), axis = 1)
disk_space_needed = sizes.mean() * self.workplan.shape[0]
# get remaining disk space after download
du = _psutil.disk_usage(self.path2folder_local)
disk_space_free_after_download = 100 - (100* (du.used + disk_space_needed)/du.total )
out = {}
out['disk_space_needed'] = disk_space_needed
out['disk_space_free_after_download'] = disk_space_free_after_download
return out
@property
def workplan(self):
if isinstance(self._workplan, type(None)):
# #### bug: problem below is that time ranges that span over multiple years will not work!
# # get the julian days (thus folders on aws) needed
# start_julian = int(_pd.to_datetime(self.start.date()).to_julian_date() - _pd.to_datetime(f'{self.start.year:04d}-01-01').to_julian_date()) + 1
# end_julian = int(_pd.to_datetime(self.end.date()).to_julian_date() - _pd.to_datetime(f'{self.end.year:04d}-01-01').to_julian_date()) + 1
# days = list(range(start_julian, end_julian+1))
# # get all the files available
# # base_folder = pl.Path(f'noaa-goes{self.satellite}')
# base_folder = self.path2folder_aws
# product_folder = base_folder.joinpath(f'{self.product}{self.scan_sector}')
# files_available = []
# year_folder = product_folder.joinpath(f'{self.start.year}')
# for day in days:
# day_folder = year_folder.joinpath(f'{day:03d}')
# hours_available = self.aws.glob(day_folder.joinpath('*').as_posix())
# hours_available = [h.split('/')[-1] for h in hours_available]
# for hour in hours_available:
# hour_folder = day_folder.joinpath(f'{hour}')
# glob_this = hour_folder.joinpath('*').as_posix()
# last_glob = self.aws.glob(glob_this)
# files_available += last_glob
#### make a data frame to all the available files in the time range
# create a dataframe with all hours in the time range
df = _pd.DataFrame(index = _pd.date_range(self.start, self.end, freq='h'), columns=['path'])
# create the path to the directory of each row above (one per houre)
product_folder = self.path2folder_aws.joinpath(f'{self.product}{self.scan_sector}')
df['path'] = df.apply(lambda row: product_folder.joinpath(str(row.name.year)).joinpath(f'{row.name.day_of_year:03d}').joinpath(f'{row.name.hour:02d}').joinpath('*'), axis= 1)
# get the path to each file in all the folders
files_available = []
for idx,row in df.iterrows():
files_available += self.aws.glob(row.path.as_posix())
#### Make workplan
workplan = _pd.DataFrame([_pl.Path(f) for f in files_available], columns=['path2file_aws'])
workplan['path2file_local'] = workplan.apply(lambda row: self.path2folder_local.joinpath(row.path2file_aws.name), axis = 1)
#### remove if local file exists
if not self._process:
workplan = workplan[~workplan.apply(lambda row: row.path2file_local.is_file(), axis = 1)]
# get file sizes ... takes to long to do for each file
# workplan['file_size_mb'] = workplan.apply(lambda row: self.aws.disk_usage(row.path2file_aws)/1e6, axis = 1)
#### get the timestamp
def row2timestamp(row):
sos = row.path2file_aws.name.split('_')[-3]
assert(sos[0] == 's'), f'Something needs fixing, this string ({sos}) should start with s.'
ts = _pd.to_datetime(sos[1:-1],format = '%Y%j%H%M%S')
return ts
workplan.index = workplan.apply(lambda row: row2timestamp(row), axis = 1)
#### truncate ... remember so far we did not consider times in start and end, only the entire days
workplan = workplan.sort_index()
workplan = workplan.truncate(self.start, self.end)
#### processing additions
if self._process:
### add path to processed file names
workplan["path2file_local_processed"] = workplan.apply(lambda row: self._process_path2processed.joinpath(f'{self._process_name_prefix}_{row.name.year}{row.name.month:02d}{row.name.day:02d}_{row.name.hour:02d}{row.name.minute:02d}{row.name.second:02d}.nc'), axis = 1)
### remove if file exists
workplan = workplan[~workplan.apply(lambda row: row.path2file_local_processed.is_file(), axis = True)]
# workplan['path2file_tmp'] = workplan.apply(lambda row: self._process_path2processed_tmp.joinpath(row.name.__str__()), axis = 1)
self._workplan = workplan
return self._workplan
@workplan.setter
def workplan(self, new_workplan):
self._workplan = new_workplan
@property
def product_available_since(self):
product_folder = self.path2folder_aws.joinpath(f'{self.product}{self.scan_sector}')
years = self.aws.glob(product_folder.joinpath('*').as_posix())
years.sort()
is2000 = True
while is2000:
yearfolder = years.pop(0)
firstyear = yearfolder.split('/')[-1]
# print(firstyear)
if firstyear != '2000':
is2000 = False
yearfolder = _pl.Path(yearfolder)
days = self.aws.glob(yearfolder.joinpath('*').as_posix())
days.sort()
firstday = int(days[0].split('/')[-1])
firstday_ts = _pd.to_datetime(firstyear) + _pd.to_timedelta(firstday, "D")
return firstday_ts
def download(self, test = False, overwrite = False, alternative_workplan = False,
error_if_low_disk_space = True):
"""
Parameters
----------
test : TYPE, optional
DESCRIPTION. The default is False.
overwrite : TYPE, optional
DESCRIPTION. The default is False.
alternative_workplan : pandas.Dataframe, optional
This will ignore the instance workplan and use the provided one
instead. The default is False.
error_if_low_disk_space : TYPE, optional
DESCRIPTION. The default is True.
Returns
-------
out : TYPE
DESCRIPTION.
"""
if isinstance(alternative_workplan, _pd.DataFrame):
workplan = alternative_workplan
else:
workplan = self.workplan
if error_if_low_disk_space:
disk_space_free_after_download = self.estimate_disk_usage()['disk_space_free_after_download']
assert(disk_space_free_after_download<90), f"This download will bring the disk usage above 90% ({disk_space_free_after_download:0.0f}%). Turn off this error by setting error_if_low_disk_space to False."
for idx, row in workplan.iterrows():
if not overwrite:
if row.path2file_local.is_file():
continue
out = self.aws.get(row.path2file_aws.as_posix(), row.path2file_local.as_posix())
if test:
break
return out
def process(self):
# deprecated first grouping is required
# group = self.workplan.groupby('path2file_local_processed')
# for p2flp, p2flpgrp in group:
# break
## for each file in group
for dt, row in self.workplan.iterrows():
if row.path2file_local_processed.is_file():
continue
if not row.path2file_local.is_file():
# print('downloading')
#### download
# download_output =
self.aws.get(row.path2file_aws.as_posix(), row.path2file_local.as_posix())
#### process
try:
self._process_function(row)
except:
print(f'error applying function on one file {row.path2file_local.name}. The raw fill will still be removed (unless keep_files is True) to avoid storage issues')
#### remove raw file
if not self.keep_files:
row.path2file_local.unlink()
#### todo: concatenate
# if this is actually desired I would think this should be done seperately, not as part of this package
# try:
# ds = _xr.open_mfdataset(p2flpgrp.path2file_tmp)
# #### save final product
# ds.to_netcdf(p2flp)
# #### remove all tmp files
# if not keep_tmp_files:
# for dt, row in p2flpgrp.iterrows():
# try:
# row.path2file_tmp.unlink()
# except FileNotFoundError:
# pass
# except:
# print('something went wrong with the concatenation. The file will not be removed')
| 2.609375
| 3
|
src/datalayer/snapshotcreator.py
|
Dabble-of-DevOps-Bio/ella
| 0
|
12778668
|
from typing import Sequence, Dict, Union
import itertools
from vardb.datamodel import workflow, assessment, annotation
class SnapshotCreator(object):
EXCLUDED_FLAG = {
"classification": "CLASSIFICATION",
"frequency": "FREQUENCY",
"region": "REGION",
"ppy": "POLYPYRIMIDINE",
"gene": "GENE",
"quality": "QUALITY",
"consequence": "CONSEQUENCE",
"segregation": "SEGREGATION",
"inheritancemodel": "INHERITANCEMODEL",
}
def __init__(self, session):
self.session = session
def _allele_id_model_id(self, model, model_ids: Sequence[int]):
allele_ids_model_ids = (
self.session.query(getattr(model, "allele_id"), getattr(model, "id"))
.filter(getattr(model, "id").in_(model_ids))
.all()
)
assert len(allele_ids_model_ids) == len(model_ids)
return {a[0]: a[1] for a in allele_ids_model_ids}
def insert_from_data(
self,
allele_ids: Sequence[int],
interpretation_snapshot_model: str, # 'allele' or 'analysis'
interpretation: Union[workflow.AnalysisInterpretation, workflow.AlleleInterpretation],
annotation_ids: Sequence[int],
custom_annotation_ids: Sequence[int],
alleleassessment_ids: Sequence[int],
allelereport_ids: Sequence[int],
excluded_allele_ids: Dict = None,
) -> Sequence[Dict]:
excluded: Dict = {}
if interpretation_snapshot_model == "analysis":
assert excluded_allele_ids is not None
excluded = excluded_allele_ids
all_allele_ids = list(
set(allele_ids).union(set(itertools.chain(*list(excluded.values()))))
)
# 'excluded' is not a concept for alleleinterpretation
elif interpretation_snapshot_model == "allele":
all_allele_ids = [interpretation.allele_id]
allele_ids_annotation_ids = self._allele_id_model_id(annotation.Annotation, annotation_ids)
allele_ids_custom_annotation_ids = self._allele_id_model_id(
annotation.CustomAnnotation, custom_annotation_ids
)
allele_ids_alleleassessment_ids = self._allele_id_model_id(
assessment.AlleleAssessment, alleleassessment_ids
)
allele_ids_allelereport_ids = self._allele_id_model_id(
assessment.AlleleReport, allelereport_ids
)
snapshot_items = list()
for allele_id in all_allele_ids:
# Check if allele_id is in any of the excluded categories
excluded_category = next((k for k, v in excluded.items() if allele_id in v), None)
snapshot_item = {
"allele_id": allele_id,
"annotation_id": allele_ids_annotation_ids.get(allele_id),
"customannotation_id": allele_ids_custom_annotation_ids.get(allele_id),
"alleleassessment_id": allele_ids_alleleassessment_ids.get(allele_id),
"allelereport_id": allele_ids_allelereport_ids.get(allele_id),
}
if interpretation_snapshot_model == "analysis":
snapshot_item["analysisinterpretation_id"] = interpretation.id
snapshot_item["filtered"] = (
SnapshotCreator.EXCLUDED_FLAG[excluded_category]
if excluded_category is not None
else None
)
elif interpretation_snapshot_model == "allele":
snapshot_item["alleleinterpretation_id"] = interpretation.id
snapshot_items.append(snapshot_item)
if interpretation_snapshot_model == "analysis":
self.session.bulk_insert_mappings(
workflow.AnalysisInterpretationSnapshot, snapshot_items
)
elif interpretation_snapshot_model == "allele":
self.session.bulk_insert_mappings(workflow.AlleleInterpretationSnapshot, snapshot_items)
return snapshot_items
| 2.296875
| 2
|
face_detection.py
|
gnublet/portfolio
| 0
|
12778669
|
<reponame>gnublet/portfolio
import cv2
import numpy as np
# Load the face, eye, nose, cascade file
face_cascade = cv2.CascadeClassifier('cascade_files/haarcascade_frontalface_alt.xml')
eye_cascade = cv2.CascadeClassifier('cascade_files/haarcascade_eye.xml')
nose_cascade = cv2.CascadeClassifier('cascade_files/haarcascade_mcs_nose.xml')
mouth_cascade = cv2.CascadeClassifier('cascade_files/haarcascade_mcs_mouth.xml')
# Check if the face cascade file has been loaded
if face_cascade.empty():
raise IOError('Unable to load the face cascade classifier xml file')
#Check if eye cascade file has been loaded correctly
if eye_cascade.empty():
raise IOError('Unable to load the eye cascade classifier xml file')
#Check if nose file loaded correctly
if nose_cascade.empty():
raise IOError('Unable to load the nose cascade classifier xml file')
#Check smile
if mouth_cascade.empty():
raise IOError('Unable to load the smile cascade classifier xml file')
# Initialize the video capture object
cap = cv2.VideoCapture(0)
# Define the scaling factor
scaling_factor = 0.5
# Loop until you hit the Esc key
while True:
# Capture the current frame and resize it
ret, frame = cap.read()
frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor,
interpolation=cv2.INTER_AREA)
# Convert to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Run the face detector on the grayscale image
face_rect = face_cascade.detectMultiScale(gray, 1.3, 5)
#1.3 scale multiplier for each stage
#5 min number of neighbors that each candidate rectangle should have so that we retain it.
#run eye, nose, mouth detector within each face rectangle
for (x,y,w,h) in face_rect:#(lowerleft (x,y), width, height)
#grab current region of interest in both color and grayscale
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
#run eye detector in grayscale roi
eye_rects = eye_cascade.detectMultiScale(roi_gray, 1.3, 3)
#nose detector
nose_rects = nose_cascade.detectMultiScale(roi_gray, 1.3,5)
#smile detector
mouth_rects = mouth_cascade.detectMultiScale(roi_gray, 2,10)
#draw blue circles around eyes
for (x_eye, y_eye, w_eye, h_eye) in eye_rects:
center = (int(x_eye + .5*w_eye), int(y_eye + .5*h_eye))
radius = (int(.3*(w_eye + h_eye)))
color = (0,0,255)
thickness = 1
cv2.circle(roi_color, center, radius, color, thickness)
#draw red rectangle around nose
for (x_nose, y_nose, w_nose, h_nose) in nose_rects:
cv2.rectangle(roi_color, (x_nose, y_nose), (x_nose+w_nose, y_nose+h_nose), (255,0,0), 1)
#draw rect around mouth
for (x_mouth, y_mouth, w_mouth, h_mouth) in mouth_rects:
cv2.rectangle(roi_color, (x_mouth, y_mouth), (x_mouth+w_mouth, y_mouth+h_mouth), (255,255,0), 1)
# Draw rectangles on the image
for (x,y,w,h) in face_rect:
cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2)
# Display the image
cv2.imshow('Face Detector', frame)
# Check if Esc key has been pressed
c = cv2.waitKey(1)
if c == 27:
break
# Release the video capture object and close all windows
cap.release()
cv2.destroyAllWindows()
| 2.59375
| 3
|
obj.py
|
mretolaza/flatShader
| 0
|
12778670
|
import struct
def color(r, g, b):
return bytes([b, g, r])
def try_int(s, base=10, val=None):
try:
return int(s, base)
except ValueError:
return val
class Obj(object):
def __init__(self, filename, fileMaterial=None):
with open(filename) as f:
self.lines = f.read().splitlines()
with open(fileMaterial) as g:
self.material = g.read().splitlines()
self.vertices = []
self.tvertices = []
self.vfaces = []
self.keyColor = []
self.colors = []
self.read()
self.getColorToDraw = ''
self.material = ''
def read(self):
self.getMaterial()
for line in self.lines:
if line:
try:
prefix, value = line.split(' ', 1)
except:
prefix = ''
if prefix == 'v':
self.vertices.append(list(map(float, value.split(' '))))
if prefix == 'vt':
self.tvertices.append(list(map(float, value.split(' '))))
elif prefix == 'f':
objToList = [list(map(try_int, face.split('/'))) for face in value.split(' ')]
objToList.append(self.getColorToDraw)
self.vfaces.append(objToList)
elif prefix == 'usemtl':
self.getColorToDraw = value
def getMaterial(self):
for line in self.material:
if line:
try:
prefix, value = line.split( ' ', 1)
except:
prefix = ''
if prefix == 'newmtl':
self.keyColor.append(value)
elif prefix == 'Kd':
self.colors.append(list(map(float, value.split( ' '))))
# agrega la textura
class Texture(object):
def __init__(self, path):
self.path = path
self.read()
def read(self):
image = open(self.path, "rb")
image.seek(2 + 4 + 4)
header_size = struct.unpack("=l", image.read(4))[0]
image.seek(2 + 4 + 4 + 4 + 4)
self.width = struct.unpack("=l", image.read(4))[0]
self.height = struct.unpack("=l", image.read(4))[0]
self.framebuffer = []
image.seek(header_size)
for y in range(self.height):
self.framebuffer.append([])
for x in range(self.width):
b = ord(image.read(1))
g = ord(image.read(1))
r = ord(image.read(1))
self.framebuffer[y].append(color(r,g,b))
image.close()
def get_color(self, tx, ty, intensity=1):
x = int(tx * self.width)
y = int(ty * self.height)
try:
return bytes(map(lambda b: round(b*intensity) if b*intensity > 0 else 0, self.framebuffer[y][x]))
except:
pass
| 2.9375
| 3
|
docs/examples/cpu_temperature_bar_graph.py
|
NotBobTheBuilder/gpiozero
| 743
|
12778671
|
<reponame>NotBobTheBuilder/gpiozero<filename>docs/examples/cpu_temperature_bar_graph.py
from gpiozero import LEDBarGraph, CPUTemperature
from signal import pause
cpu = CPUTemperature(min_temp=50, max_temp=90)
leds = LEDBarGraph(2, 3, 4, 5, 6, 7, 8, pwm=True)
leds.source = cpu
pause()
| 2.59375
| 3
|
nion/ui/CanvasItem.py
|
icbicket/nionui
| 3
|
12778672
|
"""
CanvasItem module contains classes related to canvas items.
"""
from __future__ import annotations
# standard libraries
import collections
import concurrent.futures
import contextlib
import copy
import datetime
import enum
import functools
import imageio
import logging
import operator
import sys
import threading
import types
import typing
import warnings
import weakref
# third party libraries
import numpy
# local libraries
from nion.ui import DrawingContext
from nion.utils import Event
from nion.utils import Geometry
from nion.utils import Observable
from nion.utils import Stream
if typing.TYPE_CHECKING:
from nion.ui import UserInterface
from nion.ui import MouseTrackingCanvasItem
from nion.ui import Widgets
MAX_VALUE = sys.maxsize
class Orientation(enum.Enum):
Vertical = 0
Horizontal = 1
class Constraint:
""" A constraint on an item in a layout. Preferred is only used when free sizing. """
def __init__(self) -> None:
self.minimum: typing.Optional[int] = None
self.maximum: typing.Optional[int] = None
self.preferred: typing.Optional[int] = None
def __repr__(self) -> str:
return "Constraint (min={0}, max={1}, pref={2})".format(self.minimum, self.maximum, self.preferred)
class SolverItem:
def __init__(self, constraint: Constraint) -> None:
self.constraint = constraint
self.size: typing.Optional[int] = None
self.is_constrained = False
ConstraintResultType = typing.Tuple[typing.List[int], typing.List[int]]
def constraint_solve(canvas_origin: int, canvas_size: int, canvas_item_constraints: typing.Sequence[Constraint], spacing: int = 0) -> ConstraintResultType:
"""
Solve the layout by assigning space and enforcing constraints.
Returns origins, sizes tuple.
"""
# setup information from each item
solver_items = [SolverItem(constraint) for constraint in canvas_item_constraints]
# assign preferred size, if any, to each item. items with preferred size are still
# free to change as long as they don't become constrained.
for solver_item in solver_items:
if solver_item.constraint.preferred is not None:
solver_item.size = solver_item.constraint.preferred
assert solver_item.constraint.minimum is not None
assert solver_item.constraint.maximum is not None
if solver_item.size < solver_item.constraint.minimum:
solver_item.size = solver_item.constraint.minimum
if solver_item.size > solver_item.constraint.maximum:
solver_item.size = solver_item.constraint.maximum
solver_item.is_constrained = True
if solver_item.size > solver_item.constraint.maximum:
solver_item.size = solver_item.constraint.maximum
if solver_item.size < solver_item.constraint.minimum:
solver_item.size = solver_item.constraint.minimum
solver_item.is_constrained = True
# put these here to avoid linter warnings
remaining_canvas_size = canvas_size
remaining_count = len(solver_items)
# assign the free space to the remaining items. first figure out how much space is left
# and how many items remain. then divide the space up.
finished = False
while not finished:
finished = True
remaining_canvas_size = canvas_size
remaining_count = len(solver_items)
# reset the items that we can, i.e. those that aren't already constrained and don't have a preferred size
for solver_item in solver_items:
if not solver_item.is_constrained and solver_item.constraint.preferred is None:
solver_item.size = None
# figure out how many free range items there are, i.e. those that don't already have a size assigned
for solver_item in solver_items:
if solver_item.size is not None:
remaining_canvas_size -= solver_item.size
remaining_count -= 1
# again attempt to assign sizes
for solver_item in solver_items:
if solver_item.size is None:
size = remaining_canvas_size // remaining_count
assert solver_item.constraint.minimum is not None
assert solver_item.constraint.maximum is not None
if size < solver_item.constraint.minimum:
size = solver_item.constraint.minimum
solver_item.is_constrained = True
finished = False
if size > solver_item.constraint.maximum:
size = solver_item.constraint.maximum
solver_item.is_constrained = True
finished = False
solver_item.size = size
remaining_canvas_size -= size
remaining_count -= 1
if not finished:
break
# go through again and assign any remaining space
for solver_item in solver_items:
if solver_item.size is None:
solver_item.size = remaining_canvas_size // remaining_count
# check if we're oversized. if so divide among unconstrained items, but honor minimum size.
finished = False
while not finished:
finished = True
actual_canvas_size = sum([solver_item.size for solver_item in solver_items])
assert actual_canvas_size is not None
if actual_canvas_size > canvas_size:
remaining_count = sum([not solver_item.is_constrained for solver_item in solver_items])
remaining_canvas_size = actual_canvas_size - canvas_size
if remaining_count > 0:
for solver_item in solver_items:
if not solver_item.is_constrained:
assert solver_item.size is not None
assert solver_item.constraint.minimum is not None
size = solver_item.size - remaining_canvas_size // remaining_count
if size < solver_item.constraint.minimum:
size = solver_item.constraint.minimum
solver_item.is_constrained = True
finished = False
adjustment = solver_item.size - size
solver_item.size = size
remaining_canvas_size -= adjustment
remaining_count -= 1
if not finished:
break
# check if we're undersized. if so add among unconstrained items, but honor maximum size.
finished = False
while not finished:
finished = True
actual_canvas_size = sum([solver_item.size for solver_item in solver_items])
assert actual_canvas_size is not None
if actual_canvas_size < canvas_size:
remaining_count = sum([not solver_item.is_constrained for solver_item in solver_items])
remaining_canvas_size = canvas_size - actual_canvas_size
if remaining_count > 0:
for solver_item in solver_items:
if not solver_item.is_constrained:
assert solver_item.size is not None
assert solver_item.constraint.maximum is not None
size = solver_item.size + remaining_canvas_size // remaining_count
if size > solver_item.constraint.maximum:
size = solver_item.constraint.maximum
solver_item.is_constrained = True
finished = False
adjustment = size - solver_item.size
solver_item.size = size
remaining_canvas_size -= adjustment
remaining_count -= 1
if not finished:
break
# assign layouts
# TODO: allow for various justification options (start - default, end, center, space-between, space-around)
# see https://css-tricks.com/snippets/css/a-guide-to-flexbox/
sizes = [(solver_item.size or 0) for solver_item in solver_items]
origins = list()
for index in range(len(canvas_item_constraints)):
origins.append(canvas_origin)
canvas_origin += sizes[index] + spacing
return origins, sizes
class Sizing:
"""
Describes the sizing for a particular canvas item.
Aspect ratio, width, and height can each specify minimums, maximums, and preferred values.
Width and height can be integer or floats. If floats, they specify a percentage of their
respective maximum.
Preferred values are only used when free sizing.
Collapsible items collapse to fixed size of 0 if they don't have children.
"""
def __init__(self) -> None:
self.__preferred_width: typing.Optional[typing.Union[int, float]] = None
self.__preferred_height: typing.Optional[typing.Union[int, float]] = None
self.__preferred_aspect_ratio: typing.Optional[float] = None
self.__minimum_width: typing.Optional[typing.Union[int, float]] = None
self.__minimum_height: typing.Optional[typing.Union[int, float]] = None
self.__minimum_aspect_ratio: typing.Optional[float] = None
self.__maximum_width: typing.Optional[typing.Union[int, float]] = None
self.__maximum_height: typing.Optional[typing.Union[int, float]] = None
self.__maximum_aspect_ratio: typing.Optional[float] = None
self.__collapsible: bool = False
def __repr__(self) -> str:
format_str = "Sizing (min_w={0}, max_w={1}, pref_w={2}, min_h={3}, max_h={4}, pref_h={5}, min_a={6}, max_a={7}, pref_a={8}, collapsible={9})"
return format_str.format(self.__minimum_width, self.__maximum_width, self.__preferred_width,
self.__minimum_height, self.__maximum_height, self.__preferred_height,
self.__minimum_aspect_ratio, self.__maximum_aspect_ratio, self.__preferred_aspect_ratio,
self.__collapsible)
def __eq__(self, other: typing.Any) -> bool:
if self.__preferred_width != other.preferred_width:
return False
if self.__preferred_height != other.preferred_height:
return False
if self.__preferred_aspect_ratio != other.preferred_aspect_ratio:
return False
if self.__minimum_width != other.minimum_width:
return False
if self.__minimum_height != other.minimum_height:
return False
if self.__minimum_aspect_ratio != other.minimum_aspect_ratio:
return False
if self.__maximum_width != other.maximum_width:
return False
if self.__maximum_height != other.maximum_height:
return False
if self.__maximum_aspect_ratio != other.maximum_aspect_ratio:
return False
if self.__collapsible != other.collapsible:
return False
return True
def __deepcopy__(self, memo: typing.Dict[typing.Any, typing.Any]) -> Sizing:
deepcopy = Sizing()
deepcopy._copy_from(self)
memo[id(self)] = deepcopy
return deepcopy
@property
def preferred_width(self) -> typing.Optional[typing.Union[int, float]]:
return self.__preferred_width
@property
def preferred_height(self) -> typing.Optional[typing.Union[int, float]]:
return self.__preferred_height
@property
def preferred_aspect_ratio(self) -> typing.Optional[float]:
return self.__preferred_aspect_ratio
@property
def minimum_width(self) -> typing.Optional[typing.Union[int, float]]:
return self.__minimum_width
@property
def minimum_height(self) -> typing.Optional[typing.Union[int, float]]:
return self.__minimum_height
@property
def minimum_aspect_ratio(self) -> typing.Optional[float]:
return self.__minimum_aspect_ratio
@property
def maximum_width(self) -> typing.Optional[typing.Union[int, float]]:
return self.__maximum_width
@property
def maximum_height(self) -> typing.Optional[typing.Union[int, float]]:
return self.__maximum_height
@property
def maximum_aspect_ratio(self) -> typing.Optional[float]:
return self.__maximum_aspect_ratio
@property
def collapsible(self) -> bool:
return self.__collapsible
@property
def _preferred_width(self) -> typing.Optional[typing.Union[int, float]]:
return self.__preferred_width
@_preferred_width.setter
def _preferred_width(self, value: typing.Optional[typing.Union[int, float]]) -> None:
self.__preferred_width = value
def with_preferred_width(self, width: typing.Optional[typing.Union[int, float]]) -> Sizing:
sizing = copy.deepcopy(self)
sizing._preferred_width = width
return sizing
@property
def _preferred_height(self) -> typing.Optional[typing.Union[int, float]]:
return self.__preferred_height
@_preferred_height.setter
def _preferred_height(self, value: typing.Optional[typing.Union[int, float]]) -> None:
self.__preferred_height = value
def with_preferred_height(self, height: typing.Optional[typing.Union[int, float]]) -> Sizing:
sizing = copy.deepcopy(self)
sizing._preferred_height = height
return sizing
@property
def _preferred_aspect_ratio(self) -> typing.Optional[float]:
return self.__preferred_aspect_ratio
@_preferred_aspect_ratio.setter
def _preferred_aspect_ratio(self, value: typing.Optional[float]) -> None:
self.__preferred_aspect_ratio = value
def with_preferred_aspect_ratio(self, aspect_ratio: typing.Optional[float]) -> Sizing:
sizing = copy.deepcopy(self)
sizing._preferred_aspect_ratio = aspect_ratio
return sizing
@property
def _minimum_width(self) -> typing.Optional[typing.Union[int, float]]:
return self.__minimum_width
@_minimum_width.setter
def _minimum_width(self, value: typing.Optional[typing.Union[int, float]]) -> None:
self.__minimum_width = value
def with_minimum_width(self, width: typing.Optional[typing.Union[int, float]]) -> Sizing:
sizing = copy.deepcopy(self)
sizing._minimum_width = width
return sizing
@property
def _minimum_height(self) -> typing.Optional[typing.Union[int, float]]:
return self.__minimum_height
@_minimum_height.setter
def _minimum_height(self, value: typing.Optional[typing.Union[int, float]]) -> None:
self.__minimum_height = value
def with_minimum_height(self, height: typing.Optional[typing.Union[int, float]]) -> Sizing:
sizing = copy.deepcopy(self)
sizing._minimum_height = height
return sizing
@property
def _minimum_aspect_ratio(self) -> typing.Optional[float]:
return self.__minimum_aspect_ratio
@_minimum_aspect_ratio.setter
def _minimum_aspect_ratio(self, value: typing.Optional[float]) -> None:
self.__minimum_aspect_ratio = value
def with_minimum_aspect_ratio(self, aspect_ratio: typing.Optional[float]) -> Sizing:
sizing = copy.deepcopy(self)
sizing._minimum_aspect_ratio = aspect_ratio
return sizing
@property
def _maximum_width(self) -> typing.Optional[typing.Union[int, float]]:
return self.__maximum_width
@_maximum_width.setter
def _maximum_width(self, value: typing.Optional[typing.Union[int, float]]) -> None:
self.__maximum_width = value
def with_maximum_width(self, width: typing.Optional[typing.Union[int, float]]) -> Sizing:
sizing = copy.deepcopy(self)
sizing._maximum_width = width
return sizing
@property
def _maximum_height(self) -> typing.Optional[typing.Union[int, float]]:
return self.__maximum_height
@_maximum_height.setter
def _maximum_height(self, value: typing.Optional[typing.Union[int, float]]) -> None:
self.__maximum_height = value
def with_maximum_height(self, height: typing.Optional[typing.Union[int, float]]) -> Sizing:
sizing = copy.deepcopy(self)
sizing._maximum_height = height
return sizing
@property
def _maximum_aspect_ratio(self) -> typing.Optional[float]:
return self.__maximum_aspect_ratio
@_maximum_aspect_ratio.setter
def _maximum_aspect_ratio(self, value: typing.Optional[float]) -> None:
self.__maximum_aspect_ratio = value
def with_maximum_aspect_ratio(self, aspect_ratio: typing.Optional[float]) -> Sizing:
sizing = copy.deepcopy(self)
sizing._maximum_aspect_ratio = aspect_ratio
return sizing
@property
def _collapsible(self) -> bool:
return self.__collapsible
@_collapsible.setter
def _collapsible(self, value: bool) -> None:
self.__collapsible = value
def with_collapsible(self, collapsible: bool) -> Sizing:
sizing = copy.deepcopy(self)
sizing._collapsible = collapsible
return sizing
def _copy_from(self, other: Sizing) -> None:
self.__preferred_width = other.preferred_width
self.__preferred_height = other.preferred_height
self.__preferred_aspect_ratio = other.preferred_aspect_ratio
self.__minimum_width = other.minimum_width
self.__minimum_height = other.minimum_height
self.__minimum_aspect_ratio = other.minimum_aspect_ratio
self.__maximum_width = other.maximum_width
self.__maximum_height = other.maximum_height
self.__maximum_aspect_ratio = other.maximum_aspect_ratio
self.__collapsible = other.collapsible
def _clear_height_constraint(self) -> None:
self.__preferred_height = None
self.__minimum_height = None
self.__maximum_height = None
def with_unconstrained_height(self) -> Sizing:
sizing = copy.deepcopy(self)
sizing._clear_height_constraint()
return sizing
def _clear_width_constraint(self) -> None:
self.__preferred_width = None
self.__minimum_width = None
self.__maximum_width = None
def with_unconstrained_width(self) -> Sizing:
sizing = copy.deepcopy(self)
sizing._clear_width_constraint()
return sizing
def _set_fixed_height(self, height: typing.Optional[typing.Union[int, float]]) -> None:
self.__preferred_height = height
self.__minimum_height = height
self.__maximum_height = height
def with_fixed_height(self, height: typing.Optional[typing.Union[int, float]]) -> Sizing:
sizing = copy.deepcopy(self)
sizing._set_fixed_height(height)
return sizing
def _set_fixed_width(self, width: typing.Optional[typing.Union[int, float]]) -> None:
self.__preferred_width = width
self.__minimum_width = width
self.__maximum_width = width
def with_fixed_width(self, width: typing.Optional[typing.Union[int, float]]) -> Sizing:
sizing = copy.deepcopy(self)
sizing._set_fixed_width(width)
return sizing
def _set_fixed_size(self, size: Geometry.IntSizeTuple) -> None:
size_ = Geometry.IntSize.make(size)
self._set_fixed_height(size_.height)
self._set_fixed_width(size_.width)
def with_fixed_size(self, size: Geometry.IntSizeTuple) -> Sizing:
sizing = copy.deepcopy(self)
sizing._set_fixed_size(size)
return sizing
def get_width_constraint(self, width: typing.Union[int, float]) -> Constraint:
""" Create and return a new width Constraint object made from this sizing object. """
constraint = Constraint()
if self.minimum_width is not None:
if isinstance(self.minimum_width, float) and self.minimum_width <= 1.0:
constraint.minimum = int(width * self.minimum_width)
else:
constraint.minimum = int(self.minimum_width)
else:
constraint.minimum = 0
if self.maximum_width is not None:
if isinstance(self.maximum_width, float) and self.maximum_width <= 1.0:
constraint.maximum = int(width * self.maximum_width)
else:
constraint.maximum = int(self.maximum_width)
else:
constraint.maximum = MAX_VALUE
if self.preferred_width is not None:
if isinstance(self.preferred_width, float) and self.preferred_width <= 1.0:
constraint.preferred = int(width * self.preferred_width)
else:
constraint.preferred = int(self.preferred_width)
else:
constraint.preferred = None
return constraint
def get_height_constraint(self, height: typing.Union[int, float]) -> Constraint:
""" Create and return a new height Constraint object made from this sizing object. """
constraint = Constraint()
if self.minimum_height is not None:
if isinstance(self.minimum_height, float) and self.minimum_height <= 1.0:
constraint.minimum = int(height * self.minimum_height)
else:
constraint.minimum = int(self.minimum_height)
else:
constraint.minimum = 0
if self.maximum_height is not None:
if isinstance(self.maximum_height, float) and self.maximum_height <= 1.0:
constraint.maximum = int(height * self.maximum_height)
else:
constraint.maximum = int(self.maximum_height)
else:
constraint.maximum = MAX_VALUE
if self.preferred_height is not None:
if isinstance(self.preferred_height, float) and self.preferred_height <= 1.0:
constraint.preferred = int(height * self.preferred_height)
else:
constraint.preferred = int(self.preferred_height)
else:
constraint.preferred = None
return constraint
def get_unrestrained_width(self, maximum_width: typing.Union[int, float]) -> int:
if self.maximum_width is not None:
if isinstance(self.maximum_width, float) and self.maximum_width < 1.0:
return int(self.maximum_width * maximum_width)
return int(min(self.maximum_width, maximum_width))
return int(maximum_width)
def get_unrestrained_height(self, maximum_height: typing.Union[int, float]) -> int:
if self.maximum_height is not None:
if isinstance(self.maximum_height, float) and self.maximum_height < 1.0:
return int(self.maximum_height * maximum_height)
return int(min(self.maximum_height, maximum_height))
return int(maximum_height)
class KeyboardModifiers:
def __init__(self, shift: bool = False, control: bool = False, alt: bool = False, meta: bool = False, keypad: bool = False) -> None:
self.__shift = shift
self.__control = control
self.__alt = alt
self.__meta = meta
self.__keypad = keypad
@property
def any_modifier(self) -> bool:
return self.shift or self.control or self.alt or self.meta
# shift
@property
def shift(self) -> bool:
return self.__shift
@property
def only_shift(self) -> bool:
return self.__shift and not self.__control and not self.__alt and not self.__meta
# control (command key on mac)
@property
def control(self) -> bool:
return self.__control
@property
def only_control(self) -> bool:
return self.__control and not self.__shift and not self.__alt and not self.__meta
# alt (option key on mac)
@property
def alt(self) -> bool:
return self.__alt
@property
def only_alt(self) -> bool:
return self.__alt and not self.__control and not self.__shift and not self.__meta
# option (alt key on windows)
@property
def option(self) -> bool:
return self.__alt
@property
def only_option(self) -> bool:
return self.__alt and not self.__control and not self.__shift and not self.__meta
# meta (control key on mac)
@property
def meta(self) -> bool:
return self.__meta
@property
def only_meta(self) -> bool:
return self.__meta and not self.__control and not self.__shift and not self.__alt
# keypad
@property
def keypad(self) -> bool:
return self.__keypad
@property
def only_keypad(self) -> bool:
return self.__keypad
@property
def native_control(self) -> bool:
return self.control
def visible_canvas_item(canvas_item: typing.Optional[AbstractCanvasItem]) -> typing.Optional[AbstractCanvasItem]:
return canvas_item if canvas_item and canvas_item.visible else None
class AbstractCanvasItem:
"""An item drawn on a canvas supporting mouse and keyboard actions.
CONTAINERS
A canvas item should be added to a container. It is an error to add a particular canvas item to more than one
container. The container in which the canvas item resides is accessible via the ``container`` property.
LAYOUT
The container is responsible for layout and will set the canvas bounds of this canvas item as a function of the
container layout algorithm and this canvas item's sizing information.
The ``sizing`` property is the intrinsic sizing constraints of this canvas item.
The ``layout_sizing`` property is a the sizing information used by the container layout algorithm.
If this canvas item is non-composite, then ``layout_sizing`` will be identical to this canvas item's ``sizing``.
However, if this canvas item is composite, then ``layout_sizing`` is determined by the layout algorithm and then
additionally constrained by this canvas item's ``sizing``. In this way, by leaving ``sizing`` unconstrained, the
layout can determine the sizing of this canvas item. Alternatively, by adding a constraint to ``sizing``, the layout
can be constrained. This corresponds to the contents determining the size of the container vs. the container
determining the size of the layout.
Unpredictable layout may occur if an unconstrained item is placed into an unrestrained container. Be sure to
either restrain (implicitly or explicitly) the content or the container.
Layout occurs when the structure of the item hierarchy changes, such as when a new canvas item is added to a
container. Clients can also call ``refresh_layout`` explicitly as needed.
UPDATES AND DRAWING
Update is the mechanism by which the container is notified that one of its child canvas items needs updating.
The update message will ultimately end up at the root container at which point the root container will trigger a
repaint on a thread.
Subclasses should override _repaint or _repaint_visible to implement drawing. Drawing should take place within the
canvas bounds.
"""
def __init__(self) -> None:
super().__init__()
self.__container: typing.Optional[CanvasItemComposition] = None
self.__canvas_size: typing.Optional[Geometry.IntSize] = None
self.__canvas_origin: typing.Optional[Geometry.IntPoint] = None
self.__sizing = Sizing()
self.__focused = False
self.__focusable = False
self.wants_mouse_events = False
self.wants_drag_events = False
self.on_focus_changed: typing.Optional[typing.Callable[[bool], None]] = None
self.on_layout_updated: typing.Optional[typing.Callable[[typing.Optional[Geometry.IntPoint], typing.Optional[Geometry.IntSize], bool], None]] = None
self.__cursor_shape: typing.Optional[str] = None
self.__tool_tip: typing.Optional[str] = None
self.__background_color: typing.Optional[str] = None
self.__border_color: typing.Optional[str] = None
self.__visible = True
self._has_layout = False
self.__thread = threading.current_thread()
self.__pending_update = True
self.__repaint_drawing_context: typing.Optional[DrawingContext.DrawingContext] = None
# stats for testing
self._update_count = 0
self._repaint_count = 0
self.is_root_opaque = False
def close(self) -> None:
""" Close the canvas object. """
if threading.current_thread() != self.__thread:
warnings.warn('CanvasItem closed on different thread')
import traceback
traceback.print_stack()
self.__container = None
self.on_focus_changed = None
self.on_layout_updated = None
@property
def is_ui_interaction_active(self) -> bool:
root_container = self.root_container
if root_container:
return root_container.is_ui_interaction_active
return False
@property
def canvas_size(self) -> typing.Optional[Geometry.IntSize]:
""" Returns size of canvas_rect (external coordinates). """
return self.__canvas_size
def _set_canvas_size(self, canvas_size: typing.Optional[Geometry.IntSizeTuple]) -> None:
canvas_size_ = Geometry.IntSize.make(canvas_size) if canvas_size is not None else None
if ((self.__canvas_size is None) != (canvas_size_ is None)) or (self.__canvas_size != canvas_size_):
self.__canvas_size = canvas_size_
self.update()
@property
def canvas_origin(self) -> typing.Optional[Geometry.IntPoint]:
""" Returns origin of canvas_rect (external coordinates). """
return self.__canvas_origin
def _set_canvas_origin(self, canvas_origin: typing.Optional[Geometry.IntPointTuple]) -> None:
canvas_origin_ = Geometry.IntPoint.make(canvas_origin) if canvas_origin is not None else None
if ((self.__canvas_origin is None) != (canvas_origin_ is None)) or (self.__canvas_origin != canvas_origin_):
self.__canvas_origin = canvas_origin_
self.update()
def _begin_container_layout_changed(self) -> None:
pass
def _finish_container_layout_changed(self) -> None:
pass
def _container_layout_changed(self) -> None:
pass
@property
def canvas_widget(self) -> typing.Optional[UserInterface.CanvasWidget]:
return self.container.canvas_widget if self.container else None
@property
def canvas_bounds(self) -> typing.Optional[Geometry.IntRect]:
""" Returns a rect of the internal coordinates. """
if self.canvas_size is not None:
return Geometry.IntRect((0, 0), self.canvas_size)
return None
@property
def canvas_rect(self) -> typing.Optional[Geometry.IntRect]:
""" Returns a rect of the external coordinates. """
if self.canvas_origin is not None and self.canvas_size is not None:
return Geometry.IntRect(self.canvas_origin, self.canvas_size)
return None
@property
def container(self) -> typing.Optional[CanvasItemComposition]:
""" Return the container, if any. """
return self.__container
@container.setter
def container(self, container: typing.Optional[CanvasItemComposition]) -> None:
""" Set container. """
assert self.__container is None or container is None
self.__container = container
@property
def layer_container(self) -> typing.Optional[CanvasItemComposition]:
""" Return the root container, if any. """
return self.__container.layer_container if self.__container else None
@property
def root_container(self) -> typing.Optional[RootCanvasItem]:
""" Return the root container, if any. """
return self.__container.root_container if self.__container else None
@property
def background_color(self) -> typing.Optional[str]:
return self.__background_color
@background_color.setter
def background_color(self, background_color: typing.Optional[str]) -> None:
self.__background_color = background_color
self.update()
@property
def border_color(self) -> typing.Optional[str]:
return self.__border_color
@border_color.setter
def border_color(self, border_color: typing.Optional[str]) -> None:
self.__border_color = border_color
self.update()
@property
def focusable(self) -> bool:
""" Return whether the canvas item is focusable. """
return self.__focusable
@focusable.setter
def focusable(self, focusable: bool) -> None:
"""
Set whether the canvas item is focusable.
If this canvas item is focusable and contains other canvas items, they should
not be focusable.
"""
self.__focusable = focusable
@property
def focused(self) -> bool:
""" Return whether the canvas item is focused. """
return self.__focused
def _set_focused(self, focused: bool) -> None:
""" Set whether the canvas item is focused. Only called from container. """
if focused != self.__focused:
self.__focused = focused
self.update()
if callable(self.on_focus_changed):
self.on_focus_changed(focused)
def _request_focus(self, p: typing.Optional[Geometry.IntPoint] = None,
modifiers: typing.Optional[UserInterface.KeyboardModifiers] = None) -> None:
# protected method
if not self.focused:
root_container = self.root_container
if root_container:
root_container._request_root_focus(self, p, modifiers)
def request_focus(self) -> None:
"""Request focus.
Subclasses should not override. Override _request_focus instead."""
self._request_focus()
def adjust_secondary_focus(self, p: Geometry.IntPoint, modifiers: UserInterface.KeyboardModifiers) -> None:
"""Adjust secondary focus. Default does nothing."""
pass
def clear_focus(self) -> None:
""" Relinquish focus. """
if self.focused:
root_container = self.root_container
if root_container:
root_container._set_focused_item(None)
def drag(self, mime_data: UserInterface.MimeData, thumbnail: typing.Optional[DrawingContext.RGBA32Type] = None,
hot_spot_x: typing.Optional[int] = None, hot_spot_y: typing.Optional[int] = None,
drag_finished_fn: typing.Optional[typing.Callable[[str], None]] = None) -> None:
root_container = self.root_container
if root_container:
root_container.drag(mime_data, thumbnail, hot_spot_x, hot_spot_y, drag_finished_fn)
def show_tool_tip_text(self, text: str, gx: int, gy: int) -> None:
root_container = self.root_container
if root_container:
root_container.show_tool_tip_text(text, gx, gy)
@property
def tool_tip(self) -> typing.Optional[str]:
return self.__tool_tip
@tool_tip.setter
def tool_tip(self, value: typing.Optional[str]) -> None:
self.__tool_tip = value
@property
def cursor_shape(self) -> typing.Optional[str]:
return self.__cursor_shape
@cursor_shape.setter
def cursor_shape(self, cursor_shape: typing.Optional[str]) -> None:
self.__cursor_shape = cursor_shape
root_container = self.root_container
if root_container:
root_container._cursor_shape_changed(self)
def map_to_canvas_item(self, p: Geometry.IntPointTuple, canvas_item: AbstractCanvasItem) -> Geometry.IntPoint:
""" Map the point to the local coordinates of canvas_item. """
o1 = self.map_to_root_container(Geometry.IntPoint())
o2 = canvas_item.map_to_root_container(Geometry.IntPoint())
return Geometry.IntPoint.make(p) + o1 - o2
def map_to_root_container(self, p: Geometry.IntPoint) -> Geometry.IntPoint:
""" Map the point to the coordinates of the root container. """
canvas_item: typing.Optional[AbstractCanvasItem] = self
while canvas_item: # handle case where last canvas item was root
canvas_item_origin = canvas_item.canvas_origin
if canvas_item_origin is not None: # handle case where canvas item is not root but has no parent
p = p + canvas_item_origin
canvas_item = canvas_item.container
else:
break
return p
def map_to_container(self, p: Geometry.IntPoint) -> Geometry.IntPoint:
""" Map the point to the coordinates of the container. """
canvas_origin = self.canvas_origin
assert canvas_origin
return p + canvas_origin
def map_to_global(self, p: Geometry.IntPoint) -> Geometry.IntPoint:
root_container = self.root_container
assert root_container
return root_container.map_to_global(self.map_to_root_container(p))
def _inserted(self, container: typing.Optional[AbstractCanvasItem]) -> None:
"""Subclasses may override to know when inserted into a container."""
pass
def _removed(self, container: typing.Optional[AbstractCanvasItem]) -> None:
"""Subclasses may override to know when removed from a container."""
pass
def prepare_render(self) -> None:
"""Subclasses may override to prepare for layout and repaint. DEPRECATED see _prepare_render."""
pass
def _prepare_render(self) -> None:
"""Subclasses may override to prepare for layout and repaint."""
self._prepare_render_self()
def _prepare_render_self(self) -> None:
"""Subclasses may override to prepare for layout and repaint."""
pass
def update_layout(self, canvas_origin: typing.Optional[Geometry.IntPoint],
canvas_size: typing.Optional[Geometry.IntSize], *, immediate: bool = False) -> None:
"""Update the layout with a new canvas_origin and canvas_size.
canvas_origin and canvas_size are the external bounds.
This method will be called on the render thread.
Subclasses can override this method to take action when the size of the canvas item changes, but they should
typically call super to do the actual layout.
The on_layout_updated callable will be called with the new canvas_origin and canvas_size.
The canvas_origin and canvas_size properties are valid after calling this method and _has_layout is True.
"""
self._update_self_layout(canvas_origin, canvas_size, immediate=immediate)
self._has_layout = self.canvas_origin is not None and self.canvas_size is not None
def _update_self_layout(self, canvas_origin: typing.Optional[Geometry.IntPoint],
canvas_size: typing.Optional[Geometry.IntSize], *, immediate: bool = False) -> None:
"""Update the canvas origin and size and call notification methods."""
self._set_canvas_origin(canvas_origin)
self._set_canvas_size(canvas_size)
if callable(self.on_layout_updated):
self.on_layout_updated(self.canvas_origin, self.canvas_size, immediate)
self._has_layout = self.canvas_origin is not None and self.canvas_size is not None
def refresh_layout_immediate(self) -> None:
"""Immediate re-layout the item."""
self.refresh_layout()
self.update_layout(self.canvas_origin, self.canvas_size, immediate=True)
def refresh_layout(self) -> None:
"""Invalidate the layout and trigger layout.
Items get layout from their container, so the default implementation asks the container to layout.
"""
if self.__container:
self.__container._needs_layout(self)
def _needs_layout(self, canvas_item: AbstractCanvasItem) -> None:
# pass the needs layout up the chain.
if self.__container:
self.__container._needs_layout(canvas_item)
@property
def visible(self) -> bool:
return self.__visible
@visible.setter
def visible(self, value: bool) -> None:
if self.__visible != value:
self.__visible = value
if self.__container:
self.__container.refresh_layout()
@property
def sizing(self) -> Sizing:
"""
Return sizing information for this canvas item.
The sizing property is read only, but the object itself
can be modified.
"""
return copy.deepcopy(self.__sizing)
@property
def layout_sizing(self) -> Sizing:
"""
Return layout sizing information for this canvas item.
The layout sizing is read only and cannot be modified. It is
used from the layout engine.
"""
return copy.deepcopy(self.sizing)
def copy_sizing(self) -> Sizing:
return self.sizing
def update_sizing(self, new_sizing: Sizing) -> None:
if new_sizing != self.sizing:
self.__sizing._copy_from(new_sizing)
self.refresh_layout()
def update(self) -> None:
"""Mark canvas item as needing a display update.
The canvas item will be repainted by the root canvas item.
"""
self._update_with_items()
def _update_with_items(self, canvas_items: typing.Optional[typing.Sequence[AbstractCanvasItem]] = None) -> None:
self._update_count += 1
self._updated(canvas_items)
def _updated(self, canvas_items: typing.Optional[typing.Sequence[AbstractCanvasItem]] = None) -> None:
# Notify this canvas item that a child has been updated, repaint if needed at next opportunity.
self.__pending_update = True
self._update_container(canvas_items)
def _update_container(self, canvas_items: typing.Optional[typing.Sequence[AbstractCanvasItem]] = None) -> None:
# if not in the middle of a nested update, and if this canvas item has
# a layout, update the container.
container = self.__container
if container and self._has_layout:
canvas_items = list(canvas_items) if canvas_items else list()
canvas_items.append(self)
container._update_with_items(canvas_items)
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
"""Repaint the canvas item to the drawing context.
Subclasses should override this method to paint.
This method will be called on a thread.
The drawing should take place within the canvas_bounds.
"""
assert self.canvas_size is not None
self._repaint_count += 1
def _repaint_template(self, drawing_context: DrawingContext.DrawingContext, immediate: bool) -> None:
"""A wrapper method for _repaint.
Callers should always call this method instead of _repaint directly. This helps keep the _repaint
implementations simple and easy to understand.
"""
self._repaint(drawing_context)
def _repaint_if_needed(self, drawing_context: DrawingContext.DrawingContext, *, immediate: bool = False) -> None:
# Repaint if no cached version of the last paint is available.
# If no cached drawing context is available, regular _repaint is used to make a new one which is then cached.
# The cached drawing context is typically cleared during the update method.
# Subclasses will typically not need to override this method, except in special cases.
pending_update, self.__pending_update = self.__pending_update, False
if pending_update:
repaint_drawing_context = DrawingContext.DrawingContext()
self._repaint_template(repaint_drawing_context, immediate)
self.__repaint_drawing_context = repaint_drawing_context
if self.__repaint_drawing_context:
drawing_context.add(self.__repaint_drawing_context)
def _repaint_finished(self, drawing_context: DrawingContext.DrawingContext) -> None:
# when the thread finishes the repaint, this method gets called. the normal container update
# has not been called yet since the repaint wasn't finished until now. this method performs
# the container update.
self._update_container()
def repaint_immediate(self, drawing_context: DrawingContext.DrawingContext, canvas_size: Geometry.IntSize) -> None:
self.update_layout(Geometry.IntPoint(), canvas_size)
self._repaint_template(drawing_context, immediate=True)
def _draw_background(self, drawing_context: DrawingContext.DrawingContext) -> None:
"""Draw the background. Subclasses can call this."""
background_color = self.__background_color
if background_color:
rect = self.canvas_bounds
if rect:
with drawing_context.saver():
drawing_context.begin_path()
drawing_context.rect(rect.left, rect.top, rect.width, rect.height)
drawing_context.fill_style = background_color
drawing_context.fill()
def _draw_border(self, drawing_context: DrawingContext.DrawingContext) -> None:
"""Draw the border. Subclasses can call this."""
border_color = self.__border_color
if border_color:
rect = self.canvas_bounds
if rect:
with drawing_context.saver():
drawing_context.begin_path()
drawing_context.rect(rect.left, rect.top, rect.width, rect.height)
drawing_context.stroke_style = border_color
drawing_context.stroke()
def _repaint_visible(self, drawing_context: DrawingContext.DrawingContext, visible_rect: Geometry.IntRect) -> None:
"""
Repaint the canvas item to the drawing context within the visible area.
Subclasses can override this method to paint.
This method will be called on a thread.
The drawing should take place within the canvas_bounds.
The default implementation calls _repaint(drawing_context)
"""
self._repaint_if_needed(drawing_context)
def canvas_item_at_point(self, x: int, y: int) -> typing.Optional[AbstractCanvasItem]:
canvas_items = self.canvas_items_at_point(x, y)
return canvas_items[0] if len(canvas_items) > 0 else None
def canvas_items_at_point(self, x: int, y: int) -> typing.List[AbstractCanvasItem]:
""" Return the canvas item at the point. May return None. """
canvas_bounds = self.canvas_bounds
if canvas_bounds and canvas_bounds.contains_point(Geometry.IntPoint(x=x, y=y)):
return [self]
return []
def get_root_opaque_canvas_items(self) -> typing.List[AbstractCanvasItem]:
return [self] if self.is_root_opaque else list()
def mouse_clicked(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
""" Handle a mouse click within this canvas item. Return True if handled. """
return False
def mouse_double_clicked(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
""" Handle a mouse double click within this canvas item. Return True if handled. """
return False
def mouse_entered(self) -> bool:
""" Handle a mouse entering this canvas item. Return True if handled. """
return False
def mouse_exited(self) -> bool:
""" Handle a mouse exiting this canvas item. Return True if handled. """
return False
def mouse_pressed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
""" Handle a mouse press within this canvas item. Return True if handled. """
return False
def mouse_released(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
""" Handle a mouse release within this canvas item. Return True if handled. """
return False
def mouse_position_changed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
""" Handle a mouse move within this canvas item. Return True if handled. """
return False
def wheel_changed(self, x: int, y: int, dx: int, dy: int, is_horizontal: bool) -> bool:
""" Handle a mouse wheel changed within this canvas item. Return True if handled. """
return False
def context_menu_event(self, x: int, y: int, gx: int, gy: int) -> bool:
""" Handle a context menu event. x, y are local coordinates. gx, gy are global coordinates. """
return False
def key_pressed(self, key: UserInterface.Key) -> bool:
""" Handle a key pressed while this canvas item has focus. Return True if handled. """
return False
def key_released(self, key: UserInterface.Key) -> bool:
""" Handle a key released while this canvas item has focus. Return True if handled. """
return False
def wants_drag_event(self, mime_data: UserInterface.MimeData, x: int, y: int) -> bool:
""" Determines if the item should handle certain mime_data at a certain point. Return True if handled."""
return self.wants_drag_events
def drag_enter(self, mime_data: UserInterface.MimeData) -> str:
""" Handle a drag event entering this canvas item. Return action if handled. """
return "ignore"
def drag_leave(self) -> str:
""" Handle a drag event leaving this canvas item. Return action if handled. """
return "ignore"
def drag_move(self, mime_data: UserInterface.MimeData, x: int, y: int) -> str:
""" Handle a drag event moving within this canvas item. Return action if handled. """
return "ignore"
def drop(self, mime_data: UserInterface.MimeData, x: int, y: int) -> str:
""" Handle a drop event in this canvas item. Return action if handled. """
return "ignore"
def handle_tool_tip(self, x: int, y: int, gx: int, gy: int) -> bool:
return False
def pan_gesture(self, dx: int, dy: int) -> bool:
""" Handle a pan gesture in this canvas item. Return action if handled. """
return False
def _dispatch_any(self, method: str, *args: typing.Any, **kwargs: typing.Any) -> bool:
if hasattr(self, method):
return typing.cast(bool, getattr(self, method)(*args, **kwargs))
return False
def _can_dispatch_any(self, method: str) -> bool:
return hasattr(self, method)
def _get_menu_item_state(self, command_id: str) -> typing.Optional[UserInterface.MenuItemState]:
handle_method = "handle_" + command_id
menu_item_state_method = "get_" + command_id + "_menu_item_state"
if hasattr(self, menu_item_state_method):
menu_item_state = getattr(self, menu_item_state_method)()
if menu_item_state:
return typing.cast(UserInterface.MenuItemState, menu_item_state)
if hasattr(self, handle_method):
return UserInterface.MenuItemState(title=None, enabled=True, checked=False)
return None
def simulate_click(self, p: Geometry.IntPointTuple, modifiers: typing.Optional[UserInterface.KeyboardModifiers] = None) -> None:
modifiers_ = modifiers or typing.cast("UserInterface.KeyboardModifiers", KeyboardModifiers())
self.mouse_pressed(p[1], p[0], modifiers_)
self.mouse_released(p[1], p[0], modifiers_)
def simulate_drag(self, p1: Geometry.IntPointTuple, p2: Geometry.IntPointTuple, modifiers: typing.Optional[UserInterface.KeyboardModifiers] = None) -> None:
modifiers_ = modifiers or typing.cast("UserInterface.KeyboardModifiers", KeyboardModifiers())
self.mouse_pressed(p1[1], p1[0], modifiers_)
self.mouse_position_changed(p1[1], p1[0], modifiers_)
midpoint = Geometry.midpoint(Geometry.IntPoint.make(p1).to_float_point(), Geometry.IntPoint.make(p2).to_float_point())
self.mouse_position_changed(round(midpoint[1]), round(midpoint[0]), modifiers_)
self.mouse_position_changed(p2[1], p2[0], modifiers_)
self.mouse_released(p2[1], p2[0], modifiers_)
def simulate_press(self, p: Geometry.IntPointTuple, modifiers: typing.Optional[UserInterface.KeyboardModifiers] = None) -> None:
modifiers_ = modifiers or typing.cast("UserInterface.KeyboardModifiers", KeyboardModifiers())
self.mouse_pressed(p[1], p[0], modifiers_)
def simulate_move(self, p: Geometry.IntPointTuple, modifiers: typing.Optional[UserInterface.KeyboardModifiers] = None) -> None:
modifiers_ = modifiers or typing.cast("UserInterface.KeyboardModifiers", KeyboardModifiers())
self.mouse_position_changed(p[1], p[0], modifiers_)
def simulate_release(self, p: Geometry.IntPointTuple, modifiers: typing.Optional[UserInterface.KeyboardModifiers] = None) -> None:
modifiers_ = modifiers or typing.cast("UserInterface.KeyboardModifiers", KeyboardModifiers())
self.mouse_released(p[1], p[0], modifiers_)
class CanvasItemAbstractLayout:
"""
Layout canvas items within a larger space.
Subclasses must implement layout method.
NOTE: origin=0 is at the top
"""
def __init__(self, margins: typing.Optional[Geometry.Margins] = None, spacing: typing.Optional[int] = None) -> None:
self.margins = margins if margins is not None else Geometry.Margins(0, 0, 0, 0)
self.spacing = spacing if spacing else 0
def calculate_row_layout(self, canvas_origin: Geometry.IntPoint, canvas_size: Geometry.IntSize,
canvas_items: typing.Sequence[AbstractCanvasItem]) -> ConstraintResultType:
""" Use constraint_solve to return the positions of canvas items as if they are in a row. """
canvas_item_count = len(canvas_items)
spacing_count = canvas_item_count - 1
content_left = canvas_origin.x + self.margins.left
content_width = canvas_size.width - self.margins.left - self.margins.right - self.spacing * spacing_count
constraints = [canvas_item.layout_sizing.get_width_constraint(content_width) for canvas_item in canvas_items]
return constraint_solve(content_left, content_width, constraints, self.spacing)
def calculate_column_layout(self, canvas_origin: Geometry.IntPoint, canvas_size: Geometry.IntSize,
canvas_items: typing.Sequence[AbstractCanvasItem]) -> ConstraintResultType:
""" Use constraint_solve to return the positions of canvas items as if they are in a column. """
canvas_item_count = len(canvas_items)
spacing_count = canvas_item_count - 1
content_top = canvas_origin.y + self.margins.top
content_height = canvas_size.height - self.margins.top - self.margins.bottom - self.spacing * spacing_count
constraints = [canvas_item.layout_sizing.get_height_constraint(content_height) for canvas_item in canvas_items]
return constraint_solve(content_top, content_height, constraints, self.spacing)
def update_canvas_item_layout(self, canvas_item_origin: Geometry.IntPoint, canvas_item_size: Geometry.IntSize,
canvas_item: AbstractCanvasItem, *, immediate: bool = False) -> None:
""" Given a container box, adjust a single canvas item within the box according to aspect_ratio constraints. """
# TODO: Also adjust canvas items for maximums, and positioning
aspect_ratio = canvas_item_size.aspect_ratio
rect = Geometry.IntRect(origin=canvas_item_origin, size=canvas_item_size)
layout_sizing = canvas_item.layout_sizing
if layout_sizing.minimum_aspect_ratio is not None and aspect_ratio < layout_sizing.minimum_aspect_ratio:
rect = Geometry.fit_to_aspect_ratio(rect, layout_sizing.minimum_aspect_ratio).to_int_rect()
elif layout_sizing.maximum_aspect_ratio is not None and aspect_ratio > layout_sizing.maximum_aspect_ratio:
rect = Geometry.fit_to_aspect_ratio(rect, layout_sizing.maximum_aspect_ratio).to_int_rect()
elif layout_sizing.preferred_aspect_ratio is not None:
rect = Geometry.fit_to_aspect_ratio(rect, layout_sizing.preferred_aspect_ratio).to_int_rect()
canvas_item.update_layout(rect.origin, rect.size, immediate=immediate)
def layout_canvas_items(self, x_positions: typing.Sequence[int], y_positions: typing.Sequence[int],
widths: typing.Sequence[int], heights: typing.Sequence[int],
canvas_items: typing.Sequence[AbstractCanvasItem], *, immediate: bool = False) -> None:
""" Set the container boxes for the canvas items using update_canvas_item_layout on the individual items. """
for index, canvas_item in enumerate(canvas_items):
if canvas_item is not None:
canvas_item_origin = Geometry.IntPoint(x=x_positions[index], y=y_positions[index])
canvas_item_size = Geometry.IntSize(width=widths[index], height=heights[index])
self.update_canvas_item_layout(canvas_item_origin, canvas_item_size, canvas_item, immediate=immediate)
def _combine_sizing_property(self, sizing: Sizing, canvas_item_sizing: Sizing, property: str,
combiner: typing.Callable[[typing.Any, typing.Any], typing.Any],
clear_if_missing: bool = False) -> None:
""" Utility method for updating the property of the sizing object using the combiner function and the canvas_item_sizing. """
property = "_" + property
canvas_item_value = getattr(canvas_item_sizing, property)
value = getattr(sizing, property)
if canvas_item_value is not None:
if clear_if_missing:
setattr(sizing, property, combiner(value, canvas_item_value) if value is not None else None)
else:
setattr(sizing, property, combiner(value, canvas_item_value) if value is not None else canvas_item_value)
elif clear_if_missing:
setattr(sizing, property, None)
def _get_overlap_sizing(self, canvas_items: typing.Sequence[typing.Optional[AbstractCanvasItem]]) -> Sizing:
"""
A commonly used sizing method to determine the preferred/min/max assuming everything is stacked/overlapping.
Does not include spacing or margins.
"""
sizing = Sizing()
sizing._maximum_width = 0
sizing._maximum_height = 0
sizing._preferred_width = 0
sizing._preferred_height = 0
for canvas_item in canvas_items:
if canvas_item is not None:
canvas_item_sizing = canvas_item.layout_sizing
self._combine_sizing_property(sizing, canvas_item_sizing, "preferred_width", max, True)
self._combine_sizing_property(sizing, canvas_item_sizing, "preferred_height", max, True)
self._combine_sizing_property(sizing, canvas_item_sizing, "minimum_width", max) # if any minimum_width is present, take the maximum one
self._combine_sizing_property(sizing, canvas_item_sizing, "minimum_height", max)
self._combine_sizing_property(sizing, canvas_item_sizing, "maximum_width", max, True)
self._combine_sizing_property(sizing, canvas_item_sizing, "maximum_height", max, True)
if sizing.maximum_width == 0 or len(canvas_items) == 0:
sizing._maximum_width = None
if sizing.maximum_height == 0 or len(canvas_items) == 0:
sizing._maximum_height = None
if sizing.preferred_width == 0 or len(canvas_items) == 0:
sizing._preferred_width = None
if sizing.preferred_height == 0 or len(canvas_items) == 0:
sizing._preferred_height = None
return sizing
def _get_column_sizing(self, canvas_items: typing.Sequence[AbstractCanvasItem])-> Sizing:
"""
A commonly used sizing method to determine the preferred/min/max assuming everything is a column.
Does not include spacing or margins.
"""
sizing = Sizing()
sizing._maximum_width = 0
sizing._maximum_height = 0
sizing._preferred_width = 0
for canvas_item in canvas_items:
if canvas_item is not None:
canvas_item_sizing = canvas_item.layout_sizing
self._combine_sizing_property(sizing, canvas_item_sizing, "preferred_width", max, True)
self._combine_sizing_property(sizing, canvas_item_sizing, "preferred_height", operator.add)
self._combine_sizing_property(sizing, canvas_item_sizing, "minimum_width", max)
self._combine_sizing_property(sizing, canvas_item_sizing, "minimum_height", operator.add)
self._combine_sizing_property(sizing, canvas_item_sizing, "maximum_width", max, True)
self._combine_sizing_property(sizing, canvas_item_sizing, "maximum_height", operator.add, True)
if sizing.maximum_width == 0 or len(canvas_items) == 0:
sizing._maximum_width = None
if sizing.preferred_width == 0 or len(canvas_items) == 0:
sizing._preferred_width = None
if sizing.maximum_height == MAX_VALUE or len(canvas_items) == 0:
sizing._maximum_height = None
return sizing
def _get_row_sizing(self, canvas_items: typing.Sequence[AbstractCanvasItem]) -> Sizing:
"""
A commonly used sizing method to determine the preferred/min/max assuming everything is a column.
Does not include spacing or margins.
"""
sizing = Sizing()
sizing._maximum_width = 0
sizing._maximum_height = 0
sizing._preferred_height = 0
for canvas_item in canvas_items:
if canvas_item is not None:
canvas_item_sizing = canvas_item.layout_sizing
self._combine_sizing_property(sizing, canvas_item_sizing, "preferred_width", operator.add)
self._combine_sizing_property(sizing, canvas_item_sizing, "preferred_height", max, True)
self._combine_sizing_property(sizing, canvas_item_sizing, "minimum_width", operator.add)
self._combine_sizing_property(sizing, canvas_item_sizing, "minimum_height", max)
self._combine_sizing_property(sizing, canvas_item_sizing, "maximum_width", operator.add, True)
self._combine_sizing_property(sizing, canvas_item_sizing, "maximum_height", max, True)
if sizing.maximum_width == MAX_VALUE or len(canvas_items) == 0:
sizing._maximum_width = None
if sizing.maximum_height == 0 or len(canvas_items) == 0:
sizing._maximum_height = None
if sizing.preferred_height == 0 or len(canvas_items) == 0:
sizing._preferred_height = None
return sizing
def _adjust_sizing(self, sizing: Sizing, x_spacing: int, y_spacing: int) -> None:
""" Adjust the sizing object by adding margins and spacing. Spacing is total, not per item. """
if sizing._minimum_width is not None:
sizing._minimum_width += self.margins.left + self.margins.right + x_spacing
if sizing._maximum_width is not None:
sizing._maximum_width += self.margins.left + self.margins.right + x_spacing
if sizing._preferred_width is not None:
sizing._preferred_width += self.margins.left + self.margins.right + x_spacing
if sizing._minimum_height is not None:
sizing._minimum_height += self.margins.top + self.margins.bottom + y_spacing
if sizing._maximum_height is not None:
sizing._maximum_height += self.margins.top + self.margins.bottom + y_spacing
if sizing._preferred_height is not None:
sizing._preferred_height += self.margins.top + self.margins.bottom + y_spacing
def add_canvas_item(self, canvas_item: AbstractCanvasItem, pos: typing.Optional[Geometry.IntPoint]) -> None:
"""
Subclasses may override this method to get position specific information when a canvas item is added to
the layout.
"""
pass
def remove_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
"""
Subclasses may override this method to clean up position specific information when a canvas item is removed
from the layout.
"""
pass
def layout(self, canvas_origin: Geometry.IntPoint, canvas_size: Geometry.IntSize,
canvas_items: typing.Sequence[AbstractCanvasItem], *, immediate: bool = False) -> None:
""" Subclasses must override this method to layout canvas item. """
raise NotImplementedError()
def get_sizing(self, canvas_items: typing.Sequence[AbstractCanvasItem]) -> Sizing:
"""
Return the sizing object for this layout. Includes spacing and margins.
Subclasses must implement.
"""
raise NotImplementedError()
def create_spacing_item(self, spacing: int) -> AbstractCanvasItem:
raise NotImplementedError()
def create_stretch_item(self) -> AbstractCanvasItem:
raise NotImplementedError()
class CanvasItemLayout(CanvasItemAbstractLayout):
"""
Default layout which overlays all items on one another.
Pass margins.
"""
def __init__(self, margins: typing.Optional[Geometry.Margins] = None, spacing: typing.Optional[int] = None) -> None:
super().__init__(margins, spacing)
def layout(self, canvas_origin: Geometry.IntPoint, canvas_size: Geometry.IntSize,
canvas_items: typing.Sequence[AbstractCanvasItem], *, immediate: bool = False) -> None:
for canvas_item in canvas_items:
self.update_canvas_item_layout(canvas_origin, canvas_size, canvas_item, immediate=immediate)
def get_sizing(self, canvas_items: typing.Sequence[AbstractCanvasItem]) -> Sizing:
sizing = self._get_overlap_sizing(canvas_items)
self._adjust_sizing(sizing, 0, 0)
return sizing
def create_spacing_item(self, spacing: int) -> AbstractCanvasItem:
raise NotImplementedError()
def create_stretch_item(self) -> AbstractCanvasItem:
raise NotImplementedError()
class CanvasItemColumnLayout(CanvasItemAbstractLayout):
"""
Layout items in a column.
Pass margins and spacing.
"""
def __init__(self, margins: typing.Optional[Geometry.Margins] = None, spacing: typing.Optional[int] = None,
alignment: typing.Optional[str] = None) -> None:
super().__init__(margins, spacing)
self.alignment = alignment
def layout(self, canvas_origin: Geometry.IntPoint, canvas_size: Geometry.IntSize,
canvas_items: typing.Sequence[AbstractCanvasItem], *, immediate: bool = False) -> None:
# calculate the vertical placement
y_positions, heights = self.calculate_column_layout(canvas_origin, canvas_size, canvas_items)
widths = [canvas_item.layout_sizing.get_unrestrained_width(canvas_size.width - self.margins.left - self.margins.right) for canvas_item in canvas_items]
available_width = canvas_size.width - self.margins.left - self.margins.right
if self.alignment == "start":
x_positions = [canvas_origin.x + self.margins.left for width in widths]
elif self.alignment == "end":
x_positions = [canvas_origin.x + self.margins.left + (available_width - width) for width in widths]
else:
x_positions = [round(canvas_origin.x + self.margins.left + (available_width - width) * 0.5) for width in widths]
self.layout_canvas_items(x_positions, y_positions, widths, heights, canvas_items, immediate=immediate)
def get_sizing(self, canvas_items: typing.Sequence[AbstractCanvasItem]) -> Sizing:
sizing = self._get_column_sizing(canvas_items)
self._adjust_sizing(sizing, 0, self.spacing * (len(canvas_items) - 1))
return sizing
def create_spacing_item(self, spacing: int) -> AbstractCanvasItem:
spacing_item = EmptyCanvasItem()
spacing_item.update_sizing(spacing_item.sizing.with_fixed_height(spacing).with_fixed_width(0))
return spacing_item
def create_stretch_item(self) -> AbstractCanvasItem:
spacing_item = EmptyCanvasItem()
spacing_item.update_sizing(spacing_item.sizing.with_fixed_width(0))
return spacing_item
class CanvasItemRowLayout(CanvasItemAbstractLayout):
"""
Layout items in a row.
Pass margins and spacing.
"""
def __init__(self, margins: typing.Optional[Geometry.Margins] = None, spacing: typing.Optional[int] = None,
alignment: typing.Optional[str] = None) -> None:
super().__init__(margins, spacing)
self.alignment = alignment
def layout(self, canvas_origin: Geometry.IntPoint, canvas_size: Geometry.IntSize,
canvas_items: typing.Sequence[AbstractCanvasItem], *, immediate: bool = False) -> None:
# calculate the vertical placement
x_positions, widths = self.calculate_row_layout(canvas_origin, canvas_size, canvas_items)
heights = [canvas_item.layout_sizing.get_unrestrained_height(canvas_size.height - self.margins.top - self.margins.bottom) for canvas_item in canvas_items]
available_height = canvas_size.height - self.margins.top - self.margins.bottom
if self.alignment == "start":
y_positions = [canvas_origin.y + self.margins.top for width in widths]
elif self.alignment == "end":
y_positions = [canvas_origin.y + self.margins.top + (available_height - height) for height in heights]
else:
y_positions = [round(canvas_origin.y + self.margins.top + (available_height - height) // 2) for height in heights]
self.layout_canvas_items(x_positions, y_positions, widths, heights, canvas_items, immediate=immediate)
def get_sizing(self, canvas_items: typing.Sequence[AbstractCanvasItem]) -> Sizing:
sizing = self._get_row_sizing(canvas_items)
self._adjust_sizing(sizing, self.spacing * (len(canvas_items) - 1), 0)
return sizing
def create_spacing_item(self, spacing: int) -> AbstractCanvasItem:
spacing_item = EmptyCanvasItem()
spacing_item.update_sizing(spacing_item.sizing.with_fixed_width(spacing).with_fixed_height(0))
return spacing_item
def create_stretch_item(self) -> AbstractCanvasItem:
spacing_item = EmptyCanvasItem()
spacing_item.update_sizing(spacing_item.sizing.with_fixed_height(0))
return spacing_item
class CanvasItemGridLayout(CanvasItemAbstractLayout):
"""
Layout items in a grid specified by size (IntSize).
Pass margins and spacing.
Canvas items must be added to container canvas item using
add_canvas_item with the position (IntPoint) passed as pos
parameter.
"""
def __init__(self, size: Geometry.IntSize, margins: typing.Optional[Geometry.Margins] = None, spacing: typing.Optional[int] = None) -> None:
super().__init__(margins, spacing)
assert size.width > 0 and size.height > 0
self.__size = size
self.__columns: typing.List[typing.List[typing.Optional[AbstractCanvasItem]]] = [[None for _ in range(self.__size.height)] for _ in range(self.__size.width)]
def add_canvas_item(self, canvas_item: AbstractCanvasItem, pos: typing.Optional[Geometry.IntPoint]) -> None:
assert pos
assert pos.x >= 0 and pos.x < self.__size.width
assert pos.y >= 0 and pos.y < self.__size.height
self.__columns[pos.x][pos.y] = canvas_item
def remove_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
canvas_item.close()
for x in range(self.__size.width):
for y in range(self.__size.height):
if self.__columns[x][y] == canvas_item:
self.__columns[x][y] = None
def layout(self, canvas_origin: Geometry.IntPoint, canvas_size: Geometry.IntSize,
canvas_items: typing.Sequence[AbstractCanvasItem], *, immediate: bool = False) -> None:
# calculate the horizontal placement
# calculate the sizing (x, width) for each column
canvas_item_count = self.__size.width
spacing_count = canvas_item_count - 1
content_left = canvas_origin.x + self.margins.left
content_width = canvas_size.width - self.margins.left - self.margins.right - self.spacing * spacing_count
constraints = list()
for x in range(self.__size.width):
sizing = self._get_overlap_sizing([visible_canvas_item(self.__columns[x][y]) for y in range(self.__size.height)])
constraints.append(sizing.get_width_constraint(content_width))
# run the layout engine
x_positions, widths = constraint_solve(content_left, content_width, constraints, self.spacing)
# calculate the vertical placement
# calculate the sizing (y, height) for each row
canvas_item_count = self.__size.height
spacing_count = canvas_item_count - 1
content_top = canvas_origin.y + self.margins.top
content_height = canvas_size.height - self.margins.top - self.margins.bottom - self.spacing * spacing_count
constraints = list()
for y in range(self.__size.height):
sizing = self._get_overlap_sizing([visible_canvas_item(self.__columns[x][y]) for x in range(self.__size.width)])
constraints.append(sizing.get_height_constraint(content_height))
# run the layout engine
y_positions, heights = constraint_solve(content_top, content_height, constraints, self.spacing)
# do the layout
combined_xs = list()
combined_ys = list()
combined_widths = list()
combined_heights = list()
combined_canvas_items = list()
for x in range(self.__size.width):
for y in range(self.__size.height):
canvas_item = visible_canvas_item(self.__columns[x][y])
if canvas_item is not None:
combined_xs.append(x_positions[x])
combined_ys.append(y_positions[y])
combined_widths.append(widths[x])
combined_heights.append(heights[y])
combined_canvas_items.append(canvas_item)
self.layout_canvas_items(combined_xs, combined_ys, combined_widths, combined_heights, combined_canvas_items, immediate=immediate)
def get_sizing(self, canvas_items: typing.Sequence[AbstractCanvasItem]) -> Sizing:
"""
Calculate the sizing for the grid. Treat columns and rows independently.
Override from abstract layout.
"""
sizing = Sizing().with_maximum_width(0).with_maximum_height(0).with_preferred_height(0)
# the widths
canvas_item_sizings = list()
for x in range(self.__size.width):
canvas_items_ = [visible_canvas_item(self.__columns[x][y]) for y in range(self.__size.height)]
canvas_item_sizings.append(self._get_overlap_sizing(canvas_items_))
for canvas_item_sizing in canvas_item_sizings:
self._combine_sizing_property(sizing, canvas_item_sizing, "preferred_width", operator.add)
self._combine_sizing_property(sizing, canvas_item_sizing, "minimum_width", operator.add)
self._combine_sizing_property(sizing, canvas_item_sizing, "maximum_width", operator.add, True)
# the heights
canvas_item_sizings = list()
for y in range(self.__size.height):
canvas_items_ = [visible_canvas_item(self.__columns[x][y]) for x in range(self.__size.width)]
canvas_item_sizings.append(self._get_overlap_sizing(canvas_items_))
for canvas_item_sizing in canvas_item_sizings:
self._combine_sizing_property(sizing, canvas_item_sizing, "preferred_height", operator.add)
self._combine_sizing_property(sizing, canvas_item_sizing, "minimum_height", operator.add)
self._combine_sizing_property(sizing, canvas_item_sizing, "maximum_height", operator.add, True)
if sizing.maximum_width == MAX_VALUE or len(canvas_items_) == 0:
sizing._maximum_width = None
if sizing.maximum_height == MAX_VALUE or len(canvas_items_) == 0:
sizing._maximum_height = None
if sizing.maximum_width == 0 or len(canvas_items_) == 0:
sizing._maximum_width = None
if sizing.preferred_width == 0 or len(canvas_items_) == 0:
sizing._preferred_width = None
if sizing.maximum_height == 0 or len(canvas_items_) == 0:
sizing._maximum_height = None
if sizing.preferred_height == 0 or len(canvas_items_) == 0:
sizing._preferred_height = None
self._adjust_sizing(sizing, self.spacing * (self.__size.width - 1), self.spacing * (self.__size.height - 1))
return sizing
class CompositionLayoutRenderTrait:
"""A trait (a set of methods for extending a class) allow customization of composition layout/rendering.
Since traits aren't supported directly in Python, this works by having associated methods in the
CanvasItemComposition class directly invoke the methods of this or a subclass of this object.
"""
def __init__(self, canvas_item_composition: CanvasItemComposition):
self._canvas_item_composition = canvas_item_composition
def close(self) -> None:
self._stop_render_behavior()
self._canvas_item_composition = None # type: ignore
def _stop_render_behavior(self) -> None:
pass
@property
def _needs_layout_for_testing(self) -> bool:
return False
@property
def is_layer_container(self) -> bool:
return False
def register_prepare_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
pass
def unregister_prepare_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
pass
def _container_layout_changed(self) -> None:
pass
def _try_update_layout(self, canvas_origin: typing.Optional[Geometry.IntPoint], canvas_size: typing.Optional[Geometry.IntSize], *, immediate: bool = False) -> bool:
return False
def _try_needs_layout(self, canvas_item: AbstractCanvasItem) -> bool:
return False
def _try_update_with_items(self, canvas_items: typing.Optional[typing.Sequence[AbstractCanvasItem]] = None) -> bool:
return False
def _try_updated(self) -> bool:
return False
def _try_repaint_template(self, drawing_context: DrawingContext.DrawingContext, immediate: bool) -> bool:
return False
def _try_repaint_if_needed(self, drawing_context: DrawingContext.DrawingContext, *, immediate: bool = False) -> bool:
return False
def layout_immediate(self, canvas_size: Geometry.IntSize, force: bool=True) -> None:
self._canvas_item_composition._prepare_render()
self._canvas_item_composition._update_self_layout(Geometry.IntPoint(), canvas_size, immediate=True)
self._canvas_item_composition._update_child_layouts(canvas_size, immediate=True)
def _try_repaint_immediate(self, drawing_context: DrawingContext.DrawingContext, canvas_size: Geometry.IntSize) -> bool:
return False
class CanvasItemComposition(AbstractCanvasItem):
"""A composite canvas item comprised of other canvas items.
Optionally includes a layout. Compositions without an explicit layout are stacked to fit this container.
Access child canvas items using canvas_items.
Child canvas items with higher indexes are considered to be foremost.
"""
def __init__(self, layout_render_trait: typing.Optional[CompositionLayoutRenderTrait] = None) -> None:
super().__init__()
self.__canvas_items: typing.List[AbstractCanvasItem] = list()
self.layout: CanvasItemAbstractLayout = CanvasItemLayout()
self.__layout_lock = threading.RLock()
self.__layout_render_trait = layout_render_trait or CompositionLayoutRenderTrait(self)
self.__container_layout_changed_count = 0
def close(self) -> None:
self.__layout_render_trait.close()
self.__layout_render_trait = typing.cast(typing.Any, None)
with self.__layout_lock:
canvas_items = self.canvas_items
for canvas_item in canvas_items:
canvas_item.close()
# this goes after closing; if this goes before closing, threaded canvas items don't get closed properly
# since they notify their container (to cull). to reproduce the bug, create a 1x2, then a 4x3 in the bottom.
# then close several panels and undo. not sure if this is the permanent fix or not.
self.__canvas_items = typing.cast(typing.Any, None)
super().close()
def _stop_render_behavior(self) -> None:
if self.__layout_render_trait:
self.__layout_render_trait._stop_render_behavior()
@property
def _needs_layout_for_testing(self) -> bool:
return self.__layout_render_trait._needs_layout_for_testing
@property
def layer_container(self) -> typing.Optional[CanvasItemComposition]:
return self if self.__layout_render_trait.is_layer_container else super().layer_container
def register_prepare_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
"""DEPRECATED see _prepare_render."""
self.__layout_render_trait.register_prepare_canvas_item(canvas_item)
def unregister_prepare_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
"""DEPRECATED see _prepare_render."""
self.__layout_render_trait.unregister_prepare_canvas_item(canvas_item)
def _begin_container_layout_changed(self) -> None:
# recursively increase the changed count
self.__container_layout_changed_count += 1
for canvas_item in self.canvas_items:
canvas_item._begin_container_layout_changed()
def _finish_container_layout_changed(self) -> None:
# recursively decrease the changed count
self.__container_layout_changed_count -= 1
for canvas_item in self.canvas_items:
canvas_item._finish_container_layout_changed()
# when the change count is zero, call container layout changed.
# the effect is this will occur once per composite item. only
# layers will actually do something (re-render with new layout).
if self.__container_layout_changed_count == 0:
self._container_layout_changed()
def _redraw_container(self) -> None:
self.__layout_render_trait._container_layout_changed()
def _prepare_render(self) -> None:
for canvas_item in self.__canvas_items:
canvas_item._prepare_render()
super()._prepare_render()
@property
def canvas_items_count(self) -> int:
"""Return count of canvas items managed by this composition."""
return len(self.__canvas_items)
@property
def canvas_items(self) -> typing.List[AbstractCanvasItem]:
""" Return a copy of the canvas items managed by this composition. """
return copy.copy(self.__canvas_items)
@property
def visible_canvas_items(self) -> typing.List[AbstractCanvasItem]:
with self.__layout_lock:
if self.__canvas_items is not None:
return [canvas_item for canvas_item in self.__canvas_items if canvas_item and canvas_item.visible]
return list()
def update_layout(self, canvas_origin: typing.Optional[Geometry.IntPoint],
canvas_size: typing.Optional[Geometry.IntSize], *, immediate: bool = False) -> None:
"""Override from abstract canvas item."""
if immediate or not self.__layout_render_trait._try_update_layout(canvas_origin, canvas_size, immediate=immediate):
self._update_layout(canvas_origin, canvas_size, immediate=immediate)
def layout_immediate(self, canvas_size: Geometry.IntSize, force: bool = True) -> None:
# useful for tests
self.__layout_render_trait.layout_immediate(canvas_size, force)
def _update_with_items(self, canvas_items: typing.Optional[typing.Sequence[AbstractCanvasItem]] = None) -> None:
# extra check for behavior during closing
if self.__layout_render_trait and not self.__layout_render_trait._try_update_with_items(canvas_items):
super()._update_with_items(canvas_items)
def _updated(self, canvas_items: typing.Optional[typing.Sequence[AbstractCanvasItem]] = None) -> None:
# extra check for behavior during closing
if self.__layout_render_trait and not self.__layout_render_trait._try_updated():
super()._updated(canvas_items)
def _update_layout(self, canvas_origin: typing.Optional[Geometry.IntPoint],
canvas_size: typing.Optional[Geometry.IntSize], *, immediate: bool = False) -> None:
"""Private method, but available to tests."""
with self.__layout_lock:
if self.__canvas_items is not None:
assert canvas_origin is not None
assert canvas_size is not None
canvas_origin_ = Geometry.IntPoint.make(canvas_origin)
canvas_size_ = Geometry.IntSize.make(canvas_size)
self._update_self_layout(canvas_origin_, canvas_size_, immediate=immediate)
self._update_child_layouts(canvas_size_, immediate=immediate)
def _update_child_layouts(self, canvas_size: typing.Optional[Geometry.IntSize], *, immediate: bool = False) -> None:
with self.__layout_lock:
if self.__canvas_items is not None:
assert canvas_size is not None
canvas_size = Geometry.IntSize.make(canvas_size)
self.layout.layout(Geometry.IntPoint(), canvas_size, self.visible_canvas_items, immediate=immediate)
def _needs_layout(self, canvas_item: AbstractCanvasItem) -> None:
# extra check for behavior during closing
if self.__layout_render_trait and not self.__layout_render_trait._try_needs_layout(canvas_item):
super()._needs_layout(canvas_item)
# override sizing information. let layout provide it.
@property
def layout_sizing(self) -> Sizing:
sizing = self.sizing
layout_sizing = self.layout.get_sizing(self.visible_canvas_items)
if sizing.minimum_width is not None:
layout_sizing._minimum_width = sizing.minimum_width
if sizing.maximum_width is not None:
layout_sizing._maximum_width = sizing.maximum_width
if sizing.preferred_width is not None:
layout_sizing._preferred_width = sizing.preferred_width
if sizing.minimum_height is not None:
layout_sizing._minimum_height = sizing.minimum_height
if sizing.maximum_height is not None:
layout_sizing._maximum_height = sizing.maximum_height
if sizing.preferred_height is not None:
layout_sizing._preferred_height = sizing.preferred_height
if sizing.minimum_aspect_ratio is not None:
layout_sizing._minimum_aspect_ratio = sizing.minimum_aspect_ratio
if sizing.maximum_aspect_ratio is not None:
layout_sizing._maximum_aspect_ratio = sizing.maximum_aspect_ratio
if sizing.preferred_aspect_ratio is not None:
layout_sizing._preferred_aspect_ratio = sizing.preferred_aspect_ratio
if len(self.visible_canvas_items) == 0 and sizing.collapsible:
layout_sizing._minimum_width = 0
layout_sizing._preferred_width = 0
layout_sizing._maximum_width = 0
layout_sizing._minimum_height = 0
layout_sizing._preferred_height = 0
layout_sizing._maximum_height = 0
return layout_sizing
def canvas_item_layout_sizing_changed(self, canvas_item: AbstractCanvasItem) -> None:
""" Contained canvas items call this when their layout_sizing changes. """
self.refresh_layout()
def _insert_canvas_item_direct(self, before_index: int, canvas_item: AbstractCanvasItem,
pos: typing.Optional[Geometry.IntPoint] = None) -> None:
self.insert_canvas_item(before_index, canvas_item, pos)
def insert_canvas_item(self, before_index: int, canvas_item: AbstractCanvasItem,
pos: typing.Optional[typing.Any] = None) -> AbstractCanvasItem:
""" Insert canvas item into layout. pos parameter is layout specific. """
self.__canvas_items.insert(before_index, canvas_item)
canvas_item.container = self
canvas_item._inserted(self)
self.layout.add_canvas_item(canvas_item, pos)
self.refresh_layout()
self.update()
return canvas_item
def insert_spacing(self, before_index: int, spacing: int) -> AbstractCanvasItem:
spacing_item = self.layout.create_spacing_item(spacing)
return self.insert_canvas_item(before_index, spacing_item)
def insert_stretch(self, before_index: int) -> AbstractCanvasItem:
stretch_item = self.layout.create_stretch_item()
return self.insert_canvas_item(before_index, stretch_item)
def add_canvas_item(self, canvas_item: AbstractCanvasItem, pos: typing.Optional[typing.Any] = None) -> AbstractCanvasItem:
""" Add canvas item to layout. pos parameter is layout specific. """
return self.insert_canvas_item(len(self.__canvas_items), canvas_item, pos)
def add_spacing(self, spacing: int) -> AbstractCanvasItem:
return self.insert_spacing(len(self.__canvas_items), spacing)
def add_stretch(self) -> AbstractCanvasItem:
return self.insert_stretch(len(self.__canvas_items))
def _remove_canvas_item_direct(self, canvas_item: AbstractCanvasItem) -> None:
self.__canvas_items.remove(canvas_item)
def _remove_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
canvas_item._removed(self)
canvas_item.close()
self.layout.remove_canvas_item(canvas_item)
canvas_item.container = None
self.__canvas_items.remove(canvas_item)
self.refresh_layout()
self.update()
def remove_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
""" Remove canvas item from layout. Canvas item is closed. """
self._remove_canvas_item(canvas_item)
def remove_all_canvas_items(self) -> None:
""" Remove all canvas items from layout. Canvas items are closed. """
for canvas_item in reversed(copy.copy(self.__canvas_items)):
self._remove_canvas_item(canvas_item)
def replace_canvas_item(self, old_canvas_item: AbstractCanvasItem, new_canvas_item: AbstractCanvasItem) -> None:
""" Replace the given canvas item with the new one. Canvas item is closed. """
index = self.__canvas_items.index(old_canvas_item)
self.remove_canvas_item(old_canvas_item)
self.insert_canvas_item(index, new_canvas_item)
def wrap_canvas_item(self, canvas_item: AbstractCanvasItem, canvas_item_container: CanvasItemComposition) -> None:
""" Replace the given canvas item with the container and move the canvas item into the container. """
canvas_origin = canvas_item.canvas_origin
canvas_size = canvas_item.canvas_size
index = self.__canvas_items.index(canvas_item)
# remove the existing canvas item, but without closing it.
self.layout.remove_canvas_item(canvas_item)
canvas_item.container = None
self._remove_canvas_item_direct(canvas_item)
# insert the canvas item container
# self.insert_canvas_item(index, canvas_item_container) # this would adjust splitters. don't do it.
self._insert_canvas_item_direct(index, canvas_item_container)
# insert the canvas item into the container
canvas_item_container.add_canvas_item(canvas_item)
# perform the layout using existing origin/size.
if canvas_origin is not None and canvas_size is not None:
canvas_item_container._set_canvas_origin(canvas_origin)
canvas_item_container._set_canvas_size(canvas_size)
canvas_item._set_canvas_origin(Geometry.IntPoint())
self.refresh_layout()
def unwrap_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
""" Replace the canvas item container with the canvas item. """
container = canvas_item.container
assert container
assert len(container.canvas_items) == 1
assert container.canvas_items[0] == canvas_item
enclosing_container = container.container
assert enclosing_container
index = enclosing_container.canvas_items.index(container)
# remove the existing canvas item from the container, but without closing it.
container.layout.remove_canvas_item(canvas_item)
canvas_item.container = None
container._remove_canvas_item_direct(canvas_item)
# remove container from enclosing container
enclosing_container._remove_canvas_item_direct(container)
# insert canvas item into the enclosing container
# enclosing_container.insert_canvas_item(index, canvas_item) # this would adjust splitters. don't do it.
enclosing_container._insert_canvas_item_direct(index, canvas_item)
# update the layout if origin and size already known
self.refresh_layout()
def _repaint_template(self, drawing_context: DrawingContext.DrawingContext, immediate: bool) -> None:
if not self.__layout_render_trait._try_repaint_template(drawing_context, immediate):
self._repaint_children(drawing_context, immediate=immediate)
self._repaint(drawing_context)
def _repaint_if_needed(self, drawing_context: DrawingContext.DrawingContext, *, immediate: bool = False) -> None:
if self.__layout_render_trait:
if not self.__layout_render_trait._try_repaint_if_needed(drawing_context, immediate=immediate):
super()._repaint_if_needed(drawing_context, immediate=immediate)
def repaint_immediate(self, drawing_context: DrawingContext.DrawingContext, canvas_size: Geometry.IntSize) -> None:
if not self.__layout_render_trait._try_repaint_immediate(drawing_context, canvas_size):
super().repaint_immediate(drawing_context, canvas_size)
def _repaint_children(self, drawing_context: DrawingContext.DrawingContext, *, immediate: bool = False) -> None:
"""Paint items from back to front."""
self._draw_background(drawing_context)
for canvas_item in self.visible_canvas_items:
if canvas_item._has_layout:
with drawing_context.saver():
canvas_item_rect = canvas_item.canvas_rect
if canvas_item_rect:
drawing_context.translate(canvas_item_rect.left, canvas_item_rect.top)
canvas_item._repaint_if_needed(drawing_context, immediate=immediate)
self._draw_border(drawing_context)
def _canvas_items_at_point(self, visible_canvas_items: typing.Sequence[AbstractCanvasItem], x: int, y: int) -> typing.List[AbstractCanvasItem]:
"""Returns list of canvas items under x, y, ordered from back to front."""
canvas_items: typing.List[AbstractCanvasItem] = []
point = Geometry.IntPoint(x=x, y=y)
for canvas_item in reversed(visible_canvas_items):
# the visible items can be changed while this method is running from the layout thread.
# and yet we don't want to allow this to occur; maybe the layout thread should have some
# sort of pending system, where once methods like this exit, they're allowed to update...?
canvas_item_rect = canvas_item.canvas_rect
if canvas_item_rect and canvas_item_rect.contains_point(point):
canvas_origin = typing.cast(Geometry.IntPoint, canvas_item.canvas_origin)
canvas_point = point - canvas_origin
canvas_items.extend(canvas_item.canvas_items_at_point(canvas_point.x, canvas_point.y))
canvas_items.extend(super().canvas_items_at_point(x, y))
return canvas_items
def canvas_items_at_point(self, x: int, y: int) -> typing.List[AbstractCanvasItem]:
"""Returns list of canvas items under x, y, ordered from back to front."""
return self._canvas_items_at_point(self.visible_canvas_items, x, y)
def get_root_opaque_canvas_items(self) -> typing.List[AbstractCanvasItem]:
if self.is_root_opaque:
return [self]
canvas_items = list()
for canvas_item in self.canvas_items:
canvas_items.extend(canvas_item.get_root_opaque_canvas_items())
return canvas_items
def pan_gesture(self, dx: int, dy: int) -> bool:
for canvas_item in reversed(self.visible_canvas_items):
if canvas_item.pan_gesture(dx, dy):
return True
return False
_threaded_rendering_enabled = True
class LayerLayoutRenderTrait(CompositionLayoutRenderTrait):
_layer_id = 0
_executor = concurrent.futures.ThreadPoolExecutor()
def __init__(self, canvas_item_composition: CanvasItemComposition):
super().__init__(canvas_item_composition)
LayerLayoutRenderTrait._layer_id += 1
self.__layer_id = LayerLayoutRenderTrait._layer_id
self.__layer_lock = threading.RLock()
self.__layer_drawing_context: typing.Optional[DrawingContext.DrawingContext] = None
self.__layer_seed = 0
self.__executing = False
self.__cancel = False
self.__needs_layout = False
self.__needs_repaint = False
self.__prepare_canvas_items: typing.List[AbstractCanvasItem] = list()
self._layer_thread_suppress = not _threaded_rendering_enabled # for testing
self.__layer_thread_condition = threading.Condition()
# Python 3.9+: Optional[concurrent.futures.Future[Any]]
self.__repaint_one_future: typing.Optional[typing.Any] = None
def close(self) -> None:
self._sync_repaint()
super().close()
def _stop_render_behavior(self) -> None:
self.__cancel = True
self._sync_repaint()
self.__layer_drawing_context = None
@property
def _needs_layout_for_testing(self) -> bool:
return self.__needs_layout
@property
def is_layer_container(self) -> bool:
return True
def register_prepare_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
assert canvas_item not in self.__prepare_canvas_items
self.__prepare_canvas_items.append(canvas_item)
def unregister_prepare_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
assert canvas_item in self.__prepare_canvas_items
self.__prepare_canvas_items.remove(canvas_item)
def _container_layout_changed(self) -> None:
# the section drawing code has no layout information; so it's possible for the sections to
# overlap, particularly during resizing, resulting in one layer drawing only to be overwritten
# by an older layer whose size hasn't been updated. this method is called quickly when the
# enclosing container changes layout and helps ensure that all layers in the container are drawn
# with the correct size.
if self.__layer_drawing_context:
self._canvas_item_composition._repaint_finished(self.__layer_drawing_context)
def _try_update_layout(self, canvas_origin: typing.Optional[Geometry.IntPoint], canvas_size: typing.Optional[Geometry.IntSize], *, immediate: bool = False) -> bool:
# layout self, but not the children. layout for children goes to thread.
self._canvas_item_composition._update_self_layout(canvas_origin, canvas_size)
self.__trigger_layout()
return True
def _try_needs_layout(self, canvas_item: AbstractCanvasItem) -> bool:
self.__trigger_layout()
return True
def _sync_repaint(self) -> None:
done_event = threading.Event()
with self.__layer_thread_condition:
if self.__repaint_one_future:
# Python 3.9: Optional[concurrent.futures.Future[Any]]
def repaint_done(future: typing.Any) -> None:
done_event.set()
self.__repaint_one_future.add_done_callback(repaint_done)
else:
done_event.set()
done_event.wait()
# Python 3.9: Optional[concurrent.futures.Future[Any]]
def __repaint_done(self, future: typing.Any) -> None:
with self.__layer_thread_condition:
self.__repaint_one_future = None
if self.__needs_layout or self.__needs_repaint:
self.__queue_repaint()
def __queue_repaint(self) -> None:
with self.__layer_thread_condition:
if not self.__cancel and not self.__repaint_one_future:
self.__repaint_one_future = LayerLayoutRenderTrait._executor.submit(self.__repaint_layer)
self.__repaint_one_future.add_done_callback(self.__repaint_done)
def _try_updated(self) -> bool:
with self.__layer_thread_condition:
self.__needs_repaint = True
if not self._layer_thread_suppress:
self.__queue_repaint()
# normally, this method would mark a pending update and forward the update to the container;
# however with the layer, since drawing occurs on a thread, this must occur after the thread
# is finished. if the thread is suppressed (typically during testing), use the regular flow.
if self._layer_thread_suppress:
# pass through updates in the thread is suppressed, so that updates actually occur.
return False
return True
def _try_repaint_template(self, drawing_context: DrawingContext.DrawingContext, immediate: bool) -> bool:
if immediate:
canvas_size = self._canvas_item_composition.canvas_size
if canvas_size:
self._canvas_item_composition.repaint_immediate(drawing_context, canvas_size)
else:
with self.__layer_lock:
layer_drawing_context = self.__layer_drawing_context
layer_seed = self.__layer_seed
canvas_size = self._canvas_item_composition.canvas_size
if canvas_size:
drawing_context.begin_layer(self.__layer_id, layer_seed, 0, 0, *tuple(canvas_size))
if layer_drawing_context:
drawing_context.add(layer_drawing_context)
drawing_context.end_layer(self.__layer_id, layer_seed, 0, 0, *tuple(canvas_size))
return True
def _try_repaint_if_needed(self, drawing_context: DrawingContext.DrawingContext, *, immediate: bool = False) -> bool:
# If the render behavior is a layer, it will have its own cached drawing context. Use it.
self._canvas_item_composition._repaint_template(drawing_context, immediate)
return True
def layout_immediate(self, canvas_size: Geometry.IntSize, force: bool = True) -> None:
# used for testing
orphan = len(self.__prepare_canvas_items) == 0
if orphan:
self._canvas_item_composition._inserted(None)
if force or self.__needs_layout:
self.__needs_layout = False
layer_thread_suppress, self._layer_thread_suppress = self._layer_thread_suppress, True
for canvas_item in copy.copy(self.__prepare_canvas_items):
canvas_item.prepare_render()
self._canvas_item_composition._prepare_render()
self._canvas_item_composition._update_self_layout(Geometry.IntPoint(), canvas_size, immediate=True)
self._canvas_item_composition._update_child_layouts(canvas_size, immediate=True)
self._layer_thread_suppress = layer_thread_suppress
if orphan:
self._canvas_item_composition._removed(None)
def _try_repaint_immediate(self, drawing_context: DrawingContext.DrawingContext, canvas_size: Geometry.IntSize) -> bool:
orphan = len(self.__prepare_canvas_items) == 0
if orphan:
self._canvas_item_composition._inserted(None)
layer_thread_suppress, self._layer_thread_suppress = self._layer_thread_suppress, True
self._layer_thread_suppress = True
for canvas_item in copy.copy(self.__prepare_canvas_items):
canvas_item.prepare_render()
self._canvas_item_composition._update_self_layout(Geometry.IntPoint(), canvas_size, immediate=True)
self._canvas_item_composition._update_child_layouts(canvas_size, immediate=True)
self._canvas_item_composition._repaint_children(drawing_context, immediate=True)
self._canvas_item_composition._repaint(drawing_context)
self._layer_thread_suppress = layer_thread_suppress
if orphan:
self._canvas_item_composition._removed(None)
return True
def __repaint_layer(self) -> None:
with self.__layer_thread_condition:
needs_layout = self.__needs_layout
needs_repaint = self.__needs_repaint
self.__needs_layout = False
self.__needs_repaint = False
if not self.__cancel and (needs_repaint or needs_layout):
if self._canvas_item_composition._has_layout:
try:
for canvas_item in copy.copy(self.__prepare_canvas_items):
canvas_item.prepare_render()
self._canvas_item_composition._prepare_render()
# layout or repaint that occurs during prepare render should be handled
# but not trigger another repaint after this one.
with self.__layer_thread_condition:
needs_layout = needs_layout or self.__needs_layout
self.__needs_layout = False
self.__needs_repaint = False
if needs_layout:
assert self._canvas_item_composition.canvas_size is not None
self._canvas_item_composition._update_child_layouts(
self._canvas_item_composition.canvas_size)
drawing_context = DrawingContext.DrawingContext()
self._canvas_item_composition._repaint_children(drawing_context)
self._canvas_item_composition._repaint(drawing_context)
with self.__layer_lock:
self.__layer_seed += 1
self.__layer_drawing_context = drawing_context
if not self.__cancel:
self._canvas_item_composition._repaint_finished(self.__layer_drawing_context)
except Exception as e:
import traceback
logging.debug("CanvasItem Render Error: %s", e)
traceback.print_exc()
traceback.print_stack()
def __trigger_layout(self) -> None:
with self.__layer_thread_condition:
self.__needs_layout = True
if not self._layer_thread_suppress:
self.__queue_repaint()
class LayerCanvasItem(CanvasItemComposition):
"""A composite canvas item that does layout and repainting in a thread."""
def __init__(self) -> None:
super().__init__(LayerLayoutRenderTrait(self))
def _container_layout_changed(self) -> None:
# override. a layer needs to redraw in the user interface.
self._redraw_container()
class ScrollAreaCanvasItem(AbstractCanvasItem):
"""
A scroll area canvas item with content.
The content property holds the content of the scroll area.
This scroll area controls the canvas_origin of the content, but not the
size. When the scroll area is resized, update_layout will be called on
the content, during which the content is free to adjust its canvas size.
When the call to update_layout returns, this scroll area will adjust
the canvas origin separately.
The content canvas_rect property describes the position that the content
is drawn within the scroll area. This means that content items must
already have a layout when they're added to this scroll area.
The content canvas_origin will typically be negative if the content
canvas_size is larger than the scroll area canvas size.
The content canvas_origin will typically be positive (or zero) if the
content canvas_size is smaller than the scroll area canvas size.
"""
def __init__(self, content: typing.Optional[AbstractCanvasItem] = None) -> None:
super().__init__()
self.__content: typing.Optional[AbstractCanvasItem] = None
if content:
self.content = content
self.auto_resize_contents = False
self._constrain_position = True
self.content_updated_event = Event.Event()
def close(self) -> None:
content = self.__content
self.__content = None
if content:
content.close()
super().close()
@property
def content(self) -> typing.Optional[AbstractCanvasItem]:
""" Return the content of the scroll area. """
return self.__content
@content.setter
def content(self, content: AbstractCanvasItem) -> None:
""" Set the content of the scroll area. """
# remove the old content
if self.__content:
self.__content.container = None
self.__content.on_layout_updated = None
# add the new content
self.__content = content
content.container = typing.cast(CanvasItemComposition, self) # argh
content.on_layout_updated = self.__content_layout_updated
self.update()
@property
def visible_rect(self) -> Geometry.IntRect:
content = self.__content
if content:
content_canvas_origin = content.canvas_origin
canvas_size = self.canvas_size
if content_canvas_origin and canvas_size:
return Geometry.IntRect(origin=-content_canvas_origin, size=canvas_size)
return Geometry.IntRect(origin=Geometry.IntPoint(), size=Geometry.IntSize())
def update_layout(self, canvas_origin: typing.Optional[Geometry.IntPoint],
canvas_size: typing.Optional[Geometry.IntSize], *, immediate: bool = False) -> None:
"""Override from abstract canvas item.
After setting the canvas origin and canvas size, like the abstract canvas item,
update the layout of the content if it has no assigned layout yet. Whether it has
an assigned layout is determined by whether the canvas origin and canvas size are
None or not.
"""
self._set_canvas_origin(canvas_origin)
self._set_canvas_size(canvas_size)
content = self.__content
if content:
canvas_origin = content.canvas_origin
canvas_size = content.canvas_size
if canvas_origin is None or canvas_size is None:
# if content has no assigned layout, update its layout relative to this object.
# it will get a 0,0 origin but the same size as this scroll area.
content.update_layout(Geometry.IntPoint(), self.canvas_size, immediate=immediate)
elif self.auto_resize_contents:
# if content has no assigned layout, update its layout relative to this object.
# it will get a 0,0 origin but the same size as this scroll area.
content.update_layout(canvas_origin, self.canvas_size, immediate=immediate)
# validate the content origin. this is used for the scroll bar canvas item to ensure that the content is
# consistent with the scroll bar.
self.__content_layout_updated(canvas_origin, canvas_size, immediate=immediate)
# NOTE: super is never called for this implementation
# call on_layout_updated, just like the super implementation.
if callable(self.on_layout_updated):
self.on_layout_updated(self.canvas_origin, self.canvas_size, immediate)
self._has_layout = self.canvas_origin is not None and self.canvas_size is not None
def __content_layout_updated(self, canvas_origin: typing.Optional[Geometry.IntPoint],
canvas_size: typing.Optional[Geometry.IntSize], immediate: bool = False) -> None:
# whenever the content layout changes, this method gets called.
# adjust the canvas_origin of the content if necessary. pass the canvas_origin, canvas_size of the content.
# this method is used in the scroll bar canvas item to ensure that the content stays within view and
# consistent with the scroll bar when the scroll area gets a new layout.
if self._constrain_position and canvas_origin is not None and canvas_size is not None and self.canvas_origin is not None and self.canvas_size is not None:
# when the scroll area content layout changes, this method will get called.
# ensure that the content matches the scroll position.
visible_size = self.canvas_size
content = self.__content
if content:
content_size = content.canvas_size
if content_size:
scroll_range_h = max(content_size.width - visible_size.width, 0)
scroll_range_v = max(content_size.height - visible_size.height, 0)
canvas_origin = Geometry.IntPoint(x=canvas_origin.x, y=max(min(canvas_origin.y, 0), -scroll_range_v))
canvas_origin = Geometry.IntPoint(x=max(min(canvas_origin.x, 0), -scroll_range_h), y=canvas_origin.y)
content._set_canvas_origin(canvas_origin)
self.content_updated_event.fire()
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
super()._repaint(drawing_context)
with drawing_context.saver():
canvas_origin = self.canvas_origin
canvas_size = self.canvas_size
if canvas_origin and canvas_size:
drawing_context.clip_rect(canvas_origin.x, canvas_origin.y, canvas_size.width, canvas_size.height)
content = self.__content
if content:
content_canvas_origin = content.canvas_origin
if content_canvas_origin:
drawing_context.translate(content_canvas_origin.x, content_canvas_origin.y)
visible_rect = Geometry.IntRect(origin=-content_canvas_origin, size=canvas_size)
content._repaint_visible(drawing_context, visible_rect)
def canvas_items_at_point(self, x: int, y: int) -> typing.List[AbstractCanvasItem]:
canvas_items: typing.List[AbstractCanvasItem] = []
point = Geometry.IntPoint(x=x, y=y)
content = self.__content
if content and content.canvas_rect and content.canvas_rect.contains_point(point):
content_canvas_origin = content.canvas_origin
if content_canvas_origin:
canvas_point = point - content_canvas_origin
canvas_items.extend(content.canvas_items_at_point(canvas_point.x, canvas_point.y))
canvas_items.extend(super().canvas_items_at_point(x, y))
return canvas_items
def wheel_changed(self, x: int, y: int, dx: int, dy: int, is_horizontal: bool) -> bool:
canvas_origin = self.canvas_origin
if canvas_origin:
x -= canvas_origin.x
y -= canvas_origin.y
content = self.__content
if content:
return content.wheel_changed(x, y, dx, dy, is_horizontal)
return False
def pan_gesture(self, dx: int, dy: int) -> bool:
content = self.__content
if content:
return content.pan_gesture(dx, dy)
return False
class SplitterCanvasItem(CanvasItemComposition):
def __init__(self, orientation: typing.Optional[str] = None) -> None:
super().__init__()
self.orientation = orientation if orientation else "vertical"
self.wants_mouse_events = True
self.__lock = threading.RLock()
self.__sizings: typing.List[Sizing] = []
self.__shadow_canvas_items: typing.List[AbstractCanvasItem] = []
self.__actual_sizings: typing.List[Sizing] = []
self.__tracking = False
self.on_splits_will_change: typing.Optional[typing.Callable[[], None]] = None
self.on_splits_changed: typing.Optional[typing.Callable[[], None]] = None
@classmethod
def __calculate_layout(self, orientation: str, canvas_size: Geometry.IntSize, sizings: typing.Sequence[Sizing]) -> ConstraintResultType:
if orientation == "horizontal":
content_origin = 0
content_size = canvas_size.height
constraints = [sizing.get_height_constraint(content_size) for sizing in sizings]
else:
content_origin = 0
content_size = canvas_size.width
constraints = [sizing.get_width_constraint(content_size) for sizing in sizings]
return constraint_solve(content_origin, content_size, constraints)
@property
def splits(self) -> typing.Sequence[float]:
""" Return the canvas item splits, which represent the relative size of each child. """
if self.canvas_size:
canvas_size = self.canvas_size
else:
canvas_size = Geometry.IntSize(w=640, h=480)
if self.orientation == "horizontal":
content_size = canvas_size.height
else:
content_size = canvas_size.width
with self.__lock:
sizings = copy.deepcopy(self.__sizings)
_, sizes = SplitterCanvasItem.__calculate_layout(self.orientation, canvas_size, sizings)
return [float(size) / content_size for size in sizes]
@splits.setter
def splits(self, splits: typing.Sequence[float]) -> None:
with self.__lock:
sizings = copy.deepcopy(self.__sizings)
assert len(splits) == len(sizings)
for split, sizing in zip(splits, sizings):
if self.orientation == "horizontal":
sizing._preferred_height = split
else:
sizing._preferred_width = split
with self.__lock:
self.__sizings = sizings
self.refresh_layout()
def _insert_canvas_item_direct(self, before_index: int, canvas_item: AbstractCanvasItem,
pos: typing.Optional[Geometry.IntPoint] = None) -> None:
super().insert_canvas_item(before_index, canvas_item)
def insert_canvas_item(self, before_index: int, canvas_item: AbstractCanvasItem,
sizing: typing.Optional[typing.Any] = None) -> AbstractCanvasItem:
sizing = copy.copy(sizing) if sizing else Sizing()
if self.orientation == "horizontal":
sizing._preferred_height = None
if sizing._minimum_height is None:
sizing._minimum_height = 0.1
else:
sizing._preferred_width = None
if sizing._minimum_width is None:
sizing._minimum_width = 0.1
with self.__lock:
self.__sizings.insert(before_index, sizing)
return super().insert_canvas_item(before_index, canvas_item)
def remove_canvas_item(self, canvas_item: AbstractCanvasItem) -> None:
with self.__lock:
del self.__sizings[self.canvas_items.index(canvas_item)]
super().remove_canvas_item(canvas_item)
def update_layout(self, canvas_origin: typing.Optional[Geometry.IntPoint],
canvas_size: typing.Optional[Geometry.IntSize], *, immediate: bool = False) -> None:
"""
wrap the updates in container layout changes to avoid a waterfall of
change messages. this is specific to splitter for now, but it's a general
behavior that should eventually wrap all update layout calls.
canvas items that cache their drawing bitmap (layers) need to know as quickly as possible
that their layout has changed to a new size to avoid partially updated situations where
their bitmaps overlap and a newer bitmap gets overwritten by a older overlapping bitmap,
resulting in drawing anomaly. request a repaint for each canvas item at its new size here.
this can also be tested by doing a 1x2 split; then 5x4 on the bottom; adding some images
to the bottom; resizing the 1x2 split; then undo/redo. it helps to run on a slower machine.
"""
self._begin_container_layout_changed()
try:
with self.__lock:
canvas_items = copy.copy(self.canvas_items)
sizings = copy.deepcopy(self.__sizings)
assert len(canvas_items) == len(sizings)
if canvas_size:
origins, sizes = SplitterCanvasItem.__calculate_layout(self.orientation, canvas_size, sizings)
if self.orientation == "horizontal":
for canvas_item, (origin, size) in zip(canvas_items, zip(origins, sizes)):
canvas_item_origin = Geometry.IntPoint(y=origin, x=0) # origin within the splitter
canvas_item_size = Geometry.IntSize(height=size, width=canvas_size.width)
canvas_item.update_layout(canvas_item_origin, canvas_item_size, immediate=immediate)
assert canvas_item._has_layout
for sizing, size in zip(sizings, sizes):
sizing._preferred_height = size
else:
for canvas_item, (origin, size) in zip(canvas_items, zip(origins, sizes)):
canvas_item_origin = Geometry.IntPoint(y=0, x=origin) # origin within the splitter
canvas_item_size = Geometry.IntSize(height=canvas_size.height, width=size)
canvas_item.update_layout(canvas_item_origin, canvas_item_size, immediate=immediate)
assert canvas_item._has_layout
for sizing, size in zip(sizings, sizes):
sizing._preferred_width = size
with self.__lock:
self.__actual_sizings = sizings
self.__shadow_canvas_items = canvas_items
# instead of calling the canvas item composition, call the one for abstract canvas item.
self._update_self_layout(canvas_origin, canvas_size, immediate=immediate)
self._has_layout = self.canvas_origin is not None and self.canvas_size is not None
# the next update is required because the children will trigger updates; but the updates
# might not go all the way up the chain if this splitter has no layout. by now, it will
# have a layout, so force an update.
self.update()
finally:
self._finish_container_layout_changed()
def canvas_items_at_point(self, x: int, y: int) -> typing.List[AbstractCanvasItem]:
assert self.canvas_origin is not None and self.canvas_size is not None
with self.__lock:
canvas_items = copy.copy(self.__shadow_canvas_items)
sizings = copy.deepcopy(self.__actual_sizings)
origins, _ = SplitterCanvasItem.__calculate_layout(self.orientation, self.canvas_size, sizings)
if self.orientation == "horizontal":
for origin in origins[1:]: # don't check the '0' origin
if abs(y - origin) < 6:
return [self]
else:
for origin in origins[1:]: # don't check the '0' origin
if abs(x - origin) < 6:
return [self]
return self._canvas_items_at_point(canvas_items, x, y)
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
super()._repaint(drawing_context)
assert self.canvas_origin is not None and self.canvas_size is not None
with self.__lock:
sizings = copy.deepcopy(self.__actual_sizings)
origins, _ = SplitterCanvasItem.__calculate_layout(self.orientation, self.canvas_size, sizings)
with drawing_context.saver():
drawing_context.begin_path()
for origin in origins[1:]: # don't paint the '0' origin
canvas_bounds = self.canvas_bounds
if canvas_bounds:
if self.orientation == "horizontal":
drawing_context.move_to(canvas_bounds.left, origin)
drawing_context.line_to(canvas_bounds.right, origin)
else:
drawing_context.move_to(origin, canvas_bounds.top)
drawing_context.line_to(origin, canvas_bounds.bottom)
drawing_context.line_width = 0.5
drawing_context.stroke_style = "#666"
drawing_context.stroke()
def __hit_test(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> str:
with self.__lock:
sizings = copy.deepcopy(self.__actual_sizings)
canvas_size = self.canvas_size
if canvas_size:
origins, _ = SplitterCanvasItem.__calculate_layout(self.orientation, canvas_size, sizings)
if self.orientation == "horizontal":
for index, origin in enumerate(origins[1:]): # don't check the '0' origin
if abs(y - origin) < 6:
return "horizontal"
else:
for index, origin in enumerate(origins[1:]): # don't check the '0' origin
if abs(x - origin) < 6:
return "vertical"
return "horizontal"
def mouse_pressed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
assert self.canvas_origin is not None and self.canvas_size is not None
with self.__lock:
sizings = copy.deepcopy(self.__actual_sizings)
origins, _ = SplitterCanvasItem.__calculate_layout(self.orientation, self.canvas_size, sizings)
if self.orientation == "horizontal":
for index, origin in enumerate(origins[1:]): # don't check the '0' origin
if abs(y - origin) < 6:
self.__tracking = True
self.__tracking_start_pos = Geometry.IntPoint(y=y, x=x)
self.__tracking_start_adjust = y - origin
self.__tracking_start_index = index
self.__tracking_start_preferred = int(sizings[index].preferred_height or 0)
self.__tracking_start_preferred_next = int(sizings[index + 1].preferred_height or 0)
if callable(self.on_splits_will_change):
self.on_splits_will_change()
return True
else:
for index, origin in enumerate(origins[1:]): # don't check the '0' origin
if abs(x - origin) < 6:
self.__tracking = True
self.__tracking_start_pos = Geometry.IntPoint(y=y, x=x)
self.__tracking_start_adjust = x - origin
self.__tracking_start_index = index
self.__tracking_start_preferred = int(sizings[index].preferred_width or 0)
self.__tracking_start_preferred_next = int(sizings[index + 1].preferred_width or 0)
if callable(self.on_splits_will_change):
self.on_splits_will_change()
return True
return super().mouse_pressed(x, y, modifiers)
def mouse_released(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self.__tracking = False
if callable(self.on_splits_changed):
self.on_splits_changed()
return True
def mouse_position_changed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
if self.__tracking:
with self.__lock:
old_sizings = copy.deepcopy(self.__sizings)
temp_sizings = copy.deepcopy(self.__actual_sizings)
tracking_start_preferred_next = self.__tracking_start_preferred_next or 0
tracking_start_preferred = self.__tracking_start_preferred or 0
snaps: typing.List[int] = list()
canvas_bounds = self.canvas_bounds
if canvas_bounds:
if self.orientation == "horizontal":
offset = y - self.__tracking_start_pos.y
if not modifiers.shift:
snaps.append((tracking_start_preferred_next - tracking_start_preferred) // 2)
snaps.append(canvas_bounds.height // 3 - self.__tracking_start_pos.y - self.__tracking_start_adjust)
snaps.append(2 * canvas_bounds.height // 3 - self.__tracking_start_pos.y - self.__tracking_start_adjust)
for snap in snaps:
if abs(offset - snap) < 12:
offset = snap
break
temp_sizings[self.__tracking_start_index]._preferred_height = tracking_start_preferred + offset
temp_sizings[self.__tracking_start_index + 1]._preferred_height = tracking_start_preferred_next - offset
else:
offset = x - self.__tracking_start_pos.x
if not modifiers.shift:
snaps.append((tracking_start_preferred_next - tracking_start_preferred) // 2)
snaps.append(canvas_bounds.width // 3 - self.__tracking_start_pos.x - self.__tracking_start_adjust)
snaps.append(2 * canvas_bounds.width // 3 - self.__tracking_start_pos.x - self.__tracking_start_adjust)
for snap in snaps:
if abs(offset - snap) < 12:
offset = snap
break
temp_sizings[self.__tracking_start_index]._preferred_width = tracking_start_preferred + offset
temp_sizings[self.__tracking_start_index + 1]._preferred_width = tracking_start_preferred_next - offset
# fix the size of all children except for the two in question
for index, sizing in enumerate(temp_sizings):
if index != self.__tracking_start_index and index != self.__tracking_start_index + 1:
if self.orientation == "horizontal":
sizing._set_fixed_height(sizing.preferred_height)
else:
sizing._set_fixed_width(sizing.preferred_width)
# update the layout
with self.__lock:
self.__sizings = temp_sizings
self.refresh_layout()
self.update_layout(self.canvas_origin, self.canvas_size)
# restore the freedom of the others
new_sizings = list()
for index, (old_sizing, temp_sizing) in enumerate(zip(old_sizings, temp_sizings)):
sizing = Sizing()
sizing._copy_from(old_sizing)
if index == self.__tracking_start_index or index == self.__tracking_start_index + 1:
if self.orientation == "horizontal":
sizing._preferred_height = temp_sizing.preferred_height
else:
sizing._preferred_width = temp_sizing.preferred_width
new_sizings.append(sizing)
with self.__lock:
self.__sizings = new_sizings
# update once more with restored sizings. addresses issue nionswift/605
self.refresh_layout()
return True
else:
control = self.__hit_test(x, y, modifiers)
if control == "horizontal":
self.cursor_shape = "split_vertical"
elif control == "vertical":
self.cursor_shape = "split_horizontal"
else:
self.cursor_shape = None
return super().mouse_position_changed(x, y, modifiers)
class SliderCanvasItem(AbstractCanvasItem, Observable.Observable):
"""Slider."""
thumb_width = 8
thumb_height = 16
bar_offset = 1
bar_height = 4
def __init__(self) -> None:
super().__init__()
self.wants_mouse_events = True
self.__tracking = False
self.__tracking_start = Geometry.IntPoint()
self.__tracking_value = 0.0
self.update_sizing(self.sizing.with_fixed_height(20))
self.value_stream = Stream.ValueStream[float]().add_ref()
self.value_change_stream = Stream.ValueChangeStream(self.value_stream).add_ref()
def close(self) -> None:
self.value_change_stream.remove_ref()
self.value_change_stream = typing.cast(typing.Any, None)
self.value_stream.remove_ref()
self.value_stream = typing.cast(typing.Any, None)
super().close()
@property
def value(self) -> float:
return self.value_stream.value or 0.0
@value.setter
def value(self, value: float) -> None:
if self.value != value:
self.value_stream.value = max(0.0, min(1.0, value))
self.update()
self.notify_property_changed("value")
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
thumb_rect = self.__get_thumb_rect()
bar_rect = self.__get_bar_rect()
with drawing_context.saver():
drawing_context.begin_path()
drawing_context.rect(bar_rect.left, bar_rect.top, bar_rect.width, bar_rect.height)
drawing_context.fill_style = "#CCC"
drawing_context.fill()
drawing_context.stroke_style = "#888"
drawing_context.stroke()
drawing_context.begin_path()
drawing_context.rect(thumb_rect.left, thumb_rect.top, thumb_rect.width, thumb_rect.height)
drawing_context.fill_style = "#007AD8"
drawing_context.fill()
def __get_bar_rect(self) -> Geometry.FloatRect:
canvas_size = self.canvas_size
if canvas_size:
thumb_width = self.thumb_width
bar_offset = self.bar_offset
bar_width = canvas_size.width - thumb_width - bar_offset * 2
bar_height = self.bar_height
return Geometry.FloatRect.from_tlhw(canvas_size.height / 2 - bar_height / 2, bar_offset + thumb_width / 2, bar_height, bar_width)
return Geometry.FloatRect.empty_rect()
def __get_thumb_rect(self) -> Geometry.IntRect:
canvas_size = self.canvas_size
if canvas_size:
thumb_width = self.thumb_width
thumb_height = self.thumb_height
bar_offset = self.bar_offset
bar_width = canvas_size.width - thumb_width - bar_offset * 2
# use tracking value to avoid thumb jumping around while dragging, which occurs when value gets integerized and set.
value = self.value if not self.__tracking else self.__tracking_value
return Geometry.FloatRect.from_tlhw(canvas_size.height / 2 - thumb_height / 2, value * bar_width + bar_offset, thumb_height, thumb_width).to_int_rect()
return Geometry.IntRect.empty_rect()
def mouse_pressed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
thumb_rect = self.__get_thumb_rect()
pos = Geometry.IntPoint(x=x, y=y)
if thumb_rect.inset(-2, -2).contains_point(pos):
self.__tracking = True
self.__tracking_start = pos
self.__tracking_value = self.value
self.value_change_stream.begin()
self.update()
return True
elif x < thumb_rect.left:
self.__adjust_thumb(-1)
return True
elif x > thumb_rect.right:
self.__adjust_thumb(1)
return True
return super().mouse_pressed(x, y, modifiers)
def mouse_released(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
if self.__tracking:
self.__tracking = False
self.value_change_stream.end()
self.update()
return True
return super().mouse_released(x, y, modifiers)
def mouse_position_changed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
if self.__tracking:
pos = Geometry.FloatPoint(x=x, y=y)
bar_rect = self.__get_bar_rect()
value = (pos.x - bar_rect.left) / bar_rect.width
self.__tracking_value = max(0.0, min(1.0, value))
self.value = value
return super().mouse_position_changed(x, y, modifiers)
def __adjust_thumb(self, amount: float) -> None:
self.value_change_stream.begin()
self.value = max(0.0, min(1.0, self.value + amount * 0.1))
self.value_change_stream.end()
PositionLength = collections.namedtuple("PositionLength", ["position", "length"])
class ScrollBarCanvasItem(AbstractCanvasItem):
""" A scroll bar for a scroll area. """
def __init__(self, scroll_area_canvas_item: ScrollAreaCanvasItem, orientation: typing.Optional[Orientation] = None) -> None:
super().__init__()
orientation = orientation if orientation is not None else Orientation.Vertical
self.wants_mouse_events = True
self.__scroll_area_canvas_item = scroll_area_canvas_item
self.__scroll_area_canvas_item_content_updated_listener = self.__scroll_area_canvas_item.content_updated_event.listen(self.update)
self.__tracking = False
self.__orientation = orientation
if self.__orientation == Orientation.Vertical:
self.update_sizing(self.sizing.with_fixed_width(16))
else:
self.update_sizing(self.sizing.with_fixed_height(16))
def close(self) -> None:
self.__scroll_area_canvas_item_content_updated_listener.close()
self.__scroll_area_canvas_item_content_updated_listener = typing.cast(typing.Any, None)
super().close()
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
# canvas size, thumb rect
canvas_size = self.canvas_size
thumb_rect = self.thumb_rect
if canvas_size:
# draw it
with drawing_context.saver():
# draw the border of the scroll bar
drawing_context.begin_path()
drawing_context.rect(0, 0, canvas_size.width, canvas_size.height)
if self.__orientation == Orientation.Vertical:
gradient = drawing_context.create_linear_gradient(canvas_size.width, canvas_size.height, 0, 0, canvas_size.width, 0)
else:
gradient = drawing_context.create_linear_gradient(canvas_size.width, canvas_size.height, 0, 0, 0, canvas_size.height)
gradient.add_color_stop(0.0, "#F2F2F2")
gradient.add_color_stop(0.35, "#FDFDFD")
gradient.add_color_stop(0.65, "#FDFDFD")
gradient.add_color_stop(1.0, "#F2F2F2")
drawing_context.fill_style = gradient
drawing_context.fill()
# draw the thumb, if any
if thumb_rect.height > 0 and thumb_rect.width > 0:
with drawing_context.saver():
drawing_context.begin_path()
if self.__orientation == Orientation.Vertical:
drawing_context.move_to(thumb_rect.width - 8, thumb_rect.top + 6)
drawing_context.line_to(thumb_rect.width - 8, thumb_rect.bottom - 6)
else:
drawing_context.move_to(thumb_rect.left + 6, thumb_rect.height - 8)
drawing_context.line_to(thumb_rect.right - 6, thumb_rect.height - 8)
drawing_context.line_width = 8.0
drawing_context.line_cap = "round"
drawing_context.stroke_style = "#888" if self.__tracking else "#CCC"
drawing_context.stroke()
# draw inside edge
drawing_context.begin_path()
drawing_context.move_to(0, 0)
if self.__orientation == Orientation.Vertical:
drawing_context.line_to(0, canvas_size.height)
else:
drawing_context.line_to(canvas_size.width, 0)
drawing_context.line_width = 0.5
drawing_context.stroke_style = "#E3E3E3"
drawing_context.stroke()
# draw outside
drawing_context.begin_path()
if self.__orientation == Orientation.Vertical:
drawing_context.move_to(canvas_size.width, 0)
else:
drawing_context.move_to(0, canvas_size.height)
drawing_context.line_to(canvas_size.width, canvas_size.height)
drawing_context.line_width = 0.5
drawing_context.stroke_style = "#999999"
drawing_context.stroke()
def get_thumb_position_and_length(self, canvas_length: int, visible_length: int, content_length: int, content_offset: int) -> PositionLength:
"""
Return the thumb position and length as a tuple of ints.
The canvas_length is the size of the canvas of the scroll bar.
The visible_length is the size of the visible area of the scroll area.
The content_length is the size of the content of the scroll area.
The content_offset is the position of the content within the scroll area. It
will always be negative or zero.
"""
# the scroll_range defines the maximum negative value of the content_offset.
scroll_range = max(content_length - visible_length, 0)
# content_offset should be negative, but not more negative than the scroll_range.
content_offset = max(-scroll_range, min(0, content_offset))
# assert content_offset <= 0 and content_offset >= -scroll_range
# the length of the thumb is the visible_length multiplied by the ratio of
# visible_length to the content_length. however, a minimum height is enforced
# so that the user can always grab it. if the thumb is invisible (the content_length
# is less than or equal to the visible_length) then the thumb will have a length of zero.
if content_length > visible_length:
thumb_length = int(canvas_length * (float(visible_length) / content_length))
thumb_length = max(thumb_length, 32)
# the position of the thumb is the content_offset over the content_length multiplied by
# the free range of the thumb which is the canvas_length minus the thumb_length.
thumb_position = int((canvas_length - thumb_length) * (float(-content_offset) / scroll_range))
else:
thumb_length = 0
thumb_position = 0
return PositionLength(thumb_position, thumb_length)
@property
def thumb_rect(self) -> Geometry.IntRect:
# return the thumb rect for the given canvas_size
canvas_size = self.canvas_size
if canvas_size:
index = 0 if self.__orientation == Orientation.Vertical else 1
scroll_area_canvas_size = self.__scroll_area_canvas_item.canvas_size
scroll_area_content = self.__scroll_area_canvas_item.content
if scroll_area_content and scroll_area_canvas_size:
visible_length = scroll_area_canvas_size[index]
scroll_area_rect = scroll_area_content.canvas_rect
if scroll_area_rect:
content_length = scroll_area_rect.size[index]
content_offset = scroll_area_rect.origin[index]
thumb_position, thumb_length = self.get_thumb_position_and_length(canvas_size[index], visible_length, content_length, content_offset)
if self.__orientation == Orientation.Vertical:
thumb_origin = Geometry.IntPoint(x=0, y=thumb_position)
thumb_size = Geometry.IntSize(width=canvas_size.width, height=thumb_length)
else:
thumb_origin = Geometry.IntPoint(x=thumb_position, y=0)
thumb_size = Geometry.IntSize(width=thumb_length, height=canvas_size.height)
return Geometry.IntRect(origin=thumb_origin, size=thumb_size)
return Geometry.IntRect.empty_rect()
def mouse_pressed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
thumb_rect = self.thumb_rect
pos = Geometry.IntPoint(x=x, y=y)
if thumb_rect.contains_point(pos):
self.__tracking = True
self.__tracking_start = pos
scroll_area_content = self.__scroll_area_canvas_item.content
self.__tracking_content_offset = scroll_area_content.canvas_origin if scroll_area_content else Geometry.IntPoint()
self.update()
return True
elif self.__orientation == Orientation.Vertical and y < thumb_rect.top:
self.__adjust_thumb(-1)
return True
elif self.__orientation == Orientation.Vertical and y > thumb_rect.bottom:
self.__adjust_thumb(1)
return True
elif self.__orientation != Orientation.Vertical and x < thumb_rect.left:
self.__adjust_thumb(-1)
return True
elif self.__orientation != Orientation.Vertical and x > thumb_rect.right:
self.__adjust_thumb(1)
return True
return super().mouse_pressed(x, y, modifiers)
def mouse_released(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self.__tracking = False
self.update()
return super().mouse_released(x, y, modifiers)
def __adjust_thumb(self, amount: float) -> None:
# adjust the position up or down one visible screen worth
index = 0 if self.__orientation == Orientation.Vertical else 1
scroll_area_rect = self.__scroll_area_canvas_item.canvas_rect
if scroll_area_rect:
visible_length = scroll_area_rect.size[index]
content = self.__scroll_area_canvas_item.content
if content:
content_canvas_origin = content.canvas_origin
if content_canvas_origin:
if self.__orientation == Orientation.Vertical:
new_content_offset = Geometry.IntPoint(y=round(content_canvas_origin[0] - visible_length * amount), x=content_canvas_origin[1])
else:
new_content_offset = Geometry.IntPoint(y=content_canvas_origin[0], x=round(content_canvas_origin[1] - visible_length * amount))
content.update_layout(new_content_offset, content.canvas_size)
content.update()
def adjust_content_offset(self, canvas_length: int, visible_length: int, content_length: int, content_offset: int, mouse_offset: int) -> int:
"""
Return the adjusted content offset.
The canvas_length is the size of the canvas of the scroll bar.
The visible_length is the size of the visible area of the scroll area.
The content_length is the size of the content of the scroll area.
The content_offset is the position of the content within the scroll area. It
will always be negative or zero.
The mouse_offset is the offset of the mouse.
"""
scroll_range = max(content_length - visible_length, 0)
_, thumb_length = self.get_thumb_position_and_length(canvas_length, visible_length, content_length, content_offset)
offset_rel = int(scroll_range * float(mouse_offset) / (canvas_length - thumb_length))
return max(min(content_offset - offset_rel, 0), -scroll_range)
def mouse_position_changed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
if self.__tracking:
pos = Geometry.IntPoint(x=x, y=y)
canvas_size = self.canvas_size
scroll_area_canvas_size = self.__scroll_area_canvas_item.canvas_size
if canvas_size and scroll_area_canvas_size:
scroll_area_content = self.__scroll_area_canvas_item.content
if scroll_area_content:
tracking_content_offset = self.__tracking_content_offset
scroll_area_content_canvas_size = scroll_area_content.canvas_size
if tracking_content_offset and scroll_area_content_canvas_size:
if self.__orientation == Orientation.Vertical:
mouse_offset_v = pos.y - self.__tracking_start.y
visible_height = scroll_area_canvas_size[0]
content_height = scroll_area_content_canvas_size[0]
new_content_offset_v = self.adjust_content_offset(canvas_size[0], visible_height, content_height, tracking_content_offset[0], mouse_offset_v)
new_content_offset = Geometry.IntPoint(x=tracking_content_offset[1], y=new_content_offset_v)
else:
mouse_offset_h = pos.x - self.__tracking_start.x
visible_width = scroll_area_canvas_size[1]
content_width = scroll_area_content_canvas_size[1]
new_content_offset_h = self.adjust_content_offset(canvas_size[1], visible_width, content_width, tracking_content_offset[1], mouse_offset_h)
new_content_offset = Geometry.IntPoint(x=new_content_offset_h, y=tracking_content_offset[0])
scroll_area_content._set_canvas_origin(new_content_offset)
scroll_area_content.update()
self.update()
return super().mouse_position_changed(x, y, modifiers)
class RootLayoutRenderTrait(CompositionLayoutRenderTrait):
next_section_id = 0
def __init__(self, canvas_item_composition: CanvasItemComposition) -> None:
super().__init__(canvas_item_composition)
self.__needs_repaint = False
self.__section_ids_lock = threading.RLock()
self.__section_map: typing.Dict[AbstractCanvasItem, int] = dict()
def close(self) -> None:
with self.__section_ids_lock:
section_map = self.__section_map
self.__section_map = dict()
for section_id in section_map.values():
canvas_widget = self._canvas_item_composition.canvas_widget
if canvas_widget:
canvas_widget.remove_section(section_id)
super().close()
@property
def is_layer_container(self) -> bool:
return True
def _try_needs_layout(self, canvas_item: AbstractCanvasItem) -> bool:
if self._canvas_item_composition.canvas_size:
# if this is a normal canvas item, tell it's container to layout again.
# otherwise, if this is the root, just layout the root.
container = canvas_item.container if canvas_item != self._canvas_item_composition else canvas_item
if container and container.canvas_size:
container.update_layout(container.canvas_origin, container.canvas_size)
if container == self._canvas_item_composition:
# when the root is resized, be sure to update all of the opaque items since layout
# doesn't do it automatically right now.
for canvas_item in self._canvas_item_composition.get_root_opaque_canvas_items():
canvas_item.update()
return True
def _try_update_with_items(self, canvas_items: typing.Optional[typing.Sequence[AbstractCanvasItem]] = None) -> bool:
drawing_context = DrawingContext.DrawingContext()
if self._canvas_item_composition._has_layout and self._canvas_item_composition.canvas_widget and canvas_items:
for canvas_item in canvas_items:
if canvas_item.is_root_opaque:
self._canvas_item_composition._update_count += 1
canvas_size = canvas_item.canvas_size
if canvas_size:
canvas_rect = Geometry.IntRect(canvas_item.map_to_root_container(Geometry.IntPoint(0, 0)), canvas_size)
canvas_item._repaint_template(drawing_context, immediate=False)
drawing_context.translate(-canvas_rect.left, -canvas_rect.top)
with self.__section_ids_lock:
section_id = self.__section_map.get(canvas_item, None)
if not section_id:
RootLayoutRenderTrait.next_section_id += 1
section_id = RootLayoutRenderTrait.next_section_id
self.__section_map[canvas_item] = section_id
self._canvas_item_composition.canvas_widget.draw_section(section_id, drawing_context, canvas_rect)
# break
self.__cull_unused_sections()
return True
def __cull_unused_sections(self) -> None:
canvas_items = self._canvas_item_composition.get_root_opaque_canvas_items()
with self.__section_ids_lock:
section_map = self.__section_map
self.__section_map = dict()
for canvas_item in canvas_items:
section_id = section_map.pop(canvas_item, None)
if section_id:
self.__section_map[canvas_item] = section_id
for section_id in section_map.values():
canvas_widget = self._canvas_item_composition.canvas_widget
if canvas_widget:
canvas_widget.remove_section(section_id)
RootLayoutRender = "root"
DefaultLayoutRender: typing.Optional[str] = None
class RootCanvasItem(CanvasItemComposition):
"""A root layer to interface to the widget world.
The root canvas item acts as a bridge between the higher level ui widget and a canvas hierarchy. It connects size
notifications, mouse activity, keyboard activity, focus activity, and drag and drop actions to the canvas item.
The root canvas item provides a canvas_widget property which is the canvas widget associated with this root item.
The root canvas may be focusable or not. There are two focus states that this root canvas item handles: the widget
focus and the canvas item focus. The widget focus comes from the enclosing widget. If this root canvas item has a
widget focus, then it can also have a canvas item focus to specify which specific canvas item is the focus in this
root canvas item's hierarchy.
"""
def __init__(self, canvas_widget: UserInterface.CanvasWidget, *, layout_render: typing.Optional[str] = DefaultLayoutRender) -> None:
super().__init__(RootLayoutRenderTrait(self) if layout_render == RootLayoutRender and _threaded_rendering_enabled else LayerLayoutRenderTrait(self))
self.__canvas_widget = canvas_widget
self.__canvas_widget.on_size_changed = self.size_changed
self.__canvas_widget.on_mouse_clicked = self.__mouse_clicked
self.__canvas_widget.on_mouse_double_clicked = self.__mouse_double_clicked
self.__canvas_widget.on_mouse_entered = self.__mouse_entered
self.__canvas_widget.on_mouse_exited = self.__mouse_exited
self.__canvas_widget.on_mouse_pressed = self.__mouse_pressed
self.__canvas_widget.on_mouse_released = self.__mouse_released
self.__canvas_widget.on_mouse_position_changed = self.__mouse_position_changed
self.__canvas_widget.on_grabbed_mouse_position_changed = self.__grabbed_mouse_position_changed
self.__canvas_widget.on_wheel_changed = self.wheel_changed
self.__canvas_widget.on_context_menu_event = self.__context_menu_event
self.__canvas_widget.on_key_pressed = self.__key_pressed
self.__canvas_widget.on_key_released = self.__key_released
self.__canvas_widget.on_focus_changed = self.__focus_changed
self.__canvas_widget.on_drag_enter = self.__drag_enter
self.__canvas_widget.on_drag_leave = self.__drag_leave
self.__canvas_widget.on_drag_move = self.__drag_move
self.__canvas_widget.on_drop = self.__drop
self.__canvas_widget.on_tool_tip = self.handle_tool_tip
self.__canvas_widget.on_pan_gesture = self.pan_gesture
self.__canvas_widget.on_dispatch_any = self.__dispatch_any
self.__canvas_widget.on_can_dispatch_any = self.__can_dispatch_any
self.__canvas_widget.on_get_menu_item_state = self.__get_menu_item_state
setattr(self.__canvas_widget, "_root_canvas_item", weakref.ref(self)) # for debugging
self.__drawing_context_updated = False
self.__interaction_count = 0
self.__focused_item: typing.Optional[AbstractCanvasItem] = None
self.__last_focused_item: typing.Optional[AbstractCanvasItem] = None
self.__mouse_canvas_item: typing.Optional[AbstractCanvasItem] = None # not None when the mouse is pressed
self.__mouse_tracking = False
self.__mouse_tracking_canvas_item: typing.Optional[AbstractCanvasItem] = None
self.__drag_tracking = False
self.__drag_tracking_canvas_item: typing.Optional[AbstractCanvasItem] = None
self.__grab_canvas_item: typing.Optional[MouseTrackingCanvasItem.TrackingCanvasItem] = None
self._set_canvas_origin(Geometry.IntPoint())
def close(self) -> None:
# shut down the repaint thread first
self._stop_render_behavior() # call first so that it doesn't use canvas widget
self.__mouse_tracking_canvas_item = None
self.__drag_tracking_canvas_item = None
self.__grab_canvas_item = None
self.__focused_item = None
self.__last_focused_item = None
self.__canvas_widget.on_size_changed = None
self.__canvas_widget.on_mouse_clicked = None
self.__canvas_widget.on_mouse_double_clicked = None
self.__canvas_widget.on_mouse_entered = None
self.__canvas_widget.on_mouse_exited = None
self.__canvas_widget.on_mouse_pressed = None
self.__canvas_widget.on_mouse_released = None
self.__canvas_widget.on_mouse_position_changed = None
self.__canvas_widget.on_grabbed_mouse_position_changed = None
self.__canvas_widget.on_wheel_changed = None
self.__canvas_widget.on_context_menu_event = None
self.__canvas_widget.on_key_pressed = None
self.__canvas_widget.on_key_released = None
self.__canvas_widget.on_focus_changed = None
self.__canvas_widget.on_drag_enter = None
self.__canvas_widget.on_drag_leave = None
self.__canvas_widget.on_drag_move = None
self.__canvas_widget.on_drop = None
self.__canvas_widget.on_tool_tip = None
self.__canvas_widget.on_pan_gesture = None
super().close()
# culling will require the canvas widget; clear it here (after close) so that it is availahle.
self.__canvas_widget = typing.cast(typing.Any, None)
def _repaint_finished(self, drawing_context: DrawingContext.DrawingContext) -> None:
self.__canvas_widget.draw(drawing_context)
def refresh_layout(self) -> None:
self._needs_layout(self)
@property
def root_container(self) -> typing.Optional[RootCanvasItem]:
return self
@property
def canvas_widget(self) -> UserInterface.CanvasWidget:
""" Return the canvas widget. """
return self.__canvas_widget
def map_to_global(self, p: Geometry.IntPoint) -> Geometry.IntPoint:
return self.__canvas_widget.map_to_global(p)
@property
def is_ui_interaction_active(self) -> bool:
return self.__interaction_count > 0
def _adjust_ui_interaction(self, value: int) -> None:
self.__interaction_count += value
class UIInteractionContext:
def __init__(self, root_canvas_item: RootCanvasItem) -> None:
self.__root_canvas_item = root_canvas_item
def close(self) -> None:
self.__root_canvas_item._adjust_ui_interaction(-1)
def __enter__(self) -> RootCanvasItem.UIInteractionContext:
self.__root_canvas_item._adjust_ui_interaction(1)
return self
def __exit__(self, exception_type: typing.Optional[typing.Type[BaseException]],
value: typing.Optional[BaseException], traceback: typing.Optional[types.TracebackType]) -> typing.Optional[bool]:
self.close()
return None
def _ui_interaction(self) -> contextlib.AbstractContextManager[RootCanvasItem.UIInteractionContext]:
return RootCanvasItem.UIInteractionContext(self)
@property
def focusable(self) -> bool:
""" Return whether the canvas widget is focusable. """
return self.canvas_widget.focusable
@focusable.setter
def focusable(self, focusable: bool) -> None:
""" Set whether the canvas widget is focusable. """
self.canvas_widget.focusable = focusable
def size_changed(self, width: int, height: int) -> None:
""" Called when size changes. """
# logging.debug("{} {} x {}".format(id(self), width, height))
if width > 0 and height > 0:
self._set_canvas_origin(Geometry.IntPoint())
self._set_canvas_size(Geometry.IntSize(height=height, width=width))
self._has_layout = self.canvas_origin is not None and self.canvas_size is not None
self.refresh_layout()
@property
def focused_item(self) -> typing.Optional[AbstractCanvasItem]:
"""
Return the canvas focused item. May return None.
The focused item is either this item itself or one of its
children.
"""
return self.__focused_item
def _set_focused_item(self, focused_item: typing.Optional[AbstractCanvasItem], p: typing.Optional[Geometry.IntPoint] = None, modifiers: typing.Optional[UserInterface.KeyboardModifiers] = None) -> None:
""" Set the canvas focused item. This will also update the focused property of both old item (if any) and new item (if any). """
if not modifiers or not modifiers.any_modifier:
if focused_item != self.__focused_item:
if self.__focused_item:
self.__focused_item._set_focused(False)
self.__focused_item = focused_item
if self.__focused_item:
self.__focused_item._set_focused(True)
if self.__focused_item:
self.__last_focused_item = self.__focused_item
elif focused_item:
focused_item.adjust_secondary_focus(p or Geometry.IntPoint(), modifiers)
def __focus_changed(self, focused: bool) -> None:
""" Called when widget focus changes. """
if focused and not self.focused_item:
self._set_focused_item(self.__last_focused_item)
elif not focused and self.focused_item:
self._set_focused_item(None)
def _request_root_focus(self, focused_item: typing.Optional[AbstractCanvasItem], p: typing.Optional[Geometry.IntPoint], modifiers: typing.Optional[UserInterface.KeyboardModifiers]) -> None:
"""Requests that the root widget gets focus.
This focused is different from the focus within the canvas system. This is
the external focus in the widget system.
If the canvas widget is already focused, this simply sets the focused item
to be the requested one. Otherwise, the widget has to request focus. When
it receives focus, a __focus_changed from the widget which will restore the
last focused item to be the new focused canvas item.
"""
if self.__canvas_widget.focused:
self._set_focused_item(focused_item, p, modifiers)
else:
self._set_focused_item(None, p, modifiers)
self.__last_focused_item = focused_item
self.__canvas_widget.focused = True # this will trigger focus changed to set the focus
def wheel_changed(self, x: int, y: int, dx: int, dy: int, is_horizontal: bool) -> bool:
# always give the mouse canvas item priority (for tracking outside bounds)
canvas_items = self.canvas_items_at_point(x, y)
for canvas_item in reversed(canvas_items):
if canvas_item != self:
canvas_item_point = self.map_to_canvas_item(Geometry.IntPoint(y=y, x=x), canvas_item)
if canvas_item.wheel_changed(canvas_item_point.x, canvas_item_point.y, dx, dy, is_horizontal):
return True
return False
def handle_tool_tip(self, x: int, y: int, gx: int, gy: int) -> bool:
canvas_items = self.canvas_items_at_point(x, y)
for canvas_item in reversed(canvas_items):
if canvas_item != self:
canvas_item_point = self.map_to_canvas_item(Geometry.IntPoint(y=y, x=x), canvas_item)
if canvas_item.handle_tool_tip(canvas_item_point.x, canvas_item_point.y, gx, gy):
return True
return False
def __dispatch_any(self, method: str, *args: typing.Any, **kwargs: typing.Any) -> bool:
focused_item = self.focused_item
if focused_item:
return focused_item._dispatch_any(method, *args, **kwargs)
return False
def __can_dispatch_any(self, method: str) -> bool:
focused_item = self.focused_item
if focused_item:
return focused_item._can_dispatch_any(method)
return False
def __get_menu_item_state(self, command_id: str) -> typing.Optional[UserInterface.MenuItemState]:
focused_item = self.focused_item
if focused_item:
menu_item_state = focused_item._get_menu_item_state(command_id)
if menu_item_state:
return menu_item_state
return None
def _cursor_shape_changed(self, item: AbstractCanvasItem) -> None:
if item == self.__mouse_tracking_canvas_item and self.__mouse_tracking_canvas_item:
self.__canvas_widget.set_cursor_shape(self.__mouse_tracking_canvas_item.cursor_shape)
def _restore_cursor_shape(self) -> None:
# if self.__mouse_tracking_canvas_item:
# self.__canvas_widget.set_cursor_shape(self.__mouse_tracking_canvas_item.cursor_shape)
# else:
self.__canvas_widget.set_cursor_shape(None)
def __mouse_entered(self) -> None:
self.__mouse_tracking = True
def __mouse_exited(self) -> None:
if self.__mouse_tracking_canvas_item:
self.__mouse_tracking_canvas_item.mouse_exited()
self.__mouse_tracking = False
self.__mouse_tracking_canvas_item = None
self.__canvas_widget.set_cursor_shape(None)
self.__canvas_widget.tool_tip = None
def __mouse_canvas_item_at_point(self, x: int, y: int) -> typing.Optional[AbstractCanvasItem]:
if self.__mouse_canvas_item:
return self.__mouse_canvas_item
canvas_items = self.canvas_items_at_point(x, y)
for canvas_item in canvas_items:
if canvas_item.wants_mouse_events:
return canvas_item
return None
def __request_focus(self, canvas_item: AbstractCanvasItem, p: Geometry.IntPoint, modifiers: UserInterface.KeyboardModifiers) -> None:
canvas_item_: typing.Optional[AbstractCanvasItem] = canvas_item
while canvas_item_:
if canvas_item_.focusable:
canvas_item_._request_focus(p, modifiers)
break
canvas_item_ = canvas_item_.container
def __mouse_clicked(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
with self._ui_interaction():
canvas_item = self.__mouse_canvas_item_at_point(x, y)
if canvas_item:
canvas_item_point = self.map_to_canvas_item(Geometry.IntPoint(y=y, x=x), canvas_item)
return canvas_item.mouse_clicked(canvas_item_point.x, canvas_item_point.y, modifiers)
return False
def __mouse_double_clicked(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
with self._ui_interaction():
canvas_item = self.__mouse_canvas_item_at_point(x, y)
if canvas_item:
self.__request_focus(canvas_item, Geometry.IntPoint(x=x, y=y), modifiers)
canvas_item_point = self.map_to_canvas_item(Geometry.IntPoint(y=y, x=x), canvas_item)
return canvas_item.mouse_double_clicked(canvas_item_point.x, canvas_item_point.y, modifiers)
return False
def __mouse_pressed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self._adjust_ui_interaction(1)
self.__mouse_position_changed(x, y, modifiers)
if not self.__mouse_tracking_canvas_item:
self.__mouse_tracking_canvas_item = self.__mouse_canvas_item_at_point(x, y)
if self.__mouse_tracking_canvas_item:
self.__mouse_tracking_canvas_item.mouse_entered()
self.__canvas_widget.set_cursor_shape(self.__mouse_tracking_canvas_item.cursor_shape)
self.__canvas_widget.tool_tip = self.__mouse_tracking_canvas_item.tool_tip
if self.__mouse_tracking_canvas_item:
self.__mouse_canvas_item = self.__mouse_tracking_canvas_item
canvas_item_point = self.map_to_canvas_item(Geometry.IntPoint(y=y, x=x), self.__mouse_canvas_item)
self.__request_focus_canvas_item = self.__mouse_canvas_item
return self.__mouse_canvas_item.mouse_pressed(canvas_item_point.x, canvas_item_point.y, modifiers)
return False
def __mouse_released(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
result = False
if self.__mouse_canvas_item:
if self.__request_focus_canvas_item:
self.__request_focus(self.__request_focus_canvas_item, Geometry.IntPoint(x=x, y=y), modifiers)
self.__request_focus_canvas_item = typing.cast(typing.Any, None)
canvas_item_point = self.map_to_canvas_item(Geometry.IntPoint(y=y, x=x), self.__mouse_canvas_item)
result = self.__mouse_canvas_item.mouse_released(canvas_item_point.x, canvas_item_point.y, modifiers)
self.__mouse_canvas_item = None
self.__mouse_position_changed(x, y, modifiers)
self._adjust_ui_interaction(-1)
return result
def bypass_request_focus(self) -> None:
self.__request_focus_canvas_item = typing.cast(typing.Any, None)
def __mouse_position_changed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> None:
if not self.__mouse_tracking:
# handle case where mouse is suddenly within this canvas item but it never entered. this can happen when
# the user activates the application.
self.mouse_entered()
if self.__mouse_tracking and not self.__mouse_tracking_canvas_item:
# find the existing canvas item that is or wants to track the mouse. if it's new, call entered and update
# the cursor.
self.__mouse_tracking_canvas_item = self.__mouse_canvas_item_at_point(x, y)
if self.__mouse_tracking_canvas_item:
self.__mouse_tracking_canvas_item.mouse_entered()
self.__canvas_widget.set_cursor_shape(self.__mouse_tracking_canvas_item.cursor_shape)
self.__canvas_widget.tool_tip = self.__mouse_tracking_canvas_item.tool_tip
new_mouse_canvas_item = self.__mouse_canvas_item_at_point(x, y)
if self.__mouse_tracking_canvas_item != new_mouse_canvas_item:
# if the mouse tracking canvas item changes, exit the old one and enter the new one.
if self.__mouse_tracking_canvas_item:
# there may be a case where the mouse has moved outside the canvas item and the canvas
# item has also been closed. for instance, context menu item which closes the canvas item.
# so double check whether the mouse tracking canvas item is still in the hierarchy by checking
# its container. only call mouse existed if the item is still in the hierarchy.
if self.__mouse_tracking_canvas_item.container:
self.__mouse_tracking_canvas_item.mouse_exited()
self.__canvas_widget.set_cursor_shape(None)
self.__canvas_widget.tool_tip = None
self.__mouse_tracking_canvas_item = new_mouse_canvas_item
if self.__mouse_tracking_canvas_item:
self.__mouse_tracking_canvas_item.mouse_entered()
self.__canvas_widget.set_cursor_shape(self.__mouse_tracking_canvas_item.cursor_shape)
self.__canvas_widget.tool_tip = self.__mouse_tracking_canvas_item.tool_tip
# finally, send out the actual position changed message to the (possibly new) current mouse tracking canvas
# item. also make note of the last time the cursor changed for tool tip tracking.
if self.__mouse_tracking_canvas_item:
canvas_item_point = self.map_to_canvas_item(Geometry.IntPoint(y=y, x=x), self.__mouse_tracking_canvas_item)
self.__mouse_tracking_canvas_item.mouse_position_changed(canvas_item_point.x, canvas_item_point.y, modifiers)
def __grabbed_mouse_position_changed(self, dx: int, dy: int, modifiers: UserInterface.KeyboardModifiers) -> None:
if self.__grab_canvas_item:
self.__grab_canvas_item.grabbed_mouse_position_changed(dx, dy, modifiers)
def __context_menu_event(self, x: int, y: int, gx: int, gy: int) -> bool:
with self._ui_interaction():
canvas_items = self.canvas_items_at_point(x, y)
for canvas_item in canvas_items:
canvas_item_point = self.map_to_canvas_item(Geometry.IntPoint(y=y, x=x), canvas_item)
if canvas_item.context_menu_event(canvas_item_point.x, canvas_item_point.y, gx, gy):
return True
return False
def __key_pressed(self, key: UserInterface.Key) -> bool:
self._adjust_ui_interaction(1)
if self.focused_item:
return self.focused_item.key_pressed(key)
return False
def __key_released(self, key: UserInterface.Key) -> bool:
result = False
if self.focused_item:
result = self.focused_item.key_released(key)
self._adjust_ui_interaction(-1)
return result
def __drag_enter(self, mime_data: UserInterface.MimeData) -> str:
self.__drag_tracking = True
return "accept"
def __drag_leave(self) -> str:
if self.__drag_tracking_canvas_item:
self.__drag_tracking_canvas_item.drag_leave()
self.__drag_tracking = False
self.__drag_tracking_canvas_item = None
return "accept"
def __drag_canvas_item_at_point(self, x: int, y: int, mime_data: UserInterface.MimeData) -> typing.Optional[AbstractCanvasItem]:
canvas_items = self.canvas_items_at_point(x, y)
for canvas_item in canvas_items:
if canvas_item.wants_drag_event(mime_data, x, y):
return canvas_item
return None
def __drag_move(self, mime_data: UserInterface.MimeData, x: int, y: int) -> str:
response = "ignore"
if self.__drag_tracking and not self.__drag_tracking_canvas_item:
self.__drag_tracking_canvas_item = self.__drag_canvas_item_at_point(x, y, mime_data)
if self.__drag_tracking_canvas_item:
self.__drag_tracking_canvas_item.drag_enter(mime_data)
new_drag_canvas_item = self.__drag_canvas_item_at_point(x, y, mime_data)
if self.__drag_tracking_canvas_item != new_drag_canvas_item:
if self.__drag_tracking_canvas_item:
self.__drag_tracking_canvas_item.drag_leave()
self.__drag_tracking_canvas_item = new_drag_canvas_item
if self.__drag_tracking_canvas_item:
self.__drag_tracking_canvas_item.drag_enter(mime_data)
if self.__drag_tracking_canvas_item:
canvas_item_point = self.map_to_canvas_item(Geometry.IntPoint(y=y, x=x), self.__drag_tracking_canvas_item)
response = self.__drag_tracking_canvas_item.drag_move(mime_data, canvas_item_point.x, canvas_item_point.y)
return response
def __drop(self, mime_data: UserInterface.MimeData, x: int, y: int) -> str:
with self._ui_interaction():
response = "ignore"
if self.__drag_tracking_canvas_item:
canvas_item_point = self.map_to_canvas_item(Geometry.IntPoint(y=y, x=x), self.__drag_tracking_canvas_item)
response = self.__drag_tracking_canvas_item.drop(mime_data, canvas_item_point.x, canvas_item_point.y)
self.__drag_leave()
return response
def drag(self, mime_data: UserInterface.MimeData, thumbnail: typing.Optional[DrawingContext.RGBA32Type] = None,
hot_spot_x: typing.Optional[int] = None, hot_spot_y: typing.Optional[int] = None,
drag_finished_fn: typing.Optional[typing.Callable[[str], None]] = None) -> None:
self.__canvas_widget.drag(mime_data, thumbnail, hot_spot_x, hot_spot_y, drag_finished_fn)
def grab_gesture(self, gesture_type: str) -> None:
""" Grab gesture """
self._adjust_ui_interaction(1)
self.__canvas_widget.grab_gesture(gesture_type)
def release_gesture(self, gesture_type: str) -> None:
""" Ungrab gesture """
self.__canvas_widget.release_gesture(gesture_type)
self._adjust_ui_interaction(-1)
def grab_mouse(self, grabbed_canvas_item: MouseTrackingCanvasItem.TrackingCanvasItem, gx: int, gy: int) -> None:
self._adjust_ui_interaction(1)
self.__canvas_widget.grab_mouse(gx, gy)
self.__grab_canvas_item = grabbed_canvas_item
def release_mouse(self) -> None:
self.__canvas_widget.release_mouse()
self._restore_cursor_shape()
self.__grab_canvas_item = None
self._adjust_ui_interaction(-1)
def show_tool_tip_text(self, text: str, gx: int, gy: int) -> None:
self.__canvas_widget.show_tool_tip_text(text, gx, gy)
class BackgroundCanvasItem(AbstractCanvasItem):
""" Canvas item to draw background_color. """
def __init__(self, background_color: typing.Optional[str] = None) -> None:
super().__init__()
self.background_color = background_color or "#888"
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
# canvas size
canvas_size = self.canvas_size
if canvas_size:
canvas_width = canvas_size[1]
canvas_height = canvas_size[0]
with drawing_context.saver():
drawing_context.begin_path()
drawing_context.rect(0, 0, canvas_width, canvas_height)
drawing_context.fill_style = self.background_color
drawing_context.fill()
class CellCanvasItem(AbstractCanvasItem):
""" Canvas item to draw and respond to user events for a cell.
A cell must implement the following interface:
event: update_event() - fired when the canvas item needs an update
method: paint_cell(drawing_context, rect, style) - called to draw the cell
The style parameter passed to paint_cell is a list with zero or one strings from each of the aspects below:
disabled (default is enabled)
checked, partial (default is unchecked)
hover, active (default is none)
"""
def __init__(self, cell: typing.Optional[Widgets.CellLike] = None) -> None:
super().__init__()
self.__enabled = True
self.__check_state = "unchecked"
self.__mouse_inside = False
self.__mouse_pressed = False
self.__cell = None
self.__cell_update_event_listener: typing.Optional[Event.EventListener] = None
self.cell = cell
self.style: typing.Set[str] = set()
def close(self) -> None:
self.cell = None
super().close()
@property
def enabled(self) -> bool:
return self.__enabled
@enabled.setter
def enabled(self, value: bool) -> None:
if self.__enabled != value:
self.__enabled = value
self.__update_style()
@property
def check_state(self) -> str:
return self.__check_state
@check_state.setter
def check_state(self, value: str) -> None:
assert value in ["checked", "unchecked", "partial"]
if self.__check_state != value:
self.__check_state = value
self.__update_style()
@property
def checked(self) -> bool:
return self.check_state == "checked"
@checked.setter
def checked(self, value: bool) -> None:
self.check_state = "checked" if value else "unchecked"
@property
def _mouse_inside(self) -> bool:
return self.__mouse_inside
@_mouse_inside.setter
def _mouse_inside(self, value: bool) -> None:
self.__mouse_inside = value
self.__update_style()
@property
def _mouse_pressed(self) -> bool:
return self.__mouse_pressed
@_mouse_pressed.setter
def _mouse_pressed(self, value: bool) -> None:
self.__mouse_pressed = value
self.__update_style()
def __update_style(self) -> None:
old_style = copy.copy(self.style)
# enabled state
self.style.discard('disabled')
if not self.enabled:
self.style.add('disabled')
# checked state
self.style.discard('checked')
if self.check_state == "checked":
self.style.add('checked')
# hover state
self.style.discard('hover')
self.style.discard('active')
if self._mouse_inside and self._mouse_pressed:
self.style.add('active')
elif self.__mouse_inside:
self.style.add('hover')
if self.style != old_style:
self.update()
@property
def cell(self) -> typing.Optional[Widgets.CellLike]:
return self.__cell
@cell.setter
def cell(self, new_cell: typing.Optional[Widgets.CellLike]) -> None:
if self.__cell_update_event_listener:
self.__cell_update_event_listener.close()
self.__cell_update_event_listener = None
self.__cell = new_cell
if self.__cell:
self.__cell_update_event_listener = self.__cell.update_event.listen(self.update)
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
rect = self.canvas_bounds
if self.__cell and rect is not None:
with drawing_context.saver():
self.__cell.paint_cell(drawing_context, rect, self.style)
class TwistDownCell:
def __init__(self) -> None:
super().__init__()
self.update_event = Event.Event()
def paint_cell(self, drawing_context: DrawingContext.DrawingContext, rect: Geometry.IntRect, style: typing.Set[str]) -> None:
# disabled (default is enabled)
# checked, partial (default is unchecked)
# hover, active (default is none)
if "checked" in style:
drawing_context.begin_path()
drawing_context.move_to(rect.center.x, rect.center.y + 4)
drawing_context.line_to(rect.center.x + 4.5, rect.center.y - 4)
drawing_context.line_to(rect.center.x - 4.5, rect.center.y - 4)
drawing_context.close_path()
else:
drawing_context.begin_path()
drawing_context.move_to(rect.center.x + 4, rect.center.y)
drawing_context.line_to(rect.center.x - 4, rect.center.y + 4.5)
drawing_context.line_to(rect.center.x - 4, rect.center.y - 4.5)
drawing_context.close_path()
overlay_color = None
if "disabled" in style:
overlay_color = "rgba(255, 255, 255, 0.5)"
else:
if "active" in style:
overlay_color = "rgba(128, 128, 128, 0.5)"
elif "hover" in style:
overlay_color = "rgba(128, 128, 128, 0.1)"
drawing_context.fill_style = "#444"
drawing_context.fill()
drawing_context.stroke_style = "#444"
drawing_context.stroke()
if overlay_color:
rect_args = rect.left, rect.top, rect.width, rect.height
drawing_context.begin_path()
drawing_context.rect(*rect_args)
drawing_context.fill_style = overlay_color
drawing_context.fill()
class TwistDownCanvasItem(CellCanvasItem):
def __init__(self) -> None:
super().__init__()
self.cell = TwistDownCell()
self.wants_mouse_events = True
self.on_button_clicked: typing.Optional[typing.Callable[[], None]] = None
def close(self) -> None:
self.on_button_clicked = None
super().close()
def mouse_entered(self) -> bool:
self._mouse_inside = True
return True
def mouse_exited(self) -> bool:
self._mouse_inside = False
return True
def mouse_pressed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self._mouse_pressed = True
return True
def mouse_released(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self._mouse_pressed = False
return True
def mouse_clicked(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
if self.enabled:
if callable(self.on_button_clicked):
self.on_button_clicked()
return True
class BitmapCell:
def __init__(self, rgba_bitmap_data: typing.Optional[DrawingContext.RGBA32Type] = None,
background_color: typing.Optional[str] = None, border_color: typing.Optional[str] = None) -> None:
super().__init__()
self.__rgba_bitmap_data = rgba_bitmap_data
self.__data: typing.Optional[DrawingContext.GrayscaleF32Type] = None
self.__display_limits: typing.Optional[typing.Tuple[float, float]] = None
self.__color_map_data: typing.Optional[DrawingContext.RGBA32Type] = None
self.__background_color = background_color
self.__border_color = border_color
self.update_event = Event.Event()
def set_rgba_bitmap_data(self, rgba_bitmap_data: typing.Optional[DrawingContext.RGBA32Type], trigger_update: bool = True) -> None:
self.__rgba_bitmap_data = rgba_bitmap_data
self.__data = None
self.__display_limits = None
self.__color_map_data = None
if trigger_update:
self.update_event.fire()
def set_data(self, data: typing.Optional[DrawingContext.GrayscaleF32Type],
display_limits: typing.Optional[typing.Tuple[float, float]],
color_map_data: typing.Optional[DrawingContext.RGBA32Type], trigger_update: bool = True) -> None:
self.__rgba_bitmap_data = None
self.__data = data
self.__display_limits = display_limits
self.__color_map_data = color_map_data
if trigger_update:
self.update_event.fire()
@property
def data(self) -> typing.Optional[DrawingContext.GrayscaleF32Type]:
return self.__data
@property
def rgba_bitmap_data(self) -> typing.Optional[DrawingContext.RGBA32Type]:
return self.__rgba_bitmap_data
@rgba_bitmap_data.setter
def rgba_bitmap_data(self, value: typing.Optional[DrawingContext.RGBA32Type]) -> None:
self.set_rgba_bitmap_data(value, trigger_update=True)
@property
def background_color(self) -> typing.Optional[str]:
return self.__background_color
@background_color.setter
def background_color(self, background_color: typing.Optional[str]) -> None:
self.__background_color = background_color
self.update_event.fire()
@property
def border_color(self) -> typing.Optional[str]:
return self.__border_color
@border_color.setter
def border_color(self, border_color: typing.Optional[str]) -> None:
self.__border_color = border_color
self.update_event.fire()
def paint_cell(self, drawing_context: DrawingContext.DrawingContext, rect: Geometry.IntRect, style: typing.Set[str]) -> None:
# set up the defaults
background_color = self.__background_color
border_color = self.__border_color
overlay_color = None
# configure based on style
if "disabled" in style:
overlay_color = "rgba(255, 255, 255, 0.5)"
if "checked" in style:
background_color = "rgb(64, 64, 64)"
else:
if "checked" in style:
background_color = "rgb(192, 192, 192)"
if "active" in style:
overlay_color = "rgba(128, 128, 128, 0.5)"
elif "hover" in style:
overlay_color = "rgba(128, 128, 128, 0.1)"
rect_args = rect.left, rect.top, rect.width, rect.height
bitmap_data = self.rgba_bitmap_data
raw_data = self.__data
# draw the background
if background_color:
drawing_context.begin_path()
drawing_context.rect(*rect_args)
drawing_context.fill_style = background_color
drawing_context.fill()
# draw the bitmap
if bitmap_data is not None:
image_size = typing.cast(Geometry.IntSizeTuple, bitmap_data.shape)
if image_size[0] > 0 and image_size[1] > 0:
display_rect = Geometry.fit_to_size(rect, image_size)
display_height = display_rect.height
display_width = display_rect.width
if display_rect and display_width > 0 and display_height > 0:
display_top = display_rect.top
display_left = display_rect.left
drawing_context.draw_image(bitmap_data, display_left, display_top, display_width, display_height)
if raw_data is not None:
image_size = typing.cast(Geometry.IntSizeTuple, raw_data.shape)
if image_size[0] > 0 and image_size[1] > 0:
display_rect = Geometry.fit_to_size(rect, image_size)
display_height = display_rect.height
display_width = display_rect.width
if display_rect and display_width > 0 and display_height > 0:
display_top = display_rect.top
display_left = display_rect.left
display_limits = self.__display_limits or (0.0, 0.0)
color_map_data = self.__color_map_data
drawing_context.draw_data(raw_data, display_left, display_top, display_width, display_height, display_limits[0], display_limits[1], color_map_data)
# draw the overlay style
if overlay_color:
drawing_context.begin_path()
drawing_context.rect(*rect_args)
drawing_context.fill_style = overlay_color
drawing_context.fill()
# draw the border
if border_color:
drawing_context.begin_path()
drawing_context.rect(*rect_args)
drawing_context.stroke_style = border_color
drawing_context.stroke()
class BitmapCanvasItem(CellCanvasItem):
""" Canvas item to draw rgba bitmap in bgra uint32 ndarray format. """
def __init__(self, rgba_bitmap_data: typing.Optional[DrawingContext.RGBA32Type] = None,
background_color: typing.Optional[str] = None, border_color: typing.Optional[str] = None) -> None:
super().__init__()
self.__bitmap_cell = BitmapCell(rgba_bitmap_data, background_color, border_color)
self.cell = self.__bitmap_cell
def set_rgba_bitmap_data(self, rgba_bitmap_data: typing.Optional[DrawingContext.RGBA32Type],
trigger_update: bool = True) -> None:
self.__bitmap_cell.set_rgba_bitmap_data(rgba_bitmap_data, trigger_update)
def set_data(self, data: typing.Optional[DrawingContext.GrayscaleF32Type],
display_limits: typing.Optional[typing.Tuple[float, float]],
color_map_data: typing.Optional[DrawingContext.RGBA32Type], trigger_update: bool = True) -> None:
self.__bitmap_cell.set_data(data, display_limits, color_map_data, trigger_update)
@property
def data(self) -> typing.Optional[DrawingContext.GrayscaleF32Type]:
return self.__bitmap_cell.data
@property
def rgba_bitmap_data(self) -> typing.Optional[DrawingContext.RGBA32Type]:
return self.__bitmap_cell.rgba_bitmap_data
@rgba_bitmap_data.setter
def rgba_bitmap_data(self, rgb_bitmap_data: typing.Optional[DrawingContext.RGBA32Type]) -> None:
self.__bitmap_cell.rgba_bitmap_data = rgb_bitmap_data
@property
def background_color(self) -> typing.Optional[str]:
return self.__bitmap_cell.background_color
@background_color.setter
def background_color(self, background_color: typing.Optional[str]) -> None:
self.__bitmap_cell.background_color = background_color
@property
def border_color(self) -> typing.Optional[str]:
return self.__bitmap_cell.border_color
@border_color.setter
def border_color(self, border_color: typing.Optional[str]) -> None:
self.__bitmap_cell.border_color = border_color
class BitmapButtonCanvasItem(BitmapCanvasItem):
""" Canvas item button to draw rgba bitmap in bgra uint32 ndarray format. """
def __init__(self, rgba_bitmap_data: typing.Optional[DrawingContext.RGBA32Type] = None,
background_color: typing.Optional[str] = None, border_color: typing.Optional[str] = None) -> None:
super().__init__(rgba_bitmap_data, background_color, border_color)
self.wants_mouse_events = True
self.on_button_clicked: typing.Optional[typing.Callable[[], None]] = None
def close(self) -> None:
self.on_button_clicked = None
super().close()
def mouse_entered(self) -> bool:
self._mouse_inside = True
return True
def mouse_exited(self) -> bool:
self._mouse_inside = False
return True
def mouse_pressed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self._mouse_pressed = True
return True
def mouse_released(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self._mouse_pressed = False
return True
def mouse_clicked(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
if self.enabled:
if callable(self.on_button_clicked):
self.on_button_clicked()
return True
class StaticTextCanvasItem(AbstractCanvasItem):
def __init__(self, text: typing.Optional[str] = None) -> None:
super().__init__()
self.__text = text if text is not None else str()
self.__text_color = "#000"
self.__text_disabled_color = "#888"
self.__enabled = True
self.__font = "12px"
@property
def text(self) -> str:
return self.__text
@text.setter
def text(self, text: typing.Optional[str]) -> None:
text = text if text is not None else str()
if self.__text != text:
self.__text = text
self.update()
@property
def enabled(self) -> bool:
return self.__enabled
@enabled.setter
def enabled(self, value: bool) -> None:
if self.__enabled != value:
self.__enabled = value
self.update()
@property
def text_color(self) -> str:
return self.__text_color
@text_color.setter
def text_color(self, value: str) -> None:
if self.__text_color != value:
self.__text_color = value
self.update()
@property
def text_disabled_color(self) -> str:
return self.__text_disabled_color
@text_disabled_color.setter
def text_disabled_color(self, value: str) -> None:
if self.__text_disabled_color != value:
self.__text_disabled_color = value
self.update()
@property
def font(self) -> str:
return self.__font
@font.setter
def font(self, value: str) -> None:
if self.__font != value:
self.__font = value
self.update()
def size_to_content(self, get_font_metrics_fn: typing.Callable[[str, str], UserInterface.FontMetrics],
horizontal_padding: typing.Optional[int] = None,
vertical_padding: typing.Optional[int] = None) -> None:
""" Size the canvas item to the text content. """
if horizontal_padding is None:
horizontal_padding = 4
if vertical_padding is None:
vertical_padding = 4
font_metrics = get_font_metrics_fn(self.__font, self.__text)
new_sizing = self.copy_sizing()
new_sizing._set_fixed_width(font_metrics.width + 2 * horizontal_padding)
new_sizing._set_fixed_height(font_metrics.height + 2 * vertical_padding)
self.update_sizing(new_sizing)
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
canvas_bounds = self.canvas_bounds
if canvas_bounds:
canvas_bounds_center = canvas_bounds.center
with drawing_context.saver():
drawing_context.font = self.__font
drawing_context.text_align = 'center'
drawing_context.text_baseline = 'middle'
drawing_context.fill_style = self.__text_color if self.__enabled else self.__text_disabled_color
drawing_context.fill_text(self.__text, canvas_bounds_center.x, canvas_bounds_center.y + 1)
class TextButtonCanvasItem(StaticTextCanvasItem):
def __init__(self, text: typing.Optional[str] = None) -> None:
super().__init__(text)
self.wants_mouse_events = True
self.__border_enabled = True
self.__mouse_inside = False
self.__mouse_pressed = False
self.on_button_clicked: typing.Optional[typing.Callable[[], None]] = None
def close(self) -> None:
self.on_button_clicked = None
super().close()
@property
def border_enabled(self) -> bool:
return self.__border_enabled
@border_enabled.setter
def border_enabled(self, value: bool) -> None:
if self.__border_enabled != value:
self.__border_enabled = value
self.update()
def mouse_entered(self) -> bool:
self.__mouse_inside = True
self.update()
return True
def mouse_exited(self) -> bool:
self.__mouse_inside = False
self.update()
return True
def mouse_pressed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self.__mouse_pressed = True
self.update()
return True
def mouse_released(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self.__mouse_pressed = False
self.update()
return True
def mouse_clicked(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
if self.enabled:
if callable(self.on_button_clicked):
self.on_button_clicked()
return True
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
canvas_size = self.canvas_size
if canvas_size:
with drawing_context.saver():
drawing_context.begin_path()
# drawing_context.rect(0, 0, canvas_size.width, canvas_size.height)
drawing_context.round_rect(1.0, 1.0, canvas_size.width - 2.0, canvas_size.height - 2.0, 4)
if self.enabled and self.__mouse_inside and self.__mouse_pressed:
drawing_context.fill_style = "rgba(128, 128, 128, 0.5)"
drawing_context.fill()
elif self.enabled and self.__mouse_inside:
drawing_context.fill_style = "rgba(128, 128, 128, 0.1)"
drawing_context.fill()
if self.border_enabled:
drawing_context.stroke_style = "#000"
drawing_context.line_width = 1.0
drawing_context.stroke()
super()._repaint(drawing_context)
class CheckBoxCanvasItem(AbstractCanvasItem):
def __init__(self, text: typing.Optional[str] = None) -> None:
super().__init__()
self.wants_mouse_events = True
self.__enabled = True
self.__mouse_inside = False
self.__mouse_pressed = False
self.__check_state = "unchecked"
self.__tristate = False
self.__text = text if text is not None else str()
self.__text_color = "#000"
self.__text_disabled_color = "#888"
self.__font = "12px"
self.on_checked_changed: typing.Optional[typing.Callable[[bool], None]] = None
self.on_check_state_changed: typing.Optional[typing.Callable[[str], None]] = None
def close(self) -> None:
self.on_checked_changed = None
self.on_check_state_changed = None
super().close()
@property
def enabled(self) -> bool:
return self.__enabled
@enabled.setter
def enabled(self, value: bool) -> None:
self.__enabled = value
self.update()
@property
def tristate(self) -> bool:
return self.__tristate
@tristate.setter
def tristate(self, value: bool) -> None:
self.__tristate = value
if not self.__tristate:
self.checked = self.check_state == "checked"
self.update()
@property
def check_state(self) -> str:
return self.__check_state
@check_state.setter
def check_state(self, value: str) -> None:
if self.tristate and value not in ("unchecked", "checked", "partial"):
value = "unchecked"
elif not self.tristate and value not in ("unchecked", "checked"):
value = "unchecked"
self.__check_state = value
self.update()
@property
def checked(self) -> bool:
return self.check_state == "checked"
@checked.setter
def checked(self, value: bool) -> None:
self.check_state = "checked" if value else "unchecked"
@property
def text(self) -> str:
return self.__text
@text.setter
def text(self, text: typing.Optional[str]) -> None:
text = text if text is not None else str()
if self.__text != text:
self.__text = text
self.update()
@property
def text_color(self) -> str:
return self.__text_color
@text_color.setter
def text_color(self, value: str) -> None:
if self.__text_color != value:
self.__text_color = value
self.update()
@property
def text_disabled_color(self) -> str:
return self.__text_disabled_color
@text_disabled_color.setter
def text_disabled_color(self, value: str) -> None:
if self.__text_disabled_color != value:
self.__text_disabled_color = value
self.update()
@property
def font(self) -> str:
return self.__font
@font.setter
def font(self, value: str) -> None:
if self.__font != value:
self.__font = value
self.update()
def mouse_entered(self) -> bool:
self.__mouse_inside = True
self.update()
return True
def mouse_exited(self) -> bool:
self.__mouse_inside = False
self.update()
return True
def mouse_pressed(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self.__mouse_pressed = True
self.update()
return True
def mouse_released(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self.__mouse_pressed = False
self.update()
return True
def mouse_clicked(self, x: int, y: int, modifiers: UserInterface.KeyboardModifiers) -> bool:
self._toggle_checked()
return True
def _toggle_checked(self) -> None:
if self.enabled:
if self.check_state == "checked":
self.check_state = "unchecked"
else:
self.check_state = "checked"
if callable(self.on_checked_changed):
self.on_checked_changed(self.check_state == "checked")
if callable(self.on_check_state_changed):
self.on_check_state_changed(self.check_state)
@property
def _mouse_inside(self) -> bool:
return self.__mouse_inside
@property
def _mouse_pressed(self) -> bool:
return self.__mouse_pressed
def size_to_content(self, get_font_metrics_fn: typing.Callable[[str, str], UserInterface.FontMetrics]) -> None:
""" Size the canvas item to the text content. """
horizontal_padding = 4
vertical_padding = 3
font_metrics = get_font_metrics_fn(self.__font, self.__text)
new_sizing = self.copy_sizing()
new_sizing._set_fixed_width(font_metrics.width + 2 * horizontal_padding + 14 + 4)
new_sizing._set_fixed_height(font_metrics.height + 2 * vertical_padding)
self.update_sizing(new_sizing)
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
canvas_size = self.canvas_size
if canvas_size:
with drawing_context.saver():
drawing_context.begin_path()
tx = 4 + 14 + 4
cx = 4 + 7
cy = canvas_size.height * 0.5
size = 14
size_half = 7
drawing_context.round_rect(4, cy - size_half, size, size, 4.0)
if self.check_state in ("checked", "partial"):
drawing_context.fill_style = "#FFF"
drawing_context.fill()
if self.enabled and self.__mouse_inside and self.__mouse_pressed:
drawing_context.fill_style = "rgba(128, 128, 128, 0.5)"
drawing_context.fill()
elif self.enabled and self.__mouse_inside:
drawing_context.fill_style = "rgba(128, 128, 128, 0.1)"
drawing_context.fill()
drawing_context.stroke_style = "#000"
drawing_context.line_width = 1.0
drawing_context.stroke()
if self.check_state == "checked":
drawing_context.begin_path()
drawing_context.move_to(cx - 3, cy - 2)
drawing_context.line_to(cx + 0, cy + 2)
drawing_context.line_to(cx + 8, cy - 9)
drawing_context.stroke_style = "#000"
drawing_context.line_width = 2.0
drawing_context.stroke()
elif self.check_state == "partial":
drawing_context.begin_path()
drawing_context.move_to(cx - 5, cy)
drawing_context.line_to(cx + 5, cy)
drawing_context.stroke_style = "#000"
drawing_context.line_width = 2.0
drawing_context.stroke()
drawing_context.font = self.__font
drawing_context.text_align = 'left'
drawing_context.text_baseline = 'middle'
drawing_context.fill_style = self.__text_color if self.__enabled else self.__text_disabled_color
drawing_context.fill_text(self.__text, tx, cy + 1)
super()._repaint(drawing_context)
class EmptyCanvasItem(AbstractCanvasItem):
""" Canvas item to act as a placeholder (spacer or stretch). """
def __init__(self) -> None:
super().__init__()
class RadioButtonGroup:
def __init__(self, buttons: typing.Sequence[BitmapButtonCanvasItem]) -> None:
self.__buttons = copy.copy(buttons)
self.__current_index = 0
self.on_current_index_changed: typing.Optional[typing.Callable[[int], None]] = None
for index, button in enumerate(self.__buttons):
button.checked = index == self.__current_index
for index, button in enumerate(self.__buttons):
def current_index_changed(index: int) -> None:
self.__current_index = index
for index, button in enumerate(self.__buttons):
button.checked = index == self.__current_index
if callable(self.on_current_index_changed):
self.on_current_index_changed(self.__current_index)
button.on_button_clicked = functools.partial(current_index_changed, index)
def close(self) -> None:
for button in self.__buttons:
button.on_button_clicked = None
self.on_current_index_changed = None
@property
def current_index(self) -> int:
return self.__current_index
@current_index.setter
def current_index(self, value: int) -> None:
self.__current_index = value
for index, button in enumerate(self.__buttons):
button.checked = index == self.__current_index
class DrawCanvasItem(AbstractCanvasItem):
def __init__(self, drawing_fn: typing.Callable[[DrawingContext.DrawingContext, Geometry.IntSize], None]) -> None:
super().__init__()
self.__drawing_fn = drawing_fn
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
canvas_size = self.canvas_size
if canvas_size:
self.__drawing_fn(drawing_context, canvas_size)
super()._repaint(drawing_context)
class DividerCanvasItem(AbstractCanvasItem):
def __init__(self, *, orientation: typing.Optional[str] = None, color: typing.Optional[str] = None):
super().__init__()
self.__orientation = orientation or "vertical"
if orientation == "vertical":
self.update_sizing(self.sizing.with_fixed_width(2))
else:
self.update_sizing(self.sizing.with_fixed_height(2))
self.__color = color or "#CCC"
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
canvas_size = self.canvas_size
if canvas_size:
with drawing_context.saver():
if self.__orientation == "vertical":
drawing_context.move_to(1, 0)
drawing_context.line_to(1, canvas_size.height)
else:
drawing_context.move_to(0, 1)
drawing_context.line_to(canvas_size.width, 1)
drawing_context.stroke_style = self.__color
drawing_context.stroke()
super()._repaint(drawing_context)
class ProgressBarCanvasItem(AbstractCanvasItem):
def __init__(self) -> None:
super().__init__()
self.__enabled = True
self.__progress = 0.0 # 0.0 to 1.0
self.update_sizing(self.sizing.with_fixed_height(4))
@property
def enabled(self) -> bool:
return self.__enabled
@enabled.setter
def enabled(self, value: bool) -> None:
self.__enabled = value
self.update()
@property
def progress(self) -> float:
return self.__progress
@progress.setter
def progress(self, value: float) -> None:
self.__progress = min(max(value, 0.0), 1.0)
self.update()
def _repaint(self, drawing_context: DrawingContext.DrawingContext) -> None:
canvas_bounds = self.canvas_bounds
if canvas_bounds:
canvas_size = canvas_bounds.size
canvas_bounds_center = canvas_bounds.center
with drawing_context.saver():
drawing_context.begin_path()
drawing_context.rect(0, 0, canvas_size.width, canvas_size.height)
drawing_context.close_path()
drawing_context.stroke_style = "#CCC"
drawing_context.fill_style = "#CCC"
drawing_context.fill()
drawing_context.stroke()
if canvas_size.width * self.progress >= 1:
drawing_context.begin_path()
drawing_context.rect(0, 0, canvas_size.width * self.progress, canvas_size.height)
drawing_context.close_path()
drawing_context.stroke_style = "#6AB"
drawing_context.fill_style = "#6AB"
drawing_context.fill()
drawing_context.stroke()
if canvas_size.height >= 16 and canvas_size.width * self.progress >= 50: # TODO: use font metrics to find length of text
progress_text = str(round(self.progress * 100)) + "%"
drawing_context.begin_path()
drawing_context.font = "12px sans-serif"
drawing_context.text_align = 'center'
drawing_context.text_baseline = 'middle'
drawing_context.fill_style = "#fff"
drawing_context.line_width = 2
drawing_context.fill_text(progress_text, (canvas_size.width - 6) * self.progress - 19, canvas_bounds_center.y + 1)
drawing_context.fill()
drawing_context.close_path()
super()._repaint(drawing_context)
class TimestampCanvasItem(AbstractCanvasItem):
def __init__(self) -> None:
super().__init__()
self.__timestamp: typing.Optional[datetime.datetime] = None
@property
def timestamp(self) -> typing.Optional[datetime.datetime]:
return self.__timestamp
@timestamp.setter
def timestamp(self, value: typing.Optional[datetime.datetime]) -> None:
self.__timestamp = value
# self.update()
def _repaint_if_needed(self, drawing_context: DrawingContext.DrawingContext, *, immediate: bool = False) -> None:
if self.__timestamp:
drawing_context.timestamp(self.__timestamp.isoformat())
super()._repaint(drawing_context)
def load_rgba_data_from_bytes(b: typing.ByteString, format: typing.Optional[str] = None) -> typing.Optional[DrawingContext.RGBA32Type]:
image_rgba = None
image_argb = imageio.imread(b, format)
if image_argb is not None:
image_rgba = numpy.zeros_like(image_argb)
image_rgba[:, :, 0] = image_argb[:, :, 2]
image_rgba[:, :, 1] = image_argb[:, :, 1]
image_rgba[:, :, 2] = image_argb[:, :, 0]
image_rgba[:, :, 3] = image_argb[:, :, 3]
image_rgba = image_rgba.view(numpy.uint32).reshape(image_rgba.shape[:-1])
return image_rgba
| 2.171875
| 2
|
test/module/rule/test_rule.py
|
amabowilli/cfn-python-lint
| 0
|
12778673
|
"""
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from cfnlint import CloudFormationLintRule # pylint: disable=E0401
from testlib.testcase import BaseTestCase
class TestCloudFormationRule(BaseTestCase):
""" Test CloudFormation Rule """
def test_base(self):
""" Test Base Rule """
class TestRule(CloudFormationLintRule):
""" Def Rule """
id = 'E1000'
shortdesc = 'Test Rule'
description = 'Test Rule Description'
source_url = 'https://github.com/aws-cloudformation/cfn-python-lint/'
tags = ['resources']
self.assertEqual(TestRule.id, 'E1000')
self.assertEqual(TestRule.shortdesc, 'Test Rule')
self.assertEqual(TestRule.description, 'Test Rule Description')
self.assertEqual(TestRule.source_url, 'https://github.com/aws-cloudformation/cfn-python-lint/')
self.assertEqual(TestRule.tags, ['resources'])
def test_config(self):
""" Test Configuration """
class TestRule(CloudFormationLintRule):
""" Def Rule """
id = 'E1000'
shortdesc = 'Test Rule'
description = 'Test Rule'
source_url = 'https://github.com/aws-cloudformation/cfn-python-lint/'
tags = ['resources']
def __init__(self):
"""Init"""
super(TestRule, self).__init__()
self.config_definition = {
'testBoolean': {
'default': True,
'type': 'boolean'
},
'testString': {
'default': 'default',
'type': 'string'
},
'testInteger': {
'default': 1,
'type': 'integer'
}
}
self.configure()
def get_config(self):
""" Get the Config """
return self.config
rule = TestRule()
config = rule.get_config()
self.assertTrue(config.get('testBoolean'))
self.assertEqual(config.get('testString'), 'default')
self.assertEqual(config.get('testInteger'), 1)
rule.configure({
'testBoolean': 'false',
'testString': 'new',
'testInteger': 2
})
self.assertFalse(config.get('testBoolean'))
self.assertEqual(config.get('testString'), 'new')
self.assertEqual(config.get('testInteger'), 2)
| 2.0625
| 2
|
pyqt_auto_search_bar/__init__.py
|
yjg30737/pyqt-auto-search-bar
| 0
|
12778674
|
from .autoSearchBar import AutoSearchBar
| 1.117188
| 1
|
unibit_api_v2/crypto.py
|
liuzulin/python-unibit
| 31
|
12778675
|
from .unibit import UniBit as ub
class CryptoPrice(ub):
def getHistoricalCryptoPrice(self, ticker, startDate, endDate, size=None, selectedFields=None, datatype="json"):
if isinstance(ticker, list):
ticker = ",".join(ticker)
else:
raise TypeError('ticker input should be a list')
endpoints = 'crypto/historical'
return self.make_request(endpoints=endpoints,
data={'tickers': ticker, 'startDate': startDate, 'endDate': endDate,
'datatype': datatype, 'size': size, 'selectedFields': selectedFields})
| 2.71875
| 3
|
Classification/Perceptron/perceptron.py
|
pvlawhatre/MachinePy
| 2
|
12778676
|
<reponame>pvlawhatre/MachinePy
import numpy as np
def perceptron(X_train,y_train,X_test,**kwargs):
n_train,dim=np.shape(X_train)
W=np.random.rand(dim,1)
b=np.random.rand()
old_W=np.random.rand(dim,1)
old_b=np.random.rand()
flag=0
try:
trshld=kwargs['eps']
except:
trshld=0.0001
try:
flg_count=kwargs['stable']
except:
flg_count=10
try:
min_err=10
best_W=np.random.rand(dim,1)
best_b=np.random.rand()
t_itr=kwargs['itr']
except:
pass
itr=-1
#Training
while True:
itr+=1
old_W[:]=W[:]
old_b=b
for i in range(n_train):
Xi=X_train[i,:].reshape(-1,1)
yp=np.dot(W.T,Xi)+b
if yp>0:
Y=1
else:
Y=0
error=y_train[i]-
W=W+error*Xi
b=b+error
epsilon=np.abs(np.linalg.norm(old_W-W,ord='fro')+old_b-b)
if min_err>np.sum(np.abs(error)):
best_W=W[:]
best_b=b
min_err=error
if epsilon<trshld:
flag=flag+1
else:
flag=0
if flag==flg_count:
break
try:
if t_itr<=itr:
W=best_W
b=best_b
break
except:
pass
#Prediction
n_test,_=np.shape(X_test)
yp=np.dot(W.T,X_test.T)+b
Y_hat=(yp>0)
return(Y_hat.flatten(),W,b)
| 2.640625
| 3
|
test/argparser_test.py
|
makzyt4/discogs-tagger
| 2
|
12778677
|
<reponame>makzyt4/discogs-tagger<gh_stars>1-10
import unittest
from discogstagger.argparser import ArgumentParser
class ValidURLTest(unittest.TestCase):
def test(self):
url = 'https://www.discogs.com/Radiohead-The-Bends/release/368116'
args = ['-u', url, 'abc']
parser = ArgumentParser(args)
self.assertTrue(parser['urlvalid'])
self.assertEqual(parser['url'], url)
self.assertFalse(parser['ambiguous'])
class InvalidURLTest(unittest.TestCase):
def test(self):
url = '<Invalid Url>'
args = ['-u', url, 'abc']
parser = ArgumentParser(args)
self.assertEqual(parser['url'], url)
self.assertFalse(parser['urlvalid'])
self.assertFalse(parser['ambiguous'])
class NotDiscogsURLTest(unittest.TestCase):
def test(self):
url = '<Invalid Url>'
args = ['-u', url, 'abc']
parser = ArgumentParser(args)
self.assertFalse(parser['urlvalid'])
self.assertEqual(parser['url'], url)
self.assertFalse(parser['ambiguous'])
class InteractiveIsTrueTest(unittest.TestCase):
def test(self):
args = ['-i', 'abc']
parser = ArgumentParser(args)
self.assertTrue(parser['interactive'])
self.assertFalse(parser['ambiguous'])
class InteractiveAndURLTest(unittest.TestCase):
def test(self):
url = 'https://www.discogs.com/Radiohead-The-Bends/release/368116'
args = ['-i', '-u', url, 'abc']
parser = ArgumentParser(args)
self.assertTrue(parser['ambiguous'])
class FilesAndInteractiveTest(unittest.TestCase):
def test(self):
url = 'https://www.discogs.com/Radiohead-The-Bends/release/368116'
args = ['-u', url, 'file1.flac', 'file2.flac']
parser = ArgumentParser(args)
self.assertFalse(parser['ambiguous'])
self.assertEqual(parser['files'], ['file1.flac', 'file2.flac'])
| 2.921875
| 3
|
main.py
|
H3xadecimal/Nest
| 10
|
12778678
|
<reponame>H3xadecimal/Nest<gh_stars>1-10
#!/usr/bin/env python3
"""
Load and start the Nest client.
"""
import os
import logging
import yaml
from nest import client, helpers, exceptions
DEFAULTS = {
"prefix": "nest!",
"locale": "en_US",
}
def main():
"""
Parse config from file or environment and launch bot.
"""
logger = logging.getLogger()
if os.path.isfile("config.yml"):
logger.debug("Found config, loading...")
with open("config.yml") as file:
config = yaml.safe_load(file)
else:
logger.debug("Config not found, trying to read from env...")
env = {
key[8:].lower(): val
for key, val in os.environ.items()
if key.startswith("NESTBOT_")
}
config = {"tokens": {}, "settings": {}}
for key, val in env.items():
if key.startswith("token_"):
basedict = config["tokens"]
keys = key[6:].split("_")
else:
basedict = config["settings"]
keys = key.split("_")
pointer = helpers.dictwalk(
dictionary=basedict, tree=keys[:-1], fill=True
)
if "," in val:
val = val.split(",")
pointer[keys[-1]] = val
settings = {**DEFAULTS, **config["settings"], "tokens": config["tokens"]}
bot = client.NestClient(**settings)
if settings["database"]:
bot.load_module("db")
for module in os.listdir("modules"):
# Ignore hidden directories
if not module.startswith(".") and module != "db":
try:
bot.load_module(module)
except exceptions.MissingFeatures as exc:
if (
settings.get("database", None)
and exc.features != {"database"}
):
raise
bot.run()
if __name__ == "__main__":
main()
| 2.265625
| 2
|
tests/2019/test_12_the_n_body_problem.py
|
wimglenn/advent-of-code-wim
| 20
|
12778679
|
from aoc_wim.aoc2019 import q12
test10 = """\
<x=-1, y=0, z=2>
<x=2, y=-10, z=-7>
<x=4, y=-8, z=8>
<x=3, y=5, z=-1>"""
test100 = """\
<x=-8, y=-10, z=0>
<x=5, y=5, z=10>
<x=2, y=-7, z=3>
<x=9, y=-8, z=-3>"""
def test_total_energy_after_10_steps():
assert q12.simulate(test10, n=10) == 179
def test_total_energy_after_100_steps():
assert q12.simulate(test100, n=100) == 1940
| 2.078125
| 2
|
contrastive_highlights/Interfaces/abstract_interface.py
|
yotamitai/Contrastive_Highlights
| 0
|
12778680
|
<reponame>yotamitai/Contrastive_Highlights
class AbstractInterface(object):
def __init__(self, config, output_dir):
self.output_dir = output_dir
self.config = config
def initiate(self):
return
def get_state_action_values(self, agent, state):
return
def get_state_from_obs(self, agent, obs, params=None):
return
def get_next_action(self, agent, obs, state):
return
def get_features(self, env):
return
| 2.1875
| 2
|
Day_005/day-5-1-exercise.py
|
masedos/100DaysOfCodePython
| 0
|
12778681
|
#!/usr/bin/env python
__version__ = '0.0.1'
__author__ = '<NAME>'
__email__ = '<EMAIL>'
# 🚨 Don't change the code below 👇
#student_heights = [180, 124, 165, 173, 189, 169, 146]
student_heights = input("Input a list of student heights ").split()
sum = 0
count = 0
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
sum += student_heights[n]
count += 1
average = sum / count
print(int(round(average, 0)))
| 3.96875
| 4
|
track-amazon-prices.py
|
thijsBoet/small-python-projects
| 0
|
12778682
|
import requests
import smtplib
import time
from bs4 import BeautifulSoup
URL = 'https://www.amazon.de/PowerColor-Radeon-5700-8192MB-PCI/dp/B07WT15P2P/ref=sr_1_8?__mk_de_DE=%C3%85M%C3%85%C5%BD%C3%95%C3%91&keywords=PowerColor+Radeon+RX+5700+Red+Dragon+8GB&qid=1582975984&sr=8-8#customerReviews'
def send_mail():
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login('<EMAIL>', '<PASSWORD>')
subject = 'Price alert'
body = 'Price Alert. Check the Amazon link: https://www.amazon.de/PowerColor-Radeon-5700-8192MB-PCI/dp/B07WT15P2P/ref=sr_1_8?__mk_de_DE=%C3%85M%C3%85%C5%BD%C3%95%C3%91&keywords=PowerColor+Radeon+RX+5700+Red+Dragon+8GB&qid=1582975984&sr=8-8#customerReviews'
msg = f'Subject: {subject} \n\n{body}'
server.sendmail(
'<EMAIL>',
'<EMAIL>',
msg
)
print('Email Alert has been send.')
server.quit()
def check_price(url, prefered_price):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'}
page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
title = soup.find(id='productTitle').get_text()
price = soup.find(id='priceblock_ourprice').get_text()
converted_price = float(price[0:3])
if converted_price < prefered_price:
send_mail()
while True:
check_price(URL, 350)
time.sleep(6)
| 2.890625
| 3
|
gym_ur5/envs/ur5_env.py
|
pnnayyeri/gym-ur5
| 1
|
12778683
|
<reponame>pnnayyeri/gym-ur5
import sim
import numpy as np
import time
import matplotlib.pyplot as plt
import gym
from gym import error, spaces
class UR5Env(gym.Env):
def __init__(self): # n_actions:3 (target pos), n_states:6 (3pos+3force)
self.metadata = {'render.modes': ['human']}
super().__init__()
sim.simxFinish(-1)
for _ in range(5):
self.clientID = sim.simxStart('127.0.0.1',19997,True,True,5000,5)
if self.clientID != -1:
# print('[INFO] Connected to CoppeliaSim.')
break
if self.clientID == -1:
raise IOError('[ERROR] Could not connect to CoppeliaSim.')
sim.simxSynchronous(self.clientID, True)
# sim.simxStartSimulation(self.clientID, sim.simx_opmode_oneshot)
sim.simxGetPingTime(self.clientID)
self.stepCount = 0
self.reward = 0
self.n_substeps = 10
# self.sim_timestep = 0.5 # set in coppeliaSim (not implemented)
self.n_actions = 3
self.n_states = 6
self.action_space = spaces.Box(-1., 1, shape = (self.n_actions,), dtype = 'float32')
self.observation_space = spaces.Box(-np.inf, np.inf, shape=(self.n_states,), dtype='float32')
self._getHandles()
sim.simxGetPingTime(self.clientID)
def getHandle(self, name, ignoreError = False, attempts = 5):
for _ in range(attempts):
res, out_handle = sim.simxGetObjectHandle(self.clientID, name, sim.simx_opmode_blocking)
if res == sim.simx_return_ok or ignoreError:
# print('[INFO] {} handle obtained.'.format(name))
break
sim.simxGetPingTime(self.clientID)
# if res!=sim.simx_return_ok and not ignoreError:
# print('[WARNING] Failed to find {} with error {}.'.format(name, res))
return out_handle
def __del__(self):
self.close()
def close(self):
sim.simxStopSimulation(self.clientID, sim.simx_opmode_oneshot)
sim.simxGetPingTime(self.clientID)
sim.simxFinish(self.clientID)
def step(self, action):
# action = np.clip(action, self.action_space.low, self.action_space.high)
obs = self._get_obs()
action = np.clip(action, obs[0:3]-0.1*np.ones(([1,3])), obs[0:3]+0.1*np.ones(([1,3])))[0]
self._set_action(action)
self._simulation_step()
obs = self._get_obs()
done = self._is_done()
info = {}
reward = self._getReward()
return obs, reward, done, info
def _set_action(self, action):
actionX = action[0]
actionY = action[1]
actionZ = action[2]
# print('[DATA] X:{:.4f}, Y:{:.4f}, Z:{:.4f}'.format(actionX,actionY,actionZ))
sim.simxSetFloatSignal(self.clientID, 'actionX', actionX, sim.simx_opmode_oneshot)
sim.simxSetFloatSignal(self.clientID, 'actionY', actionY, sim.simx_opmode_oneshot)
sim.simxSetFloatSignal(self.clientID, 'actionZ', actionZ, sim.simx_opmode_oneshot)
sim.simxGetPingTime(self.clientID)
def _simulation_step(self):
#for _ in range(self.n_substeps):
sim.simxSynchronousTrigger(self.clientID)
sim.simxGetPingTime(self.clientID)
# while self._getTargetPos(False) is not self._getFinalPos(False): # keep triggering until movement is done
# sim.simxSynchronousTrigger(self.clientID)
# sim.simxGetPingTime(self.clientID)
def _get_obs(self):
X, Y, Z = self.getKinectXYZ(False)
# X, Y, Z = self._getTargetPosFromKinect(False) # changed observation with exact target pos
forces = self.getForce(False)
return [X, Y, Z, forces[0][2], forces[1][2], forces[2][2]]
def _is_done(self):
pathIsDone = sim.simxGetFloatSignal(self.clientID,'movePathDone',sim.simx_opmode_blocking)[1]
sim.simxGetPingTime(self.clientID)
return True if pathIsDone==1 else False
def reset(self):
sim.simxSetFloatSignal(self.clientID, 'renderEnv', 0, sim.simx_opmode_oneshot)
sim.simxGetPingTime(self.clientID)
self.resetSim()
self.prepareSim()
obs = self._get_obs()
return obs
def render(self, mode='human'):
sim.simxSetFloatSignal(self.clientID, 'renderEnv', 1, sim.simx_opmode_oneshot)
sim.simxGetPingTime(self.clientID)
def _getHandles(self):
'''
print('getting tip handle...')
self.tipHandle = self.getHandle('UR5_link7_visible')
print('tip handle obtained successfully.')
'''
self.jointHandles = []
# print('[INFO] getting joint handles...')
for i in range(1,7):
self.jointHandles.append(self.getHandle('UR5_joint{}'.format(i)))
# print('[INFO] joint handles obtained successfully.')
# print('[INFO] getting dummy handles...')
self.tipDummyHandle = self.getHandle('Tip')
self.targetDummyHandle = self.getHandle('TargetDummy')
self.testDummyHandle = self.getHandle('TestDummy')
# print('[INFO] dummy handles obtained successfully.')
self.targetObjectHandle = self.getHandle('TargetObject')
# print('[INFO] target object handle obtained successfully.')
# print('[INFO] getting force sensor handles...')
self.kinectHandle = self.getHandle('kinect_rgb')
self.fsHandles = []
for i in range(1,4):
self.fsHandles.append(self.getHandle('JacoHand_forceSens2_finger{}'.format(i)))
# print('[INFO] force sensor handles obtained successfully.')
def _getTipPos(self, initialize = True):
if initialize:
ret, pos = sim.simxGetObjectPosition(self.clientID, self.tipDummyHandle, -1, sim.simx_opmode_streaming)
else:
ret, pos = sim.simxGetObjectPosition(self.clientID, self.tipDummyHandle, -1, sim.simx_opmode_buffer)
if ret == sim.simx_return_ok:
return pos
else:
# print('[WARNING] problem in getting tip position.')
return -1
def _getTargetPos(self, initialize = True):
if initialize:
ret, pos = sim.simxGetObjectPosition(self.clientID, self.targetObjectHandle, -1, sim.simx_opmode_streaming)
else:
ret, pos = sim.simxGetObjectPosition(self.clientID, self.targetObjectHandle, -1, sim.simx_opmode_buffer)
if ret == sim.simx_return_ok:
return pos
else:
# print('[WARNING] problem in getting target position.')
return -1
def _getTargetPosFromKinect(self, initialize = True):
if initialize:
ret, pos = sim.simxGetObjectPosition(self.clientID, self.targetObjectHandle, self.kinectHandle, sim.simx_opmode_streaming)
else:
ret, pos = sim.simxGetObjectPosition(self.clientID, self.targetObjectHandle, self.kinectHandle, sim.simx_opmode_buffer)
if ret == sim.simx_return_ok:
return pos
else:
# print('[WARNING] problem in getting target position.')
return -1
def _getFinalPos(self, initialize = True):
if initialize:
ret, pos = sim.simxGetObjectPosition(self.clientID, self.testDummyHandle, -1, sim.simx_opmode_streaming)
else:
ret, pos = sim.simxGetObjectPosition(self.clientID, self.testDummyHandle, -1, sim.simx_opmode_buffer)
if ret == sim.simx_return_ok:
return pos
else:
# print('[WARNING] problem in getting tip position.')
return -1
def getKinectXYZ(self, initialize = True):
if initialize:
X = sim.simxGetFloatSignal(self.clientID,'actX',sim.simx_opmode_streaming)[1]
Y = sim.simxGetFloatSignal(self.clientID,'actY',sim.simx_opmode_streaming)[1]
Z = sim.simxGetFloatSignal(self.clientID,'actZ',sim.simx_opmode_streaming)[1]
else:
X = sim.simxGetFloatSignal(self.clientID,'actX',sim.simx_opmode_buffer)[1]
Y = sim.simxGetFloatSignal(self.clientID,'actY',sim.simx_opmode_buffer)[1]
Z = sim.simxGetFloatSignal(self.clientID,'actZ',sim.simx_opmode_buffer)[1]
sim.simxGetPingTime(self.clientID)
return X,Y,Z
def getForce(self, initialize = True):
if initialize:
F1 = sim.simxReadForceSensor(self.clientID,self.fsHandles[0],sim.simx_opmode_streaming)[2]
F2 = sim.simxReadForceSensor(self.clientID,self.fsHandles[1],sim.simx_opmode_streaming)[2]
F3 = sim.simxReadForceSensor(self.clientID,self.fsHandles[2],sim.simx_opmode_streaming)[2]
else:
F1 = sim.simxReadForceSensor(self.clientID,self.fsHandles[0],sim.simx_opmode_buffer)[2]
F2 = sim.simxReadForceSensor(self.clientID,self.fsHandles[1],sim.simx_opmode_buffer)[2]
F3 = sim.simxReadForceSensor(self.clientID,self.fsHandles[2],sim.simx_opmode_buffer)[2]
sim.simxGetPingTime(self.clientID)
return [F1,F2,F3]
def getForceMagnitude(self, initialize = True):
if initialize:
F1 = sim.simxReadForceSensor(self.clientID,self.fsHandles[0],sim.simx_opmode_streaming)[2]
F2 = sim.simxReadForceSensor(self.clientID,self.fsHandles[1],sim.simx_opmode_streaming)[2]
F3 = sim.simxReadForceSensor(self.clientID,self.fsHandles[2],sim.simx_opmode_streaming)[2]
else:
F1 = sim.simxReadForceSensor(self.clientID,self.fsHandles[0],sim.simx_opmode_buffer)[2]
F2 = sim.simxReadForceSensor(self.clientID,self.fsHandles[1],sim.simx_opmode_buffer)[2]
F3 = sim.simxReadForceSensor(self.clientID,self.fsHandles[2],sim.simx_opmode_buffer)[2]
sim.simxGetPingTime(self.clientID)
return [np.linalg.norm(F1),np.linalg.norm(F2),np.linalg.norm(F3)]
def initializeFunctions(self):
self.getKinectXYZ(True)
self.getForce(True)
self.getForceMagnitude(True)
self._getTipPos(True)
self._getTargetPos(True)
self._getTargetPosFromKinect(True)
self._getFinalPos(True)
def _getReward(self):
tipPos = self._getTipPos(False)
targetPos = self._getTargetPos(False)
dist = np.linalg.norm(np.array(tipPos)-np.array(targetPos))
self.stepCount += 1
# self.reward = self.reward + (1/self.stepCount)*((-dist*dist)-self.reward)
self.reward = self.reward - (dist*dist)
return self.reward
def prepareSim(self):
self.initializeFunctions()
isTracking = sim.simxGetFloatSignal(self.clientID,'isTracking',sim.simx_opmode_streaming)[1]
while isTracking != 1:
sim.simxSynchronousTrigger(self.clientID)
isTracking = sim.simxGetFloatSignal(self.clientID,'isTracking',sim.simx_opmode_buffer)[1]
sim.simxGetPingTime(self.clientID)
X,Y,Z = self.getKinectXYZ(True)
actionX = X
actionY = Y
actionZ = Z
# print(actionX,actionY,actionZ)
# print('[DATA] X:{:.4f}, Y:{:.4f}, Z:{:.4f}'.format(actionX,actionY,actionZ))
sim.simxSetFloatSignal(self.clientID, 'actionX', actionX, sim.simx_opmode_oneshot)
sim.simxSetFloatSignal(self.clientID, 'actionY', actionY, sim.simx_opmode_oneshot)
sim.simxSetFloatSignal(self.clientID, 'actionZ', actionZ, sim.simx_opmode_oneshot)
sim.simxGetPingTime(self.clientID)
# print('[INFO] simulation is ready for tracking.')
def resetSim(self):
# print('[INFO] reseting sim...')
ret = sim.simxStopSimulation(self.clientID,sim.simx_opmode_blocking)
if ret == sim.simx_return_ok:
# print('[INFO] sim reset successfully.')
time.sleep(1)
else:
raise IOError('[ERROR] problem in reseting sim...')
sim.simxGetPingTime(self.clientID)
# print('[INFO] starting sim in synchronous mode...')
sim.simxSynchronous(self.clientID, True)
sim.simxGetPingTime(self.clientID)
ret = sim.simxStartSimulation(self.clientID,sim.simx_opmode_oneshot)
# if ret == sim.simx_return_ok:
# print('[INFO] sim started successfully.')
sim.simxGetPingTime(self.clientID)
sim.simxClearFloatSignal(self.clientID, 'actionX', sim.simx_opmode_blocking)
sim.simxClearFloatSignal(self.clientID, 'actionY', sim.simx_opmode_blocking)
sim.simxClearFloatSignal(self.clientID, 'actionZ', sim.simx_opmode_blocking)
sim.simxGetPingTime(self.clientID)
self.stepCount = 0
self.reward = 0
def doTracking(self):
self.resetSim()
self.prepareSim()
pathIsDone = sim.simxGetFloatSignal(self.clientID,'movePathDone',sim.simx_opmode_streaming)[1]
posX = []
posY = []
posZ = []
tactile1 = []
reward = []
while pathIsDone == 0:
X,Y,Z = self.getKinectXYZ(False)
# forces = self.getForce(False)
# diffForce = (forces[0][0] + ((forces[1][0] + forces[2][0]) / 2))/2
# print('[DATA] diff force: {:.4f}'.format(diffForce))
actionX = X # + 0.005*diffForce
actionY = Y
actionZ = Z
# print('[DATA] X:{:.4f}, Y:{:.4f}, Z:{:.4f}'.format(actionX,actionY,actionZ))
sim.simxSetFloatSignal(self.clientID, 'actionX', actionX, sim.simx_opmode_oneshot)
sim.simxSetFloatSignal(self.clientID, 'actionY', actionY, sim.simx_opmode_oneshot)
sim.simxSetFloatSignal(self.clientID, 'actionZ', actionZ, sim.simx_opmode_oneshot)
sim.simxGetPingTime(self.clientID)
sim.simxSynchronousTrigger(self.clientID)
forces = self.getForceMagnitude(False)
posX.append(X)
posY.append(Y)
posZ.append(Z)
tactile1.append(forces[0])
reward.append(self._getReward())
sim.simxGetPingTime(self.clientID)
pathIsDone = sim.simxGetFloatSignal(self.clientID,'movePathDone',sim.simx_opmode_buffer)[1]
# time.sleep(0.5)
# print('[INFO] tracking is done.')
# print('[DATA] accumulated reward: {}'.format(np.sum(np.array(reward))))
sim.simxStopSimulation(self.clientID,sim.simx_opmode_blocking)
| 2.390625
| 2
|
src/text_mining.py
|
desiguel/asx-announce-analysis
| 6
|
12778684
|
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.decomposition import PCA, IncrementalPCA
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
from sklearn.grid_search import GridSearchCV
from sklearn import cross_validation as cv
from sklearn import metrics
from time import time
import pickle
import warnings
from text_utilities import *
# Ignore deprecation warnings.
warnings.filterwarnings("ignore")
# Script Precondition:
# Need to have data.pkl and labels.pkl available.
# Run load_data.py to generate these files if haven't already done so.
# Load data.
data = pickle.load(open('data_all.pkl', "rb"))
labels = pickle.load(open('labels_all.pkl', "rb"))
# Transform the data - vectorise and apply tf-idf.
data = CountVectorizer().fit_transform(data)
tf_idf_transform = TfidfTransformer(use_idf=True).fit(data)
data = tf_idf_transform.transform(data)
print("\nData frame shape:")
print(data.shape)
# Dimensionality reduction
print("\nRunning dimensionality reduction (custom)")
data = feature_reduction(data, labels, 0.85)
print("\nData frame shape after dimensionality reduction (custom):")
print(data.shape)
# Dimensionality reduction
print("\nRunning dimensionality reduction (PCA)")
pca = IncrementalPCA(n_components=50, batch_size=100)
pca.fit(data.toarray())
data = pca.transform(data.toarray())
print("\nPCA explained variance:")
print(pca.explained_variance_ratio_)
print(sum(pca.explained_variance_ratio_))
print("\nData frame shape after dimensionality reduction (custom):")
print(data.shape)
# Splitting the data up into 60% training set, 20% cross-validation and 20% testing sets.
x_train, x_test, y_train, y_test = cv.train_test_split(data, labels, test_size=0.30, random_state=1)
# Test Logistical Regression classifier
print("\nRunning Logistic Regression classifier and tuning using grid search..")
t0 = time()
# Grid search for best LR parameters
cost_range = [1e-3, 0.1, 1, 100]
parameters = dict(C=cost_range)
grid = GridSearchCV(LogisticRegression(), param_grid=parameters, cv=2, n_jobs=7, verbose=3)
grid.fit(x_train, y_train)
print("\nThe best LR parameters are %s with a score of %0.2f"
% (grid.best_params_, grid.best_score_))
predicted = grid.predict(x_test)
accuracy = np.mean(predicted == y_test)
print(metrics.classification_report(y_test, predicted))
print(metrics.confusion_matrix(y_test, predicted))
t1 = time()
print("\nLR classification time: {} sec".format(round((t1-t0), 2)))
print("\nRunning SVM classifier and tuning using grid search..\n")
t0 = time()
# Grid search for best SVM parameters
cost_range = [0.1, 1, 10, 100, 1000]
gamma_range = [1e-5, 0.1, 1, 10, 100]
parameters = dict(gamma=gamma_range, C=cost_range)
grid = GridSearchCV(SVC(), param_grid=parameters, cv=2, n_jobs=7, verbose=3)
grid.fit(x_train, y_train)
print("\nThe best SVM parameters are %s with a score of %0.2f"
% (grid.best_params_, grid.best_score_))
print("\nClassification time: {} sec".format(round((t1-t0), 2)))
predicted = grid.predict(x_test)
accuracy = np.mean(predicted == y_test)
print(metrics.classification_report(y_test, predicted))
print(metrics.confusion_matrix(y_test, predicted))
t1 = time()
print("\nSVM classification time: {} sec".format(round((t1-t0), 2)))
print("\nRunning MLP classifier and tuning using grid search..\n")
t0 = time()
# Grid search for best SVM parameters
alpha_range = [1e-5, 1e-3, 0.1, 10, 100]
layer1_range = [5, 10, 30, 40, 50]
layer2_range = [5, 10, 30, 40, 50]
layer3_range = [5, 10, 30, 40, 50]
hidden_layer_range = np.vstack(np.meshgrid(layer1_range, layer2_range, layer3_range)).reshape(3, -1).T
hidden_layer_range = [tuple(i) for i in hidden_layer_range]
parameters = dict(solver=['lbfgs'], alpha=alpha_range,
hidden_layer_sizes=hidden_layer_range, random_state=[1])
grid = GridSearchCV(MLPClassifier(), param_grid=parameters, cv=2, n_jobs=7, verbose=3)
grid.fit(x_train, y_train)
print("\nThe best MLP parameters are %s with a score of %0.2f"
% (grid.best_params_, grid.best_score_))
print("\nClassification time: {} sec".format(round((t1-t0), 2)))
predicted = grid.predict(x_test)
accuracy = np.mean(predicted == y_test)
print(metrics.classification_report(y_test, predicted))
print(metrics.confusion_matrix(y_test, predicted))
t1 = time()
print("\nMLP classification time: {} sec".format(round((t1-t0), 2)))
| 2.8125
| 3
|
discursus_core/discursus_repo.py
|
discursus-io/dio_data_stack
| 6
|
12778685
|
from dagster import repository
from pipelines import mine_gdelt_data
from pipelines import build_data_warehouse
from schedules import mine_gdelt_data_schedule, build_data_warehouse_schedule
@repository
def discursus_repository():
pipelines = [
mine_gdelt_data,
build_data_warehouse
]
schedules = [
mine_gdelt_data_schedule,
build_data_warehouse_schedule
]
return pipelines + schedules
| 1.828125
| 2
|
scripts/main.py
|
michaellyoungg/DeerVision
| 1
|
12778686
|
<filename>scripts/main.py
# {tkinter}
from tkinter import *
from tkinter import filedialog, Button, messagebox
# {playback}
from playbackController import PlayBack
# {thermography}
from thermography import Thermography
# {WebODM}
from webodmAPI import WebODMAPI
# {Python}
import time
import os
from PIL import ImageTk, Image
status_codes = {
"QUEUED": 10,
"RUNNING": 20,
"FAILED": 30,
"COMPLETED": 40,
"CANCELED": 50
}
class DeerVision(Tk):
def __init__(self):
super(DeerVision, self).__init__()
# WebODM Api Call
self.odm_API = WebODMAPI()
self.list_dir = ""
directory = os.getcwd()
# global flag to hide widget
self.enableDropDown = False
# initialize tkinter window
self.title("Remote Intelligence")
self.geometry("700x700")
self.configure(background="white")
self.resizable(False, False)
# project name and id
self.project_name = ""
self.project_id = ""
self.existingProjects = StringVar()
# Adding RI logo to window
self.RI_img = ImageTk.PhotoImage(Image.open(os.path.join(directory, 'images', 'RI_Logo.jpg')))
self.iconLabel = Label(self, image=self.RI_img, bd=1)
self.iconLabel.grid(column=0, row=0, columnspan=6)
# Add initial frame
self.initFrame = LabelFrame(self, text="Project Details", bg="white", padx=50, pady=30)
self.initFrame.grid(column=2, row=1)
# Add buttons to initial frame
self.createProjectBtn = Button(self.initFrame, text="Create New Project", pady=10, width=30,
command=self.createNewProject)
self.createProjectBtn.grid(column=0, row=1)
self.dummyLabel1 = Label(self.initFrame, bd=1, bg="white")
self.dummyLabel1.grid(column=0, row=4)
self.addTask = Button(self.initFrame, text="Add New Task To Existing Project", pady=10, width=30,
command=self.uploadProjectHelper)
self.addTask.grid(column=0, row=7)
self.dummyLabel2 = Label(self.initFrame, bd=1, bg="white")
self.dummyLabel2.grid(column=0, row=10)
self.webBtn = Button(self.initFrame, text="WebODM Settings", pady=10, width=30,
command=self.webODMSettings)
self.webBtn.grid(column=0, row=13)
self.dummyLabel3 = Label(self.initFrame, bd=1, bg="white")
self.dummyLabel3.grid(column=0, row=16)
self.viewStitchBtn = Button(self.initFrame, text="View Stitched Image", pady=10, width=30,
command=self.RunPlayback)
self.viewStitchBtn.grid(column=0, row=19)
def createNewProject(self):
def submitNewProject():
project_name = name.get("1.0", END)
# create new project
auth = self.odm_API.authenticate()
try:
self.project_id = self.odm_API.create_new_project(project_name, auth)
except:
messagebox.showinfo("Error", "Unable to create a new project. Please try again")
else:
messagebox.showinfo("Success", "Created new project: " + project_name)
self.project_name = project_name
newProjectWindow.destroy()
self.uploadProject()
newProjectWindow = Toplevel()
# Initialize window
newProjectWindow.title("Create New Project")
newProjectWindow.geometry("500x300")
newProjectWindow.configure(background="white")
newProjectWindow.resizable(False, False)
# Create input field
Label(newProjectWindow, text=" Project Name", bg="white").grid(column=1, row=1, pady=20, padx=20)
name = Text(newProjectWindow, height=1, width=30, borderwidth=5)
name.grid(column=2, row=1)
Label(newProjectWindow, text="Description", bg="white").grid(column=1, row=6, pady=20, padx=20)
description = Text(newProjectWindow, height=5, width=30, borderwidth=5)
description.grid(column=2, row=6)
submitBtn = Button(newProjectWindow, text="Submit", bg="white", command=submitNewProject)
submitBtn.grid(column=2, row=10)
def uploadProjectHelper(self):
self.enableDropDown = True
self.uploadProject()
def uploadProject(self):
projectsWindow = Toplevel()
def destroyProjectsWindow():
projectsWindow.destroy()
self.loadWebODM()
# Initialize window
projectsWindow.title("Projects")
projectsWindow.geometry("300x300")
projectsWindow.configure(background="white")
projectsWindow.resizable(False, False)
# Add upload frame
uploadFrame = LabelFrame(projectsWindow, text="Begin Upload", bg="white", padx=50, pady=30)
uploadFrame.pack()
# Separate for uploading to existing project
if (self.enableDropDown):
# variable label for drop down
self.existingProjects.set("Select Existing Project")
auth = self.odm_API.authenticate()
obj = self.odm_API.get_list_of_projects(auth)
projects = []
for project in obj['results']:
projects.append(project['name'])
# Create drop down menu
dropDown = OptionMenu(uploadFrame, self.existingProjects, *projects)
dropDown.grid(column=0, row=1)
dummyLabel1 = Label(uploadFrame, bd=1, bg="white")
dummyLabel1.grid(column=0, row=4)
# Add buttons and padding for upload frame
newBtn = Button(uploadFrame, text="Select Folder", width=21, command=self.loadFile)
newBtn.grid(column=0, row=7)
dummyLabel2 = Label(uploadFrame, bd=1, bg="white")
dummyLabel2.grid(column=0, row=10)
submitBtn = Button(uploadFrame, text="Submit", width=21, command=destroyProjectsWindow)
submitBtn.grid(column=0, row=13)
def webODMSettings(self):
profileSettingsWindow = Toplevel()
#def saveChanges():
# post request to update user settings
#def cancel():
# destroy window
# initialize window
profileSettingsWindow.title("Profile")
profileSettingsWindow.geometry("500x300")
profileSettingsWindow.configure(background="white")
profileSettingsWindow.resizable(False, False)
# get user info
auth = self.odm_API.authenticate()
user_info = self.odm_API.get_user(2, auth)
# set user properties
uNameVar = StringVar()
uNameVar.set(user_info['username'])
fNameVar = StringVar()
fNameVar.set(user_info['first_name'])
lNameVar = StringVar()
lNameVar.set(user_info['last_name'])
emailVar = StringVar()
emailVar.set(user_info['email'])
# Create input field
Label(profileSettingsWindow, text="Username", bg="white").grid(column=1, row=1, pady=20, padx=20)
userName = Entry(profileSettingsWindow, textvariable=uNameVar, bg='white', width=30)
userName.grid(column=2, row=1)
Label(profileSettingsWindow, text="First Name", bg="white").grid(column=1, row=4, pady=20, padx=20)
firstName = Entry(profileSettingsWindow, textvariable=fNameVar, bg='white', width=30)
firstName.grid(column=2, row=4)
Label(profileSettingsWindow, text="Last Name", bg="white").grid(column=1, row=7, pady=20, padx=20)
lastName = Entry(profileSettingsWindow, textvariable=lNameVar, bg='white', width=30)
lastName.grid(column=2, row=7)
Label(profileSettingsWindow, text="Email ", bg="white").grid(column=1, row=10, pady=20, padx=20)
email = Entry(profileSettingsWindow, textvariable=emailVar, bg='white', width=30)
email.grid(column=2, row=10)
saveBtn = Button(profileSettingsWindow, text="Save Changes", bg="white", command=saveChanges)
saveBtn.grid(column=2, row=13)
saveBtn = Button(profileSettingsWindow, text="Cancel", bg="white", command=cancel)
saveBtn.grid(column=2, row=16)
def loadFile(self):
file_name = filedialog.askdirectory(initialdir="./")
if file_name:
self.list_dir = file_name
messagebox.showinfo("Directory", "Selected directory: " + self.list_dir)
else:
messagebox.showinfo("Error", "Invalid file directory, try again!")
raise ValueError("Invalid file directory")
return self.list_dir
def loadWebODM(self):
auth = self.odm_API.authenticate()
if self.enableDropDown:
self.project_name = self.existingProjects.get()
self.enableDropDown = False
if self.project_name == "":
return messagebox.showinfo("ERROR", "Project name not properly set")
if not auth:
# handle lack of authentication
return
self.odm_API.load_images(self.list_dir)
# get project id for current project
obj = self.odm_API.get_list_of_projects(auth)
# ISSUE -- not getting project ID
for project in obj['results']:
if project['name'] == self.project_name:
self.project_id = project['id']
# stitch images
task_id = self.odm_API.stitch_images(self.project_id, auth)
# get progress
if task_id:
self.get_status(task_id)
self.odm_API.download_tif(task_id)
def RunPlayback(self):
picURL = self.directory + '/orthophoto.tif'
Thermo = Thermography(imageURL=picURL, colorMode="red")
PlayBack(self.project_name, Thermo)
# FIX -- status message here
def get_status(self, task_id):
statusWindow = Toplevel()
statusWindow.title("Status Window")
statusWindow.geometry("300x300")
statusWindow.configure(background="white")
statusWindow.resizable(False, False)
frame = LabelFrame(statusWindow, bg="white", padx=50, pady=30)
frame.pack()
text = Text(statusWindow, width=21)
btn = Button(frame, text="Finish", width=21)
btn.grid(column=0, row=7)
while True:
text.delete(1.0, END)
res = self.odm_API.get_stitch_status(self.project_id, task_id)
if res['status'] == status_codes["COMPLETED"]:
print("Task has completed!")
text.insert(END, "Task has completed!")
break
elif res['status'] == status_codes["FAILED"]:
print("Task failed: {}".format(res))
text.insert(END, "Task failed: {}".format(res))
sys.exit(1)
elif res['status'] == status_codes["QUEUED"]:
print("Task has been qeued")
text.insert(END, "Task has been qeued")
time.sleep(3)
else:
print("Processing, hold on...")
text.insert(END, "Processing, hold on...")
time.sleep(3)
self.update_idletasks()
if __name__ == "__main__":
deer_process = DeerVision()
deer_process.mainloop()
| 2.6875
| 3
|
leetcode/sort/heap.py
|
deevarvar/myLab
| 0
|
12778687
|
#! /usr/bin/python
def heapify(array):
# first non-leaf node
nlnode = (len(array) - 1)/2
for i in reversed(range(nlnode)):
siftdown(array, i, len(array) - 1)
print "index {} {}".format(i, array)
def siftdown(array, start, end):
root = start
while (2*root + 1) <= end: # at lease one left child
anchor = root
lefti = 2*root +1
righti = lefti + 1
if array[lefti] > array[anchor]:
anchor = lefti
if righti <= end and array[righti] > array[anchor]:
anchor = righti
if anchor == root:
return
else:
tmp = array[root]
array[root] = array[anchor]
array[anchor] = tmp
root = anchor
def heapsort(array):
heapify(array)
print "after heapify is {}".format(array)
count = len(array) - 1
while count > 0:
tmp = array[0]
array[0] = array[count]
array[count] = tmp
count = count - 1
siftdown(array, 0, count)
print "after heapifysort is {}".format(array)
if __name__ == '__main__':
array = [6, 2, 8, 0, 4, 7, 10]
barray = array[:]
barray.sort()
print "standard array is {}".format(barray)
heapsort(array)
| 4.0625
| 4
|
Dummy_code/dummy1.py
|
garima-softuvo/Flask_practice
| 0
|
12778688
|
<gh_stars>0
from flask import Flask, request, jsonify
import json
import os
import sqlite3
app = Flask(__name__)
path = r"/home/softuvo/Garima/Flask Practice/Flask_practice/files"
files = os.listdir(path)
for f in files:
filename=os.path.join(path, f)
def convertToBinaryData(filename):
# Convert digital data to binary format
with open(filename, 'rb') as file:
binaryData = file.read()
# print(binaryData)
return binaryData
def db_connection():
conn = None
try:
conn = sqlite3.connect("data.sqlite")
except sqlite3.error as e:
print(e)
return conn
@app.route("/users", methods=["GET", "POST"])
def users():
conn = db_connection()
cursor = conn.cursor()
if request.method == "GET":
cursor= conn.execute("SELECT * FROM Employees")
dbtable= [
dict(id=row[0], name=row[1], salary=row[2], files= row[3])
for row in cursor.fetchall()
]
if dbtable is not None:
return jsonify(dbtable)
if request.method == "POST":
name = request.form["name"]
salary = request.form["salary"]
files = request.form["files"]
sql = """INSERT INTO Employees (name, salary, files)
VALUES (?, ?, ?)"""
files = convertToBinaryData(filename)
data_tuple = (filename, files)
cursor = cursor.execute(sql, (name, salary, data_tuple))
conn.commit()
return f"Employee with the id: {cursor.lastrowid} created successfully", 201
if __name__ == "__main__":
app.run(port=5001, debug =True)
| 3.3125
| 3
|
trolly/label.py
|
WoLpH/Trolly
| 1
|
12778689
|
from . import trelloobject
class Label(trelloobject.TrelloObject):
'''
Class representing a Trello Label
'''
def __init__(self, trello_client, label_id, name=''):
super(Label, self).__init__(trello_client)
self.id = label_id
self.name = name
self.base_uri = '/labels/' + self.id
def get_label_information(self, query_params=None):
'''
Get all information for this Label. Returns a dictionary of values.
'''
return self.fetch_json(
uri_path=self.base_uri,
query_params=query_params or {}
)
def get_items(self, query_params=None):
'''
Get all the items for this label. Returns a list of dictionaries.
Each dictionary has the values for an item.
'''
return self.fetch_json(
uri_path=self.base_uri + '/checkItems',
query_params=query_params or {}
)
def update_label(self, name):
'''
Update the current label. Returns a new Label object.
'''
label_json = self.fetch_json(
uri_path=self.base_uri,
http_method='PUT',
query_params={'name': name}
)
return self.create_label(label_json)
| 3.109375
| 3
|
tda-api_test.py
|
kspringfield13/MoneyTree
| 0
|
12778690
|
<reponame>kspringfield13/MoneyTree<filename>tda-api_test.py
from tda import auth, client
from tda.orders.common import OrderType, Duration, Session
from tda.orders.generic import OrderBuilder
from tda.orders.equities import equity_buy_limit
import json, config
try:
c = auth.client_from_token_file(config.tda_token_path, config.tda_api_key)
except FileNotFoundError:
from selenium import webdriver
with webdriver.Chrome(executable_path='/Users/kylespringfield/Dev/MoneyTree/chromedriver') as driver:
c = auth.client_from_login_flow(
driver, config.tda_api_key, config.tda_redirect_uri, config.tda_token_path)
# r = c.get_price_history('AAPL',
# period_type=client.Client.PriceHistory.PeriodType.YEAR,
# period=client.Client.PriceHistory.Period.TWENTY_YEARS,
# frequency_type=client.Client.PriceHistory.FrequencyType.DAILY,
# frequency=client.Client.PriceHistory.Frequency.DAILY)
# assert r.status_code == 200, r.raise_for_status()
# print(json.dumps(r.json(), indent=4))
# # Get quotes
# res = c.get_quotes('AAPL')
# print(json.dumps(res.json(), indent=4))
# # Get Fundamentals
# res = c.search_instruments(['AAPL'], c.Instrument.Projection.FUNDAMENTAL)
# print(json.dumps(res.json(), indent=4))
# # Get movers
res = c.get_movers(index='SPX.X', direction=c.Movers.Direction.UP, change=c.Movers.Change.PERCENT)
print(json.dumps(res.json(), indent=4))
# # Options
# print(json.dumps(res.json(), indent=4))
# res = c.get_option_chain('AAPL')
# print(json.dumps(res.json(), indent=4))
# res = c.get_option_chain('AAPL', contract_type=c.Options.ContractType.CALL,
# strike=120)
# print(json.dumps(res.json(), indent=4))
# # Account Info
# res = c.get_account(config.tda_account_id)
# print(json.dumps(res.json(), indent=4))
| 2.125
| 2
|
lilu/data_layer/__init__.py
|
xyla-io/lambda_lilu
| 0
|
12778691
|
<reponame>xyla-io/lambda_lilu
from .base import get_connection, run_query
from .query import Query, UnloadQuery
from .locator import ResourceLocator, locator_factory
from .encryptor import Encryptor, Decryptor
| 1.242188
| 1
|
funowl/terminals/Terminals.py
|
clin113jhu/funowl
| 23
|
12778692
|
# String pattern matches used in Functional Owl
# The following productions are taken from ShExJ.py from the ShExJSG project
from typing import Union, Any
from funowl.terminals.Patterns import String, Pattern
class HEX(String):
pattern = Pattern(r'[0-9]|[A-F]|[a-f]')
python_type = Union[int, str]
class UCHAR(String):
pattern = Pattern(r'\\\\u({HEX})({HEX})({HEX})({HEX})|\\\\U({HEX})({HEX})({HEX})({HEX})({HEX})({HEX})({HEX})({HEX})'.format(HEX=HEX.pattern))
class IRIREF(String):
pattern = Pattern(r'([^\u0000-\u0020\u005C\u007B\u007D<>"|^`]|({UCHAR}))*'.format(UCHAR=UCHAR.pattern))
class PN_CHARS_BASE(String):
pattern = Pattern(r'[A-Z]|[a-z]|[\u00C0-\u00D6]|[\u00D8-\u00F6]|[\u00F8-\u02FF]|[\u0370-\u037D]|[\u037F-\u1FFF]|[\u200C-\u200D]|[\u2070-\u218F]|[\u2C00-\u2FEF]|[\u3001-\uD7FF]|[\uF900-\uFDCF]|[\uFDF0-\uFFFD]|[\U00010000-\U000EFFFF]')
class PN_CHARS_U(String):
pattern = Pattern(r'({PN_CHARS_BASE})|_'.format(PN_CHARS_BASE=PN_CHARS_BASE.pattern))
class PN_CHARS(String):
pattern = Pattern(r'({PN_CHARS_U})|\-|[0-9]|\\u00B7|[\u0300-\u036F]|[\u203F-\u2040]'.format(PN_CHARS_U=PN_CHARS_U.pattern))
class PNAME_NS(String):
pattern = Pattern(r'({PN_CHARS_BASE})((({PN_CHARS})|\.)*({PN_CHARS}))?'
.format(PN_CHARS=PN_CHARS.pattern, PN_CHARS_BASE=PN_CHARS_BASE.pattern))
class OPT_PNAME_NS(String):
pattern = Pattern(r'(({PN_CHARS_BASE})((({PN_CHARS})|\.)*({PN_CHARS}))?)?'
.format(PN_CHARS=PN_CHARS.pattern, PN_CHARS_BASE=PN_CHARS_BASE.pattern))
class PNAME_LOCAL(String):
pattern = Pattern(r'(({PN_CHARS_U})|[0-9])((({PN_CHARS})|\.)*({PN_CHARS}))?'.format(PN_CHARS_U=PN_CHARS_U.pattern, PN_CHARS=PN_CHARS.pattern))
class BLANK_NODE_LABEL(String):
pattern = Pattern(r'_:(({PN_CHARS_U})|[0-9])((({PN_CHARS})|\.)*({PN_CHARS}))?'.format(PN_CHARS=PN_CHARS.pattern, PN_CHARS_U=PN_CHARS_U.pattern))
class PNAME_LN(String):
pattern = Pattern(r'({PNAME_NS})?:{PNAME_LOCAL}'.format(PNAME_NS=PNAME_NS.pattern, PNAME_LOCAL=PNAME_LOCAL.pattern))
class QUOTED_STRING(String):
pattern = Pattern(r'^".*"$|.*')
python_type = Any
| 2.9375
| 3
|
scripts/generate_html.py
|
biancaitian/gurobi-official-examples
| 4
|
12778693
|
<reponame>biancaitian/gurobi-official-examples
import os
path = '../documents'
output = '../dist'
for root, dirs, files in os.walk(path):
for file in files:
# print(os.path.join(root,file))
if file.endswith(".ipynb"):
# 过滤掉 check point 的 ipynb
if file.find('-checkpoint') < 0:
# print(file.find('-checkpoint'))
print(root)
print(file)
os.system(
"jupyter nbconvert --to html " + os.path.join(root, file) + ' --output-dir ' + output)
| 2.75
| 3
|
DelibeRating/DelibeRating/deliberating-env/Lib/site-packages/etc/admin/__init__.py
|
Severose/DelibeRating
| 25
|
12778694
|
<reponame>Severose/DelibeRating<filename>DelibeRating/DelibeRating/deliberating-env/Lib/site-packages/etc/admin/__init__.py
from .admins import ReadonlyAdmin
from .models import CustomModelPage
| 1.054688
| 1
|
src/parse.py
|
Arsh25/Oracl
| 0
|
12778695
|
import pcapkit
import json
from pymongofunct import insert_data
def pcaptojson(file) -> dict:
return(pcapkit.extract(fin=file, nofile=True, format='json', auto=False,
engine='deafult', extension=False, layer='Transport', tcp=True, ip=True,strict=True, store=False))
def pcapparse(obj) -> dict:
main = {}
data = {}
pcap_dict = obj.info.info2dict()
try:
time = (pcap_dict['time_epoch'])
main["time_epoc"] = time
except KeyError:
pass
try:
macdstdirt = (pcap_dict['ethernet']['dst'])
macdst = []
for delim in macdstdirt:
if delim != '\'' and delim != '[' and delim != ']' and delim != ',' and delim != ' ':
macdst.append(delim)
finalmacdst = ''.join(macdst)
data["macdst"] = finalmacdst
except KeyError:
pass
try:
connecttype = (pcap_dict['ethernet']['type'])
data["type"] = str(connecttype)
except KeyError:
pass
try:
macsrcdirt = (pcap_dict['ethernet']['src'])
macsrc = []
for delim in macsrcdirt:
if delim != '\'' and delim != '[' and delim != ']' and delim != ',' and delim != ' ':
macsrc.append(delim)
finalmacsrc = ''.join(macsrc)
data["macsrc"] = finalmacsrc
except KeyError:
pass
try:
tcpdstport = (pcap_dict['ethernet']['ipv4']['tcp']['dstport'])
data["tcpdstport"] = tcpdstport
except KeyError:
pass
try:
tcpsrcport = (pcap_dict['ethernet']['ipv4']['tcp']['srcport'])
data["tcpsrcport"] = tcpsrcport
except KeyError:
pass
try:
udpdstport = (pcap_dict['ethernet']['ipv4']['udp']['dstport'])
data["udpdstport"] = udpdstport
except KeyError:
pass
try:
udpsrcport = (pcap_dict['ethernet']['ipv4']['udp']['srcport'])
data["udpsrcport"] = udpsrcport
except KeyError:
pass
try:
ipv4proto = (pcap_dict['ethernet']['ipv4']['proto'])
data["ipv4proto"] = str(ipv4proto)
except KeyError:
pass
try:
ipv4src = (pcap_dict['ethernet']['ipv4']['src'])
data["ipv4src"] = str(ipv4src)
except KeyError:
pass
try:
ipv4dst = (pcap_dict['ethernet']['ipv4']['dst'])
data["ipv4dst"] = str(ipv4dst)
except KeyError:
pass
try:
ipv6proto = (pcap_dict['ethernet']['ipv6']['proto'])
data["ipv6proto"] = str(ipv6proto)
except KeyError:
pass
try:
ipv6src = (pcap_dict['ethernet']['ipv6']['src'])
data["ipv6src"] = str(ipv6src)
except KeyError:
pass
try:
ipv6dst = (pcap_dict['ethernet']['ipv6']['dst'])
data["ipv6dst"] = str(ipv6dst)
except KeyError:
pass
try:
ipv6tcpdstport = (pcap_dict['ethernet']['ipv6']['tcp']['dstport'])
data["ipv6tcpdstport"] = ipv6tcpdstport
except KeyError:
pass
try:
ipv6tcpsrcport = (pcap_dict['ethernet']['ipv6']['tcp']['srcport'])
data["ipv6tcpsrcport"] = ipv6tcpsrcport
except KeyError:
pass
try:
ipv6udpdstport = (pcap_dict['ethernet']['ipv6']['udp']['dstport'])
data["ipv6udpdstport"] = ipv6udpdstport
except KeyError:
pass
try:
ipv6udpsrcport = (pcap_dict['ethernet']['ipv6']['udp']['srcport'])
data["ipv6udpsrcport"] = ipv6udpsrcport
except KeyError:
pass
main["data"] = data
insert_data('localhost','oracl','pcaps',main)
return main
def pcaplist(jsondict) -> list:
final = []
for obj in jsondict:
final.append(pcapparse(obj))
return final
def pcapwork(filename):
jsondict = pcaptojson(filename)
return pcaplist(jsondict)
| 2.671875
| 3
|
torchwi/loss/FreqLoss.py
|
pkgpl/TorchWI
| 5
|
12778696
|
import torch
import numpy as np
from torchwi.utils.ctensor import ca2rt, rt2ca
class FreqL2Loss(torch.autograd.Function):
@staticmethod
def forward(ctx, frd, true):
# resid: (nrhs, 2*nx) 2 for real and imaginary
resid = frd - true
resid_c = rt2ca(resid)
l2 = np.real(0.5*np.sum(resid_c*np.conjugate(resid_c)))
ctx.save_for_backward(resid)
return torch.tensor(l2)
@staticmethod
def backward(ctx, grad_output):
resid, = ctx.saved_tensors
grad_input = ca2rt(np.conjugate(rt2ca(resid)))
return grad_input, None
| 2.359375
| 2
|
venv/lib/python3.9/site-packages/setupcfg/options/__init__.py
|
xanderstevenson/devnet-support-helper
| 2
|
12778697
|
<filename>venv/lib/python3.9/site-packages/setupcfg/options/__init__.py
#!/usr/bin/env pythons
"""
http://setuptools.readthedocs.io/en/latest/setuptools.html#options
"""
KEYS = [
"zip_safe",
"setup_requires",
"install_requires",
"extras_require",
"python_requires",
"entry_points",
"use_2to3",
"use_2to3_fixers",
"use_2to3_exclude_fixers",
"convert_2to3_doctests",
"scripts",
"eager_resources",
"dependency_links",
"tests_require",
"include_package_data",
"packages",
"package_dir",
"package_data",
"exclude_package_data",
"namespace_packages",
"py_modules",
]
| 1.359375
| 1
|
main/aio/multi.py
|
chaosannals/trial-python
| 0
|
12778698
|
from asyncio import sleep, wait, get_event_loop, ensure_future
async def work(t):
await sleep(t)
print('time {}'.format(t))
return t
def on_done(t):
print(t.result())
async def main():
# 协程
coroutines = []
for i in range(2):
c = work(i)
print(type(c))
coroutines.append(c)
await wait(coroutines)
# 任务
tasks = []
for i in range(10):
c = work(i)
t = ensure_future(c)
t.add_done_callback(on_done)
print(type(t))
tasks.append(t)
await wait(tasks)
loop = get_event_loop()
loop.run_until_complete(main())
loop.close()
| 3.3125
| 3
|
main.py
|
arrickx/DateNotification
| 0
|
12778699
|
import csv
from datetime import datetime
aday,bday=[],[]
today = datetime.today().strftime('%m/%d')
with open('data.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if today in row['Birthday']:
bday.append([row['Name'], row['E-Mail'],row['Birthday']])
if today in row['Anniversary']:
aday.append([row['Name'], row['E-Mail'],row['Anniversary']])
for i in aday:
print(('Hi! %s')%(i[0]))
| 3.453125
| 3
|
data/preprocessed/extract-data.py
|
janfreyberg/healthy-brain-eeg
| 1
|
12778700
|
<filename>data/preprocessed/extract-data.py
from pathlib import Path
import os
import shutil
import sys
import platform
# where the compressed data is stored
datadir = Path('D:\\') / 'cmi-hbn'
# where 7zip is stored
if platform.system() == 'Windows':
zipcommand = '7z'
# find the compressed Files
tarfiles = datadir.glob('*.tar.gz')
# extraction
for tarfile in tarfiles:
# only proceed if there isn't a folder already:
subjectid = tarfile.name[:-7]
# extract the preproc eeg data
if not os.path.isdir(datadir / subjectid):
# build the command to extract
command = (
# extract the tar
zipcommand + ' x "' + str(tarfile) + '" -so | ' +
# extract the files
zipcommand + ' x -aoa -si -ttar -o' + '"' + str(datadir) + '"'
)
# run the command
print(command)
os.system(command)
# remove any unwanted files
try:
shutil.rmtree(datadir / subjectid / 'EEG' / 'raw')
except:
pass
try:
shutil.rmtree(datadir / subjectid / 'EEG' /
'preprocessed' / 'mat_format')
except:
pass
try:
shutil.rmtree(datadir / subjectid / 'Eyetracking' / 'idf')
except:
try:
shutil.rmtree(datadir / subjectid /
'Eyetracking' / 'idf_format')
except:
pass
# remove the TAR file itself
os.remove(tarfile)
| 2.796875
| 3
|
tests/ea/mutation/mutator/conftest.py
|
stevenbennett96/stk
| 21
|
12778701
|
import pytest
from pytest_lazyfixture import lazy_fixture
# Fixtures must be visible for lazy_fixture() calls.
from .fixtures import * # noqa
@pytest.fixture(
params=(
lazy_fixture('random_building_block'),
lazy_fixture('random_topology_graph'),
lazy_fixture('similar_building_block'),
lazy_fixture('random_mutator'),
),
)
def case_data(request):
return request.param
| 1.898438
| 2
|
setup.py
|
eduardogpg/pybose
| 3
|
12778702
|
<reponame>eduardogpg/pybose
from setuptools import setup, find_packages
from pathlib import Path
this_directory = Path(__file__).parent
# long_description = (this_directory / "README.md").read_text()
with open(this_directory / "README.md", encoding="utf8") as file:
long_description = file.read()
VERSION = '0.1.10'
DESCRIPTION = 'Python generator project'
setup(
name = 'pynumbat',
packages = ['pynumbat'],
entry_points={
"console_scripts":
["pynumbat=pynumbat.__main__:main"]
},
include_package_data=True,
version = VERSION,
license='MIT',
description = DESCRIPTION,
long_description_content_type="text/markdown",
long_description=long_description,
author = '<NAME>',
author_email = '<EMAIL>',
url = 'https://github.com/eduardogpg/pygenerate',
keywords = ['Python Generate', 'Generate', 'Project'],
install_requires=[
'click',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
],
)
| 1.671875
| 2
|
ffptutils/scripts/__init__.py
|
sekineh/ffptutils-py
| 0
|
12778703
|
__all__ = ['csv2ffpt', 'ffpt2csv']
| 1.070313
| 1
|
src/opendr/perception/activity_recognition/x3d/algorithm/x3d.py
|
makistsantekidis/opendr
| 217
|
12778704
|
<gh_stars>100-1000
""" Adapted from: https://github.com/facebookresearch/SlowFast
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from .head_helper import X3DHead
from .resnet_helper import ResStage
from .stem_helper import VideoModelStem
import pytorch_lightning as pl
class X3D(pl.LightningModule):
"""
X3D model,
adapted from https://github.com/facebookresearch/SlowFast
<NAME>.
"X3D: Expanding Architectures for Efficient Video Recognition."
https://arxiv.org/abs/2004.04730
"""
def __init__(
self,
dim_in: int,
image_size: int,
frames_per_clip: int,
num_classes: int,
conv1_dim: int,
conv5_dim: int,
num_groups: int,
width_per_group: int,
width_factor: float,
depth_factor: float,
bottleneck_factor: float,
use_channelwise_3x3x3: bool,
dropout_rate: float,
head_activation: str,
head_batchnorm: bool,
fc_std_init: float,
final_batchnorm_zero_init: bool,
loss_name="cross_entropy",
):
super().__init__()
self.norm_module = torch.nn.BatchNorm3d
self.loss_name = loss_name
exp_stage = 2.0
self.dim_conv1 = conv1_dim
self.dim_res2 = (
_round_width(self.dim_conv1, exp_stage, divisor=8)
if False # hparams.X3D.SCALE_RES2
else self.dim_conv1
)
self.dim_res3 = _round_width(self.dim_res2, exp_stage, divisor=8)
self.dim_res4 = _round_width(self.dim_res3, exp_stage, divisor=8)
self.dim_res5 = _round_width(self.dim_res4, exp_stage, divisor=8)
self.block_basis = [
# blocks, c, stride
[1, self.dim_res2, 2],
[2, self.dim_res3, 2],
[5, self.dim_res4, 2],
[3, self.dim_res5, 2],
]
num_groups = num_groups
width_per_group = width_per_group
dim_inner = num_groups * width_per_group
w_mul = width_factor
d_mul = depth_factor
dim_res1 = _round_width(self.dim_conv1, w_mul)
# Basis of temporal kernel sizes for each of the stage.
temp_kernel = [
[[5]], # conv1 temporal kernels.
[[3]], # res2 temporal kernels.
[[3]], # res3 temporal kernels.
[[3]], # res4 temporal kernels.
[[3]], # res5 temporal kernels.
]
self.s1 = VideoModelStem(
dim_in=[dim_in],
dim_out=[dim_res1],
kernel=[temp_kernel[0][0] + [3, 3]],
stride=[[1, 2, 2]],
padding=[[temp_kernel[0][0][0] // 2, 1, 1]],
norm_module=self.norm_module,
stem_func_name="x3d_stem",
)
# blob_in = s1
dim_in = dim_res1
dim_out = dim_in
for stage, block in enumerate(self.block_basis):
dim_out = _round_width(block[1], w_mul)
dim_inner = int(bottleneck_factor * dim_out)
n_rep = _round_repeats(block[0], d_mul)
prefix = "s{}".format(stage + 2) # start w res2 to follow convention
s = ResStage(
dim_in=[dim_in],
dim_out=[dim_out],
dim_inner=[dim_inner],
temp_kernel_sizes=temp_kernel[1],
stride=[block[2]],
num_blocks=[n_rep],
num_groups=[dim_inner] if use_channelwise_3x3x3 else [num_groups],
num_block_temp_kernel=[n_rep],
nonlocal_inds=[[]],
nonlocal_group=[1],
nonlocal_pool=[[1, 2, 2], [1, 2, 2]],
instantiation="dot_product",
trans_func_name="x3d_transform",
stride_1x1=False,
norm_module=self.norm_module,
dilation=[1],
drop_connect_rate=0.0,
)
dim_in = dim_out
self.add_module(prefix, s)
spat_sz = int(math.ceil(image_size / 32.0))
self.head = X3DHead(
dim_in=dim_out,
dim_inner=dim_inner,
dim_out=conv5_dim,
num_classes=num_classes,
pool_size=(frames_per_clip, spat_sz, spat_sz),
dropout_rate=dropout_rate,
act_func=head_activation,
bn_lin5_on=bool(head_batchnorm),
)
init_weights(self, fc_std_init, bool(final_batchnorm_zero_init))
def forward(self, x: Tensor):
# The original slowfast code was set up to use multiple paths, wrap the input
x = [x] # type:ignore
for module in self.children():
x = module(x)
return x
def training_step(self, batch, batch_idx):
x, y = batch
x = self.forward(x)
loss = getattr(F, self.loss_name, F.cross_entropy)(x, y)
self.log('train/loss', loss)
self.log('train/acc', _accuracy(x, y))
return loss
def validation_step(self, batch, batch_idx):
x, y = batch
x = self.forward(x)
loss = getattr(F, self.loss_name, F.cross_entropy)(x, y)
self.log('val/loss', loss)
self.log('val/acc', _accuracy(x, y))
return loss
def test_step(self, batch, batch_idx):
x, y = batch
x = self.forward(x)
loss = getattr(F, self.loss_name, F.cross_entropy)(x, y)
self.log('test/loss', loss)
self.log('test/acc', _accuracy(x, y))
return loss
def _accuracy(x: Tensor, y: Tensor):
return torch.sum(x.argmax(dim=1) == y) / len(y)
def _round_width(width, multiplier, min_depth=8, divisor=8):
"""Round width of filters based on width multiplier."""
if not multiplier:
return width
width *= multiplier
min_depth = min_depth or divisor
new_filters = max(min_depth, int(width + divisor / 2) // divisor * divisor)
if new_filters < 0.9 * width:
new_filters += divisor
return int(new_filters)
def _round_repeats(repeats, multiplier):
"""Round number of layers based on depth multiplier."""
multiplier = multiplier
if not multiplier:
return repeats
return int(math.ceil(multiplier * repeats))
def c2_msra_fill(module: nn.Module) -> None:
"""
Initialize `module.weight` using the "MSRAFill" implemented in Caffe2.
Also initializes `module.bias` to 0.
Args:
module (torch.nn.Module): module to initialize.
"""
# pyre-ignore
nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
if module.bias is not None: # pyre-ignore
nn.init.constant_(module.bias, 0)
def init_weights(model, fc_init_std=0.01, zero_init_final_bn=True):
"""
Performs ResNet style weight initialization.
Args:
fc_init_std (float): the expected standard deviation for fc layer.
zero_init_final_bn (bool): if True, zero initialize the final bn for
every bottleneck.
"""
for m in model.modules():
if isinstance(m, nn.Conv3d):
"""
Follow the initialization method proposed in:
{He, Kaiming, et al.
"Delving deep into rectifiers: Surpassing human-level
performance on imagenet classification."
arXiv preprint arXiv:1502.01852 (2015)}
"""
c2_msra_fill(m)
elif isinstance(m, nn.BatchNorm3d):
if (
hasattr(m, "transform_final_bn") and
m.transform_final_bn and
zero_init_final_bn
):
batchnorm_weight = 0.0
else:
batchnorm_weight = 1.0
if m.weight is not None:
m.weight.data.fill_(batchnorm_weight)
if m.bias is not None:
m.bias.data.zero_()
if isinstance(m, nn.Linear):
m.weight.data.normal_(mean=0.0, std=fc_init_std)
if m.bias is not None:
m.bias.data.zero_()
| 1.984375
| 2
|
test.py
|
mitmedialab/MediaCloud-WordEmbeddingsServer
| 0
|
12778705
|
import unittest
import sys
import os
import logging
from dotenv import load_dotenv
# load env-vars from .env file if there is one
basedir = os.path.abspath(os.path.dirname(__file__))
test_env = os.path.join(basedir, '.env')
if os.path.isfile(test_env):
load_dotenv(dotenv_path=os.path.join(basedir, '.env'), verbose=True)
import server.test.modelstest as models
test_classes = [
models.ModelsTest,
]
# set up all logging to DEBUG (cause we're running tests here!)
logging.basicConfig(level=logging.DEBUG)
log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
log_handler = logging.FileHandler(os.path.join('logs', 'test.log'))
log_handler.setFormatter(log_formatter)
# now run all the tests
suites = [unittest.TestLoader().loadTestsFromTestCase(test_class) for test_class in test_classes]
if __name__ == "__main__":
suite = unittest.TestSuite(suites)
test_result = unittest.TextTestRunner(verbosity=2).run(suite)
if not test_result.wasSuccessful():
sys.exit(1)
| 2.515625
| 3
|
app/settings/arq.py
|
leosussan/fastapi-gino-arq-postgres
| 289
|
12778706
|
<filename>app/settings/arq.py
from arq.connections import RedisSettings
from .globals import REDIS_IP, REDIS_PORT
settings = RedisSettings(host=REDIS_IP, port=REDIS_PORT)
| 1.46875
| 1
|
src/blrequests/authentication.py
|
circius/bl-requests
| 0
|
12778707
|
# -*- coding: utf-8 -*-
"""Encapsulates functions which handle credentials.
"""
from blrequests.data_definitions import Credentials
import subprocess
import configparser
import os.path
CONFIG_FILE = ".blrequestsrc"
CONFIG_FILE_EXISTS = os.path.exists(CONFIG_FILE)
def fetch_credentials() -> Credentials:
"""Produces a Credentials object based on the contents of the
CONFIG_FILE or, alternatively, interactively.
"""
if CONFIG_FILE_EXISTS:
return parse_config_file(CONFIG_FILE)
else:
return get_credentials_interactively()
def get_pass_output(parameter: str) -> str:
"""consumes a parameter for the GNU password manager PASS and
produces the corresponding output of that program.
"""
return subprocess.run(
["pass", parameter], capture_output=True, text=True
).stdout.strip()
def parse_config_file(filepath: str) -> Credentials:
"""Produces a Credentials object based on the contents of a config
file.
"""
config = configparser.ConfigParser()
config.read(filepath)
print(config)
print([config["Authentication"][option] for option in config["Authentication"]])
username, password, passeval = [
config["Authentication"][option] for option in config["Authentication"]
]
if passeval:
password = get_pass_output(passeval)
return (username, password)
def get_credentials_interactively() -> Credentials:
""" Gets credentials for the bl interactively
"""
return ("placeholder-user", "placeholder-pass")
| 3.3125
| 3
|
server/manager/dataManager.py
|
pengzhuo/gameServer
| 0
|
12778708
|
# coding: utf-8
import redis
from models.singleton import Singleton
from common.config import *
class DataManager:
__metaclass__ = Singleton
redis_instance = None # redis实例
def __init__(self):
self.redis_instance = redis.StrictRedis(REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_PASSWORD)
def save_room_info(self, room):
self.redis_instance.set("room:{0}".format(room.room_id), room.toJson())
def get_room_info(self, room_id):
return self.redis_instance.get("room:{0}".format(room_id))
def save_user_info(self, user):
self.redis_instance.set("user:{0}".format(user.userId), user.toJson())
def get_user_info(self, uuid):
return self.redis_instance.get("user:{0}".format(uuid))
data_manager = DataManager()
| 2.484375
| 2
|
lfs/criteria/models/criteria.py
|
naro/django-lfs
| 0
|
12778709
|
<gh_stars>0
# django imports
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.contenttypes import generic
from django.db import models
from django.utils.translation import ugettext_lazy as _, ugettext
from django.template import RequestContext
from django.template.loader import render_to_string
# lfs imports
import lfs.core.utils
from lfs import shipping
from lfs.caching.utils import lfs_get_object_or_404
from lfs.core.models import Shop, Country
from lfs.criteria.models.criteria_objects import CriteriaObjects
from lfs.criteria.settings import EQUAL
from lfs.criteria.settings import LESS_THAN
from lfs.criteria.settings import LESS_THAN_EQUAL
from lfs.criteria.settings import GREATER_THAN
from lfs.criteria.settings import GREATER_THAN_EQUAL
from lfs.criteria.settings import NUMBER_OPERATORS
from lfs.criteria.settings import SELECT_OPERATORS
from lfs.criteria.settings import IS, IS_NOT, IS_VALID, IS_NOT_VALID
from lfs.payment.models import PaymentMethod
from lfs.shipping.models import ShippingMethod
class Criterion(object):
"""Base class for all lfs criteria.
"""
class Meta:
app_label = "criteria"
def as_html(self, request, position):
"""Renders the criterion as html in order to displayed it within several
forms.
"""
template = "manage/criteria/%s_criterion.html" % self.content_type
return render_to_string(template, RequestContext(request, {
"id": "%s%s" % (self.content_type, self.id),
"operator": self.operator,
"value": self.value,
"position": position,
}))
class CartPriceCriterion(models.Model, Criterion):
"""A criterion for the cart price.
"""
operator = models.PositiveIntegerField(_(u"Operator"), blank=True, null=True, choices=NUMBER_OPERATORS)
price = models.FloatField(_(u"Price"), default=0.0)
def __unicode__(self):
return ugettext("Cart Price: %(operator)s %(price)s") % {'operator': self.get_operator_display(), 'price': self.price}
@property
def content_type(self):
"""Returns the content_type of the criterion as lower string.
This is for instance used to select the appropriate form for the
criterion.
"""
return u"price"
@property
def name(self):
"""Returns the descriptive name of the criterion.
"""
return ugettext(u"Cart Price")
def is_valid(self, request, product=None):
"""Returns True if the criterion is valid.
If product is given the price is taken from the product otherwise from
the cart.
"""
if product is not None:
cart_price = product.get_price(request)
else:
from lfs.cart import utils as cart_utils
cart = cart_utils.get_cart(request)
if cart is None:
return False
cart_price = cart.get_price_gross(request)
if self.operator == LESS_THAN and (cart_price < self.price):
return True
if self.operator == LESS_THAN_EQUAL and (cart_price <= self.price):
return True
if self.operator == GREATER_THAN and (cart_price > self.price):
return True
if self.operator == GREATER_THAN_EQUAL and (cart_price >= self.price):
return True
if self.operator == EQUAL and (cart_price == self.price):
return True
return False
@property
def value(self):
"""Returns the value of the criterion.
"""
return self.price
class CombinedLengthAndGirthCriterion(models.Model, Criterion):
"""A criterion for the combined length and girth.
"""
operator = models.PositiveIntegerField(_(u"Operator"), blank=True, null=True, choices=NUMBER_OPERATORS)
clag = models.FloatField(_(u"Width"), default=0.0)
def __unicode__(self):
return ugettext("CLAG: %(operator)s %(clag)s") % {'operator': self.get_operator_display(),
'clag': self.clag}
@property
def content_type(self):
"""Returns the content_type of the criterion as lower string.
This is for instance used to select the appropriate form for the
criterion.
"""
return u"combinedlengthandgirth"
@property
def name(self):
"""Returns the descriptive name of the criterion.
"""
return ugettext(u"Combined length and girth")
def is_valid(self, request, product=None):
"""Returns True if the criterion is valid.
If product is given the combined length and girth is taken from the
product otherwise from the cart.
"""
if product is not None:
clag = (2 * product.get_width()) + (2 * product.get_height()) + product.get_length()
else:
from lfs.cart import utils as cart_utils
cart = cart_utils.get_cart(request)
if cart is None:
return False
cart_clag = 0
max_width = 0
max_length = 0
total_height = 0
for item in cart.get_items():
if max_length < item.product.get_length():
max_length = item.product.get_length()
if max_width < item.product.get_width():
max_width = item.product.get_width()
total_height += item.product.get_height()
clag = (2 * max_width) + (2 * total_height) + max_length
if self.operator == LESS_THAN and (clag < self.clag):
return True
if self.operator == LESS_THAN_EQUAL and (clag <= self.clag):
return True
if self.operator == GREATER_THAN and (clag > self.clag):
return True
if self.operator == GREATER_THAN_EQUAL and (clag >= self.clag):
return True
if self.operator == EQUAL and (clag == self.clag):
return True
return False
@property
def value(self):
"""Returns the value of the criterion.
"""
return self.clag
class CountryCriterion(models.Model, Criterion):
"""A criterion for the shipping country.
"""
operator = models.PositiveIntegerField(_(u"Operator"), blank=True, null=True, choices=SELECT_OPERATORS)
countries = models.ManyToManyField(Country, verbose_name=_(u"Countries"))
def __unicode__(self):
values = []
for value in self.value.all():
values.append(value.name)
return ugettext("Country: %(operator)s %(countries)s") % {'operator': self.get_operator_display(),
'countries': ", ".join(values)}
@property
def content_type(self):
"""Returns the content_type of the criterion as lower string.
This is for instance used to select the appropriate form for the
criterion.
"""
return u"country"
@property
def name(self):
"""Returns the descriptive name of the criterion.
"""
return ugettext(u"Country")
def is_valid(self, request, product=None):
"""Returns True if the criterion is valid.
"""
country = shipping.utils.get_selected_shipping_country(request)
if self.operator == IS:
return country in self.countries.all()
else:
return country not in self.countries.all()
@property
def value(self):
"""Returns the value of the criterion.
"""
return self.countries
def as_html(self, request, position):
"""Renders the criterion as html in order to be displayed within several
forms.
"""
shop = lfs_get_object_or_404(Shop, pk=1)
countries = []
for country in shop.shipping_countries.all():
if country in self.countries.all():
selected = True
else:
selected = False
countries.append({
"id": country.id,
"name": country.name,
"selected": selected,
})
return render_to_string("manage/criteria/country_criterion.html", RequestContext(request, {
"id": "%s%s" % (self.content_type, self.id),
"operator": self.operator,
"value": self.value,
"position": position,
"countries": countries,
}))
class HeightCriterion(models.Model, Criterion):
"""
"""
operator = models.PositiveIntegerField(blank=True, null=True, choices=NUMBER_OPERATORS)
height = models.FloatField(_(u"Height"), default=0.0)
def __unicode__(self):
return ugettext("Height: %(operator)s %(height)s") % {'operator': self.get_operator_display(),
'height': self.height}
@property
def content_type(self):
"""Returns the content_type of the criterion as lower string.
This is for instance used to select the appropriate form for the
criterion.
"""
return u"height"
@property
def name(self):
"""Returns the descriptive name of the criterion.
"""
return ugettext(u"Height")
def is_valid(self, request, product=None):
"""Returns True if the criterion is valid.
If product is given the height is taken from the product otherwise from
the cart.
"""
if product is not None:
cart_height = product.get_height()
else:
from lfs.cart import utils as cart_utils
cart = cart_utils.get_cart(request)
if cart is None:
return False
cart_height = 0
for item in cart.get_items():
cart_height += (item.product.get_height() * item.amount)
if self.operator == LESS_THAN and (cart_height < self.height):
return True
if self.operator == LESS_THAN_EQUAL and (cart_height <= self.height):
return True
if self.operator == GREATER_THAN and (cart_height > self.height):
return True
if self.operator == GREATER_THAN_EQUAL and (cart_height >= self.height):
return True
if self.operator == EQUAL and (cart_height == self.height):
return True
return False
@property
def value(self):
"""Returns the value of the criterion.
"""
return self.height
class LengthCriterion(models.Model, Criterion):
"""A criterion for the length.
"""
operator = models.PositiveIntegerField(_(u"Operator"), blank=True, null=True, choices=NUMBER_OPERATORS)
length = models.FloatField(_(u"Length"), default=0.0)
def __unicode__(self):
return ugettext("Length: %(operator)s %(length)s") % {'operator': self.get_operator_display(),
'length': self.length}
@property
def content_type(self):
"""Returns the content_type of the criterion as lower string.
This is for instance used to select the appropriate form for the
criterion.
"""
return u"length"
@property
def name(self):
"""Returns the descriptive name of the criterion.
"""
return ugettext(u"Length")
def is_valid(self, request, product=None):
"""Returns True if the criterion is valid.
If product is given the length is taken from the product otherwise from
the cart.
"""
if product is not None:
max_length = product.get_length()
else:
from lfs.cart import utils as cart_utils
cart = cart_utils.get_cart(request)
if cart is None:
return False
max_length = 0
for item in cart.get_items():
if max_length < item.product.get_length():
max_length = item.product.get_length()
if self.operator == LESS_THAN and (max_length < self.length):
return True
if self.operator == LESS_THAN_EQUAL and (max_length <= self.length):
return True
if self.operator == GREATER_THAN and (max_length > self.length):
return True
if self.operator == GREATER_THAN_EQUAL and (max_length >= self.length):
return True
if self.operator == EQUAL and (max_length == self.length):
return True
return False
@property
def value(self):
"""Returns the value of the criterion.
"""
return self.length
class PaymentMethodCriterion(models.Model, Criterion):
"""A criterion for the payment method.
"""
operator = models.PositiveIntegerField(_(u"Operator"), blank=True, null=True, choices=SELECT_OPERATORS)
payment_methods = models.ManyToManyField(PaymentMethod, verbose_name=_(u"Payment methods"))
criteria_objects = generic.GenericRelation(CriteriaObjects,
object_id_field="criterion_id", content_type_field="criterion_type")
def __unicode__(self):
values = []
for value in self.value.all():
values.append(value.name)
return ugettext("Payment: %(operator)s %(payments)s") % {'operator': self.get_operator_display(),
'payments': ", ".join(values)}
@property
def content_type(self):
"""Returns the content_type of the criterion as lower string.
This is for instance used to select the appropriate form for the
criterion.
"""
return u"payment_method"
@property
def name(self):
"""Returns the descriptive name of the criterion.
"""
return ugettext(u"Payment method")
def is_valid(self, request, product=None):
"""Returns True if the criterion is valid.
"""
# see ShippingMethodCriterion for what's going on here
import lfs.shipping.utils
content_object = self.criteria_objects.filter()[0].content
if isinstance(content_object, PaymentMethod):
is_payment_method = True
else:
is_payment_method = False
if not is_payment_method and self.operator == IS:
payment_method = lfs.payment.utils.get_selected_payment_method(request)
return payment_method in self.payment_methods.all()
elif not is_payment_method and self.operator == IS_NOT:
payment_method = lfs.payment.utils.get_selected_payment_method(request)
return payment_method not in self.payment_methods.all()
elif self.operator == IS_VALID:
for pm in self.payment_methods.all():
if not lfs.criteria.utils.is_valid(request, pm, product):
return False
return True
elif self.operator == IS_NOT_VALID:
for pm in self.payment_methods.all():
if lfs.criteria.utils.is_valid(request, pm, product):
return False
return True
else:
return False
@property
def value(self):
"""Returns the value of the criterion.
"""
return self.payment_methods
def as_html(self, request, position):
"""Renders the criterion as html in order to be displayed within several
forms.
"""
selected_payment_methods = self.payment_methods.all()
payment_methods = []
for pm in PaymentMethod.objects.filter(active=True):
if pm in selected_payment_methods:
selected = True
else:
selected = False
payment_methods.append({
"id": pm.id,
"name": pm.name,
"selected": selected,
})
return render_to_string("manage/criteria/payment_method_criterion.html", RequestContext(request, {
"id": "%s%s" % (self.content_type, self.id),
"operator": self.operator,
"value": self.value,
"position": position,
"payment_methods": payment_methods,
}))
class ShippingMethodCriterion(models.Model, Criterion):
"""A criterion for the shipping method.
"""
operator = models.PositiveIntegerField(_(u"Operator"), blank=True, null=True, choices=SELECT_OPERATORS)
shipping_methods = models.ManyToManyField(ShippingMethod, verbose_name=_(u"Shipping methods"))
criteria_objects = generic.GenericRelation(CriteriaObjects,
object_id_field="criterion_id", content_type_field="criterion_type")
def __unicode__(self):
values = []
for value in self.value.all():
values.append(value.name)
return ugettext("Shipping: %(operator)s %(shipping)s") % {'operator': self.get_operator_display(),
'shipping': ", ".join(values)}
@property
def content_type(self):
"""Returns the content_type of the criterion as lower string.
This is for instance used to select the appropriate form for the
criterion.
"""
return u"shipping_method"
@property
def name(self):
"""Returns the descriptive name of the criterion.
"""
return ugettext(u"Shipping method")
def is_valid(self, request, product=None):
"""Returns True if the criterion is valid.
"""
# Check whether the criteria is part of a shipping method if so the
# operator IS and IS_NOT are not allowed. This will later exluded by the
# UID.
# The reason why we have to check this is that the get_selected_shipping_method
# checks for valid shipping methods and call this method again, so that
# we get an infinte recursion.
import lfs.shipping.utils
content_object = self.criteria_objects.filter()[0].content
if isinstance(content_object, ShippingMethod):
is_shipping_method = True
else:
is_shipping_method = False
if not is_shipping_method and self.operator == IS:
shipping_method = lfs.shipping.utils.get_selected_shipping_method(request)
return shipping_method in self.shipping_methods.all()
elif not is_shipping_method and self.operator == IS_NOT:
shipping_method = lfs.shipping.utils.get_selected_shipping_method(request)
return shipping_method not in self.shipping_methods.all()
elif self.operator == IS_VALID:
for sm in self.shipping_methods.all():
if not lfs.criteria.utils.is_valid(request, sm, product):
return False
return True
elif self.operator == IS_NOT_VALID:
for sm in self.shipping_methods.all():
if lfs.criteria.utils.is_valid(request, sm, product):
return False
return True
else:
return False
@property
def value(self):
"""Returns the value of the criterion.
"""
return self.shipping_methods
def as_html(self, request, position):
"""Renders the criterion as html in order to be displayed within several
forms.
"""
selected_shipping_methods = self.shipping_methods.all()
shipping_methods = []
for sm in ShippingMethod.objects.filter(active=True):
if sm in selected_shipping_methods:
selected = True
else:
selected = False
shipping_methods.append({
"id": sm.id,
"name": sm.name,
"selected": selected,
})
return render_to_string("manage/criteria/shipping_method_criterion.html", RequestContext(request, {
"id": "%s%s" % (self.content_type, self.id),
"operator": self.operator,
"value": self.value,
"position": position,
"shipping_methods": shipping_methods,
}))
class UserCriterion(models.Model, Criterion):
"""A criterion for user content objects
"""
users = models.ManyToManyField(User)
@property
def content_type(self):
"""Returns the content_type of the criterion as lower string.
This is for instance used to select the appropriate form for the
criterion.
"""
return u"user"
@property
def name(self):
"""Returns the descriptive name of the criterion.
"""
return ugettext(u"User")
def is_valid(self, request, product=None):
"""Returns True if the criterion is valid.
"""
return request.user in self.users.all()
@property
def value(self):
"""Returns the value of the criterion.
"""
return self.users
class WeightCriterion(models.Model, Criterion):
"""
"""
operator = models.PositiveIntegerField(_(u"Operator"), blank=True, null=True, choices=NUMBER_OPERATORS)
weight = models.FloatField(_(u"Weight"), default=0.0)
def __unicode__(self):
return ugettext("Weight: %(operator)s %(weight)s") % {'operator': self.get_operator_display(),
'weight': self.weight}
@property
def content_type(self):
"""Returns the content_type of the criterion as lower string.
This is for instance used to select the appropriate form for the
criterion.
"""
return u"weight"
@property
def name(self):
"""Returns the descriptive name of the criterion.
"""
return ugettext(u"Weight")
def is_valid(self, request, product=None):
"""Returns True if the criterion is valid.
If product is given the weight is taken from the product otherwise from
the cart.
"""
if product is not None:
cart_weight = product.get_weight()
else:
from lfs.cart import utils as cart_utils
cart = cart_utils.get_cart(request)
if cart is None:
return False
cart_weight = 0
for item in cart.get_items():
cart_weight += (item.product.get_weight() * item.amount)
if self.operator == LESS_THAN and (cart_weight < self.weight):
return True
if self.operator == LESS_THAN_EQUAL and (cart_weight <= self.weight):
return True
if self.operator == GREATER_THAN and (cart_weight > self.weight):
return True
if self.operator == GREATER_THAN_EQUAL and (cart_weight >= self.weight):
return True
if self.operator == EQUAL and (cart_weight == self.weight):
return True
return False
@property
def value(self):
"""Returns the value of the criterion.
"""
return self.weight
class WidthCriterion(models.Model, Criterion):
"""
"""
operator = models.PositiveIntegerField(_(u"Operator"), blank=True, null=True, choices=NUMBER_OPERATORS)
width = models.FloatField(_(u"Width"), default=0.0)
def __unicode__(self):
return ugettext("Width: %(operator)s %(width)s") % {'operator': self.get_operator_display(),
'width': self.width}
@property
def content_type(self):
"""Returns the content_type of the criterion as lower string.
This is for instance used to select the appropriate form for the
criterion.
"""
return u"width"
@property
def name(self):
"""Returns the descriptive name of the criterion.
"""
return ugettext(u"Height")
def is_valid(self, request, product=None):
"""Returns True if the criterion is valid.
If product is given the width is taken from the product otherwise from
the cart.
"""
if product is not None:
max_width = product.get_width()
else:
from lfs.cart import utils as cart_utils
cart = cart_utils.get_cart(request)
if cart is None:
return False
max_width = 0
for item in cart.get_items():
if max_width < item.product.get_width():
max_width = item.product.get_width()
if self.operator == LESS_THAN and (max_width < self.width):
return True
if self.operator == LESS_THAN_EQUAL and (max_width <= self.width):
return True
if self.operator == GREATER_THAN and (max_width > self.width):
return True
if self.operator == GREATER_THAN_EQUAL and (max_width >= self.width):
return True
if self.operator == EQUAL and (max_width == self.width):
return True
return False
@property
def value(self):
"""Returns the value of the criterion.
"""
return self.width
class DistanceCriterion(models.Model, Criterion):
"""
"""
operator = models.PositiveIntegerField(_(u"Operator"), blank=True, null=True, choices=NUMBER_OPERATORS)
distance = models.FloatField(_(u"Distance"), default=0.0)
module = models.CharField(blank=True, max_length=100)
def __unicode__(self):
return ugettext("Distance: %(operator)s %(distance)s") % {'operator': self.get_operator_display(),
'distance': self.distance}
@property
def content_type(self):
"""Returns the content_type of the criterion as lower string.
This is for instance used to select the appropriate form for the
criterion.
"""
return u"distance"
@property
def name(self):
"""Returns the descriptive name of the criterion.
"""
return ugettext(u"Distance")
def is_valid(self, request, product=None):
"""Returns True if the criterion is valid.
"""
try:
m = lfs.core.utils.import_module(settings.LFS_DISTANCE_MODULE)
current_distance = m.get_distance(request)
except (ImportError, AttributeError):
current_distance = 0
if self.operator == LESS_THAN and (current_distance < self.distance):
return True
if self.operator == LESS_THAN_EQUAL and (current_distance <= self.distance):
return True
if self.operator == GREATER_THAN and (current_distance > self.distance):
return True
if self.operator == GREATER_THAN_EQUAL and (current_distance >= self.distance):
return True
if self.operator == EQUAL and (current_distance == self.distance):
return True
return False
@property
def value(self):
"""Returns the value of the criterion.
"""
return self.distance
| 2.0625
| 2
|
engram/result.py
|
rgrannell1/engram.py
| 0
|
12778710
|
<filename>engram/result.py
#!/usr/bin/env python3
import traceback
import logging
logger = logging.getLogger(__name__)
class Result(object):
def __init__(self, value):
self.value = value.value if isinstance(value, Result) else value
@staticmethod
def of(fn):
"""Create a Result from the return result of a normal function.
"""
return Ok(None).then(lambda _: fn( ))
def from_ok(self):
"""Extract the contents of a Ok object
Throws a TypeError when called on a non-success object.
>> Err('contents').from_ok()
'contents'
>> Ok('contents').from_ok()
TypeError('attempted to call from_ok on a Err object.')
"""
if isinstance(self, Ok):
return self.value
elif isinstance(self, Err):
raise TypeError("attempted to call from_ok on a Err object.")
def from_err(self):
"""Extract the contents of a Err object
Throws a TypeError when called on a non-failure object.
>> Err('contents').from_err()
'contents'
>> Ok('contents').from_err()
TypeError('attempted to call from_err on a Ok object.')
"""
if isinstance(self, Err):
return self.value
elif isinstance(self, Self):
raise TypeError("attempted to call from_err on a Ok object.")
def is_ok(self):
"""Is this Result a Ok instance?
"""
return isinstance(self, Ok)
def is_err(self):
"""Is this Result a Err instance?
"""
return isinstance(self, Err)
class Err(Result):
def __init__(self, value):
self.value = value.value if isinstance(value, Result) else value
logging.error(self.value)
#traceback.print_exc()
def __str__(self):
return "Err(%s)" % (str(self.value))
def then(self, fn):
return self
def tap(self, fn):
return self
def product_of(self):
return self
def cross(self, results):
return self
class Ok(Result):
def __init__(self, value):
super(Ok, self).__init__(value)
def __str__(self):
return "Ok(%s)" % (str(self.value))
def then(self, fn):
try:
result = fn(self.value)
if isinstance(result, Err):
return result
else:
return Ok(result)
except Exception as err:
return Err(err)
return result
def tap(self, fn):
"""apply a function to a Result object, but only keep the new result if the call fails.
"""
result = self.then(fn)
if isinstance(result, Err):
return result
else:
return self
def cross(self, results):
"""get the product of two Result object.
>> Ok('a').cross(Ok(['b']))
Ok(['a', 'b'])
"""
values = [self.value]
for result in results:
if not isinstance(result, Result):
raise Exception("result wasn't a Result instance.")
if isinstance(result, Ok):
values.append(result.value)
else:
return result
return Ok(values)
def product_of(self):
values = []
for result in self.value:
if not isinstance(result, Result):
raise Exception("result wasn't a Result instance.")
if isinstance(result, Ok):
values.append(result.value)
else:
return result
return Ok(values)
| 2.8125
| 3
|
src/preprocess.py
|
mjpekala/faster-membranes
| 0
|
12778711
|
""" Preprocess the ISBI data set.
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2015, JHU/APL"
__license__ = "Apache 2.0"
import argparse, os.path
import numpy as np
from scipy.stats.mstats import mquantiles
import scipy.io
import emlib
def get_args():
"""Command line parameters for the 'deploy' procedure.
You will probably want to override the train/valid/test split
to better suit your problem of interest...
"""
parser = argparse.ArgumentParser()
parser.add_argument('-X', dest='dataFileName', type=str, required=True,
help='EM data file')
parser.add_argument('-Y', dest='labelsFileName', type=str, required=True,
help='Ground truth labels for X')
parser.add_argument('--train-slices', dest='trainSlices',
type=str, default='range(10)',
help='which slices to use for training')
parser.add_argument('--valid-slices', dest='validSlices',
type=str, default='range(10,20)',
help='which slices to use for validation')
parser.add_argument('--test-slices', dest='testSlices',
type=str, default='range(20,30)',
help='which slices to use for test')
parser.add_argument('--brightness-quantile', dest='brightQuant',
type=float, default=0.97,
help='top quantile for non-membrane pixels.')
parser.add_argument('--out-dir', dest='outDir',
type=str, default='./',
help='output directory')
args = parser.parse_args()
assert(args.brightQuant <= 1.0)
assert(args.brightQuant > 0)
# map strings to python objects (XXX: a cleaner way than eval)
args.trainSlices = eval(args.trainSlices)
args.validSlices = eval(args.validSlices)
args.testSlices = eval(args.testSlices)
return args
if __name__ == "__main__":
args = get_args();
#outDir = os.path.split(args.dataFileName)[0]
if not os.path.isdir(args.outDir):
os.mkdir(args.outDir)
X = emlib.load_cube(args.dataFileName, np.uint8)
Y = emlib.load_cube(args.labelsFileName, np.uint8)
# remap Y labels from ISBI convention to membrane-vs-non-membrane
Y[Y==0] = 1; # membrane
Y[Y==255] = 0; # non-membrane
# change type of Y so can use -1 as a value.
Y = Y.astype(np.int8)
Xtrain = X[args.trainSlices,:,:]; Ytrain = Y[args.trainSlices,:,:]
Xvalid = X[args.validSlices,:,:]; Yvalid = Y[args.validSlices,:,:]
Xtest = X[args.testSlices,:,:]; Ytest = Y[args.testSlices,:,:]
# brightness thresholding
thresh = mquantiles(np.concatenate((Xtrain[Ytrain==1], Xvalid[Yvalid==1])), args.brightQuant)
pctOmitted = 100.0*np.sum(X > thresh) / np.prod(np.size(X))
print('[preprocess]: percent of pixels omitted by brightness filter: %0.2f' % pctOmitted)
Ytrain[Xtrain > thresh] = -1
Yvalid[Xvalid > thresh] = -1
Ytest[Xtest > thresh] = -1
# save results
np.save(os.path.join(args.outDir, 'Xtrain.npy'), Xtrain)
np.save(os.path.join(args.outDir, 'Ytrain.npy'), Ytrain)
np.save(os.path.join(args.outDir, 'Xvalid.npy'), Xvalid)
np.save(os.path.join(args.outDir, 'Yvalid.npy'), Yvalid)
if Xtest.size > 0:
np.save(os.path.join(args.outDir, 'Xtest.npy'), Xtest)
np.save(os.path.join(args.outDir, 'Ytest.npy'), Ytest)
# also a matlab version
scipy.io.savemat(os.path.join(args.outDir, 'Xtrain.mat'), {'Xtrain' : Xtrain})
scipy.io.savemat(os.path.join(args.outDir, 'Ytrain.mat'), {'Ytrain' : Ytrain})
scipy.io.savemat(os.path.join(args.outDir, 'Xvalid.mat'), {'Xvalid' : Xvalid})
scipy.io.savemat(os.path.join(args.outDir, 'Yvalid.mat'), {'Yvalid' : Yvalid})
if Xtest.size > 0:
scipy.io.savemat(os.path.join(args.outDir, 'Xtest.mat'), {'Xtest' : Xtest})
scipy.io.savemat(os.path.join(args.outDir, 'Ytest.mat'), {'Ytest' : Ytest})
print('[preprocess]: done!')
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
| 2.3125
| 2
|
config/config.py
|
KingsleyXie/Yatpd
| 1
|
12778712
|
import yaml
def get(filename='config/config.yaml'):
with open(filename, 'r') as stream:
data = yaml.safe_load(stream)
return data
if __name__ == '__main__':
print(get())
| 2.4375
| 2
|
django_double_accounting/blackbook/charts.py
|
bsiebens/django-double-accounting
| 0
|
12778713
|
<gh_stars>0
from datetime import timedelta, date
from .models import CurrencyConversion
import json
def get_color_code(i):
color_codes = ["98, 181, 229", "134, 188, 37", "152, 38, 73", "124, 132, 131", "213, 216, 135", "247, 174, 248"]
color = (i - 1) % len(color_codes)
return color_codes[color]
class Chart:
def __init__(self, data):
self.data = data
def generate_json(self):
chart_data = self._generate_chart_data()
chart_options = self._generate_chart_options()
chart_data["options"] = chart_options
return json.dumps(chart_data).replace('"<<', "").replace('>>"', "")
def _generate_chart_data(self):
raise NotImplementedError
def _generate_chart_options(self):
return self._get_default_options()
def _get_default_options(self):
return {
"maintainAspectRatio": False,
"legend": {
"display": False,
},
"animation": {"duration": 0},
"responsive": True,
"tooltips": {
"backgroundColor": "#f5f5f5",
"titleFontColor": "#333",
"bodyFontColor": "#666",
"bodySpacing": 4,
"xPadding": 12,
"mode": "nearest",
"intersect": 0,
"position": "nearest",
},
"scales": {
"yAxes": [
{
"barPercentage": 1.6,
"gridLines": {"drawBorder": False, "color": "rgba(225,78,202,0.1)", "zeroLineColor": "transparent"},
"ticks": {"padding": 20, "fontColor": "#9a9a9a"},
}
],
"xAxes": [
{
"type": "time",
"time": {"unit": "day"},
"barPercentage": 1.6,
"gridLines": {"drawBorder": False, "color": "rgba(225,78,202,0.1)", "zeroLineColor": "transparent"},
"ticks": {"padding": 20, "fontColor": "#9a9a9a"},
}
],
},
}
class AccountChart(Chart):
def __init__(self, data, accounts, start_date, end_date, *args, **kwargs):
self.start_date = start_date
self.end_date = end_date
self.accounts = accounts
super().__init__(data=data, *args, **kwargs)
def _generate_chart_options(self):
options = self._get_default_options()
# options["tooltips"]["callbacks"] = {
# "label": "<<function(tooltipItems, data) { return data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.yLabel + ' (%s)'; }>>"
# % get_currency(self.currency, self.user)
# }
if abs((self.end_date - self.start_date).days) > 150:
options["scales"]["xAxes"][0]["time"]["unit"] = "week"
return options
def _generate_chart_data(self):
dates = []
for days_to_add in range(abs((self.end_date - self.start_date).days) + 1):
day = self.start_date + timedelta(days=days_to_add)
dates.append(day)
data = {"type": "line", "data": {"labels": [date.strftime("%d %b %Y") for date in dates], "datasets": []}}
accounts = {}
for item in self.data:
account_key = "{account} - {currency}".format(account=item.account.accountstring, currency=item.currency)
if account_key in accounts.keys():
accounts[account_key][item.journal_entry.date] = accounts[account_key].get(item.journal_entry.date, 0) + item.amount
else:
accounts[account_key] = {item.journal_entry.date: item.amount}
for account in self.accounts:
for currency in account.currencies.all():
account_key = "{account} - {currency}".format(account=account.accountstring, currency=currency.code)
if account_key not in accounts.keys():
accounts[account_key] = {}
start_balance = account.balance_until_date(self.start_date - timedelta(days=1))
for currency in start_balance:
account_key = "{account} - {currency}".format(account=account.accountstring, currency=currency[1])
if account_key in accounts.keys():
accounts[account_key][self.start_date] = accounts[account_key].get(self.start_date, 0) + currency[0]
else:
accounts[account_key] = {self.start_date: currency[0]}
counter = 1
for account, date_entries in accounts.items():
color = get_color_code(counter)
counter += 1
account_data = {
"label": account,
"fill": "!1",
"borderColor": "rgba({color}, 1.0)".format(color=color),
"borderWidth": 2,
"borderDash": [],
"borderDash0ffset": 0,
"pointBackgroundColor": "rgba({color}, 1.0)".format(color=color),
"pointBorderColor": "rgba(255,255,255,0)",
"pointHoverBackgroundColor": "rgba({color}, 1.0)".format(color=color),
"pointBorderWidth": 20,
"pointHoverRadius": 4,
"pointHoverBorderWidth": 15,
"pointRadius": 4,
"data": [],
}
if abs((self.end_date - self.start_date).days) > 150:
account_data["pointRadius"] = 0
for date_index in range(len(dates)):
date = dates[date_index]
value = 0
if date_index != 0:
value = account_data["data"][date_index - 1]
if date in date_entries.keys():
value += float(date_entries[date])
account_data["data"].append(round(value, 2))
data["data"]["datasets"].append(account_data)
return data
class TransactionChart(Chart):
def __init__(self, data, payee=False, expenses_budget=False, expenses_tag=False, *args, **kwargs):
self.payee = payee
self.expenses_budget = expenses_budget
self.expenses_tag = expenses_tag
super().__init__(data=data, *args, **kwargs)
def _generate_chart_options(self):
options = self._get_default_options()
options["scales"] = {}
options["legend"] = {"position": "right"}
return options
def _generate_chart_data(self):
data = {
"type": "pie",
"data": {
"labels": [],
"datasets": [
{
"data": [],
"borderWidth": [],
"backgroundColor": [],
"borderColor": [],
},
],
},
}
amounts = {}
self.data = [item for item in self.data if item.amount < 0]
for transaction in self.data:
series_name = "Unknown - {currency}".format(currency=transaction.currency.code)
if self.payee:
if transaction.journal_entry.payee is not None:
series_name = "{name} - {currency}".format(name=transaction.journal_entry.payee, currency=transaction.currency.code)
amounts[series_name] = amounts.get(series_name, 0) + float(transaction.amount)
elif self.expenses_tag:
for tag in transaction.journal_entry.tags.all():
series_name = "{name} - {currency}".format(name=tag, currency=transaction.currency.code)
amounts[series_name] = amounts.get(series_name, 0) + float(transaction.amount)
elif self.expenses_budget:
for budget in transaction.journal_entry.budgets.all():
series_name = "{name} - {currency}".format(name=budget.name, currency=budget.currency.code)
amounts[series_name] = amounts.get(series_name, 0) + float(
CurrencyConversion.convert(base_currency=transaction.currency, target_currency=budget.currency, amount=transaction.amount)
)
else:
amounts[series_name] = amounts.get(series_name, 0) + float(transaction.amount)
counter = 1
for series, amount in amounts.items():
color = get_color_code(counter)
counter += 1
data["data"]["labels"].append(series)
data["data"]["datasets"][0]["data"].append(round(amount, 2))
data["data"]["datasets"][0]["borderWidth"].append(2)
data["data"]["datasets"][0]["backgroundColor"].append("rgba({color}, 1.0)".format(color=color))
data["data"]["datasets"][0]["borderColor"].append("rgba(255, 255, 255, 1.0)".format(color=color))
return data
| 2.375
| 2
|
map_test.py
|
CrazyJ36/python
| 0
|
12778714
|
<reponame>CrazyJ36/python
#!/usr/bin/env python3
# The library module function 'map' takes A function and
# an iterable as arguments, returns A new iterable with
# the function applied to each argument.
nums = [2, 5, 1]
# the function adds one to any arg.
def add_one(x):
return x + 1
# map function taking add_one as it's function to act on,
# with the parameter nums for add_one.
# This is converted to list with list(items) to be printable.
result = list(map(add_one, nums))
print(result)
| 4.59375
| 5
|
calpy/rqa/rqa.py
|
robert-cochran/Calpy
| 6
|
12778715
|
import numpy
import math
#from .. import utilities
class phase_space(object):
"""Phase space class.
"""
def __init__(self, xs, tau=1, m=2, eps=.001):
self.tau, self.m, self.eps = tau, m, eps
N = int(len(xs)-m*tau+tau)
self.matrix = numpy.empty([N,m],dtype=float)
for i in range(N):
self.matrix[i,:] = xs[i:i+1+int(m*tau-tau):tau]
self.recurrence_matrix = None
return None
def __repr__(self):
return "phase_space()"
def __str__(self):
return "{} with shape {} and (tau, m, eps) = ({}, {}, {})".format(type(self.matrix), self.matrix.shape, self.tau, self.m, self.eps)
def __hash__(self):
return id(self)
def __eq__(self, other):
return id(self) == id(other)
def _Theta(x, y, eps):
"""Theta tmp
Args:
x:
y:
eps:
Returns:
int: 0 or 1.
"""
sm = 0
for k in range(len(x)):
sm += (x[k]-y[k])**2
if sm > eps:
return 0
return 1
_recurrence_matrix_cache = dict()
def recurrence_matrix(xps, yps=None, joint=False):
"""Computes cross-reccurence matrix when two inputs are given and self-reccurence otherwise.
Args:
xps (numpy.array): Phase_space object(s).
yps (numpy.array, optional): Phase_space object for cross reccurence. Defaults to none.
joint (bool, optional): Should joint reccurence be calculated? Defaults to False.
Returns:
numpy.array : A 2D numpy matrix.
"""
if not yps:
yps, cross = xps, False
else:
cross = True
if (xps,yps,joint) in _recurrence_matrix_cache:
return _recurrence_matrix_cache[xps, yps, joint]
if (xps.matrix.shape, xps.tau, xps.m, xps.eps) != (yps.matrix.shape, yps.tau, yps.m, yps.eps):
print("Error: Input phase spaces have different parameters.")
return
if joint:
return numpy.multiply( recurrence_matrix(xps), recurrence_matrix(yps) )
BB, AA, tau, m, eps = yps.matrix, xps.matrix, xps.tau, xps.m, xps.eps
N = AA.shape[0]
ans = numpy.full([N, N],0)
for i in range(N):
for j in range(N if cross else i+1):
#ans[i][j] = _Theta( AA[i], BB[j], eps)
ans[i][j] = numpy.linalg.norm(AA[i]-BB[j])
_recurrence_matrix_cache[xps,yps,joint] = ans
return _recurrence_matrix_cache[xps, yps, joint]
def cross_recurrence_matrix( xps, yps ):
"""Cross reccurence matrix.
Args:
xps (numpy.array):
yps (numpy.array):
Returns:
numpy.array : A 2D numpy array.
"""
return recurrence_matrix( xps, yps )
def joint_recurrence_matrix( xps, yps ):
"""Joint reccurence matrix.
Args:
xps (numpy.array):
yps (numpy.array):
Returns:
numpy.array : A 2D numpy array.
"""
return recurrence_matrix( xps, yps, joint=True )
def recurrence_rate( AA ):
"""Computes reccurence-rate from reccurence matrix.
Args:
AA (numpy.array): A reccurence matrix.
Returns:
numpy.array : A numpy array.
"""
isLower = utilities.is_lower_triangular(AA)
N = AA.shape[0]
ans = numpy.zeros( N, dtype=float )
for k in range(1,N):
tmp = numpy.sum(AA[:k,:k])
ans[k] += tmp
for i in range(1, N-k):
if isLower:
tmp += numpy.sum(AA[i+k-1,i:i+k]) - numpy.sum(AA[i-1:i-1+k,i-1])
else:
tmp += numpy.sum( AA[i+k-1, i:i+k] ) \
+ numpy.sum( AA[i:i+k-1, i+k-1] ) \
- numpy.sum( AA[i-1:i-1+k, i-1] ) \
- numpy.sum( AA[i-1, i:i-1+k] )
ans[k] += tmp
ans[k] /= 0.5*(N-k)*k**2 if isLower else (N-k)*k**2
return ans
_measures_cache = dict()
def determinism( AA ):
"""Calculates percentage of recurrence points which form diagonal lines.
Args:
AA (numpy.array): A reccurence matrix.
Returns:
float: The determinism.
"""
if (id(AA),"determinism") in _measures_cache:
return _measures_cache[id(AA),"determinism"]
isLower = utilities.is_lower_triangular(AA)
N = AA.shape[0]
H = dict()
for key in range(N):
H[key] = 0
def lower_DET(x):
for i in range(1, N):
isPrev = False
count = 0
for j in range(i, N):
#search for consective lines in AA[idx1,idx1-idx]
if x[j, j-i]:
if isPrev:
count += 1
else:
count = 1
isPrev = True
elif isPrev:
isPrev = False
H[count] += 1 if count > 1 else 0
count = 0
H[count] += 1 if count>1 else 0
return
lower_DET(AA)
if not isLower:
lower_DET(numpy.transpose(AA))
num, avg, max_L = 0, 0, 0
for key, val in H.items():
max_L = key if val else max_L
num += key*val
avg += val
dem = numpy.sum(AA)
ENTR = 0
if avg:
for key, val in H.items():
p = val/avg
ENTR -= p*math.log(p) if p else 0
PRED = num/avg
else:
ENTR = None
PRED = 0
DIV = 1/max_L if max_L else float('inf')
_measures_cache[id(AA),"determinism"] = num/dem
_measures_cache[id(AA),"pred"] = PRED
_measures_cache[id(AA),"divergence"] = DIV
_measures_cache[id(AA),"entropy"] = ENTR
return _measures_cache[id(AA),"determinism"]
def divergence( AA ):
"""Divergence
Args:
AA (numpy.array): A numpy array.
Returns:
numpy.array: The answer.
"""
if (id(AA),"divergence") not in _measures_cache:
determinism(AA)
return _measures_cache[id(AA),"divergence"]
def entropy( AA ):
"""Entropy
Args:
AA (numpy.array): A numpy array.
Returns:
numpy.array: The answer.
"""
if (id(AA),"entropy") not in _measures_cache:
determinism(AA)
return _measures_cache[id(AA),"entropy"]
def pred( AA ):
"""Pred
Args:
AA (numpy.array): A numpy array.
Returns:
numpy.array: The answer.
"""
if (id(AA),"pred") not in _measures_cache:
determinism(AA)
return _measures_cache[id(AA),"pred"]
def trend( AA, longterm=False ):
"""Calculate the TREND of a give 1d numpy array R.
Args:
AA (numpy.array(float)): A 2D matrix.
longterm (bool, optional): Should long-term trend be calculate? Defaults to False.
Returns:
float: The medium and long range trends a float tuple (Med, Long)
"""
N = AA.shape[0]
R_med = R[:N//2] - np.mean(R[:N//2])
R_long = R[:-1] - np.mean(R[:-1])
coef = np.array([i - N//4 +1 for i in range(N//2)])
Med = np.dot(coef, R_med)/np.dot(coef, coef)
coef = np.array([i - N//2 +1 for i in range(N-1)])
Long = np.dot(coef, R_long)/np.dot(coef, coef)
return Long if longterm else Med
def laminarity( AA ): #+ Trapping
"""Laminarity. Calculates percentage of recurrence points which form verticle lines.
This function calculates Trapping as a side effect.
Args:
AA (numpy.array(float)): A 2D matrix.
Returns:
float: The laminarity
"""
N = AA.shape[0]
H = dict()
for key in range(N):
H[key] = 0
#Lower Lam
for j in range(N):
isPrev, count = False, 0
for i in range(j+1, N):
#search for consecutive lines in M[i, j]
if AA[i, j]:
if isPrev:
count += 1
else:
isPrev, count = True, 1
elif isPrev:
H[count] += 1 if count > 1 else 0
isPrev, count = False, 0
H[count] += 1 if count > 1 else 0
#Upper Lam
if not utilities.is_lower_triangular(AA):
for j in range(N):
isPrev, count = False, 0
for i in range(j):
#search for consecutive lines in M[idx1, idx]
if AA[i,j]:
if isPrev:
count += 1
else:
isPrev, count = True, 1
elif isPrev:
H[count] += 1 if count > 1 else 0
isPrev, count = False, 0
H[count] += 1 if count > 1 else 0
num, avg= 0, 0
for key, val in H.items():
avg += val
num += key*val
dem = num + numpy.sum(AA)
LAMI = num/dem
TRAP = num/avg if avg else 0
_measures_cache[id(AA),"laminarity"] = LAMI
_measures_cache[id(AA),"trapping"] = TRAP
return _measures_cache[id(AA),"laminarity"]
def trapping( AA ):
"""Trapping. Calculates ...
This function calculates Laminiarity as a side effect.
Args:
AA (numpy.array(float)): A 2D matrix.
Returns:
float: The trapping
"""
if (id(AA),"trapping") not in _measures_cache:
return laminarity(AA)
return _measures_cache[id(AA),"trapping"]
| 3.328125
| 3
|
04-perfectionnez-vous/coffee.py
|
gruiick/openclassrooms-py
| 0
|
12778716
|
#!/usr/bin/env python3
# coding: utf-8
#
# $Id: coffee.py 1.1 $
# SPDX-License-Identifier: BSD-2-Clause
def name(func):
def inner(*args, **kwargs):
print('Running this method:', func.__name__)
return func(*args, **kwargs)
return inner
class CoffeeMachine():
water_level = 100
@name
def _start_machine(self):
if self.water_level > 20:
return True
else:
print('Please add water.')
return False
@name
def __boil_water(self):
return 'boiling...'
@name
def make_coffee(self):
if self._start_machine():
self.water_level -= 20
print(self.__boil_water())
print('Coffee is ready.')
machine = CoffeeMachine()
for i in range(0, 5):
machine.make_coffee()
machine.make_coffee()
machine._start_machine()
machine._CoffeeMachine__boil_water()
| 3.375
| 3
|
paper/plot_cert2016.py
|
lunpin1101/acobe
| 1
|
12778717
|
<filename>paper/plot_cert2016.py
#!/usr/bin/python3
import csv, gzip, json, matplotlib, numpy, os, random
matplotlib.use ('Agg')
import matplotlib.pyplot
exp = 'expbeh'
votes = 3
r1 = '/home/lunpin/anom/cert2016/r6.1/' + exp
r2 = '/home/lunpin/anom/cert2016/r6.2/' + exp
r1 = '/media/lunpin/ext-drive/bizon/anom/cert2016/r6.1/' + exp
r2 = '/media/lunpin/ext-drive/bizon/anom/cert2016/r6.2/' + exp
def main ():
print ('heatmap for Group (r1s2)')
http = Heatmap ('JPH1910', r1, '2020-03-07_s1beh_3', 'anom1_labeledldap.txt', group=True)
httpscale = Heatmap ('JPH1910', r1, '2020-03-07_s1beh_3', 'anom1_labeledldap.txt', group=True, scaling=True)
plotHeatmaps ('acobe-r1s2-group_' + exp, 'JPH1910', [http, httpscale],
['HTTP (working hours)', 'HTTP (off hours)',
'Scaled (working hours)', 'Scaled (off hours)'])
print ('heatmap for JPH1910 (r1s2)')
device = Heatmap ('JPH1910', r1, '2020-03-07_s1beh_1', 'anom1_labeledldap.txt')
http = Heatmap ('JPH1910', r1, '2020-03-07_s1beh_3', 'anom1_labeledldap.txt')
plotHeatmaps ('acobe-r1s2-JPH1910_' + exp, 'JPH1910', [device, http],
['Device (working hours)', 'Device (off hours)',
'HTTP (working hours)', 'HTTP (off hours)'])
print ('Plot Metrics')
acobe = readExperiments (r1, '2020-03-07_s1beh_1', 'anom1_labeledldap.txt')
acobe.extend (readExperiments (r1, '2020-03-07_s1beh_2', 'anom1_labeledldap.txt'))
acobe.extend (readExperiments (r1, '2020-03-07_s1beh_3', 'anom1_labeledldap.txt'))
acobe.extend (readExperiments (r2, '2020-03-07_s1beh_1', 'anom1_labeledldap.txt'))
acobe.extend (readExperiments (r2, '2020-03-07_s1beh_2', 'anom1_labeledldap.txt'))
acobe.extend (readExperiments (r2, '2020-03-07_s1beh_3', 'anom1_labeledldap.txt'))
acobe.extend (readExperiments (r2, '2020-03-07_s2beh_1', 'anom2_labeledldap.txt'))
acobe.extend (readExperiments (r2, '2020-03-07_s2beh_2', 'anom2_labeledldap.txt'))
acobe.extend (readExperiments (r2, '2020-03-07_s2beh_3', 'anom2_labeledldap.txt'))
plotMetric ('acobe_metric_' + exp, [
['N=3', getMetric (acobe, days=1, votes=3)],
['N=2', getMetric (acobe, days=1, votes=2)],
['N=1', getMetric (acobe, days=1, votes=1)]])
ain1 = readExperiments (r1, '2020-02-15_s1beh_16', 'anom1_labeledldap.txt')
ain1.extend (readExperiments (r2, '2020-02-15_s1beh_16', 'anom1_labeledldap.txt'))
ain1.extend (readExperiments (r2, '2020-02-15_s2beh_16', 'anom2_labeledldap.txt'))
egh = readExperiments (r1, '2020-04-04_s1beh_1', 'anom1_labeledldap.txt')
egh.extend (readExperiments (r1, '2020-04-04_s1beh_2', 'anom1_labeledldap.txt'))
egh.extend (readExperiments (r1, '2020-04-04_s1beh_3', 'anom1_labeledldap.txt'))
egh.extend (readExperiments (r2, '2020-04-04_s1beh_1', 'anom1_labeledldap.txt'))
egh.extend (readExperiments (r2, '2020-04-04_s1beh_2', 'anom1_labeledldap.txt'))
egh.extend (readExperiments (r2, '2020-04-04_s1beh_3', 'anom1_labeledldap.txt'))
egh.extend (readExperiments (r2, '2020-04-04_s2beh_1', 'anom2_labeledldap.txt'))
egh.extend (readExperiments (r2, '2020-04-04_s2beh_2', 'anom2_labeledldap.txt'))
egh.extend (readExperiments (r2, '2020-04-04_s2beh_3', 'anom2_labeledldap.txt'))
t4f = readExperiments (r1, '2020-04-05_s1beh_1', 'anom1_labeledldap.txt')
t4f.extend (readExperiments (r1, '2020-04-05_s1beh_2', 'anom1_labeledldap.txt'))
t4f.extend (readExperiments (r1, '2020-04-05_s1beh_3', 'anom1_labeledldap.txt'))
t4f.extend (readExperiments (r2, '2020-04-05_s1beh_1', 'anom1_labeledldap.txt'))
t4f.extend (readExperiments (r2, '2020-04-05_s1beh_2', 'anom1_labeledldap.txt'))
t4f.extend (readExperiments (r2, '2020-04-05_s1beh_3', 'anom1_labeledldap.txt'))
t4f.extend (readExperiments (r2, '2020-04-05_s2beh_1', 'anom2_labeledldap.txt'))
t4f.extend (readExperiments (r2, '2020-04-05_s2beh_2', 'anom2_labeledldap.txt'))
t4f.extend (readExperiments (r2, '2020-04-05_s2beh_3', 'anom2_labeledldap.txt'))
d1 = readExperiments (r1, '2020-05-27_s1beh_1', 'anom1_labeledldap.txt')
d1.extend (readExperiments (r1, '2020-05-27_s1beh_2', 'anom1_labeledldap.txt'))
d1.extend (readExperiments (r1, '2020-05-27_s1beh_3', 'anom1_labeledldap.txt'))
d1.extend (readExperiments (r2, '2020-05-27_s1beh_1', 'anom1_labeledldap.txt'))
d1.extend (readExperiments (r2, '2020-05-27_s1beh_2', 'anom1_labeledldap.txt'))
d1.extend (readExperiments (r2, '2020-05-27_s1beh_3', 'anom1_labeledldap.txt'))
d1.extend (readExperiments (r2, '2020-05-27_s2beh_1', 'anom2_labeledldap.txt'))
d1.extend (readExperiments (r2, '2020-05-27_s2beh_2', 'anom2_labeledldap.txt'))
d1.extend (readExperiments (r2, '2020-05-27_s2beh_3', 'anom2_labeledldap.txt'))
liu = readExperiments (r1, '2020-06-07_s1beh_1', 'anom1_labeledldap.txt')
liu.extend (readExperiments (r1, '2020-06-07_s1beh_2', 'anom1_labeledldap.txt'))
liu.extend (readExperiments (r1, '2020-06-07_s1beh_3', 'anom1_labeledldap.txt'))
liu.extend (readExperiments (r1, '2020-06-07_s1beh_4', 'anom1_labeledldap.txt'))
liu.extend (readExperiments (r2, '2020-06-07_s1beh_1', 'anom1_labeledldap.txt'))
liu.extend (readExperiments (r2, '2020-06-07_s1beh_2', 'anom1_labeledldap.txt'))
liu.extend (readExperiments (r2, '2020-06-07_s1beh_3', 'anom1_labeledldap.txt'))
liu.extend (readExperiments (r2, '2020-06-07_s1beh_4', 'anom1_labeledldap.txt'))
liu.extend (readExperiments (r2, '2020-06-07_s2beh_1', 'anom2_labeledldap.txt'))
liu.extend (readExperiments (r2, '2020-06-07_s2beh_2', 'anom2_labeledldap.txt'))
liu.extend (readExperiments (r2, '2020-06-07_s2beh_3', 'anom2_labeledldap.txt'))
liu.extend (readExperiments (r2, '2020-06-07_s2beh_4', 'anom2_labeledldap.txt'))
liuf = readExperiments (r1, '2020-06-08_s1beh_1', 'anom1_labeledldap.txt')
liuf.extend (readExperiments (r1, '2020-06-08_s1beh_2', 'anom1_labeledldap.txt'))
liuf.extend (readExperiments (r1, '2020-06-08_s1beh_3', 'anom1_labeledldap.txt'))
liuf.extend (readExperiments (r2, '2020-06-08_s1beh_1', 'anom1_labeledldap.txt'))
liuf.extend (readExperiments (r2, '2020-06-08_s1beh_2', 'anom1_labeledldap.txt'))
liuf.extend (readExperiments (r2, '2020-06-08_s1beh_3', 'anom1_labeledldap.txt'))
liuf.extend (readExperiments (r2, '2020-06-08_s2beh_1', 'anom2_labeledldap.txt'))
liuf.extend (readExperiments (r2, '2020-06-08_s2beh_2', 'anom2_labeledldap.txt'))
liuf.extend (readExperiments (r2, '2020-06-08_s2beh_3', 'anom2_labeledldap.txt'))
plotMetric ('metric_' + exp, [
['Acobe', getMetric (acobe, days=1, votes=votes)],
['Base-FF', getMetric (liuf, days=1, votes=votes)],
['Baseline', getMetric (liu, days=1, votes=4)],
['1-Day', getMetric (d1, days=1, votes=votes)],
['No-Group', getMetric (egh, days=1, votes=votes)],
['All-in-1', getMetric (ain1, days=1, votes=1)],
])
print ('exlude group behavior')
plotExperiment ('egh-r1s1-device_' + exp, r1, '2020-04-04_s1beh_1', 'anom1_labeledldap.txt')
plotExperiment ('egh-r1s1-http_' + exp, r1, '2020-04-04_s1beh_3', 'anom1_labeledldap.txt')
print ('acobe')
plotExperiment ('acobe-r1s1-device_' + exp, r1, '2020-03-07_s1beh_1', 'anom1_labeledldap.txt')
plotExperiment ('acobe-r1s1-file_' + exp, r1, '2020-03-07_s1beh_2', 'anom1_labeledldap.txt')
plotExperiment ('acobe-r1s1-http_' + exp, r1, '2020-03-07_s1beh_3', 'anom1_labeledldap.txt')
print ('all features together in one autoencoder')
plotExperiment ('ain1-r1s1_' + exp, r1, '2020-02-15_s1beh_16', 'anom1_labeledldap.txt')
print ('slice a day by 24 time frames')
plotExperiment ('4tf-r1s1-device_' + exp, r1, '2020-04-05_s1beh_1', 'anom1_labeledldap.txt')
plotExperiment ('4tf-r1s1-http_' + exp, r1, '2020-04-05_s1beh_3', 'anom1_labeledldap.txt')
print ('single day reconstruction')
plotExperiment ('1dr-r1s1-device_' + exp, r1, '2020-05-27_s1beh_1', 'anom1_labeledldap.txt')
plotExperiment ('1dr-r1s1-http_' + exp, r1, '2020-05-27_s1beh_3', 'anom1_labeledldap.txt')
print ('liuliu')
plotExperiment ('liu-r1s1_' + exp, r1, '2020-06-07_s1beh_3', 'anom1_labeledldap.txt')
plotExperiment ('liuf-r1s1_' + exp, r1, '2020-06-08_s1beh_3', 'anom1_labeledldap.txt')
def plotMetric (filepath, metrics):
# preprocessing metrics
for label, metric in metrics:
TP = metric ['TP']
FP = metric ['FP']
TN = [FP [-1] - fp for fp in FP]
FN = [TP [-1] - tp for tp in TP]
for m in ['Precision', 'Recall', 'TP Rate', 'FP Rate']: metric [m] = []
for i in range (0, len (TP)):
tp, fp, tn, fn = TP [i], FP [i], TN [i], FN [i]
metric ['Precision'].append ( 0.0 if tp + fp == 0 else tp / (tp + fp) )
metric ['Recall'].append ( 0.0 if tp + fn == 0 else tp / (tp + fn) )
metric ['FP Rate'].append ( 0.0 if fp +tn == 0 else fp / (fp + tn) )
metric ['TP Rate'] = metric ['Recall']
# plot ROC and F1
styles = ['k-o', 'k-s', 'k-^', 'k:v', 'k:D', 'k:X', 'k:P']
fontsize, lw, ms = 14, 2.5, 10
for figname, xmetric, ymetric, in [
['roc', 'FP Rate', 'TP Rate'],
['f1', 'Recall', 'Precision']]:
fig = matplotlib.pyplot.figure ()
ax = fig.add_subplot (1, 1, 1)
for i, obj in enumerate (metrics):
label, metric = obj
auc = 0
for j in range (1, len (metric [xmetric])):
a_b = metric [ymetric][j] + metric [ymetric][j - 1]
a_h = metric [xmetric][j] - metric [xmetric][j - 1]
auc += a_b * a_h / 2
if figname == 'roc': label = label + ' (' + '{:5.2f}'.format (auc * 100) + '%)'
print (label, metric ['TP'], metric ['FP'])
if figname == 'roc': ax.plot (metric [xmetric], metric [ymetric], styles [i], lw=lw, ms=ms, label=label)
if figname == 'f1': ax.plot (metric [xmetric][1:], metric [ymetric][1:], styles [i], lw=lw, ms=ms, label=label)
ax.legend (fontsize=fontsize)
fig.tight_layout ()
matplotlib.pyplot.savefig ('_'.join ([filepath, figname]) + '.png', dpi=128)
matplotlib.pyplot.close (fig)
def getMetric (experiments, days=1, votes=1):
# get lists of normal/abnormal users
normals, abnormals = [], []
for experiment in experiments:
normals.extend (experiment.normals)
abnormals.extend (experiment.abnormals)
normals = set (normals)
abnormals = set (abnormals)
# get user ranks
ranks = {}
for experiment in experiments:
r = experiment.getAbnormalUserRank (days)
for user in r:
if user not in ranks: ranks [user] = []
ranks [user].append (r [user])
# derive TPs and FPs
Ps, TPs, FPs = set (), [0], [0]
for rank in range (0, len (normals) + len (abnormals)):
# if len (TPs) - 1 == len (abnormals): break
for user in ranks:
if user in Ps: continue # already reported
if sum ([r >= rank for r in ranks [user]]) >= votes:
Ps.add (user) # add to reported list
if user in normals: FPs [-1] += 1
else: # identify TP: extend arrays
TPs.append (TPs [-1] + 1)
FPs.append (FPs [-1])
# append the rest of normal users
TPs.append (TPs [-1])
FPs.append (len (normals))
return {'TP': TPs, 'FP': FPs, 'abnormals': {user: ranks [user] for user in abnormals}}
def plotExperiment (filename, dataset, expid=None, label=None):
experiments = readExperiments (dataset, expid, label)
for index, experiment in enumerate (experiments):
output = filename + 'g' + str (index + 1) if len (experiments) > 1 else filename
plotTrends (output, experiment)
return experiments [0] if len (experiments) == 1 else experiments
def plotTrends (filename, experiment, head=0, tail=9999, sample=9999):
fontsize, normallw, abnormallw, markersize = 14, 0.5, 3, 10
normals = list (experiment.normals)
abnormals = list (experiment.abnormals)
dates = experiment.dates
xaxis = numpy.arange (len (dates))
fig = matplotlib.pyplot.figure ()
ax = fig.add_subplot (1, 1, 1)
scores = []
# plot scores of normal users
random.shuffle (normals)
normals = normals [: sample]
discarded = 0
for uid in normals:
trend = experiment.users [uid].trends ['score']
scores.extend (trend)
discard = False
for i in range (0, len (trend) - 15):
subtrend = trend [i: i+15]
if min (subtrend) == max (subtrend): discard = True; discarded += 1; break
# if discard: continue # disccard straight lines for EGH
ax.plot (xaxis, trend, '-', color='grey', lw=normallw)
# plot scores of abnormal users
for uid in abnormals:
trend = experiment.users [uid].trends ['score']
scores.extend (trend)
ax.plot (xaxis, trend, 'k-', lw=abnormallw, markersize=markersize, label=uid)
# emphasize on compromise dates
x, y = [], []
for date in experiment.users [uid].compromises:
if date not in dates: continue
index = dates.index (date)
x.append (index)
y.append (trend [index])
minscore = min (scores)
ax.plot (x, [minscore] * len (x), 'k*', markersize=markersize)
# xticks and labels
xticks = [xaxis [0]]
for index, date in enumerate (dates):
if '/01/' in date: xticks.append (index)
xticks.append (xaxis [-1])
xticklabels = [dates [i] for i in xticks]
# title
mean = numpy.mean (scores)
std = numpy.std (scores)
title = 'mean: ' + '{:.4f}'.format (mean) + ', std: ' + '{:.4f}'.format (std)
# finalize
ax.set_xticks (xticks)
ax.set_xticklabels (xticklabels, fontsize=fontsize, rotation=45, ha='right', rotation_mode='anchor')
ax.yaxis.set_tick_params (labelsize=fontsize)
ax.legend (fontsize=fontsize)
ax.set_title (title, fontsize=fontsize)
fig.tight_layout ()
matplotlib.pyplot.savefig ('_'.join ([filename, 'trends']) + '.png', dpi=128)
matplotlib.pyplot.close (fig)
if discarded > 0: print (filename, 'trends discarded', str (discarded))
def plotHeatmaps (filepath, user, heatmaps, titles=None):
fontsize, markersize = 9, 5
n_bitmaps, bitmapIndex = sum (heatmap.timeframes for heatmap in heatmaps), 0
fig, axs = matplotlib.pyplot.subplots (nrows=n_bitmaps, ncols=1, sharex=True, sharey=False)
# plot heatmaps
for heatmap in heatmaps:
for timeframe in range (0, heatmap.timeframes):
ax = axs [bitmapIndex]
title = None if titles is None else titles [bitmapIndex]
bitmapIndex += 1
# enlarge features (rows) by scale and then plot
imap, scale = [], 10
for row in heatmap.bitmap [timeframe]:
for i in range (0, scale): imap.append (row)
# xticks and xticklabels
dates, xticks = heatmap.experiment.dates, [0]
for index, date in enumerate (dates):
if '/01/' in date: xticks.append (index)
xticks.append (len (dates) -1)
xticklabels = [dates [i] for i in xticks]
# yticks and yticklabels
features = heatmap.features
yticks = [i * scale for i in range (0, len (features) + 1)]
yticklabels = ['f' + str (i + 1) for i in range (0, len (yticks) - 1)] + [None]
# plot compromises on the last figures
if bitmapIndex == n_bitmaps:
compromises = []
for i in range (0, scale): imap.append ([0] * len (dates)) # empty line for compromise marks
yticks = yticks + [(len (features) + 1) * scale]
for date in heatmap.experiment.users [user].compromises:
if date not in dates: continue
compromises.append (dates.index (date))
positions = [yticks [-1] - (scale / 2)] * len (compromises)
ax.plot (compromises, positions, 'k*', markersize=markersize)
# de-normalize imap
vmin, vmax = 0.0, 1.0
if True:
vmax = 3.0
vmin = 0.0 - vmax
imap = numpy.array (imap) * 2 * vmax - vmax
# finalize subfigure
if heatmap.scaling: im = ax.imshow (imap, cmap='gray_r', aspect='auto')
else: im = ax.imshow (imap, cmap='gray_r', aspect='auto', vmin=vmin, vmax=vmax)
ax.set_xticks (xticks)
ax.set_xticklabels (xticklabels, fontsize=fontsize)
matplotlib.pyplot.setp (ax.get_xticklabels (), rotation=45, ha='right', rotation_mode='anchor')
ax.set_yticks (yticks)
ax.set_yticklabels (yticklabels, fontsize=fontsize)
ax.set_title (title, fontsize=fontsize)
# matplotlib.pyplot.setp (ax.get_yticklabels (), rotation=45, ha='right', rotation_mode='anchor')
cb = fig.colorbar (im, ax=ax)
cb.minorticks_on ()
# finalize whole figure
fig.tight_layout ()
matplotlib.pyplot.savefig (filepath + '.png', dpi=128)
matplotlib.pyplot.close (fig)
class Experiment (object):
def __init__ (self, directory, label='label.txt'):
# read labels (csv)
users, normals, abnormals = {}, set (), set ()
for line in csv.reader (open (os.path.join (directory, label), 'r')):
user = User (line)
users [user.uid] = user
if user.isAbnormal (): abnormals.add (user.uid)
else: normals.add (user.uid)
# read results (json)
evaluation = {} # evaluation [date]
for filename in os.listdir (os.path.join (directory, 'results')):
if '.result.log' not in filename [-11: ]: continue
for line in open (os.path.join (directory, 'results', filename), 'r'):
uid, score, date, model = json.loads (line)
obj = {'uid': uid, 'score': score, 'date': date, 'model': model}
if date not in evaluation: evaluation [date] = []
evaluation [date].append (obj)
# sort evaluation
for date in evaluation:
evaluation [date] = sorted (evaluation [date], key=lambda obj: obj ['score'], reverse=True)
# get sorted dates
def dtoi (date):
MM, DD, YYYY = date.split ('/')
YYYY = int (YYYY) * 10000
MM = int (MM) * 100
DD = int (DD) * 1
return YYYY + MM + DD
dates = sorted (list (evaluation.keys ()), key=lambda date: dtoi (date))
# get trends
for date in dates:
currentrank, currentscore = 0, 0
for rank, user in enumerate (evaluation [date]):
if user ['score'] != currentscore:
currentrank, currentscore = rank, user ['score']
uid = user ['uid']
users [uid].trends ['rank'].append (currentrank + 1)
users [uid].trends ['score'].append (currentscore)
# finalize
self.directory = directory
self.users = users
self.normals = normals
self.abnormals = abnormals
self.dates = dates
def getAbnormalUserRank (self, days=1):
# sort all abnormal data points
scores = []
for user in self.abnormals: scores.extend (self.users [user].trends ['score'])
scores = sorted (list (set (scores)), reverse=True)
ret_rank = {}
rank_count = 0
TPs = 0
# score as moving threshold
for score in scores:
for user in self.users: # order of normal users is irrelevant to results
if self.users [user].countAbnormalDays (score) >= days:
if user not in ret_rank:
rank_count += 1
ret_rank [user] = rank_count
if user in self.abnormals: TPs += 1
if TPs == len (self.abnormals): break
return ret_rank
class User (object):
ABNORMAL_TAGS = ['Abnormal', 'abnormal']
def __init__ (self, line):
if isinstance (line, str): line = list (csv.reader ([line])) [0]
self.uid = line [0]
self.groups = line [1: 5] # business_unit,functional_unit,department,team
self.label = line [5]
self.compromises = line [6: ]
self.trends = {'rank': [], 'score': []}
self.sortedtrends = None
self.hasAbnormalRaise = None
self.mean = None
self.std = None
def isAbnormal (self, date=None):
if date is None: return self.label in self.ABNORMAL_TAGS
return self.label in self.ABNORMAL_TAGS and date in self.compromises
def isNormal (self, date=None):
return not self.isAbnormal (date)
def csv (self):
line = [self.uid] + self.groups + [self.label]
if self.isAbnormal (): line += self.compromises
return line
def csvstr (self):
return ','.join (self.csv ()) + '\n'
def sortedTrends (self):
if self.sortedtrends is None: self.sortedtrends = sorted (self.trends ['score'], reverse=True)
return self.sortedtrends
def mean (self):
if self.mean is None: self.mean = numpy.mean (self.trends ['score'])
return self.mean
def std (self):
if self.std is None: self.std = numpy.std (self.trends ['score'])
return self.std
def hasAbnormalRaise (self, scale=3.0):
if self.hasAbnormalRaise is not None: return self.hasAbnormalRaise
trends = self.trends ['score']
for index in range (1, len (trends)):
past = trends [: index]
mean, std = numpy.mean (past), numpy.std (past)
std = 0.0001 if std == 0.0 else std
if (trend [index] - mean) / std > scale:
self.hasAbnormalRaise = True
return hasAbnormalRaise
def countAbnormalDays (self, threshold):
ret = 0
for score in self.sortedTrends ():
if score <= threshold: return ret
ret += 1
return ret
class Heatmap (object):
def __init__ (self, user, dataset, expid=None, label=None, timeframes=2, group=False, scaling=False):
experiments = readExperiments (dataset, expid, label)
# find experiment
for experiment in experiments:
if user in experiment.normals or user in experiment.abnormals: break
# read data and save it to a heatmap
heatmap = {}
directory = os.path.join (experiment.directory, 'heatmaps.raw')
for filename in os.listdir (directory):
if user not in filename: continue
obj = json.loads (gzip.open (os.path.join (directory, filename), 'r').read ())
dates, features, bitmap = obj ['xaxis'], obj ['yaxis'], obj ['bitmap']
features = features [: int (len (features) / 2)] # exclude group behavior
for i, feature in enumerate (features):
if feature not in heatmap: heatmap [feature] = {}
for j, date in enumerate (dates):
if date not in heatmap [feature]: heatmap [feature][date] = {}
timeframe = int (j / (int (len (dates) / 2)))
if group: heatmap [feature][date][timeframe] = bitmap [i + len (features)][j]
else: heatmap [feature][date][timeframe] = bitmap [i][j]
# transform heatmap to bitmaps
bitmap = []
for timeframe in range (0, timeframes):
bitmap.append ([])
for feature in features:
bitmap [timeframe].append ([])
for date in experiment.dates:
bitmap [timeframe][-1].append (heatmap [feature][date][timeframe])
# finalize
self.experiment = experiment
self.timeframes = timeframes
self.features = features
self.heatmap = heatmap
self.bitmap = bitmap
self.scaling = scaling
def readExperiments (dataset, expid=None, label=None):
if expid is not None:
experiments = []
for group in os.listdir (os.path.join (dataset, expid)):
experiments.append (Experiment (os.path.join (dataset, expid, group), label))
# except: print (dataset, expid, label, 'not ready')
else: experiments = dataset if isinstance (dataset, list) else [dataset]
return experiments
if __name__ == '__main__': main ()
| 2.46875
| 2
|
aot/meta_triggers/metatrigger.py
|
jaycheungchunman/age-of-triggers
| 8
|
12778718
|
<reponame>jaycheungchunman/age-of-triggers
from abc import ABC, abstractmethod
class MetaTrigger(ABC):
pass
@abstractmethod
def setup(self, scenario):
pass
def triggers_to_activate(self):
return []
class EffectGenerator(ABC):
@abstractmethod
def generate(self, player_id, info={}):
pass
class ConditionGenerator(ABC):
@abstractmethod
def generate(self, player_id, info={}):
pass
| 2.4375
| 2
|
deepstochlog/network.py
|
ML-KULeuven/deepstochlog
| 10
|
12778719
|
<filename>deepstochlog/network.py
from typing import List
import torch.nn as nn
from deepstochlog.term import Term
class Network(object):
def __init__(
self,
name: str,
neural_model: nn.Module,
index_list: List[Term],
concat_tensor_input=True,
):
self.name = name
self.neural_model = neural_model
self.computation_graphs = dict()
self.index_list = index_list
self.index_mapping = dict()
if index_list is not None:
for i, elem in enumerate(index_list):
self.index_mapping[elem] = i
self.concat_tensor_input = concat_tensor_input
def term2idx(self, term: Term) -> int:
#TODO(giuseppe) index only with the functor
# key = term #old
key = Term(str(term.functor))
if key not in self.index_mapping:
raise Exception(
"Index was not found, did you include the right Term list as keys? Error item: "
+ str(term)
+ " "
+ str(type(term))
+ ".\nPossible values: "
+ ", ".join([str(k) for k in self.index_mapping.keys()])
)
return self.index_mapping[key]
def idx2term(self, index: int) -> Term:
return self.index_list[index]
def to(self, *args, **kwargs):
self.neural_model.to(*args, **kwargs)
class NetworkStore:
def __init__(self, *networks: Network):
self.networks = dict()
for n in networks:
self.networks[n.name] = n
def get_network(self, name: str) -> Network:
return self.networks[name]
def to_device(self, *args, **kwargs):
for network in self.networks.values():
network.to(*args, **kwargs)
def get_all_net_parameters(self):
all_parameters = list()
for network in self.networks.values():
all_parameters.extend(network.neural_model.parameters())
return all_parameters
def __add__(self, other: "NetworkStore"):
return NetworkStore(
*(list(self.networks.values()) + list(other.networks.values()))
)
| 2.6875
| 3
|
bot/sticker/error.py
|
TinderBrazil/sticker-thief
| 0
|
12778720
|
<filename>bot/sticker/error.py
class StickerError(Exception):
def __init__(self, message):
super(StickerError, self).__init__()
self.message = message
def __str__(self):
return '{}'.format(self.message)
class NameAlreadyOccupied(StickerError):
pass
class PackInvalid(StickerError):
pass
class PackNotModified(StickerError):
pass
class NameInvalid(StickerError):
pass
class PackFull(StickerError):
pass
class FileTooBig(StickerError):
pass
class FileDimensionInvalid(StickerError):
pass
class InvalidAnimatedSticker(StickerError):
pass
class UnknwonError(StickerError):
pass
EXCEPTIONS = {
# pack name is already used
'sticker set name is already occupied': NameAlreadyOccupied,
# the bot doesn't own the pack/pack name doesn't exist/pack has been deleted
'STICKERSET_INVALID': PackInvalid,
'Stickerset_invalid': PackInvalid, # new exception description
'STICKERSET_NOT_MODIFIED': PackNotModified,
# invalid pack name, eg. starting with a number
'sticker set name invalid': NameInvalid,
# pack is full
'Stickers_too_much': PackFull, # old exception description
'Stickerpack_stickers_too_much': PackFull, # new exception description
# png size > 350 kb
'file is too big': FileTooBig,
# invalid png size
'Sticker_png_dimensions': FileDimensionInvalid,
# this happens when we receive an animated sticker which is no longer compliant with the current specifications
# it also should have as mime type "application/x-bad-tgsticker"
# https://core.telegram.org/animated_stickers
'Wrong file type': InvalidAnimatedSticker,
# not an actual API exception, we reiase it when we receive an unknown exception
'ext_unknown_api_exception': UnknwonError
}
| 2.484375
| 2
|
src/jackdaw/RuntimeChecks/__init__.py
|
miicck/jackdaw
| 0
|
12778721
|
import traceback
class CallStructureException(Exception):
pass
def must_be_called_from(method):
for frame in traceback.extract_stack():
if frame.name == method.__name__ and frame.filename == method.__globals__['__file__']:
return
raise CallStructureException("Method called incorrectly!")
| 2.8125
| 3
|
Python_Crash_Courses_V2/O_Name.py
|
obareau/python_travaux_pratiques
| 1
|
12778722
|
# Return name with each words capitalized
name = "<NAME>"
print(name.title())
# Ada Lovelace
# Some useful methods
name2 = "<NAME>"
print(name2.upper())
print(name2.lower())
# ADA LOVELACE
# ada lovelace
# Using Variables in Strings
gender = "miss"
first_name = "ada"
last_name = "lovelace"
# f is for f-strings
full_name = f"{gender} {first_name} {last_name}"
print(f"\tHello, \n\t{full_name.title()}!")
# Stripping Whitespace
favorite_language = " python "
print (favorite_language.rstrip())
print (favorite_language.lstrip())
| 4.1875
| 4
|
exact_solvers/shallow_water.py
|
haraldschilly/riemann_book
| 0
|
12778723
|
<reponame>haraldschilly/riemann_book<filename>exact_solvers/shallow_water.py
import sys, os
import numpy as np
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
import warnings
from ipywidgets import interact
from ipywidgets import widgets, Checkbox, fixed
from utils import riemann_tools
from collections import namedtuple
warnings.filterwarnings("ignore")
conserved_variables = ('Depth', 'Momentum')
primitive_variables = ('Depth', 'Velocity')
left, middle, right = (0, 1, 2)
State = namedtuple('State', conserved_variables)
Primitive_State = namedtuple('PrimState', primitive_variables)
def pospart(x):
return np.maximum(1.e-15,x)
def primitive_to_conservative(h, u):
hu = h*u
return h, hu
def conservative_to_primitive(h, hu):
# Check that h>=0 where it is not np.nan:
assert np.nanmin(h)>=0
# We should instead check that hu is zero everywhere that h is
u = hu/pospart(h)
return h, u
def cons_to_prim(q):
return conservative_to_primitive(*q)
def exact_riemann_solution(q_l, q_r, grav=1., force_waves=None,
primitive_inputs=False, include_contact=False):
"""Return the exact solution to the Riemann problem with initial states q_l, q_r.
The solution is given in terms of a list of states, a list of speeds (each of which
may be a pair in case of a rarefaction fan), and a function reval(xi) that gives the
solution at a point xi=x/t.
The input and output vectors are the conserved quantities.
"""
if primitive_inputs:
h_l, u_l = q_l
h_r, u_r = q_r
hu_l = h_l*u_l
hu_r = h_r*u_r
else:
h_l, u_l = conservative_to_primitive(*q_l)
h_r, u_r = conservative_to_primitive(*q_r)
hu_l = q_l[1]
hu_r = q_r[1]
# Compute left and right state sound speeds
c_l = np.sqrt(grav*h_l)
c_r = np.sqrt(grav*h_r)
# Define the integral curves and hugoniot loci
# Avoid warnings due to negative depths in fsolve calls
integral_curve_1 = lambda h: u_l + 2*(np.sqrt(grav*h_l) -
np.sqrt(grav*np.maximum(h,0)))
integral_curve_2 = lambda h: u_r - 2*(np.sqrt(grav*h_r) -
np.sqrt(grav*np.maximum(h,0)))
hugoniot_locus_1 = lambda h: (h_l*u_l + (h-h_l)*(u_l -
np.sqrt(grav*h_l*(1 + (h-h_l)/h_l) * (1 + (h-h_l)/(2*h_l)))))/h
hugoniot_locus_2 = lambda h: (h_r*u_r + (h-h_r)*(u_r +
np.sqrt(grav*h_r*(1 + (h-h_r)/h_r) * (1 + (h-h_r)/(2*h_r)))))/h
# Check whether the 1-wave is a shock or rarefaction
def phi_l(h):
if (h>=h_l and force_waves!='raref') or force_waves=='shock':
return hugoniot_locus_1(h)
else:
return integral_curve_1(h)
# Check whether the 2-wave is a shock or rarefaction
def phi_r(h):
if (h>=h_r and force_waves!='raref') or force_waves=='shock':
return hugoniot_locus_2(h)
else:
return integral_curve_2(h)
ws = np.zeros(4)
wave_types = ['', '']
dry_velocity_l = u_l + 2*np.sqrt(grav*h_l)
dry_velocity_r = u_r - 2*np.sqrt(grav*h_r)
if dry_velocity_l < dry_velocity_r:
# Dry middle state
h_m = 0
# This is a bit arbitrary:
u_m = 0.5*(dry_velocity_l + dry_velocity_r)
hu_m = u_m * h_m
ws[0] = u_l - c_l
ws[1] = dry_velocity_l
ws[2] = dry_velocity_r
ws[3] = u_r + c_r
elif h_l == 0:
# Dry left state; 2-rarefaction only
h_m = 0
u_m = dry_velocity_r
hu_m = u_m * h_m
ws[0] = 0
ws[1] = 0
ws[2] = dry_velocity_r
ws[3] = u_r + c_r
elif h_r == 0:
# Dry right state; 1-rarefaction only
h_m = 0
u_m = dry_velocity_l
hu_m = u_m * h_m
ws[0] = u_l - c_l
ws[1] = dry_velocity_l
ws[2] = 0
ws[3] = 0
else:
phi = lambda h: phi_l(h)-phi_r(h)
# Compute middle state h, hu by finding curve intersection
guess = (u_l-u_r+2.*np.sqrt(grav)*(np.sqrt(h_l)+np.sqrt(h_r)))**2./16./grav
h_m, _, ier, msg = fsolve(phi, guess, full_output=True, xtol=1.e-14)
# For strong rarefactions, sometimes fsolve needs help
if ier!=1:
h_m, _, ier, msg = fsolve(phi, guess,full_output=True,factor=0.1,xtol=1.e-10)
# This should not happen:
if ier!=1:
print('Warning: fsolve did not converge.')
print(msg)
u_m = phi_l(h_m)
hu_m = u_m * h_m
# Find shock and rarefaction speeds
if (h_m>h_l and force_waves!='raref') or force_waves=='shock':
wave_types[0] = 'shock'
ws[0] = (hu_l - hu_m) / (h_l - h_m)
ws[1] = ws[0]
else:
wave_types[0] = 'raref'
c_m = np.sqrt(grav * h_m)
ws[0] = u_l - c_l
ws[1] = u_m - c_m
if (h_m>h_r and force_waves!='raref') or force_waves=='shock':
wave_types[1] = 'shock'
ws[2] = (hu_r - hu_m) / (h_r - h_m)
ws[3] = ws[2]
else:
wave_types[0] = 'raref'
c_m = np.sqrt(grav * h_m)
ws[2] = u_m + c_m
ws[3] = u_r + c_r
# Find solution inside rarefaction fans (in primitive variables)
def raref1(xi):
RiemannInvariant = u_l + 2*np.sqrt(grav*h_l)
h = ((RiemannInvariant - xi)**2 / (9*grav))
u = (xi + np.sqrt(grav*h))
hu = h*u
return h, hu
def raref2(xi):
RiemannInvariant = u_r - 2*np.sqrt(grav*h_r)
h = ((RiemannInvariant - xi)**2 / (9*grav))
u = (xi - np.sqrt(grav*h))
hu = h*u
return h, hu
q_m = np.squeeze(np.array((h_m, hu_m)))
states = np.column_stack([q_l,q_m,q_r])
speeds = [[], []]
if wave_types[0] is 'shock':
speeds[0] = ws[0]
else:
speeds[0] = (ws[0],ws[1])
if wave_types[1] is 'shock':
speeds[1] = ws[2]
else:
speeds[1] = (ws[2],ws[3])
if include_contact:
states = np.column_stack([q_l,q_m,q_m,q_r])
um = q_m[1]/q_m[0]
speeds = [speeds[0],um,speeds[1]]
wave_types = [wave_types[0],'contact',wave_types[1]]
def reval(xi):
"""
Function that evaluates the Riemann solution for arbitrary xi = x/t.
Sets the solution to nan in an over-turning rarefaction wave
for illustration purposes of this non-physical solution.
"""
rar1 = raref1(xi)
rar2 = raref2(xi)
h_out = (xi<=ws[0])*h_l + \
(xi>ws[0])*(xi<=ws[1])*rar1[0] + \
(xi>ws[1])*(xi<=ws[0])*1e9 + \
(xi>ws[1])*(xi<=ws[2])*h_m + \
(xi>ws[2])*(xi<=ws[3])*rar2[0] + \
(xi>ws[3])*(xi<=ws[2])*1e9 + \
(xi>ws[3])*h_r
h_out[h_out>1e8] = np.nan
hu_out = (xi<=ws[0])*hu_l + \
(xi>ws[0])*(xi<=ws[1])*rar1[1] + \
(xi>ws[1])*(xi<=ws[0])*1e9 + \
(xi>ws[1])*(xi<=ws[2])*hu_m + \
(xi>ws[2])*(xi<=ws[3])*rar2[1] + \
(xi>ws[3])*(xi<=ws[2])*1e9 + \
(xi>ws[3])*hu_r
hu_out[hu_out>1e8] = np.nan
return h_out, hu_out
return states, speeds, reval, wave_types
def integral_curve(h, hstar, hustar, wave_family, g=1., y_axis='u'):
"""
Return u or hu as a function of h for integral curves through
(hstar, hustar).
"""
ustar = hustar / pospart(hstar)
if wave_family == 1:
if y_axis == 'u':
return ustar + 2*(np.sqrt(g*hstar) - np.sqrt(g*h))
else:
return h*ustar + 2*h*(np.sqrt(g*hstar) - np.sqrt(g*h))
else:
if y_axis == 'u':
return ustar - 2*(np.sqrt(g*hstar) - np.sqrt(g*h))
else:
return h*ustar - 2*h*(np.sqrt(g*hstar) - np.sqrt(g*h))
def hugoniot_locus(h, hstar, hustar, wave_family, g=1., y_axis='u'):
"""
Return u or hu as a function of h for the Hugoniot locus through
(hstar, hustar).
"""
ustar = hustar / hstar
alpha = h - hstar
d = np.sqrt(g*hstar*(1 + alpha/hstar)*(1 + alpha/(2*hstar)))
if wave_family == 1:
if y_axis == 'u':
return (hustar + alpha*(ustar - d))/pospart(h)
else:
return hustar + alpha*(ustar - d)
else:
if y_axis == 'u':
return (hustar + alpha*(ustar + d))/pospart(h)
else:
return hustar + alpha*(ustar + d)
def phase_plane_curves(hstar, hustar, state, g=1., wave_family='both', y_axis='u', ax=None,
plot_unphysical=False):
"""
Plot the curves of points in the h - u or h-hu phase plane that can be
connected to (hstar,hustar).
state = 'qleft' or 'qright' indicates whether the specified state is ql or qr.
wave_family = 1, 2, or 'both' indicates whether 1-waves or 2-waves should be plotted.
Colors in the plots indicate whether the states can be connected via a shock or rarefaction.
"""
if ax is None:
fig, ax = plt.subplots()
h = np.linspace(0, hstar, 200)
if wave_family in [1,'both']:
if state == 'qleft' or plot_unphysical:
u = integral_curve(h, hstar, hustar, 1, g, y_axis=y_axis)
ax.plot(h,u,'b', label='1-rarefactions')
if state == 'qright' or plot_unphysical:
u = hugoniot_locus(h, hstar, hustar, 1, g, y_axis=y_axis)
ax.plot(h,u,'--r', label='1-shocks')
if wave_family in [2,'both']:
if state == 'qleft' or plot_unphysical:
u = hugoniot_locus(h, hstar, hustar, 2, g, y_axis=y_axis)
ax.plot(h,u,'--r', label='2-shocks')
if state == 'qright' or plot_unphysical:
u = integral_curve(h, hstar, hustar, 2, g, y_axis=y_axis)
ax.plot(h,u,'b', label='2-rarefactions')
h = np.linspace(hstar, 3, 200)
if wave_family in [1,'both']:
if state == 'qright' or plot_unphysical:
u = integral_curve(h, hstar, hustar, 1, g, y_axis=y_axis)
ax.plot(h,u,'--b', label='1-rarefactions')
if state == 'qleft' or plot_unphysical:
u = hugoniot_locus(h, hstar, hustar, 1, g, y_axis=y_axis)
ax.plot(h,u,'r', label='1-shocks')
if wave_family in [2,'both']:
if state == 'qright' or plot_unphysical:
u = hugoniot_locus(h, hstar, hustar, 2, g, y_axis=y_axis)
ax.plot(h,u,'r', label='2-shocks')
if state == 'qleft' or plot_unphysical:
u = integral_curve(h, hstar, hustar, 2, g, y_axis=y_axis)
ax.plot(h,u,'--b', label='2-rarefactions')
# plot and label the point (hstar, hustar)
ax.set_xlabel('Depth (h)')
if y_axis == 'u':
ustar = hustar/hstar
ax.set_ylabel('Velocity (u)')
else:
ustar = hustar # Fake it
ax.set_ylabel('Momentum (hu)')
ax.plot([hstar],[ustar],'ko',markersize=5)
ax.text(hstar + 0.1, ustar - 0.2, state, fontsize=13)
def make_axes_and_label(x1=-.5, x2=6., y1=-2.5, y2=2.5):
plt.plot([x1,x2],[0,0],'k')
plt.plot([0,0],[y1,y2],'k')
plt.axis([x1,x2,y1,y2])
plt.legend()
plt.xlabel("h = depth",fontsize=15)
plt.ylabel("hu = momentum",fontsize=15)
def phase_plane_plot(q_l, q_r, g=1., ax=None, force_waves=None, y_axis='u',
approx_states=None, hmin=0, color='g', include_contact=False):
r"""Plot the Hugoniot loci or integral curves in the h-u or h-hu plane."""
# Solve Riemann problem
states, speeds, reval, wave_types = \
exact_riemann_solution(q_l, q_r, g, force_waves=force_waves,
include_contact=include_contact)
# Set plot bounds
if ax is None:
fig, ax = plt.subplots()
x = states[0,:]
if y_axis == 'hu':
y = states[1,:]
else:
y = states[1,:]/pospart(states[0,:])
if states[0,middle] == 0:
dry_velocity_l = states[1,left]/pospart(states[0,left]) + 2*np.sqrt(g*states[0,left])
dry_velocity_r = states[1,right]/pospart(states[0,right]) - 2*np.sqrt(g*states[0,right])
y[1] = 1./(np.abs(np.sign(dry_velocity_l))+np.abs(np.sign(dry_velocity_r))) * \
(dry_velocity_l+dry_velocity_r)
xmax, xmin = max(x), min(x)
ymax = max(abs(y))
dx = xmax - xmin
ymax = max(abs(y))
ax.set_xlim(hmin, xmax + 0.5*dx)
ax.set_ylim(-1.5*ymax, 1.5*ymax)
ax.set_xlabel('Depth (h)')
if y_axis == 'u':
ax.set_ylabel('Velocity (u)')
else:
ax.set_ylabel('Momentum (hu)')
# Plot curves
h_l = states[0,left]
h1 = np.linspace(1.e-2,h_l)
h2 = np.linspace(h_l,xmax+0.5*dx)
if wave_types[0] == 'shock':
hu1 = hugoniot_locus(h1, h_l, states[1,left], wave_family=1, g=g, y_axis=y_axis)
hu2 = hugoniot_locus(h2, h_l, states[1,left], wave_family=1, g=g, y_axis=y_axis)
ax.plot(h1,hu1,'--r', label='Hugoniot locus (unphysical)')
ax.plot(h2,hu2,'r', label='Hugoniot locus (physical)')
else:
hu1 = integral_curve(h1, h_l, states[1,left], wave_family=1, g=g, y_axis=y_axis)
hu2 = integral_curve(h2, h_l, states[1,left], wave_family=1, g=g, y_axis=y_axis)
ax.plot(h1,hu1,'b', label='Integral curve (physical)')
ax.plot(h2,hu2,'--b', label='Integral curve (unphysical)')
h_r = states[0,right]
h1 = np.linspace(1.e-2,h_r)
h2 = np.linspace(h_r,xmax+0.5*dx)
if wave_types[1] == 'shock':
hu1 = hugoniot_locus(h1, states[0,right], states[1,right], wave_family=2, g=g, y_axis=y_axis)
hu2 = hugoniot_locus(h2, states[0,right], states[1,right], wave_family=2, g=g, y_axis=y_axis)
ax.plot(h1,hu1,'--r', label='Hugoniot locus (unphysical)')
ax.plot(h2,hu2,'r', label='Hugoniot locus (physical)')
else:
hu1 = integral_curve(h1, states[0,right], states[1,right], wave_family=2, g=g, y_axis=y_axis)
hu2 = integral_curve(h2, states[0,right], states[1,right], wave_family=2, g=g, y_axis=y_axis)
ax.plot(h1,hu1,'b', label='Integral curve (physical)')
ax.plot(h2,hu2,'--b', label='Integral curve (unphysical)')
for xp,yp in zip(x,y):
ax.plot(xp,yp,'ok',markersize=10, label='Exact solution states')
# Label states
if include_contact:
state_labels = ('Left', 'Middle', '', 'Right')
else:
state_labels = ('Left', 'Middle', 'Right')
for i,label in enumerate(state_labels):
ax.text(x[i] + 0.025*dx,y[i] + 0.025*ymax, label)
if approx_states is not None:
u = approx_states[1,:]/(approx_states[0,:]+1.e-15)
h = approx_states[0,:]
ax.plot(h,u,'o-',color=color,markersize=10,zorder=0, label='Approximate solution')
# The code below generates a legend with just one
# entry for each kind of line/marker, even if
# multiple plotting calls were made with that type
# of line/marker.
# It avoids making entries for lines/markers that
# don't actually appear on the given plot.
# It also alphabetizes the entries.
handles, labels = ax.get_legend_handles_labels()
i = np.arange(len(labels))
filter = np.array([])
unique_labels = list(set(labels))
for ul in unique_labels:
filter = np.append(filter,[i[np.array(labels)==ul][0]])
handles = [handles[int(f)] for f in filter]
labels = [labels[int(f)] for f in filter]
order = sorted(range(len(labels)), key=labels.__getitem__)
handles = [handles[i] for i in order]
labels = [labels[i] for i in order]
#ax.legend(handles,labels)
def plot_hugoniot_loci(plot_1=True,plot_2=False,y_axis='hu'):
h = np.linspace(0.001,3,100)
hstar = 1.0
legend = plot_1*['1-loci'] + plot_2*['2-loci']
for hustar in np.linspace(-4,4,15):
if plot_1:
hu = hugoniot_locus(h,hstar,hustar,wave_family=1,y_axis=y_axis)
plt.plot(h,hu,'-',color='coral')
if plot_2:
hu = hugoniot_locus(h,hstar,hustar,wave_family=2,y_axis=y_axis)
plt.plot(h,hu,'-',color='maroon')
plt.axis((0,3,-3,3))
plt.xlabel('depth h')
if y_axis=='hu':
plt.ylabel('momentum hu')
else:
plt.ylabel('velocity u')
plt.title('Hugoniot loci')
plt.legend(legend,loc=1)
plt.show()
def lambda_1(q, _, g=1.):
"Characteristic speed for shallow water 1-waves."
h, hu = q
if h > 0:
u = hu/h
return u - np.sqrt(g*h)
else:
return 0
def lambda_2(q, _, g=1.):
"Characteristic speed for shallow water 2-waves."
h, hu = q
if h > 0:
u = hu/h
return u + np.sqrt(g*h)
else:
return 0
def lambda_tracer(q, _, g=1.):
h, hu = q
if h > 0:
u = hu/h
return u
else:
return 0
# == Move to demos?
def make_demo_plot_function(h_l=3., h_r=1., u_l=0., u_r=0,
figsize=(10,3), hlim=(0,3.5), ulim=(-1,1),
force_waves=None, stripes=True):
from matplotlib.mlab import find
g = 1.
q_l = primitive_to_conservative(h_l,u_l)
q_r = primitive_to_conservative(h_r,u_r)
x = np.linspace(-1.,1.,1000)
states, speeds, reval, wave_types = \
exact_riemann_solution(q_l,q_r,g,force_waves=force_waves)
# compute particle trajectories:
def reval_rho_u(x):
q = reval(x)
rho = q[0]
u = q[1]/q[0]
rho_u = np.vstack((rho,u))
return rho_u
if stripes:
x_traj, t_traj, xmax = \
riemann_tools.compute_riemann_trajectories(states, speeds,
reval_rho_u,
wave_types, i_vel=1,
xmax=2,
rho_left=h_l/4.,
rho_right=h_r/4.)
else:
x_traj, t_traj, xmax = \
riemann_tools.compute_riemann_trajectories(states, speeds,
reval_rho_u,
wave_types, i_vel=1,
xmax=2,
num_left=3,
num_right=3)
num_vars = len(primitive_variables)
def plot_shallow_water_demo(t=0.5, fig=0):
if t == 0:
q = np.zeros((2,len(x)))
q[0,:] = q_l[0]*(x<=0) + q_r[0]*(x>0)
q[1,:] = q_l[1]*(x<=0) + q_r[1]*(x>0)
else:
q = np.array(reval(x/t))
if t<0.02:
q[1] = np.where(x<0, q_l[1], q_r[1])
primitive = conservative_to_primitive(q[0],q[1])
if fig == 0:
fig = plt.figure(figsize=figsize)
show_fig = True
else:
show_fig = False
axes = [0]*num_vars
for i in range(num_vars):
axes[i] = fig.add_subplot(1,num_vars,i+1)
q = primitive[i]
plt.plot(x,q,'-k',linewidth=3)
plt.title(primitive_variables[i])
if t != 0:
plt.suptitle('Solution at time $t='+str(t)+'$',fontsize=12)
else:
plt.suptitle('Initial data',fontsize=12)
axes[i].set_xlim(-1,1)
if i==0 and force_waves != 'raref':
# plot stripes only on depth plot
# (and suppress if nonphysical solution plotted)
n = find(t > t_traj)
if len(n)==0:
n = 0
else:
n = min(n.max(), len(t_traj)-1)
for j in range(1, x_traj.shape[1]-1):
j1 = find(x_traj[n,j] > x)
if len(j1)==0:
j1 = 0
else:
j1 = min(j1.max(), len(x)-1)
j2 = find(x_traj[n,j+1] > x)
if len(j2)==0:
j2 = 0
else:
j2 = min(j2.max(), len(x)-1)
# set advected color for density plot:
if x_traj[0,j]<0:
# shades of red for fluid starting from x<0
if np.mod(j,2)==0:
c = 'lightblue'
alpha = 1.0
else:
c = 'dodgerblue'
alpha = 1.0
else:
# shades of blue for fluid starting from x<0
if np.mod(j,2)==0:
c = 'cornflowerblue'
alpha = 1.0
else:
c = 'blue'
alpha = 1.0
plt.fill_between(x[j1:j2],q[j1:j2],0,color=c,alpha=alpha)
axes[0].set_ylim(hlim)
axes[1].set_ylim(ulim)
if show_fig:
plt.show()
return plot_shallow_water_demo
def macro_riemann_plot(which,context='notebook',figsize=(10,3)):
"""
Some simulations to show that the Riemann solution describes macroscopic behavior
in the Cauchy problem.
"""
from IPython.display import HTML
from clawpack import pyclaw
from matplotlib import animation
from clawpack.riemann import shallow_roe_tracer_1D
depth = 0
momentum = 1
tracer = 2
solver = pyclaw.ClawSolver1D(shallow_roe_tracer_1D)
solver.num_eqn = 3
solver.num_waves = 3
solver.bc_lower[0] = pyclaw.BC.wall
solver.bc_upper[0] = pyclaw.BC.wall
x = pyclaw.Dimension(-1.0,1.0,2000,name='x')
domain = pyclaw.Domain(x)
state = pyclaw.State(domain,solver.num_eqn)
state.problem_data['grav'] = 1.0
grid = state.grid
xc = grid.p_centers[0]
hl = 3.
hr = 1.
ul = 0.
ur = 0.
xs = 0.1
alpha = (xs-xc)/(2.*xs)
if which=='linear':
state.q[depth,:] = hl*(xc<=-xs) + hr*(xc>xs) + (alpha*hl + (1-alpha)*hr)*(xc>-xs)*(xc<=xs)
state.q[momentum,:] = hl*ul*(xc<=-xs) + hr*ur*(xc>xs) + (alpha*hl*ul + (1-alpha)*hr*ur)*(xc>-xs)*(xc<=xs)
elif which=='oscillatory':
state.q[depth,:] = hl*(xc<=-xs) + hr*(xc>xs) + (alpha*hl + (1-alpha)*hr+0.2*np.sin(8*np.pi*xc/xs))*(xc>-xs)*(xc<=xs)
state.q[momentum,:] = hl*ul*(xc<=-xs) + hr*ur*(xc>xs) + (alpha*hl*ul + (1-alpha)*hr*ur+0.2*np.cos(8*np.pi*xc/xs))*(xc>-xs)*(xc<=xs)
state.q[tracer,:] = xc
claw = pyclaw.Controller()
claw.tfinal = 0.5
claw.solution = pyclaw.Solution(state,domain)
claw.solver = solver
claw.keep_copy = True
claw.num_output_times = 5
claw.verbosity = 0
claw.run()
fig = plt.figure(figsize=figsize)
ax_h = fig.add_subplot(121)
ax_u = fig.add_subplot(122)
fills = []
frame = claw.frames[0]
h = frame.q[0,:]
u = frame.q[1,:]/h
b = 0*h
surface = h+b
tracer = frame.q[2,:]
x, = frame.state.grid.p_centers
line, = ax_h.plot(x, surface,'-k',linewidth=3)
line_u, = ax_u.plot(x, u,'-k',linewidth=3)
fills = {'navy': None,
'blue': None,
'cornflowerblue': None,
'deepskyblue': None}
colors = fills.keys()
def set_stripe_regions(tracer):
widthl = 0.3/hl
widthr = 0.3/hr
# Designate areas for each color of stripe
stripes = {}
stripes['navy'] = (tracer>=0)
stripes['blue'] = (tracer % widthr>=widthr/2.)*(tracer>=0)
stripes['cornflowerblue'] = (tracer<=0)
stripes['deepskyblue'] = (tracer % widthl>=widthl/2.)*(tracer<=0)
return stripes
stripes = set_stripe_regions(tracer)
for color in colors:
fills[color] = ax_h.fill_between(x,b,surface,facecolor=color,where=stripes[color],alpha=0.5)
ax_h.set_xlabel('$x$'); ax_u.set_xlabel('$x$')
ax_h.set_xlim(-1,1); ax_h.set_ylim(0,3.5)
ax_u.set_xlim(-1,1); ax_u.set_ylim(-1,1)
ax_u.set_title('Velocity'); ax_h.set_title('Depth')
def fplot(frame_number):
fig.suptitle('Solution at time $t='+str(frame_number/10.)+'$',fontsize=12)
# Remove old fill_between plots
for color in colors:
fills[color].remove()
frame = claw.frames[frame_number]
h = frame.q[0,:]
u = frame.q[1,:]/h
b = 0*h
tracer = frame.q[2,:]
surface = h+b
line.set_data(x,surface)
line_u.set_data(x,u)
stripes = set_stripe_regions(tracer)
for color in colors:
fills[color] = ax_h.fill_between(x,b,surface,facecolor=color,where=stripes[color],alpha=0.5)
return line,
if context in ['notebook','html']:
anim = animation.FuncAnimation(fig, fplot, frames=len(claw.frames), interval=200, repeat=False)
plt.close()
return HTML(anim.to_jshtml())
else: # PDF output
fplot(0)
plt.show()
fplot(2)
return fig
def make_plot_functions(h_l, h_r, u_l, u_r,
g=1.,force_waves=None,extra_lines=None,stripes=True,
include_contact=False):
q_l = State(Depth = h_l,
Momentum = h_l*u_l)
q_r = State(Depth = h_r,
Momentum = h_r*u_r)
states, speeds, reval, wave_types = \
exact_riemann_solution(q_l,q_r,g, force_waves=force_waves,
include_contact=include_contact)
plot_function_stripes = make_demo_plot_function(h_l,h_r,u_l,u_r,
figsize=(7,2),hlim=(0,4.5),ulim=(-2,2),
force_waves=force_waves,stripes=stripes)
def plot_function_xt_phase(plot_1_chars=False,plot_2_chars=False,plot_tracer_chars=False):
plt.figure(figsize=(7,2))
ax = plt.subplot(121)
riemann_tools.plot_waves(states, speeds, reval, wave_types, t=0,
ax=ax, color='multi')
if plot_1_chars:
riemann_tools.plot_characteristics(reval,lambda_1,
axes=ax,extra_lines=extra_lines)
if plot_2_chars:
riemann_tools.plot_characteristics(reval,lambda_2,
axes=ax,extra_lines=extra_lines)
if plot_tracer_chars:
riemann_tools.plot_characteristics(reval,lambda_tracer,
axes=ax,extra_lines=extra_lines)
ax = plt.subplot(122)
phase_plane_plot(q_l,q_r,g,ax=ax,
force_waves=force_waves,y_axis='u',
include_contact=include_contact)
plt.title('Phase plane')
plt.show()
return plot_function_stripes, plot_function_xt_phase
def plot_riemann_SW(h_l,h_r,u_l,u_r,g=1.,force_waves=None,extra_lines=None,
tracer=False, particle_paths=True):
stripes = not tracer
plot_function_stripes, plot_function_xt_phase = \
make_plot_functions(h_l,h_r,u_l,u_r,g,
force_waves,extra_lines,stripes=stripes,
include_contact=tracer)
interact(plot_function_stripes,
t=widgets.FloatSlider(value=0.,min=0,max=.5), fig=fixed(0))
if tracer:
interact(plot_function_xt_phase,
plot_1_chars=Checkbox(description='1-characteristics',
value=False),
plot_2_chars=Checkbox(description='2-characteristics'),
plot_tracer_chars=Checkbox(description='Tracer characteristics'))
elif particle_paths:
interact(plot_function_xt_phase,
plot_1_chars=Checkbox(description='1-characteristics',
value=False),
plot_2_chars=Checkbox(description='2-characteristics'),
plot_tracer_chars=Checkbox(description='Particle paths'))
else:
interact(plot_function_xt_phase,
plot_1_chars=Checkbox(description='1-characteristics',
value=False),
plot_2_chars=Checkbox(description='2-characteristics'),
plot_tracer_chars=fixed(value=False)) # suppress checkbox
| 2.71875
| 3
|
tournamentcontrol/competition/migrations/0006_sportingpulse_import_fields.py
|
goodtune/vitriolic
| 0
|
12778724
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('competition', '0005_alter_club_facebook_youtube_position'),
]
operations = [
migrations.AddField(
model_name='division',
name='sportingpulse_url',
field=models.URLField(help_text='Here be dragons! Enter at own risk!', max_length=1024, null=True, blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='match',
name='external_identifier',
field=models.CharField(db_index=True, max_length=20, unique=True, null=True, blank=True),
preserve_default=True,
),
]
| 1.695313
| 2
|
doc/source/examples/transform.py
|
WhiteSheet/pcsg
| 0
|
12778725
|
import math
import pcsg
from exampleimg import runtime
from exampleimg import conf
def _setAttributes2D (attributes):
return attributes.override ({
'camera.view': (0, 0, 0, 0, 0, 0, 8)
})
def _setAttributes (attributes):
return attributes.override ({
'camera.view': (0, 0, 0, 70, 0, 30, 12),
'camera.projection': 'perspective'
})
def _posttransform (item):
return pcsg.transform.Translate (pcsg.solid.LinearExtrude (height = 1, children = (item)), z = 2)
# Examples for transform.Translate
class Translate:
"""
"""
@staticmethod
def example_a (attributes, isThumbnail):
"""
Transform solid on x-axis
import pcsg
body = pcsg.solid.Sphere (radius = 1)
item = pcsg.transform.Translate (body, y = 2)
"""
body = pcsg.solid.Sphere (radius = 1, attributes = {'material': conf.getMaterial (0)})
item = pcsg.transform.Translate (body, y = 2, attributes = {'material': conf.getMaterial (1)})
a = _setAttributes (attributes)
return ((a, body),(a, item))
@staticmethod
def example_b (attributes, isThumbnail):
"""
Transform solid on x- and y-axis
import pcsg
body = pcsg.solid.Sphere (radius = 1)
item = pcsg.transform.Translate (body, x = 1, y = 2)
"""
body = pcsg.solid.Sphere (radius = 1, attributes = {'material': conf.getMaterial (0)})
item = pcsg.transform.Translate (body, x = 1, y = 2, attributes = {'material': conf.getMaterial (1)})
a = _setAttributes (attributes)
return ((a, body),(a, item))
@staticmethod
def example_c (attributes, isThumbnail):
"""
Transform solid by vector
import pcsg
body = pcsg.solid.Sphere (radius = 1)
item = pcsg.transform.Translate (body, (1, 2, -2))
"""
body = pcsg.solid.Sphere (radius = 1, attributes = {'material': conf.getMaterial (0)})
item = pcsg.transform.Translate (body, (1, 2, -2), attributes = {'material': conf.getMaterial (1)})
a = _setAttributes (attributes)
return ((a, body),(a, item))
@staticmethod
def example_d (attributes, isThumbnail):
"""
Transform shape by vector
import pcsg
body = pcsg.shape.Circle (radius = 0.5)
item = pcsg.transform.Translate (body, (0.5, 1))
"""
body = pcsg.shape.Circle (radius = 0.5, attributes = {'material': conf.getMaterial (0)})
item = pcsg.transform.Translate (body, (0.5, 1), attributes = {'material': conf.getMaterial (1)})
a = _setAttributes2D (attributes)
return ((a, body),(a, item))
# Examples for transform.Scale
class Scale:
"""
"""
@staticmethod
def example_a (attributes, isThumbnail):
"""
Scale solid on x-axis
import pcsg
body = pcsg.solid.Sphere (radius = 1)
item = pcsg.transform.Scale (body, sy = 2)
"""
body = pcsg.solid.Sphere (radius = 1, attributes = {'material': conf.getMaterial (0)})
item = pcsg.transform.Scale (body, sy = 2, attributes = {'material': conf.getMaterial (2)})
a = _setAttributes (attributes)
return ((a, body),(a, item))
@staticmethod
def example_b (attributes, isThumbnail):
"""
Scale solid on x- and y-axis
import pcsg
body = pcsg.solid.Sphere (radius = 1)
item = pcsg.transform.Scale (body, sx = 0.6, sy = 1.3)
"""
body = pcsg.solid.Sphere (radius = 1, attributes = {'material': conf.getMaterial (0)})
item = pcsg.transform.Scale (body, sx = 0.6, sy = 1.3, attributes = {'material': conf.getMaterial (2)})
a = _setAttributes (attributes)
return ((a, body),(a, item))
@staticmethod
def example_c (attributes, isThumbnail):
"""
Scale solid by vector
import pcsg
body = pcsg.solid.Sphere (radius = 1)
item = pcsg.transform.Scale (body, (1.7, 0.9, 1.2))
"""
body = pcsg.solid.Sphere (radius = 1, attributes = {'material': conf.getMaterial (0)})
item = pcsg.transform.Scale (body, (1.7, 0.9, 1.2), attributes = {'material': conf.getMaterial (2)})
a = _setAttributes (attributes)
return ((a, body),(a, item))
@staticmethod
def example_d (attributes, isThumbnail):
"""
Scale shape by vector
import pcsg
body = pcsg.shape.Circle (radius = 0.5)
item = pcsg.transform.Scale (body, (0.5, 1))
"""
body = pcsg.shape.Circle (radius = 0.5, attributes = {'material': conf.getMaterial (0)})
item = pcsg.transform.Scale (body, (0.5, 1), attributes = {'material': conf.getMaterial (2)})
a = _setAttributes2D (attributes)
return ((a, body),(a, item))
# Examples for transform.Rotate
class Rotate:
"""
"""
@staticmethod
def example_a (attributes, isThumbnail):
"""
Rotate solid around x-axis
import pcsg
body = pcsg.solid.Cube (size = 1)
item = pcsg.transform.Rotate (body, rx = 25)
"""
body = pcsg.solid.Cube (size = 1, attributes = {'material': conf.getMaterial (0)})
item = pcsg.transform.Rotate (body, rx = 25, attributes = {'material': conf.getMaterial (3)})
a = _setAttributes (attributes)
return ((a, body),(a, item))
@staticmethod
def example_b (attributes, isThumbnail):
"""
Rotate solid around x- and y-axis
import pcsg
body = pcsg.solid.Cube (size = 1)
item = pcsg.transform.Rotate (body, rx = 25, ry = 15)
"""
body = pcsg.solid.Cube (size = 1, attributes = {'material': conf.getMaterial (0)})
item = pcsg.transform.Rotate (body, rx = 25, ry = 15, attributes = {'material': conf.getMaterial (3)})
a = _setAttributes (attributes)
return ((a, body),(a, item))
@staticmethod
def example_c (attributes, isThumbnail):
"""
Rotate solid around vector
import pcsg
body = pcsg.solid.Cube (size = 1)
item = pcsg.transform.Rotate (body, (10, 20, 35))
"""
body = pcsg.solid.Cube (size = 1, attributes = {'material': conf.getMaterial (0)})
item = pcsg.transform.Rotate (body, (10, 20, 35), attributes = {'material': conf.getMaterial (3)})
a = _setAttributes (attributes)
return ((a, body),(a, item))
@staticmethod
def example_d (attributes, isThumbnail):
"""
Rotate shape around z-axis
import pcsg
body = pcsg.transform.Translate (
pcsg.shape.Square (size = 0.5),
x = 1
)
item = pcsg.transform.Rotate (body, rz = 30)
"""
body = pcsg.transform.Translate (
pcsg.shape.Square (size = 0.5),
x = 1,
attributes = {'material': conf.getMaterial (0)}
)
item = pcsg.transform.Rotate (body, rz = 30, attributes = {'material': conf.getMaterial (3)})
a = _setAttributes2D (attributes)
return ((a, body),(a, item))
| 2.6875
| 3
|
main.py
|
aiziXx/WechatHelper
| 3
|
12778726
|
<gh_stars>1-10
'''
Function:
微信小助手主函数
Author:
Charles
微信公众号:
Charles的皮卡丘
'''
import os
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Wechat helper(微信小助手), Author: Charles, WeChat Official Accounts: Charles_pikachu(微信公众号: Charles的皮卡丘), Version: V0.1.0")
parser.add_argument('-o', dest='option', help='Choose the function you need, including <analysisFriends>, <antiWithdrawal>, <wechatRobot> and <autoReply>.\
(选择你需要的功能, 可选项包括: 好友分析<analysisFriends>, 消息防撤回<antiWithdrawal>, 开启自动聊天机器人<wechatRobot> 和 微信消息自动回复<autoReply>)')
parser.add_argument('-k', dest='keywords', help='Keywords for <autoReply>, use "*" to separate if keywords is more than one.(选择autoRelpy功能时的关键词, 若有多个关键词则用*分隔)')
parser.add_argument('-c', dest='contents', help='Contents for <autoReply>, use "*" to separate if contents is more than one.(选择autoRelpy功能时的回复内容, 若有多个回复内容则用*分隔)')
args = parser.parse_args()
if args.option == 'analysisFriends':
from utils.analysisFriends import analysisFriends
print('[INFO]: analysisFriends...')
savedir = os.path.join(os.getcwd(), 'results')
analysisFriends().run(savedir=savedir)
print('[INFO]: analysis friends successfully, results saved into %s...(微信好友分析成功, 结果保存在%s...)' % (savedir, savedir))
elif args.option == 'antiWithdrawal':
from utils.antiWithdrawal import antiWithdrawal
print('[INFO]: antiWithdrawal...')
antiWithdrawal().run()
elif args.option == 'wechatRobot':
from utils.wechatRobot import wechatRobot
print('[INFO]: wechatRobot...')
wechatRobot().run()
elif args.option == 'autoReply':
from utils.autoReply import autoReply
print('[INFO]: autoReply...')
keywords = args.keywords
contents = args.contents
if keywords:
keywords = keywords.split('*')
if contents:
contents = contents.split('*')
autoReply().run(keywords=keywords, replycontents=contents)
else:
print('[INFO]: argparse error...(参数解析出错, 可选项必须是<analysisFriends>, <antiWithdrawal>, <wechatRobot> 或 <autoReply>)')
| 3.140625
| 3
|
source/socket-client.py
|
Chu3an/rpi-iot-lesson
| 0
|
12778727
|
import socket
HOST, PORT = '127.0.0.1', 8000
clientMessage = 'Hello!'
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
client.connect((HOST, PORT))
client.sendall(clientMessage.encode())
serverMessage = str(client.recv(1024), encoding='utf-8')
print('Server:', serverMessage)
| 2.734375
| 3
|
conanfile.py
|
mmha/conan-opencl-icd-loader
| 0
|
12778728
|
<filename>conanfile.py
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake, tools
import os
class KhronosOpenCLICDLoaderConan(ConanFile):
name = "khronos-opencl-icd-loader"
version = "20190412"
description = "The OpenCL ICD Loader"
topics = ("conan", "opencl", "opencl-icd-loader", "build-system",
"icd-loader")
url = "https://github.com/bincrafters/conan-khronos-opencl-icd-loader"
homepage = "https://github.com/KhronosGroup/OpenCL-ICD-Loader"
author = "Bincrafters <<EMAIL>>"
license = "Apache-2.0"
exports = ["LICENSE.md"]
exports_sources = [
"CMakeLists.txt", "0001-static-library.patch",
"0002-Work-around-missing-declarations-in-MinGW-headers.patch",
"0003-Don-t-include-MS-DX-SDK-headers-for-MinGW.patch",
"0004-Set-CMAKE_C_STANDARD.patch"
]
generators = "cmake"
settings = "os", "arch", "compiler", "build_type"
options = {"fPIC": [True, False], "shared": [True, False]}
default_options = {"fPIC": True, "shared": False}
requires = "khronos-opencl-headers/20190412@bincrafters/stable"
_source_subfolder = "source_subfolder"
_build_subfolder = "build_subfolder"
def config_options(self):
if self.settings.os == "Windows":
del self.options.fPIC
def configure(self):
del self.settings.compiler.libcxx
def source(self):
commit = "66ecca5dce2c4425a48bdb0cf0de606e4da43ab5"
sha256 = "3af9efaf9ebc68e1fb18b7904ec71004a9e71cf074e2ce70b719382b65f2b609"
tools.get("{0}/archive/{1}.tar.gz".format(self.homepage, commit),
sha256=sha256)
extracted_dir = "OpenCL-ICD-Loader-" + commit
os.rename(extracted_dir, self._source_subfolder)
def _configure_cmake(self):
cmake = CMake(self)
cmake.configure(build_folder=self._build_subfolder)
return cmake
def _is_mingw(self):
subsystem_matches = self.settings.get_safe("os.subsystem") in [
"msys", "msys2"
]
compiler_matches = self.settings.os == "Windows" and self.settings.compiler == "gcc"
return subsystem_matches or compiler_matches
def build(self):
tools.patch(base_path=self._source_subfolder,
patch_file="0001-static-library.patch")
if self._is_mingw():
tools.patch(
base_path=self._source_subfolder,
patch_file=
"0002-Work-around-missing-declarations-in-MinGW-headers.patch")
tools.patch(base_path=self._source_subfolder,
patch_file=
"0003-Don-t-include-MS-DX-SDK-headers-for-MinGW.patch")
tools.patch(base_path=self._source_subfolder,
patch_file="0004-Set-CMAKE_C_STANDARD.patch")
cmake = self._configure_cmake()
cmake.build()
def package(self):
self.copy(pattern="LICENSE",
dst="licenses",
src=self._source_subfolder)
cmake = self._configure_cmake()
cmake.install()
def package_info(self):
self.cpp_info.libs = tools.collect_libs(self)
if self.settings.os == "Linux":
self.cpp_info.libs.extend(["pthread", "dl"])
elif self.settings.os == "Windows" and \
self.settings.get_safe("os.subsystem") != "wsl":
self.cpp_info.libs.append("cfgmgr32")
| 1.976563
| 2
|
mkdocs.py
|
dsbowen/flask-download-btn
| 1
|
12778729
|
<filename>mkdocs.py
from docstr_md.python import PySoup, compile_md
from docstr_md.src_href import Github
src_href = Github('https://github.com/dsbowen/flask-download-btn/blob/master')
path = 'flask_download_btn/__init__.py'
soup = PySoup(path=path, parser='sklearn', src_href=src_href)
compile_md(soup, compiler='sklearn', outfile='docs_md/manager.md')
path = 'flask_download_btn/download_btn_mixin.py'
soup = PySoup(path=path, parser='sklearn', src_href=src_href)
soup.rm_properties()
soup.objects[-1].rm_methods('handle_form_functions', 'create_file_functions')
soup.import_path = 'flask_download_btn'
compile_md(soup, compiler='sklearn', outfile='docs_md/download_btn_mixin.md')
| 2.28125
| 2
|
pecan/lang/optimizer/arithmetic.py
|
ondrik-misc-code/Pecan
| 0
|
12778730
|
#!/usr/bin/env python3.6
# -*- coding=utf-8 -*-
from pecan.lang.ir_transformer import IRTransformer
from pecan.lang.optimizer.basic_optimizer import BasicOptimizer
from pecan.lang.ir import *
class ArithmeticOptimizer(BasicOptimizer):
def constant_eq(self, node, val):
return type(node) is IntConst and node.val == val
def transform_Add(self, node):
if self.constant_eq(node.a, 0):
self.changed = True
return self.transform(node.b)
elif self.constant_eq(node.b, 0):
self.changed = True
return self.transform(node.a)
else:
return Add(self.transform(node.a), self.transform(node.b)).with_type(node.get_type())
def transform_Sub(self, node):
if self.constant_eq(node.b, 0):
self.changed = True
return self.transform(node.a)
else:
return Sub(self.transform(node.a), self.transform(node.b)).with_type(node.get_type())
def transform_Equals(self, node):
# we can only do the following transformation once we know types, otherwise we will be unable to resolve the dynamic call to 'adder'
if node.a.get_type() is not None and node.b.get_type() is not None:
if type(node.a) is VarRef and type(node.b) is Add:
self.changed = True
return self.transform(Call('adder', [node.b.a, node.b.b, node.a]))
elif type(node.b) is VarRef and type(node.a) is Add:
self.changed = True
return self.transform(Call('adder', [node.a.a, node.a.b, node.b]))
return super().transform_Equals(node)
| 2.78125
| 3
|
notes/2017-10-10-voxel-reconstruction/figures/my_draw_scene.py
|
talonchandler/dipsim
| 0
|
12778731
|
<reponame>talonchandler/dipsim<gh_stars>0
import numpy as np
import subprocess
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def draw_scene(scene_string, filename='out.png', my_ax=None, dpi=500,
save_file=False, chop=True):
asy_string = """
import three;
import graph3;
settings.outformat = "pdf";
settings.prc = true;
settings.embed= true;
settings.render=16;
size(6cm,6cm);
currentprojection = orthographic(1, 1, 1);
void circle(real Theta, real Alpha, bool dash, triple color) {
triple normal = expi(Theta, 0);
real h = 1 - sqrt(2 - 2*cos(Alpha) - sin(Alpha)^2);
real radius = sin(Alpha);
path3 mycircle = circle(c=h*normal, r=radius, normal=normal);
if (dash) {
draw(mycircle, p=linetype(new real[] {8,8}, offset=xpart(color))+rgb(xpart(color), ypart(color), zpart(color)));
} else {
draw(mycircle, p=rgb(xpart(color), ypart(color), zpart(color)));
}
}
void ellipse(real Theta, real Phi, real a, real b, real theta, bool dash, triple color) {
triple normal = expi(Theta, Phi);
real a_scaled = a/max(a, b);
real b_scaled = b/max(a, b);
path3 mycircle = rotate(degrees(Phi), Z)*rotate(degrees(Theta), Y)*shift(Z)*rotate(degrees(theta), Z)*scale(a_scaled, b_scaled, 1)*circle(c=O, r=0.05, normal=Z);
if (dash) {
draw(mycircle, p=linetype(new real[] {8,8}, offset=xpart(color))+rgb(xpart(color), ypart(color), zpart(color)));
} else {
draw(mycircle, p=rgb(xpart(color), ypart(color), zpart(color)));
}
}
void mydot(real Theta, triple color) {
triple normal = expi(Theta, 0);
dot(normal, p=rgb(xpart(color), ypart(color), zpart(color)));
}
void arrow(real c, real Theta, real Phi_Pol, triple color, bool dash) {
if (dash) {
draw(rotate(Theta, Y)*rotate(Phi_Pol, Z)*(Z--(Z+0.2*X)), p=linetype(new real[] {4,4}, offset=xpart(color))+rgb(xpart(color), ypart(color), zpart(color)), arrow=Arrow3(emissive(rgb(xpart(color), ypart(color), zpart(color)))));
draw(rotate(Theta, Y)*rotate(Phi_Pol, Z)*(Z--(Z-0.2*X)), p=linetype(new real[] {4,4}, offset=xpart(color))+rgb(xpart(color), ypart(color), zpart(color)), arrow=Arrow3(emissive(rgb(xpart(color), ypart(color), zpart(color)))));
} else {
draw(rotate(Theta, Y)*rotate(Phi_Pol, Z)*(Z--(Z+0.2*X)), p=rgb(xpart(color), ypart(color), zpart(color)), arrow=Arrow3(emissive(rgb(xpart(color), ypart(color), zpart(color)))));
draw(rotate(Theta, Y)*rotate(Phi_Pol, Z)*(Z--(Z-0.2*X)), p=rgb(xpart(color), ypart(color), zpart(color)), arrow=Arrow3(emissive(rgb(xpart(color), ypart(color), zpart(color)))));
}
}
void dip_arrow(real X, real Y, real Theta, real Phi, real length, triple color) {
//draw(-expi(Theta, Phi)--expi(Theta, Phi));
draw(shift((X, Y, 0))*(O--length*expi(Theta, Phi)), p=rgb(xpart(color), ypart(color), zpart(color)), arrow=Arrow3(emissive(rgb(xpart(color), ypart(color), zpart(color)))));
draw(shift((X, Y, 0))*(O--(-length*expi(Theta, Phi))), p=rgb(xpart(color), ypart(color), zpart(color)), arrow=Arrow3(emissive(rgb(xpart(color), ypart(color), zpart(color)))));
dot((X,Y,0), p=rgb(xpart(color), ypart(color), zpart(color)));
}
void watson(real Theta, real Phi, real kappa, real x, real y, real z) {
int n_phi = 10;
int n_theta = 10;
real max_radius = 0;
if(kappa > 0){
max_radius = exp(kappa);
}
else{
max_radius = 1.0;
}
for(int i=0; i <= n_theta; ++i) {
real Theta_i = pi*i/n_theta;
real weight = exp(kappa*(cos(Theta_i)**2))/max_radius;
path3 mycircle = circle(c=Z*weight*cos(Theta_i), r=weight*sin(Theta_i));
draw(shift((x, y, z))*rotate(angle=degrees(Phi), u=O, v=Z)*rotate(angle=degrees(Theta), u=O, v=Y)*mycircle);
}
triple f(real t) {
real weight = exp(kappa*(cos(t)**2))/max_radius;
return (0, weight*sin(t), weight*cos(t));
}
path3 phi_path = graph(f, 0, 2pi, operator ..);
for(int i=0; i <= n_phi; ++i) {
real Phi_i = 2*pi*i/n_theta;
draw(shift((x, y, z))*rotate(angle=degrees(Phi), u=O, v=Z)*rotate(angle=degrees(Theta), u=O, v=Y)*rotate(angle=degrees(Phi_i), u=(0,0,0), v=(0,0,1))*phi_path);
}
}
real len = 50;
draw((-len,-len)--(len,-len)--(len,len)--(-len,len)--(-len,-len), white);
draw(scale(50, 50, 0)*unitplane, surfacepen=white+opacity(0.5));
defaultpen(fontsize(8pt));
draw((0, -10, 0)--(10, -10, 0), L=Label("$10$ px", position=MidPoint, align=NW));
dotfactor=2;
"""
asy_string += scene_string
asy_string += "dot(O);shipout(scale(4.0)*currentpicture.fit());"
text_file = open("temp.asy", "w")
text_file.write(asy_string)
text_file.close()
subprocess.call(['asy', 'temp.asy'])
subprocess.call(['convert', '-density', str(dpi), '-units', 'PixelsPerInch', 'temp.pdf', 'temp.png'])
im = mpimg.imread('temp.png')
# Chop top of im to make it square and fix asy error
if chop:
im = im[int(im.shape[1]*0.075):,:,:]
f = plt.figure(figsize=(5, 5), frameon=False)
local_ax = plt.axes([0, 0, 1, 1]) # x, y, width, height
if my_ax == None:
my_ax = local_ax
for ax in [local_ax, my_ax]:
#draw_axis(ax)
ax.spines['right'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])
# Plot
ax.imshow(im, interpolation='none')
# Save
if save_file:
print("Saving: "+filename)
f.savefig(filename, dpi=dpi)
subprocess.call(['rm', 'temp.asy', 'temp.pdf', 'temp.png'])
return ax
| 2.4375
| 2
|
zinnia/migrations/__init__.py
|
Boondockers-Welcome/django-blog-zinnia
| 1,522
|
12778732
|
"""Migrations for Zinnia"""
| 1.09375
| 1
|
utils/tools.py
|
yshen47/iq
| 59
|
12778733
|
<reponame>yshen47/iq
"""Contains a set of helper functions.
"""
class Dict2Obj(dict):
"""Converts dicts to objects.
"""
def __getattr__(self, name):
if name in self:
return self[name]
else:
raise AttributeError("No such attribute: " + name)
def __setattr__(self, name, value):
self[name] = value
def __delattr__(self, name):
if name in self:
del self[name]
else:
raise AttributeError("No such attribute: " + name)
def merge(self, other, overwrite=True):
for name in other:
if overwrite or name not in self:
self[name] = other[name]
| 3.0625
| 3
|
tests/test_suite.py
|
ikethecoder/sae-postgres
| 1
|
12778734
|
<gh_stars>1-10
import sys, os
import logging
from unittest import TestCase
from client.cli import CLI
from tests.expect import Expect
log = logging.getLogger(__name__)
logging.basicConfig(level=os.environ['LOG_LEVEL'],
format='%(asctime)s - %(levelname)s - %(message)s')
creds = {
"PGHOST" : os.environ['PGHOST'],
"PGPORT" : os.environ['PGPORT'],
"PGUSER" : os.environ['PGUSER'],
"PGPASSWORD" : os.environ['PGPASSWORD'],
"PGDATABASE" : os.environ['PGDATABASE']
}
class TestSuite(TestCase):
# def tearDown(self):
def setUp(self):
self.clean()
self.prepare_test_db()
self.prepare()
def clean(self):
admin = CLI(creds, True)
db = "test_db"
admin.execute("DROP DATABASE IF EXISTS %s;" % db, False)
databases = ["orig_db", "orig_db_2"]
for rdb in databases:
admin.execute("DROP DATABASE %s;" % rdb, False)
admin.execute("DROP ROLE %s_admin;" % rdb, False)
admin.execute("DROP ROLE %s_user;" % rdb, False)
admin.execute("DROP ROLE %s_enduser;" % rdb, False)
admin.execute("DROP ROLE %s_contribute;" % rdb, False)
admin.execute("DROP ROLE %s_readonly;" % rdb, False)
for n in range(1):
rdb = "project_%s" % (n + 1)
admin.execute("DROP DATABASE %s;" % rdb, False)
admin.execute("DROP ROLE %s_contribute;" % rdb, False)
admin.execute("DROP ROLE %s_readonly;" % rdb, False)
admin.execute("DROP ROLE %s_min_public;" % rdb, False)
for u in range(1):
user = "%s_user_%s" % (rdb, (u + 1))
admin.execute("DROP ROLE %s;" % user, False)
admin.execute("DROP ROLE %s;" % 'user_x', False)
admin.execute("DROP ROLE %s;" % 'tmp_user', False)
admin.execute("DROP ROLE %s;" % 'tmp_user_incremental', False)
admin.execute("DROP DATABASE temp_db;", False)
admin.execute("DROP ROLE %s;" % 'i_test_user', False)
for n in range(10):
admin.execute("DROP ROLE user_%s;" % n, False)
admin.execute("DROP OWNED BY %s_contribute;" % db, False)
admin.execute("DROP ROLE %s_contribute;" % db, False)
admin.execute("DROP OWNED BY %s_readonly;" % db, False)
admin.execute("DROP ROLE %s_readonly;" % db, False)
admin.execute("DROP OWNED BY %s_min_public;" % db, False)
admin.execute("DROP ROLE %s_min_public;" % db, False)
admin.close()
return self
def prepare_test_db(self):
admin = CLI(creds, True)
db = "test_db"
try:
admin.execute("CREATE DATABASE %s;" % db, True)
admin.execute_template("sql/new_database.sql.tpl", APP_DATABASE=db)
user = "user_x"
admin_on_db = CLI({**creds, **{"PGDATABASE":db}}, True)
admin_on_db.execute_template("sql/setup_new_database.sql.tpl")
admin_on_db.execute_template("sql/setup_roles.sql.tpl", WORKSPACE=db)
admin_on_db.execute_template("sql/user.sql.tpl", USER=user, PASSWORD=<PASSWORD>)
admin_on_db.execute_template("sql/user_connect.sql.tpl", APP_DATABASE=db, USER=user)
admin_on_db.execute_template("sql/setup_user.sql.tpl", WORKSPACE=db, USER=user)
admin_on_db.execute_template("sql/setup_user_2.sql.tpl", WORKSPACE=db, USER=user)
for n in range(10):
admin_on_db.execute_template("sql/user.sql.tpl", USER="user_%s" % n, PASSWORD=Expect.TMP_PASSWORD)
admin_on_db.execute_template("sql/user_connect.sql.tpl", APP_DATABASE=db, USER="user_%s" % n)
finally:
admin.close()
def prepare(self):
admin = CLI(creds, True)
try:
for n in range(1):
rdb = "project_%s" % (n + 1)
admin.execute("CREATE DATABASE %s;" % rdb, True)
admin.execute_template("sql/new_database.sql.tpl", APP_DATABASE=rdb)
admin_on_db = CLI({**creds, **{"PGDATABASE":rdb}}, True)
admin_on_db.execute_template("sql/setup_new_database.sql.tpl")
admin_on_db.execute_template("sql/setup_roles.sql.tpl", WORKSPACE=rdb)
for u in range(1):
user = "%s_user_%s" % (rdb, (u + 1))
admin_on_db.execute_template("sql/user.sql.tpl", USER=user, PASSWORD=Expect.TMP_PASSWORD)
admin_on_db.execute_template("sql/user_connect.sql.tpl", APP_DATABASE=rdb, USER=user)
admin_on_db.execute_template("sql/setup_user.sql.tpl", WORKSPACE=rdb, USER=user)
admin_on_db.execute_template("sql/setup_user_2.sql.tpl", WORKSPACE=rdb, USER=user)
admin_on_db.close()
finally:
admin.close()
return self
def test_simple_user_creating_database(self):
admin = Expect(creds)
try:
user = 'i_test_user'
admin.execute('show search_path')
admin.execute_template("sql/original_db_prep.sql", POSTGRES_APP_USERNAME=user, POSTGRES_APP_PASSWORD=Expect.TMP_PASSWORD)
admin.execute("ALTER USER %s CREATEDB" % user, True)
enduser_on_db = Expect({**creds, **{"PGUSER": user, "PGPASSWORD": Expect.TMP_PASSWORD}})
db = "temp_db"
try:
enduser_on_db.execute("CREATE DATABASE %s" % db, True)
finally:
enduser_on_db.execute("DROP ROLE %s_contribute" % db, False)
enduser_on_db.execute("DROP ROLE %s_readonly" % db, False)
enduser_on_db.execute("DROP DATABASE %s" % db, False)
enduser_on_db.close()
finally:
admin.close()
def test_set_search_path(self):
admin = Expect(creds)
try:
databases = ['orig_db']
for db in databases:
admin.execute("CREATE DATABASE %s;" % db, True)
admin.execute_template("sql/original_db_prep.sql", APP_DATABASE=db, POSTGRES_APP_USERNAME='%s_admin' % db, POSTGRES_APP_PASSWORD=Expect.TMP_PASSWORD)
admin_on_db = Expect({**creds, **{"PGDATABASE":db}})
admin_on_db.execute_template("sql/original_db_setup.sql", APP_DATABASE=db, WORKSPACE=db, POSTGRES_APP_PASSWORD=Expect.TMP_PASSWORD)
admin_on_db.execute_template("sql/original_db_user_setup.sql", WORKSPACE=db, USER='%s_enduser' % db, PASSWORD=Expect.TMP_PASSWORD)
admin_on_db.close()
admin.execute("ALTER DATABASE %s SET search_path = working_data" % db, True)
enduser_on_db = Expect({**creds, **{"PGDATABASE":db, "PGUSER": "%s_enduser" % db, "PGPASSWORD": Expect.TMP_PASSWORD}})
enduser_on_db.match_results('sql/query_search_path.sql', 'results/test_set_search_path/results.txt')
enduser_on_db.close()
finally:
admin.close()
# def test_original_verify_permissions(self):
# admin = Expect(creds)
# admin.execute('grant all on database template1 to public', True)
# try:
# databases = ['orig_db', 'orig_db_2']
# for db in databases:
# admin.execute("CREATE DATABASE %s;" % db, True)
# admin.execute_template("sql/original_db_prep.sql", APP_DATABASE=db, POSTGRES_APP_USERNAME='%s_admin' % db, POSTGRES_APP_PASSWORD=Expect.TMP_PASSWORD)
# admin_on_db = Expect({**creds, **{"PGDATABASE":db}})
# admin_on_db.execute("REVOKE ALL ON SCHEMA public FROM public", True)
# #admin_on_db.execute('GRANT ALL ON SCHEMA public to public', True)
# admin_on_db.execute_template("sql/original_db_setup.sql", APP_DATABASE=db, WORKSPACE=db, POSTGRES_APP_PASSWORD=Expect.TMP_PASSWORD)
# admin_on_db.execute("ALTER ROLE %s_contribute SET search_path = working_data" % db, True)
# admin_on_db.execute_template("sql/original_db_user_setup.sql", WORKSPACE=db, USER='%s_enduser' % db, PASSWORD=Expect.TMP_PASSWORD)
# #admin_on_db.execute("CREATE USER %s WITH ENCRYPTED PASSWORD '%s'" % ("%s_enduser" % db, Expect.TMP_PASSWORD))
# admin_on_db.close()
# #admin.execute("ALTER DATABASE %s SET search_path = working_data" % db, True)
# enduser_on_db = Expect({**creds, **{"PGDATABASE":db, "PGUSER": "%s_enduser" % db, "PGPASSWORD": Expect.TMP_PASSWORD}})
# enduser_on_db.execute('show search_path')
# enduser_on_db.execute_template("sql/original_db_tables.sql", TABLE='test_table_1')
# enduser_on_db.execute_template("sql/original_db_tables.sql", TABLE='test_table_2')
# enduser_on_db.close()
# for db in databases:
# admin_db = Expect({**creds, **{"PGDATABASE":db}})
# for user in databases:
# admin_db.match_results("sql/query_permissions.sql.tpl", "results/test_original_verify_permissions/perms_%s_enduser_in_%s.txt" % (user,db), USER='%s_enduser' % user)
# #admin_db.match_results("sql/query_grants.sql", "results/test_original_verify_permissions/grants_%s.txt" % (db))
# #admin_db.match_results("sql/query_database.sql", "results/test_original_verify_permissions/access_%s.txt" % (db))
# admin_db.close()
# db = 'orig_db'
# enduser_on_db = Expect({**creds, **{"PGDATABASE":db, "PGUSER": "%s_enduser" % 'orig_db_2', "PGPASSWORD": Expect.TMP_PASSWORD}})
# enduser_on_db.expect_execute("select * from test_table_1", 'permission denied for relation test_table_1')
# enduser_on_db.close()
# enduser_on_db = Expect({**creds, **{"PGDATABASE":db, "PGUSER": "%s_user" % 'orig_db_2', "PGPASSWORD": Expect.TMP_PASSWORD}})
# enduser_on_db.expect_execute("select * from test_table_1", 'permission denied for relation test_table_1')
# enduser_on_db.close()
# # REVOKE ALL ON DATABASE template1 FROM public;
# # REVOKE ALL ON DATABASE hostdb FROM public;
# admin_db = CLI({**creds, **{"PGDATABASE":db}})
# df = admin_db.execute('SELECT datname FROM pg_database WHERE datistemplate = false')
# admin_db.close()
# admin_on_db = Expect({**creds, **{"PGDATABASE":db}})
# admin_on_db.execute_template('sql/query_defaults.sql')
# admin_on_db.execute_template('sql/query_roles.sql')
# admin_on_db.close()
# finally:
# admin.close()
def test_simple(self):
admin = CLI(creds)
db = "test_db"
admin.execute("SELECT current_user", True)
def test_user_connect_access(self):
admin = CLI(creds)
try:
user = "tmp_user"
db = "test_db"
userdb = Expect(creds)
admin.execute_template("sql/user.sql.tpl", USER=user, PASSWORD=Expect.TMP_PASSWORD)
userdb.expect_connect(db, user, 'FATAL: permission denied for database')
admin.execute_template("sql/user_connect.sql.tpl", APP_DATABASE=db, USER=user)
userdb.expect_connect(db, user)
admin_on_test_db = Expect({**creds, **{"PGDATABASE":db}})
admin_on_test_db.match_results("sql/query_permissions.sql.tpl", "results/test_user_connect_access/perms.txt", USER='user_x')
admin_on_test_db.close()
userdb.close()
finally:
admin.close()
def test_single_project(self):
admin = CLI(creds)
try:
db = "test_db"
prep_db = Expect({**creds, **{"PGDATABASE":db}})
prep_db.execute_template("sql/test_data_project.sql.tpl")
prep_db.close()
user = Expect({**creds, **{"PGUSER":'user_x', "PGDATABASE":db, "PGPASSWORD":Expect.TMP_PASSWORD}})
user.expect_execute("SELECT * from pg_settings", 'permission denied for relation pg_settings')
user.expect_success("SELECT * from protected_data.table_1")
user.expect_execute("CREATE TABLE protected_data.table_2 (name varchar(20));", 'permission denied for schema protected_data')
user.expect_success("CREATE TABLE working_data.table_2 (name varchar(20));")
admin_on_test_db = Expect({**creds, **{"PGDATABASE":db}})
admin_on_test_db.match_results("sql/query_permissions.sql.tpl", 'results/test_single_project/perms.txt', USER='user_x')
admin_on_test_db.close()
user.close()
finally:
admin.close()
def test_cross_project_connect_to_database(self):
admin = Expect(creds)
try:
admin.expect_connect('test_db', 'project_1_user_1', 'User does not have CONNECT privilege.')
admin.expect_connect('project_1', 'project_1_user_1')
finally:
admin.close()
return self
def test_no_existing_table(self):
con = Expect({**creds, **{"PGUSER":'project_1_user_1', "PGDATABASE":'project_1', "PGPASSWORD":Expect.TMP_PASSWORD}})
try:
con.expect_execute("SELECT * from protected_data.table_1", 'relation "protected_data.table_1" does not exist')
finally:
con.close()
return self
def test_cross_project_attempt_to_grant_usage(self):
admin = CLI(creds)
db = "test_db"
try:
hacker_user = Expect({**creds, **{"PGUSER":'user_x', "PGDATABASE":db, "PGPASSWORD":Expect.TMP_PASSWORD}})
hacker_user.execute_template("sql/test_data_force_grant_1.sql.tpl", WORKSPACE=db, USER='project_1_user_1')
con = Expect({**creds, **{"PGUSER":'project_1_user_1', "PGDATABASE":'project_1', "PGPASSWORD":Expect.TMP_PASSWORD}})
con.expect_execute("SELECT * from test_db.protected_data.table_1", 'cross-database references are not implemented')
con.close()
hacker_user.close()
finally:
admin.close()
return self
def test_cross_project_granting_access_without_connect(self):
con = Expect(creds)
try:
con.expect_connect('test_db', 'project_1_user_1', 'User does not have CONNECT privilege')
finally:
con.close()
return self
def test_hacker_granting_access_with_connect(self):
db = "test_db"
admin_on_test_db = CLI({**creds, **{"PGDATABASE":db}})
try:
hacker_user = Expect({**creds, **{"PGUSER":'user_x', "PGDATABASE":db, "PGPASSWORD":Expect.TMP_PASSWORD}})
hacker_user.execute_template("sql/test_data_force_grant_1.sql.tpl", WORKSPACE=db, USER='project_1_user_1')
# grant user connect
admin_on_test_db.execute_template("sql/user_connect.sql.tpl", APP_DATABASE=db, USER='project_1_user_1')
con = Expect({**creds, **{"PGUSER":'project_1_user_1', "PGDATABASE":db, "PGPASSWORD":Expect.TMP_PASSWORD}})
con.expect_execute("SELECT * from protected_data.table_1", 'permission denied for schema protected_data')
admin_on_test_db.execute_template("sql/query_permissions.sql.tpl", USER='project_1_user_1')
con.close()
admin_on_test_db.close()
finally:
admin_on_test_db.close()
return self
def test_hacker_trying_to_grant_role_to_another_user(self):
db = "test_db"
hacker_user = Expect({**creds, **{"PGUSER":'user_x', "PGDATABASE":db, "PGPASSWORD":Expect.TMP_PASSWORD}})
try:
hacker_user.expect_execute("GRANT %s_contribute TO %s;" % (db,'project_1_user_1'), 'must have admin option on role "test_db_contribute"')
finally:
hacker_user.close()
return self
def test_hacker_trying_to_create_schema(self):
db = "test_db"
admin_on_test_db = CLI({**creds, **{"PGDATABASE":db}})
try:
# Create tables
admin_on_test_db.execute("GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA pg_catalog TO " + "user_x")
hacker_user = Expect({**creds, **{"PGUSER":'user_x', "PGDATABASE":db, "PGPASSWORD":Expect.TMP_PASSWORD}})
hacker_user.execute_template("sql/test_table.sql.tpl", TABLE='user_x_table')
admin_on_test_db.execute_template("sql/query_permissions.sql.tpl", USER='user_x')
hacker_user.expect_execute("CREATE SCHEMA %s;" % 'new_schema', 'permission denied for database test_db')
hacker_user.close()
finally:
admin_on_test_db.close()
return self
def test_incremental_user_access(self):
db = "test_db"
admin_on_test_db = CLI({**creds, **{"PGDATABASE":db}})
try:
prep_db = Expect({**creds, **{"PGDATABASE":db}})
prep_db.execute_template("sql/test_data_project.sql.tpl")
user = "tmp_user_incremental"
admin_on_test_db.execute_template("sql/user.sql.tpl", USER=user, PASSWORD=Expect.TMP_PASSWORD)
prep_db.expect_connect(db, user, 'User does not have CONNECT privilege.')
admin_on_test_db.execute_template("sql/user_connect.sql.tpl", APP_DATABASE=db, USER=user)
user_db = Expect({**creds, **{"PGUSER":user, "PGDATABASE":db, "PGPASSWORD":Expect.TMP_PASSWORD}})
user_db.expect_execute("SELECT * from pg_settings", 'permission denied for relation pg_settings')
user_db.expect_execute("SELECT * from protected_data.table_1", 'permission denied for schema protected_data')
admin_on_test_db.execute_template("sql/setup_user.sql.tpl", WORKSPACE=db, USER=user)
user_db.expect_success("SELECT * from protected_data.table_1")
user_db.expect_execute("CREATE TABLE protected_data.table_2 (name varchar(20));", 'permission denied for schema protected_data')
user_db.expect_execute("CREATE TABLE working_data.table_2 (name varchar(20));", 'permission denied for schema pg_catalog')
admin_on_test_db.execute_template("sql/setup_user_2.sql.tpl", WORKSPACE=db, USER=user)
user_db.expect_success("CREATE TABLE working_data.table_2 (name varchar(20));")
prep_db.match_results("sql/query_permissions.sql.tpl", 'results/test_incremental_user_access/perms.txt', USER=user)
user_db.close()
prep_db.close()
finally:
admin_on_test_db.close()
# def test_single_project(self):
# admin = CLI(creds)
# try:
# db = "test_db"
# prep_db = Expect({**creds, **{"PGDATABASE":db}})
# user = Expect({**creds, **{"PGUSER":'user_x', "PGDATABASE":db, "PGPASSWORD":Expect.TMP_PASSWORD}})
# user.expect_success("SELECT * from pg_settings")
# admin_on_test_db = CLI({**creds, **{"PGDATABASE":db}})
# admin_on_test_db.execute_template("sql/query_permissions.sql.tpl", USER='user_x')
# admin_on_test_db.execute_template("sql/setup_new_database.sql.tpl")
# user.expect_execute("SELECT * from pg_settings", 'permission denied for relation pg_settings')
# admin_on_test_db.execute_template("sql/query_permissions.sql.tpl", USER='user_x')
# admin_on_test_db.execute_template("sql/setup_schemas.sql.tpl", WORKSPACE=db)
# prep_db.execute_template("sql/test_data_project.sql.tpl")
# admin_on_test_db.execute_template("sql/query_permissions.sql.tpl", USER='user_x')
# user.expect_execute("SELECT * from protected_data.table_1", 'permission denied for schema protected_data')
# admin_on_test_db.execute_template("sql/setup_user.sql.tpl", WORKSPACE=db, USER='user_x')
# user.expect_execute("SELECT * from protected_data.table_1")
# user.expect_execute("CREATE TABLE protected_data.table_2 (name varchar(20));", 'permission denied for schema protected_data')
# user.expect_execute("CREATE TABLE working_data.table_2 (name varchar(20));", 'permission denied for schema pg_catalog')
# admin_on_test_db.execute_template("sql/setup_user_2.sql.tpl", WORKSPACE=db, USER='user_x')
# user.expect_execute("CREATE TABLE working_data.table_2 (name varchar(20));")
# admin_on_test_db.execute_template("sql/query_permissions.sql.tpl", USER='user_x')
# user.close()
# admin_on_test_db.close()
# finally:
# admin.close()
| 2.40625
| 2
|
tests/demo/stocklab_demo/nodes/Price.py
|
hchsiao/stocklab
| 1
|
12778735
|
<gh_stars>1-10
from stocklab.node import *
from stocklab.core.runtime import FooCrawler
class Price(DataNode):
crawler_entry = FooCrawler.bar
args = Args(
date_idx = Arg(type=int),
stock = Arg(),
)
schema = Schema(
stock = {'key': True},
date = {'type': 'integer', 'key': True},
price = {'type': 'integer'},
note = {},
)
def evaluate(date_idx, stock):
table = Price.db[Price.name]
query = table.stock == stock
query &= table.date == date_idx
retval = Price.db(query).select(limitby=(0, 1))
if retval:
return retval[0].price
else:
raise CrawlerTrigger(date=date_idx, stock_id=stock)
| 2.65625
| 3
|
demos/zipoisson.py
|
mbannick/CorrelatedCounts
| 3
|
12778736
|
<reponame>mbannick/CorrelatedCounts
# -*- coding: utf-8 -*-
"""
Zero-Inflated Poisson Demo
~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from ccount.simulate import ZIPoissonSimulation
from ccount.models import ZeroInflatedPoisson
import numpy as np
zip_p_error = []
zip_beta_error = []
i = 0
while i < 100:
# set up the simulation
m = 100
n = 2
d = [1]*n
p = 0.5
x = [np.ones((m, d[j])) for j in range(n)]
beta = [np.array([0.1]*d[j]) for j in range(n)]
D = np.array([[1.0, 0.1], [0.1, 1.0]])
s_zip = ZIPoissonSimulation(m=m, n=n, d=d)
s_zip.update_params(p=p, x=x, beta=beta, D=D)
Y = s_zip.simulate()
# fit the model
d = np.array([[1]*n, d])
X = [[np.ones((m, 1)) for j in range(n)], x]
# true parameters in the right form
beta = [[np.array([np.log(p/(1.0 - p))]), np.array([np.log(p/(1.0 - p))])],
[np.array([0.1]), np.array([0.1])]]
D = np.array([np.eye(n)*1e-10, D])
U = np.array([np.zeros(s_zip.u.shape), s_zip.u])
theta = np.vstack(s_zip.theta).T
P = np.array([np.ones(theta.shape)*p, theta])
m_zip = ZeroInflatedPoisson(m=m, d=d, Y=Y, X=X)
m_zip.update_params(D=D, U=U)
m_zip.optimize_params(optimize_beta=True,
optimize_U=False,
compute_D=False,
max_iters=5)
error = np.array(m_zip.beta) - np.array(beta)
zip_p_error.append(error[0])
zip_beta_error.append(error[1])
print(f"Estimated beta... {m_zip.beta}")
print(f"True beta........ {beta}")
i += 1
mean_zip_p_error = sum(zip_p_error) / len(zip_p_error)
mean_zip_beta_error = sum(zip_beta_error) / len(zip_beta_error)
print(f"Overall p error for ZIP is {mean_zip_p_error}")
print(f"Overall beta error for ZIP is {mean_zip_beta_error}")
| 2.265625
| 2
|
2015/day_03/3_2.py
|
sunjerry019/adventOfCode18
| 0
|
12778737
|
<gh_stars>0
#!/usr/bin/env python3
import numpy as np
inputFile = open("3.in",'r')
inputContents = inputFile.readlines()[0].strip()
visited = {(0, 0)}
currPerson = 0
currPositions = [np.array([0, 0], dtype=int), np.array([0, 0], dtype=int)] # x, y
ordnung = {
'^' : np.array([ 0, 1], dtype=int),
'>' : np.array([ 1, 0], dtype=int),
'<' : np.array([ -1, 0], dtype=int),
'v' : np.array([ 0, -1], dtype=int)
}
for instruction in inputContents:
currPerson ^= 1
currPositions[currPerson] += ordnung[instruction]
visited.add(tuple(currPositions[currPerson]))
print(len(visited))
| 3.125
| 3
|
T567_CheckInclusion.py
|
zoubohao/LeetCodes
| 0
|
12778738
|
<reponame>zoubohao/LeetCodes<gh_stars>0
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
s1Size = len(s1)
s2Size = len(s2)
if s2Size < s1Size:
return False
left = 0
right = s1Size
valid = 0
need = {}
window = {}
for ele in s1:
if ele in need: need[ele] += 1
else: need[ele] = 1
needSize = len(need)
### Fixed window size
for i in range(s1Size):
curChar = s2[i]
if curChar not in window: window[curChar] = 1
else: window[curChar] += 1
if curChar in need and window[curChar] == need[curChar]:
valid += 1
if valid == needSize:
return True
while right < s2Size:
### add one char
addChar = s2[right]
if addChar in window: window[addChar] += 1
else: window[addChar] = 1
if addChar in need and window[addChar] == need[addChar]:
valid += 1
### currently remove one char
removeChar = s2[left]
if removeChar in need:
if window[removeChar] == need[removeChar]:
valid -= 1
window[removeChar] -= 1
right += 1
left += 1
if valid == needSize:
return True
return False
s = Solution()
print(s.checkInclusion("ab", "eidboaooo"))
| 3.171875
| 3
|
tests/test_fil2h5.py
|
lacker/blimpy
| 1
|
12778739
|
<filename>tests/test_fil2h5.py
"""
# test_fil2h5
"""
import pytest
import os
import blimpy as bl
from tests.data import voyager_fil
def test_fil2h5_conversion():
""" Tests the conversion of fil files into h5 in both light and heavy modes.
"""
# Creating test file.
bl.fil2h5.make_h5_file(voyager_fil, new_filename='test.h5')
# Creating a "large" test file.
bl.fil2h5.make_h5_file(voyager_fil, new_filename='test_large.h5', max_load=0.001)
# Testing filename
bl.fil2h5.make_h5_file(voyager_fil, new_filename='test')
# Deleting test file
os.remove('test.h5')
os.remove('test_large.h5')
def test_help():
"""
The user of these tests should verify that the help statement
was printed as expected; this test merely verifies that the
system exited.
"""
with pytest.raises(SystemExit):
bl.fil2h5.cmd_tool(['-h'])
def test_cmd_tool():
"""
This is the same large test file, but now through the cmd tool.
"""
#with pytest.raises(SystemExit):
bl.fil2h5.cmd_tool([voyager_fil, '-n', 'cmd.h5', '-l', '0.001'])
def test_no_args():
"""
The cmd tool needs to exit, mandating a file name.
"""
with pytest.raises(SystemExit):
bl.fil2h5.cmd_tool()
if __name__ == "__main__":
test_fil2h5_conversion()
| 2.5625
| 3
|
Statistics/main_numpy.py
|
hui-shao/python-toolk
| 3
|
12778740
|
<reponame>hui-shao/python-toolk
#简单现行回归:只有一个自变量 y=k*x+b 预测使 (y-y*)^2 最小
import numpy as np
def fitSLR(x,y):
n=len(x) #获取x的长度,x是list
dinominator = 0#初始化分母
numerator=0 #初始化分子
for i in range(0,n): #求b1
numerator += (x[i]-np.mean(x))*(y[i]-np.mean(y))
dinominator += (x[i]-np.mean(x))**2 #**表示平方
print("numerator:"+str(numerator))
print("dinominator:"+str(dinominator))
b1 = numerator/float(dinominator) #得出b1
b0 = np.mean(y)/float(np.mean(x)) #得出b0
return b0,b1
# y= b0+x*b1
def prefict(x,b0,b1): #定义一个简单的线性方程
return b0+x*b1
x=[1,3,2,1,3]
y=[14,24,18,17,27]
b0,b1=fitSLR(x, y)
y_predict = prefict(6,b0,b1)
print("y_predict:"+str(y_predict))
| 3.609375
| 4
|
occult/horoscopes.py
|
CelinaWalkowicz/Discord-Bots
| 0
|
12778741
|
'''
Horoscope Attributes of the Occult Bot
'''
# Imports
import requests, json
# Variables
# Emojis
aries_emoji = '\N{ARIES}'
taurus_emoji = '\N{TAURUS}'
gemini_emoji = '\N{GEMINI}'
cancer_emoji = '\N{CANCER}'
leo_emoji = '\N{LEO}'
virgo_emoji = '\N{VIRGO}'
libra_emoji = '\N{LIBRA}'
scorpio_emoji = '\N{SCORPIUS}'
sagittarius_emoji = '\N{SAGITTARIUS}'
capricorn_emoji = '\N{CAPRICORN}'
aquarius_emoji = '\N{AQUARIUS}'
pisces_emoji = '\N{PISCES}'
# Functions
def month_num_to_name(month_num):
"""
Takes a String or Int input of a Month's Number, and returns
a string of the the name of the corresponding Month.
"""
month_names = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'Novemeber', 'December',
]
# Save Month Index to Determine Month Name
idx = int(month_num) - 1
month = month_names[idx]
return month
def horo_date(json_data):
'Converts YYYY-MM-DD date to MonthName DD, YYYY'
# Separate Parts of the Date
year = json_data['date'][:4]
month_num = json_data['date'][5:7]
day = json_data['date'][8:]
month = month_num_to_name(month_num)
return f'{month} {day}, {year}'
def get_horoscope(zodiac):
'Retrieves Daily Horoscopes for Specified Zodiac'
# Aquarius
if zodiac == 'aquarius':
response = requests.get("https://ohmanda.com/api/horoscope/aquarius")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{aquarius_emoji} {json_data['sign'].upper()} {aquarius_emoji}
{date}
{json_data['horoscope']}
'''
# Pisces
elif zodiac == 'pisces':
response = requests.get("https://ohmanda.com/api/horoscope/pisces")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{pisces_emoji} {json_data['sign'].upper()} {pisces_emoji}
{date}
{json_data['horoscope']}
'''
# Aries
elif zodiac == 'aries':
response = requests.get("https://ohmanda.com/api/horoscope/aries")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{aries_emoji} {json_data['sign'].upper()} {aries_emoji}
{date}
{json_data['horoscope']}
'''
# Taurus
elif zodiac == 'taurus':
response = requests.get("https://ohmanda.com/api/horoscope/taurus")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{taurus_emoji} {json_data['sign'].upper()} {taurus_emoji}
{date}
{json_data['horoscope']}
'''
# Gemini
elif zodiac == 'gemini':
response = requests.get("https://ohmanda.com/api/horoscope/gemini")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{gemini_emoji} {json_data['sign'].upper()} {gemini_emoji}
{date}
{json_data['horoscope']}
'''
# Cancer
elif zodiac == 'cancer':
response = requests.get("https://ohmanda.com/api/horoscope/cancer")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{cancer_emoji} {json_data['sign'].upper()} {cancer_emoji}
{date}
{json_data['horoscope']}
'''
# Leo
elif zodiac == 'leo':
response = requests.get("https://ohmanda.com/api/horoscope/leo")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{leo_emoji} {json_data['sign'].upper()} {leo_emoji}
{date}
{json_data['horoscope']}
'''
# Virgo
elif zodiac == 'virgo':
response = requests.get("https://ohmanda.com/api/horoscope/virgo")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{virgo_emoji} {json_data['sign'].upper()} {virgo_emoji}
{date}
{json_data['horoscope']}
'''
# Libra
elif zodiac == 'libra':
response = requests.get("https://ohmanda.com/api/horoscope/libra")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{libra_emoji} {json_data['sign'].upper()} {libra_emoji}
{date}
{json_data['horoscope']}
'''
# Scorpio
elif zodiac == 'scorpio':
response = requests.get("https://ohmanda.com/api/horoscope/scorpio")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{scorpio_emoji} {json_data['sign'].upper()} {scorpio_emoji}
{date}
{json_data['horoscope']}
'''
# Sagittarius
elif zodiac == 'sagittarius':
response = requests.get("https://ohmanda.com/api/horoscope/sagittarius")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{sagittarius_emoji} {json_data['sign'].upper()} {sagittarius_emoji}
{date}
{json_data['horoscope']}
'''
# Capricorn
elif zodiac == 'capricorn':
response = requests.get("https://ohmanda.com/api/horoscope/capricorn")
json_data = json.loads(response.text)
date = horo_date(json_data)
horoscope = f'''
{capricorn_emoji} {json_data['sign'].upper()} {capricorn_emoji}
{date}
{json_data['horoscope']}
'''
return(horoscope)
| 3.703125
| 4
|
cielo/api/funcao.py
|
CharlesTenorio/strive_api
| 0
|
12778742
|
<reponame>CharlesTenorio/strive_api<gh_stars>0
import json
import logging
from cieloApi3 import Environment
from cieloApi3 import Merchant
from cieloApi3 import Sale
from cieloApi3 import Customer
from cieloApi3 import CreditCard
from cieloApi3 import CieloEcommerce
from cieloApi3 import Payment
from decouple import config
loogger = logging.getLogger('erro_cielo')
url_prd = config('CIELO_PRD_PUT_POST')
id_cliente = config('MERCHANT_ID')
key_cliente = config('MERCHANT_KEY')
id_cliente_hoodid = config('MERCHANT_ID_HOODID')
key_cliente_hoodid = config('MERCHANT_KEY_HODID')
environment = Environment(sandbox=False)
merchant = Merchant(id_cliente, key_cliente)
def comprar_credito(id_compra, cliente, numero_cartao, seguranca, bandeira, validade, valor, qtd_parcela):
msg_retorno = ''
codigo_transacao = ''
x = ''
try:
sale = Sale(id_compra)
sale.customer = Customer(cliente)
credit_card = CreditCard(seguranca, bandeira)
credit_card.expiration_date = validade
credit_card.security_code = seguranca
credit_card.card_number = numero_cartao
credit_card.holder = cliente
sale.payment = Payment(valor)
sale.payment.credit_card = credit_card
sale.payment.installments = qtd_parcela
cielo_ecommerce = CieloEcommerce(merchant, environment)
response_create_sale = cielo_ecommerce.create_sale(sale)
x = json.dumps(response_create_sale, indent=3, sort_keys=True)
# payment_id = sale.payment.payment_id
resultado = json.loads(x)
codigo_transacao = resultado["Payment"]["Tid"]
msg_retorno = resultado["Payment"]["ReturnMessage"]
except KeyError as e:
print(e)
return (msg_retorno, codigo_transacao)
| 2.171875
| 2
|
tests/test_standard_templates.py
|
TopOfMinds/dw-generator
| 5
|
12778743
|
import sqlite3
import unittest
from collections import namedtuple
from datetime import datetime
from dwgenerator.dbobjects import Schema, Table, Column, create_typed_table, Hub, Link, Satellite, MetaDataError, MetaDataWarning
from dwgenerator.mappings import TableMappings, ColumnMappings, Mappings
from dwgenerator.templates import Templates
TableMapping = namedtuple('TableMapping',
'source_schema source_table source_filter target_schema target_table')
ColumnMapping = namedtuple('ColumnMapping',
'src_schema src_table src_column transformation tgt_schema tgt_table tgt_column')
class TestStandardTemplates(unittest.TestCase):
# Prepare the DB
def setUp(self):
self.dbtype = 'standard'
self.start_ts = datetime.fromisoformat('2021-06-01T12:10:00+00:00').timestamp()
self.templates = Templates(self.dbtype)
self.connection = sqlite3.connect(':memory:')
self.cur = self.connection.cursor()
self.cur.execute("ATTACH DATABASE ':memory:' AS db")
def tearDown(self):
self.connection.close()
# Create table definitions
def create_customer_h(self, **properties):
target_table = create_typed_table(
Table('db', 'customer_h', [
Column('customer_key', 'text'),
Column('ssn', 'text'),
Column('load_dts', 'numeric'),
Column('rec_src', 'text'),
], **properties))
target_table.check()
return target_table
def create_sales_line_customer_l(self, **properties):
target_table = create_typed_table(
Table('db', 'sales_line_customer_l', [
Column('sales_line_customer_l_key', 'text'),
Column('sales_line_key', 'text'),
Column('customer_key', 'text'),
Column('load_dts', 'numeric'),
Column('rec_src', 'text'),
], **properties))
target_table.check()
return target_table
def create_customer_s(self, **properties):
target_table = create_typed_table(
Table('db', 'customer_s', [
Column('customer_key', 'text'),
Column('load_dts', 'numeric'),
Column('ssn', 'text'),
Column('name', 'text'),
Column('rec_src', 'text'),
], **properties))
target_table.check()
return target_table
# Create mappings
def create_customer_h_mappings(self, target_table):
# I use the same source and target database as sqlite cannot create views that use other dbs
table_mappings = TableMappings([t._asdict() for t in [
TableMapping("db", "customers", "", "db", "customer_h"),
TableMapping("db", "sales_lines", "", "db", "customer_h")
]])
column_mappings = ColumnMappings([c._asdict() for c in [
ColumnMapping("db", "customers", "ssn", "", "db", "customer_h", "customer_key"),
ColumnMapping("db", "customers", "ssn", "", "db", "customer_h", "ssn"),
ColumnMapping("db", "customers", "load_dts", "", "db", "customer_h", "load_dts"),
ColumnMapping("db", "customers", "", "'db'", "db", "customer_h", "rec_src"),
ColumnMapping("db", "sales_lines", "ssn", "", "db", "customer_h", "customer_key"),
ColumnMapping("db", "sales_lines", "ssn", "", "db", "customer_h", "ssn"),
ColumnMapping("db", "sales_lines", "load_dts", "", "db", "customer_h", "load_dts"),
ColumnMapping("db", "sales_lines", "", "'db'", "db", "customer_h", "rec_src"),
]])
mappings = Mappings(table_mappings, column_mappings, [target_table] + column_mappings.source_tables())
mappings.check(target_table)
return mappings
def create_sales_line_customer_l_mappings(self, target_table):
# I use the same source and target database as sqlite cannot create views that use other dbs
table_mappings = TableMappings([
TableMapping("db", "sales_lines", "", "db", "sales_line_customer_l")._asdict()
])
column_mappings = ColumnMappings([c._asdict() for c in [
ColumnMapping("db", "sales_lines", "txn_id,ssn", "", "db", "sales_line_customer_l", "sales_line_customer_l_key"),
ColumnMapping("db", "sales_lines", "txn_id", "", "db", "sales_line_customer_l", "sales_line_key"),
ColumnMapping("db", "sales_lines", "ssn", "", "db", "sales_line_customer_l", "customer_key"),
ColumnMapping("db", "sales_lines", "load_dts", "", "db", "sales_line_customer_l", "load_dts"),
ColumnMapping("db", "sales_lines", "", "'db'", "db", "sales_line_customer_l", "rec_src"),
]])
mappings = Mappings(table_mappings, column_mappings, [target_table] + column_mappings.source_tables())
mappings.check(target_table)
return mappings
def create_customer_s_mappings(self, target_table):
# I use the same source and target database as sqlite cannot create views that use other dbs
table_mappings = TableMappings([
TableMapping("db", "customers", "", "db", "customer_s")._asdict()
])
column_mappings = ColumnMappings([c._asdict() for c in [
ColumnMapping("db", "customers", "ssn", "", "db", "customer_s", "customer_key"),
ColumnMapping("db", "customers", "load_dts", "", "db", "customer_s", "load_dts"),
ColumnMapping("db", "customers", "ssn", "", "db", "customer_s", "ssn"),
ColumnMapping("db", "customers", "name", "", "db", "customer_s", "name"),
ColumnMapping("db", "customers", "", "'db'", "db", "customer_s", "rec_src"),
]])
mappings = Mappings(table_mappings, column_mappings, [target_table] + column_mappings.source_tables())
mappings.check(target_table)
return mappings
# Create and put test data in source tables
def create_customers(self):
self.cur.execute('CREATE TABLE db.customers (ssn, name, load_dts)')
ts = self.start_ts
self.cur.executemany('INSERT INTO db.customers VALUES(?, ?, ?)', [
('198001010101', 'Michael', ts),
('199001010101', 'Jessica', ts + 1),
('199201010101', 'Ashley', ts + 2),
])
def create_sales_lines(self):
self.cur.execute('CREATE TABLE db.sales_lines (txn_id, ssn, load_dts)')
ts = self.start_ts
self.cur.executemany('INSERT INTO db.sales_lines VALUES(?, ?, ?)', [
('1234', '198001010101', ts + 20),
('2345', '199001010101', ts + 21),
('2345', '199001010101', ts + 3600),
('3456', '199201010101', ts + 3601),
])
# Utils
def render_view(self, target_table, mappings):
[(_, sql), *rest] = self.templates.render(target_table, mappings)
self.assertTrue(len(rest) == 0)
return sql
def executescript(self, sql, args):
for (key, value) in args.items():
sql = sql.replace(f':{key}', str(value))
self.cur.executescript(sql)
# Test the data vault objects
## Test views
def test_hub_view(self):
target_table = self.create_customer_h()
mappings = self.create_customer_h_mappings(target_table)
sql = self.render_view(target_table, mappings)
self.create_customers()
self.create_sales_lines()
self.cur.executescript(sql)
result = list(self.cur.execute('SELECT * FROM db.customer_h ORDER BY load_dts'))
expected = [
('198001010101', '198001010101', 1622549400.0, 'db'),
('199001010101', '199001010101', 1622549401.0, 'db'),
('199201010101', '199201010101', 1622549402.0, 'db')
]
self.assertEqual(result, expected)
def test_link_view(self):
target_table = self.create_sales_line_customer_l()
mappings = self.create_sales_line_customer_l_mappings(target_table)
sql = self.render_view(target_table, mappings)
self.create_sales_lines()
self.cur.executescript(sql)
result = list(self.cur.execute('SELECT * FROM db.sales_line_customer_l ORDER BY load_dts'))
expected = [
('1234|198001010101', '1234', '198001010101', 1622549420.0, 'db'),
('2345|199001010101', '2345', '199001010101', 1622549421.0, 'db'),
('3456|199201010101', '3456', '199201010101', 1622553001.0, 'db'),
]
self.assertEqual(result, expected)
def test_satellite_view(self):
target_table = self.create_customer_s()
mappings = self.create_customer_s_mappings(target_table)
sql = self.render_view(target_table, mappings)
self.create_customers()
self.cur.executescript(sql)
result = list(self.cur.execute('SELECT * FROM db.customer_s ORDER BY load_dts'))
expected = [
('198001010101', 1622549400.0, '198001010101', 'Michael', 'db'),
('199001010101', 1622549401.0, '199001010101', 'Jessica', 'db'),
('199201010101', 1622549402.0, '199201010101', 'Ashley', 'db'),
]
self.assertEqual(result, expected)
## Test persited tables
def test_hub_persisted(self):
target_table = self.create_customer_h(generate_type='table')
mappings = self.create_customer_h_mappings(target_table)
[(ddl_path, ddl), (etl_path, etl)] = self.templates.render(target_table, mappings)
self.assertEqual(ddl_path.as_posix(), 'db/customer_h_t.sql')
self.assertEqual(etl_path.as_posix(), 'db/customer_h_etl.sql')
self.cur.executescript(ddl)
result = list(self.cur.execute("PRAGMA db.table_info('customer_h')"))
expected = [
(0, 'customer_key', 'text', 0, None, 1),
(1, 'ssn', 'text', 0, None, 0),
(2, 'load_dts', 'numeric', 0, None, 0),
(3, 'rec_src', 'text', 0, None, 0)
]
self.assertEqual(result, expected)
self.create_customers()
self.create_sales_lines()
ts = self.start_ts
# print(etl)
self.executescript(etl, {'start_ts': ts, 'end_ts': ts + 2})
result1 = list(self.cur.execute('SELECT * FROM db.customer_h ORDER BY load_dts'))
expected1 = [
('198001010101', '198001010101', 1622549400.0, 'db'),
('199001010101', '199001010101', 1622549401.0, 'db'),
]
self.assertEqual(result1, expected1)
self.executescript(etl, {'start_ts': ts + 2, 'end_ts': ts + 4000})
result2 = list(self.cur.execute('SELECT * FROM db.customer_h ORDER BY load_dts'))
expected2 = expected1 + [
('199201010101', '199201010101', 1622549402.0, 'db')
]
self.assertEqual(result2, expected2)
def test_link_persisted(self):
target_table = self.create_sales_line_customer_l(generate_type='table')
mappings = self.create_sales_line_customer_l_mappings(target_table)
[(ddl_path, ddl), (etl_path, etl)] = self.templates.render(target_table, mappings)
self.assertEqual(ddl_path.as_posix(), 'db/sales_line_customer_l_t.sql')
self.assertEqual(etl_path.as_posix(), 'db/sales_line_customer_l_etl.sql')
self.cur.executescript(ddl)
result = list(self.cur.execute("PRAGMA db.table_info('sales_line_customer_l')"))
expected = [
(0, 'sales_line_customer_l_key', 'text', 0, None, 1),
(1, 'sales_line_key', 'text', 0, None, 0),
(2, 'customer_key', 'text', 0, None, 0),
(3, 'load_dts', 'numeric', 0, None, 0),
(4, 'rec_src', 'text', 0, None, 0)
]
self.assertEqual(result, expected)
self.create_sales_lines()
ts = self.start_ts
# print(etl)
self.executescript(etl, {'start_ts': ts + 0, 'end_ts': ts + 3600})
result1 = list(self.cur.execute('SELECT * FROM db.sales_line_customer_l ORDER BY load_dts'))
expected1 = [
('1234|198001010101', '1234', '198001010101', 1622549420.0, 'db'),
('2345|199001010101', '2345', '199001010101', 1622549421.0, 'db'),
]
self.assertEqual(result1, expected1)
self.executescript(etl, {'start_ts': ts + 3600, 'end_ts': ts + 7200})
result2 = list(self.cur.execute('SELECT * FROM db.sales_line_customer_l ORDER BY load_dts'))
expected2 = expected1 + [
('3456|199201010101', '3456', '199201010101', 1622553001.0, 'db'),
]
self.assertEqual(result2, expected2)
def test_satellite_persisted(self):
target_table = self.create_customer_s(generate_type='table')
mappings = self.create_customer_s_mappings(target_table)
[(ddl_path, ddl), (etl_path, etl)] = self.templates.render(target_table, mappings)
self.assertEqual(ddl_path.as_posix(), 'db/customer_s_t.sql')
self.assertEqual(etl_path.as_posix(), 'db/customer_s_etl.sql')
self.cur.executescript(ddl)
result = list(self.cur.execute("PRAGMA db.table_info('customer_s')"))
expected = [
(0, 'customer_key', 'text', 0, None, 1),
(1, 'load_dts', 'numeric', 0, None, 2),
(2, 'ssn', 'text', 0, None, 0),
(3, 'name', 'text', 0, None, 0),
(4, 'rec_src', 'text', 0, None, 0)
]
self.assertEqual(result, expected)
self.create_customers()
ts = self.start_ts
# print(etl)
self.executescript(etl, {'start_ts': ts, 'end_ts': ts + 2})
result1 = list(self.cur.execute('SELECT * FROM db.customer_s ORDER BY load_dts'))
expected1 = [
('198001010101', 1622549400.0, '198001010101', 'Michael', 'db'),
('199001010101', 1622549401.0, '199001010101', 'Jessica', 'db'),
]
self.assertEqual(result1, expected1)
self.executescript(etl, {'start_ts': ts + 2, 'end_ts': ts + 4})
result2 = list(self.cur.execute('SELECT * FROM db.customer_s ORDER BY load_dts'))
expected2 = expected1 + [
('199201010101', 1622549402.0, '199201010101', 'Ashley', 'db'),
]
self.assertEqual(result2, expected2)
| 2.453125
| 2
|
xl_tensorflow/models/vision/detection/loss/yolo_loss.py
|
Lannister-Xiaolin/xl_tensorflow
| 0
|
12778744
|
<reponame>Lannister-Xiaolin/xl_tensorflow
#!usr/bin/env python3
# -*- coding: UTF-8 -*-
import tensorflow as tf
from xl_tensorflow.models.vision.detection.dataloader.utils.anchors_yolo import YOLOV3_ANCHORS
import tensorflow.keras.backend as K
from ..body.yolo import yolo_head, box_iou
class YoloLoss(tf.keras.losses.Loss):
"""yolo损失函数
定义模型为标准输出,把yolo head写入模型里面(即还原成相对坐标形式)
不把损失函数写入模型里面
"""
defalt_anchors = YOLOV3_ANCHORS
def __init__(self,
scale_stage,
input_shape,
num_class,
iou_loss="",
anchors=None,
ignore_thresh=.4,
print_loss=False,
trunc_inf=False,
iou_scale=4.0,
avg_loss_object=False,
name='yolo_loss'):
"""
计算每个stage的损失
Args:
scale_stage: ie 1: 13X13 2:26X26 3:52X52
anchors: anchors for yolo
ignore_thresh: float,0-1, the iou threshold whether to ignore object confidence loss
"""
super(YoloLoss, self).__init__(reduction=tf.losses.Reduction.NONE, name=name)
anchor_masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]] if (anchors and (len(anchors) // 3) == 3) or (
not anchors) else [[3, 4, 5], [1, 2, 3]]
self.scale_stage = scale_stage
self.ignore_thresh = ignore_thresh
self.anchor = anchors[anchor_masks[scale_stage]] if \
anchors else self.defalt_anchors[anchor_masks[scale_stage]]
self.input_shape = input_shape
self.num_class = num_class
self.iou_loss = iou_loss
self.iou_scale = iou_scale
self.avg_loss_object = avg_loss_object
self.print_loss = print_loss
self.grid_shape = ((input_shape[0] // 32) * (scale_stage + 1), (input_shape[1] // 32) * (scale_stage + 1))
self.trunc_inf = trunc_inf
def call(self, y_true, y_pred):
"""
y_pred: shape like (batch, gridx,gridy,3,(5+class))
y_true: shape like (batch,gridx,gridy,3,(5+class))
anchors: array, shape=(N, 2), wh, default value:
num_classes: integer
ignore_thresh: float, the iou threshold whether to ignore object confidence loss
Returns
loss: tensor, shape=(1,)
"""
loss = 0
batch_tensor = tf.cast(tf.shape(y_pred)[0], K.dtype(y_true[0]))
grid_shape = K.cast(K.shape(y_pred)[1:3], K.dtype(y_true))
# 真实值掩码,无目标的对应位置为0 ,shape like gridx,gridy,3,1
object_mask = y_true[..., 4:5]
object_count = tf.reduce_sum(object_mask) + 1.0
true_class_probs = y_true[..., 5:]
grid, raw_pred, pred_xy, pred_wh = yolo_head(y_pred,
self.anchor,
self.input_shape,
calc_loss=True)
pred_box = K.concatenate([pred_xy, pred_wh])
# relative to specified gird
raw_true_xy = y_true[..., :2] * grid_shape[::-1] - grid
# wh 还原到与yolobody对应的值即原文中的tw和th
raw_true_wh = K.log(y_true[..., 2:4] / self.anchor * self.input_shape[::-1] + 1e-10)
raw_true_wh = K.switch(object_mask, raw_true_wh, K.zeros_like(raw_true_wh)) # avoid log(0)=-inf
# box_loss_scale used for scale imbalance large value for small object and small value for large object
box_loss_scale = 2 - y_true[..., 2:3] * y_true[..., 3:4]
# Find ignore mask, iterate over each of batch.
object_mask_bool = K.cast(object_mask, 'bool')
def iou_best(elems):
pred_box_one, y_true_one, object_mask_bool_one = elems
true_box_one = tf.boolean_mask(y_true_one[..., 0:4], object_mask_bool_one[..., 0])
iou = box_iou(pred_box_one, true_box_one)
best_iou = K.cast(K.max(iou, axis=-1) < self.ignore_thresh, tf.float32)
return best_iou
ignore_mask = tf.map_fn(iou_best, (pred_box, y_true, object_mask_bool), tf.float32)
ignore_mask = K.expand_dims(ignore_mask, -1)
"""
损失函数组成:
1、中心定位误差,采用交叉熵,只计算有真实目标位置的损失
2、宽度高度误差,使用L2损失,只计算有真实目标位置的损失
3、是否包含目标的置信度计算,包含两部分,一个是真实目标位置的binary crossentropy,
一个是其他位置的binary crossentropy,不包含与真实目标iou大于0.5的位置,即负样本损失
4、各个类别的损失函数,只计算有真实目标位置的损失
"""
# K.binary_crossentropy is helpful to avoid exp overflow. 相等时为极值点
confidence_loss = object_mask * K.binary_crossentropy(object_mask, raw_pred[..., 4:5], from_logits=True) + \
(1 - object_mask) * K.binary_crossentropy(object_mask, raw_pred[..., 4:5],
from_logits=True) * ignore_mask
class_loss = object_mask * K.binary_crossentropy(true_class_probs, raw_pred[..., 5:], from_logits=True)
confidence_loss = tf.reduce_sum(confidence_loss) / batch_tensor
class_loss = tf.reduce_sum(class_loss) / batch_tensor
if self.avg_loss_object:
class_loss = class_loss / object_count
confidence_loss = confidence_loss / object_count
class_loss = tf.identity(class_loss, "class_loss")
confidence_loss = tf.identity(confidence_loss, "confidence_loss")
if self.iou_loss in ("giou", "ciou", "diou", "iou"):
iou = box_iou(pred_box, y_true, method=self.iou_loss, as_loss=True, trunc_inf=self.trunc_inf)
iou_loss = object_mask * (1 - tf.expand_dims(iou, -1))
# todo 是否除以均值
iou_loss = (tf.reduce_sum(iou_loss) / batch_tensor) * self.iou_scale
if self.avg_loss_object:
iou_loss = iou_loss / object_count
iou_loss = tf.identity(iou_loss, self.iou_loss + "_loss")
loss += iou_loss + confidence_loss + class_loss
if self.print_loss:
tf.print("\n" + str(
self.scale_stage) + ":\tiou:", iou_loss, "\tconfidence:", confidence_loss,
"\tclass:", class_loss)
else:
xy_loss = object_mask * box_loss_scale * K.binary_crossentropy(raw_true_xy, raw_pred[..., 0:2],
from_logits=True)
wh_loss = object_mask * box_loss_scale * 0.5 * K.square(raw_true_wh - raw_pred[..., 2:4])
xy_loss = tf.reduce_sum(xy_loss) / batch_tensor
wh_loss = tf.reduce_sum(wh_loss) / batch_tensor
mse_loss = xy_loss + wh_loss
if self.avg_loss_object:
mse_loss = mse_loss / object_count
loss += mse_loss + confidence_loss + class_loss
if self.print_loss:
tf.print("\n" + str(
self.scale_stage) + ":\tmse:", mse_loss, "\tconfidence:", confidence_loss,
"\tclass:", class_loss)
return loss
| 2.203125
| 2
|
tests/test_response.py
|
therefromhere/webtest
| 0
|
12778745
|
#coding: utf-8
from __future__ import unicode_literals
import sys
import webtest
from webtest.debugapp import debug_app
from webob import Request
from webob.response import gzip_app_iter
from webtest.compat import PY3
from tests.compat import unittest
import webbrowser
def links_app(environ, start_response):
req = Request(environ)
status = "200 OK"
responses = {
'/': """
<html>
<head><title>page with links</title></head>
<body>
<a href="/foo/">Foo</a>
<a href='bar'>Bar</a>
<a href='baz/' id='id_baz'>Baz</a>
<a href='#' id='fake_baz'>Baz</a>
<a href='javascript:alert("123")' id='js_baz'>Baz</a>
<script>
var link = "<a href='/boo/'>Boo</a>";
</script>
<a href='/spam/'>Click me!</a>
<a href='/egg/'>Click me!</a>
<button
id="button1"
onclick="location.href='/foo/'"
>Button</button>
<button
id="button2">Button</button>
<button
id="button3"
onclick="lomistakecation.href='/foo/'"
>Button</button>
</body>
</html>
""",
'/foo/': (
'<html><body>This is foo. <a href="bar">Bar</a> '
'</body></html>'
),
'/foo/bar': '<html><body>This is foobar.</body></html>',
'/bar': '<html><body>This is bar.</body></html>',
'/baz/': '<html><body>This is baz.</body></html>',
'/spam/': '<html><body>This is spam.</body></html>',
'/egg/': '<html><body>Just eggs.</body></html>',
'/utf8/': """
<html>
<head><title>Тестовая страница</title></head>
<body>
<a href='/foo/'>Менделеев</a>
<a href='/baz/' title='Поэт'>Пушкин</a>
<img src='/egg/' title='Поэт'>
<script>
var link = "<a href='/boo/'>Злодейская ссылка</a>";
</script>
</body>
</html>
""",
'/no_form/': """
<html>
<head><title>Page without form</title></head>
<body>
<h1>This is not the form you are looking for</h1>
</body>
</html>
""",
'/one_forms/': """
<html>
<head><title>Page without form</title></head>
<body>
<form method="POST" id="first_form"></form>
</body>
</html>
""",
'/many_forms/': """
<html>
<head><title>Page without form</title></head>
<body>
<form method="POST" id="first_form"></form>
<form method="POST" id="second_form"></form>
</body>
</html>
""",
'/html_in_anchor/': """
<html>
<head><title>Page with HTML in an anchor tag</title></head>
<body>
<a href='/foo/'>Foo Bar<span class='baz qux'>Quz</span></a>
</body>
</html>
""",
'/json/': '{"foo": "bar"}',
}
utf8_paths = ['/utf8/']
body = responses[req.path_info]
body = body.encode('utf8')
headers = [
('Content-Type', str('text/html')),
('Content-Length', str(len(body)))
]
if req.path_info in utf8_paths:
headers[0] = ('Content-Type', str('text/html; charset=utf-8'))
# PEP 3333 requires native strings:
headers = [(str(k), str(v)) for k, v in headers]
start_response(str(status), headers)
return [body]
def gzipped_app(environ, start_response):
status = "200 OK"
encoded_body = list(gzip_app_iter([b'test']))
headers = [
('Content-Type', str('text/html')),
('Content-Encoding', str('gzip')),
]
# PEP 3333 requires native strings:
headers = [(str(k), str(v)) for k, v in headers]
start_response(str(status), headers)
return encoded_body
class TestResponse(unittest.TestCase):
def test_repr(self):
def _repr(v):
br = repr(v)
if len(br) > 18:
br = br[:10] + '...' + br[-5:]
br += '/%s' % len(v)
return br
app = webtest.TestApp(debug_app)
res = app.post('/')
self.assertEqual(
repr(res),
'<200 OK text/plain body=%s>' % _repr(res.body)
)
res.content_type = None
self.assertEqual(
repr(res),
'<200 OK body=%s>' % _repr(res.body)
)
res.location = 'http://pylons.org'
self.assertEqual(
repr(res),
'<200 OK location: http://pylons.org body=%s>' % _repr(res.body)
)
res.body = b''
self.assertEqual(
repr(res),
'<200 OK location: http://pylons.org no body>'
)
def test_mustcontains(self):
app = webtest.TestApp(debug_app)
res = app.post('/', params='foobar')
res.mustcontain('foobar')
self.assertRaises(IndexError, res.mustcontain, 'not found')
res.mustcontain('foobar', no='not found')
res.mustcontain('foobar', no=['not found', 'not found either'])
self.assertRaises(IndexError, res.mustcontain, no='foobar')
self.assertRaises(
TypeError,
res.mustcontain, invalid_param='foobar'
)
def test_click(self):
app = webtest.TestApp(links_app)
self.assertIn('This is foo.', app.get('/').click('Foo'))
self.assertIn(
'This is foobar.',
app.get('/').click('Foo').click('Bar')
)
self.assertIn('This is bar.', app.get('/').click('Bar'))
# should skip non-clickable links
self.assertIn(
'This is baz.',
app.get('/').click('Baz')
)
self.assertIn('This is baz.', app.get('/').click(linkid='id_baz'))
self.assertIn('This is baz.', app.get('/').click(href='baz/'))
self.assertIn(
'This is spam.',
app.get('/').click('Click me!', index=0)
)
self.assertIn(
'Just eggs.',
app.get('/').click('Click me!', index=1)
)
self.assertIn(
'This is foo.',
app.get('/html_in_anchor/').click('baz qux')
)
def dont_match_anchor_tag():
app.get('/html_in_anchor/').click('href')
self.assertRaises(IndexError, dont_match_anchor_tag)
def multiple_links():
app.get('/').click('Click me!')
self.assertRaises(IndexError, multiple_links)
def invalid_index():
app.get('/').click('Click me!', index=2)
self.assertRaises(IndexError, invalid_index)
def no_links_found():
app.get('/').click('Ham')
self.assertRaises(IndexError, no_links_found)
def tag_inside_script():
app.get('/').click('Boo')
self.assertRaises(IndexError, tag_inside_script)
def test_click_utf8(self):
app = webtest.TestApp(links_app, use_unicode=False)
resp = app.get('/utf8/')
self.assertEqual(resp.charset, 'utf-8')
if not PY3:
# No need to deal with that in Py3
self.assertIn("Тестовая страница".encode('utf8'), resp)
self.assertIn("Тестовая страница", resp, resp)
target = 'Менделеев'.encode('utf8')
self.assertIn('This is foo.', resp.click(target, verbose=True))
def test_click_u(self):
app = webtest.TestApp(links_app)
resp = app.get('/utf8/')
self.assertIn("Тестовая страница", resp)
self.assertIn('This is foo.', resp.click('Менделеев'))
def test_clickbutton(self):
app = webtest.TestApp(links_app)
self.assertIn(
'This is foo.',
app.get('/').clickbutton(buttonid='button1', verbose=True)
)
self.assertRaises(
IndexError,
app.get('/').clickbutton, buttonid='button2'
)
self.assertRaises(
IndexError,
app.get('/').clickbutton, buttonid='button3'
)
def test_referer(self):
app = webtest.TestApp(links_app)
resp = app.get('/').click('Foo')
self.assertIn('Referer', resp.request.headers)
self.assertEqual(resp.request.headers['Referer'], 'http://localhost/')
resp = app.get('/').clickbutton(buttonid='button1')
self.assertIn('Referer', resp.request.headers)
self.assertEqual(resp.request.headers['Referer'], 'http://localhost/')
resp = app.get('/one_forms/').form.submit()
self.assertIn('Referer', resp.request.headers)
self.assertEqual(resp.request.headers['Referer'], 'http://localhost/one_forms/')
def test_xml_attribute(self):
app = webtest.TestApp(links_app)
resp = app.get('/no_form/')
self.assertRaises(
AttributeError,
getattr,
resp, 'xml'
)
resp.content_type = 'text/xml'
resp.xml
@unittest.skipIf('PyPy' in sys.version, 'skip lxml tests on pypy')
def test_lxml_attribute(self):
app = webtest.TestApp(links_app)
resp = app.post('/')
resp.content_type = 'text/xml'
print(resp.body)
print(resp.lxml)
def test_html_attribute(self):
app = webtest.TestApp(links_app)
res = app.post('/')
res.content_type = 'text/plain'
self.assertRaises(
AttributeError,
getattr, res, 'html'
)
def test_no_form(self):
app = webtest.TestApp(links_app)
resp = app.get('/no_form/')
self.assertRaises(
TypeError,
getattr,
resp, 'form'
)
def test_one_forms(self):
app = webtest.TestApp(links_app)
resp = app.get('/one_forms/')
self.assertEqual(resp.form.id, 'first_form')
def test_too_many_forms(self):
app = webtest.TestApp(links_app)
resp = app.get('/many_forms/')
self.assertRaises(
TypeError,
getattr,
resp, 'form'
)
def test_showbrowser(self):
def open_new(f):
self.filename = f
webbrowser.open_new = open_new
app = webtest.TestApp(debug_app)
res = app.post('/')
res.showbrowser()
def test_unicode_normal_body(self):
app = webtest.TestApp(debug_app)
res = app.post('/')
self.assertRaises(
AttributeError,
getattr, res, 'unicode_normal_body'
)
res.charset = 'latin1'
res.body = 'été'.encode('latin1')
self.assertEqual(res.unicode_normal_body, 'été')
def test_testbody(self):
app = webtest.TestApp(debug_app)
res = app.post('/')
res.charset = 'utf8'
res.body = 'été'.encode('latin1')
res.testbody
def test_xml(self):
app = webtest.TestApp(links_app)
resp = app.get('/no_form/')
self.assertRaises(
AttributeError,
getattr,
resp, 'xml'
)
resp.content_type = 'text/xml'
resp.xml
def test_json(self):
app = webtest.TestApp(links_app)
resp = app.get('/json/')
with self.assertRaises(AttributeError):
resp.json
resp.content_type = 'text/json'
self.assertIn('foo', resp.json)
resp.content_type = 'application/json'
self.assertIn('foo', resp.json)
resp.content_type = 'application/vnd.webtest+json'
self.assertIn('foo', resp.json)
def test_unicode(self):
app = webtest.TestApp(links_app)
resp = app.get('/')
if not PY3:
unicode(resp)
print(resp.__unicode__())
def test_content_dezips(self):
app = webtest.TestApp(gzipped_app)
resp = app.get('/')
self.assertEqual(resp.body, b'test')
class TestFollow(unittest.TestCase):
def get_redirects_app(self, count=1, locations=None):
"""Return an app that issues a redirect ``count`` times"""
remaining_redirects = [count] # this means "nonlocal"
if locations is None:
locations = ['/'] * count
def app(environ, start_response):
headers = [('Content-Type', str('text/html'))]
if remaining_redirects[0] == 0:
status = "200 OK"
body = b"done"
else:
status = "302 Found"
body = b''
nextloc = str(locations.pop(0))
headers.append(('location', nextloc))
remaining_redirects[0] -= 1
headers.append(('Content-Length', str(len(body))))
# PEP 3333 requires native strings:
headers = [(str(k), str(v)) for k, v in headers]
start_response(str(status), headers)
return [body]
return webtest.TestApp(app)
def test_follow_with_cookie(self):
app = webtest.TestApp(debug_app)
app.get('/?header-set-cookie=foo=bar')
self.assertEqual(app.cookies['foo'], 'bar')
resp = app.get('/?status=302%20Found&header-location=/')
resp = resp.follow()
resp.mustcontain('HTTP_COOKIE: foo=bar')
def test_follow(self):
app = self.get_redirects_app(1)
resp = app.get('/')
self.assertEqual(resp.status_int, 302)
resp = resp.follow()
self.assertEqual(resp.body, b'done')
# can't follow non-redirect
self.assertRaises(AssertionError, resp.follow)
def test_follow_relative(self):
app = self.get_redirects_app(2, ['hello/foo/', 'bar'])
resp = app.get('/')
self.assertEqual(resp.status_int, 302)
resp = resp.follow()
self.assertEqual(resp.status_int, 302)
resp = resp.follow()
self.assertEqual(resp.body, b'done')
self.assertEqual(resp.request.url, 'http://localhost/hello/foo/bar')
def test_follow_twice(self):
app = self.get_redirects_app(2)
resp = app.get('/').follow()
self.assertEqual(resp.status_int, 302)
resp = resp.follow()
self.assertEqual(resp.status_int, 200)
def test_maybe_follow_200(self):
app = self.get_redirects_app(0)
resp = app.get('/').maybe_follow()
self.assertEqual(resp.body, b'done')
def test_maybe_follow_once(self):
app = self.get_redirects_app(1)
resp = app.get('/').maybe_follow()
self.assertEqual(resp.body, b'done')
def test_maybe_follow_twice(self):
app = self.get_redirects_app(2)
resp = app.get('/').maybe_follow()
self.assertEqual(resp.body, b'done')
def test_maybe_follow_infinite(self):
app = self.get_redirects_app(100000)
self.assertRaises(AssertionError, app.get('/').maybe_follow)
| 2.546875
| 3
|
publications/models.py
|
tarsisferreira/personalsite
| 0
|
12778746
|
<reponame>tarsisferreira/personalsite
from django.db import models
class Journal(models.Model):
"""
A journal
"""
journal = models.CharField(max_length=500)
def __unicode__(self):
return self.journal
class Author(models.Model):
"""
A single author
"""
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
middle_name = models.CharField(max_length=20)
def __unicode__(self):
return self.first_name + " " + self.last_name
class Publication(models.Model):
"""
A single publication, mapped to a pubmed ID.
"""
pmid = models.IntegerField()
pubdate = models.DateTimeField('date published')
title = models.CharField(max_length=500)
journal = models.ForeignKey(Journal)
pages = models.CharField(max_length=20)
volume = models.IntegerField()
ip = models.IntegerField()
author = models.ManyToManyField(Author, through="Authorship")
def __unicode__(self):
return self.title
class Authorship(models.Model):
"""
Relationship between author and publication. Allows us to
keep track of authorship order
"""
author = models.ForeignKey(Author)
publication = models.ForeignKey(Publication)
order = models.IntegerField()
def __unicode__(self):
return "author: " + self.author + " #" + str(self.order) + ", publication: " + self.publication
class Resource(models.Model):
"""
Contains a resource related to a publication
"""
publication = models.ForeignKey(Publication, blank=True, null=True)
name = models.CharField(max_length=500)
description = models.CharField(max_length=5000)
datalink = models.CharField(max_length=100)
date = models.DateTimeField('date published')
def __unicode__(self):
return "Resource: " + self.name + ": " + self.description
class PressRelease(models.Model):
"""
Contains a press release related to a publication
"""
publication = models.ForeignKey(Publication)
prdate = models.DateTimeField('date published')
title = models.CharField(max_length=100)
journal = models.ForeignKey(Journal)
link = models.CharField(max_length=200)
def __unicode__(self):
return "PR: " + self.title
| 2.59375
| 3
|
sabi/sync.py
|
sabi-ai/sabi
| 0
|
12778747
|
from sabi.api_client import ApiClient
class Sync(ApiClient):
headers = None
def __init__(self, api_key, host = None):
version = 'v1'
base = f'{version}/sync'
super().__init__(api_key, base, host)
def save_individuals(self, individuals):
"""
Example for valid payload:
[
{
"id": "1",
"name": "joe"
}
]
"""
response = self.put('individuals',json=individuals)
return response
def save_states(self, states):
"""
Example for valid payload:
[
{
"id": "ddwe3-23sx-aas42",
"name": "Backlog",
"flow": "In Development",
"position": 4,
"is_complete": false,
"is_wip": true
}
]
"""
response = self.put('status',json=states)
return response
def save_projects(self, states):
"""
Example for valid payload:
[
{
"project_id": "ddwe3-23sx-aas42",
"name": "Testing Me",
"short_name": "TM",
"description":"",
"json": {}
}
]
"""
response = self.put('projects',json=states)
return response
def save_labels(self, labels):
"""
Example for valid payload:
[
{
"id": "foo",
"name": "foo"
}
]
"""
response = self.put('labels',json=labels)
return response
def save_fields(self, fields):
"""
Example for valid payload:
[
{
"id": "foo",
"name": "foo",
"is_custom": true,
"type": "text",
"json": "{}"
}
]
"""
response = self.put('fields',json=fields)
return response
def save_ticket_assignments(self, ticket_assignments):
"""
Example for valid payload:
[
{
"ticket_id": "ddwe3-23sx-aas42",
"individual_id": "44fd-4rwas-3344",
"add_or_remove": "added/removed",
"datetime": "2019-03-28 17:43:58.48+00"
}
]
"""
response = self.put('tickets','assignment',json=ticket_assignments)
return response
def save_ticket_labels(self, ticket_labels):
"""
Example for valid payload:
[
{
"ticket_id": "ddwe3-23sx-aas42",
"label_id": "44fd-4rwas-3344",
"add_or_remove": "added/removed",
"datetime": "2019-03-28 17:43:58.48+00"
}
]
"""
response = self.put('tickets','label',json=ticket_labels)
return response
def save_ticket_status_changes(self, ticket_status_changes):
"""
Example for valid payload:
[
{
"ticket_id": "344",
"from_state": "State A",
"to_state": "State B",
"datetime": "2019-03-28 17:43:58.48+00"
}
]
"""
response = self.put('tickets','status','changes',json=ticket_status_changes)
return response
def save_tickets(self, tickets):
"""
Example for valid payload:
[
{
"ticket_id": "tt43d-344frf-w34d",
"name": "Story name",
"description": "Story description",
"type": "Bug",
"parent_id": "ff43d-sdd34-sd42",
"created_at": "2021-04-04",
"deleted": false,
"estimate": 5
}
]
"""
response = self.put('tickets',json=tickets)
return response
def delete_tickets(self, tickets):
"""
Example for valid payload:
[
{
"ticket_id": "tt43d-344frf-w34d",
"deleted": false
}
]
"""
response = self.delete('tickets',json=tickets)
return response
def save_pagination(self, pagination_information):
"""
Example for valid payload:
[
{
"object_type": "tickets",
"next_pull": "https://clubhouse.com/api/v1/tickets/next_object/foo",
"query": "2021-04-01..2021-04-31"
}
]
"""
response = self.put('pagination',json=pagination_information)
return response
def get_pagination(self):
"""
No Payload Required, returns all paginiation rows
"""
response = self.get('pagination')
return response
def get_missing_individuals(self):
"""
No Payload Required, returns all missing individuals
"""
response = self.get('individuals','missing')
return response
def get_missing_statuses(self):
"""
No Payload Required, returns all missing individuals
"""
response = self.get('status','missing')
return response
def get_ticket(self, ticket_id):
response = self.get('tickets',ticket_id)
return response
def get_fields(self):
response = self.get('fields')
return response
| 2.421875
| 2
|
tests/test_accumulators.py
|
YiqingZhouKelly/pyqmc
| 0
|
12778748
|
import numpy as np
from pyqmc.energy import energy
from pyqmc.accumulators import LinearTransform
def test_transform():
""" Just prints things out;
TODO: figure out a thing to test.
"""
from pyscf import gto, scf
import pyqmc
r = 1.54 / 0.529177
mol = gto.M(
atom="H 0. 0. 0.; H 0. 0. %g" % r,
ecp="bfd",
basis="bfd_vtz",
unit="bohr",
verbose=1,
)
mf = scf.RHF(mol).run()
wf = pyqmc.slater_jastrow(mol, mf)
enacc = pyqmc.EnergyAccumulator(mol)
print(list(wf.parameters.keys()))
transform = LinearTransform(wf.parameters)
x = transform.serialize_parameters(wf.parameters)
nconfig = 10
configs = pyqmc.initial_guess(mol, nconfig)
wf.recompute(configs)
pgrad = wf.pgradient()
gradtrans = transform.serialize_gradients(pgrad)
assert gradtrans.shape[1] == len(x)
assert gradtrans.shape[0] == nconfig
if __name__ == "__main__":
test_transform()
| 2.21875
| 2
|
src/mlscratch/measurer/probs_measurer.py
|
aicroe/mlscratch
| 0
|
12778749
|
"""ProbsMeasurer's module."""
import numpy as np
from mlscratch.tensor import Tensor
from .measurer import Measurer
class ProbsMeasurer(Measurer[float]):
"""Computes how many samples were evaluated correctly by
getting the most probable label/index in the probability array."""
def measure(
self,
result: Tensor,
expected: Tensor) -> float:
batch_size, *_ = result.shape
result_max_indices = np.argmax(result, axis=-1)
expected_max_indices = np.argmax(expected, axis=-1)
asserts = np.sum(result_max_indices == expected_max_indices)
return asserts / batch_size
| 2.5625
| 3
|
cbe/cbe/physical_object/views.py
|
cdaf/cbe
| 3
|
12778750
|
from rest_framework import permissions, renderers, viewsets
from cbe.physical_object.models import Structure, Vehicle, Device, Owner
from cbe.physical_object.serializers import StructureSerializer, VehicleSerializer, DeviceSerializer
class StructureViewSet(viewsets.ModelViewSet):
queryset = Structure.objects.all()
serializer_class = StructureSerializer
permission_classes = (permissions.DjangoModelPermissions, )
class VehicleViewSet(viewsets.ModelViewSet):
queryset = Vehicle.objects.all()
serializer_class = VehicleSerializer
permission_classes = (permissions.DjangoModelPermissions, )
class DeviceViewSet(viewsets.ModelViewSet):
queryset = Device.objects.all()
serializer_class = DeviceSerializer
permission_classes = (permissions.DjangoModelPermissions, )
| 2.140625
| 2
|