content
stringlengths 0
894k
| type
stringclasses 2
values |
---|---|
from django.apps import AppConfig
class TrantoolConfig(AppConfig):
name = 'transtool'
# todo check settings and show errors if there are any mistakes
|
python
|
from layout import fonts
import pygame
from utils import gen_text_object
class Button:
def __init__(self, display, x, y, w, h,
color_active, color_inactive, border_w, border_color, pressed_down_color, text_color_norm,
text_color_pressed, text='', action=None, jump_inc=0):
self.display = display
self.x, self.y = x, y
self.w, self.h = w, h
self.color_active = color_active
self.color_inactive = color_inactive
self.color_pressed_down = pressed_down_color
self.border_w = border_w
self.border_color = border_color
self.text_color_norm = text_color_norm
self.text_color_pressed = text_color_pressed
self.text = text
self.fg = None
self.bg = None
self.action = action
self.jump_inc = jump_inc
self.mouse_over = False
self.pressed_down = False
def invoke(self):
if self.mouse_over:
self.mouse_over = False
if self.action is not None:
return self.action()
def find_collision(self, x, y):
return self.bg.collidepoint(x, y)
def draw(self):
self.bg = pygame.draw.rect(
self.display, self.border_color,
(self.x - self.border_w, self.y - self.border_w,
self.w + self.border_w * 2, self.h + self.border_w * 2)
)
if self.pressed_down:
bg_color = self.color_pressed_down
text_color = self.text_color_pressed
elif self.mouse_over:
bg_color = self.color_active
text_color = self.text_color_norm
else:
bg_color = self.color_inactive
text_color = self.text_color_norm
self.fg = pygame.draw.rect(
self.display, bg_color,
(self.x, self.y,
self.w, self.h)
)
text_surf, text_rect = gen_text_object(text=self.text, font=fonts.button, color=text_color)
text_rect.center = (self.x + self.w * 0.5, self.y + self.h * 0.5)
self.display.blit(text_surf, text_rect)
def jump_up(self):
self.y -= self.jump_inc
|
python
|
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:40 ms, 在所有 Python3 提交中击败了88.07% 的用户
内存消耗:13.4 MB, 在所有 Python3 提交中击败了42.98% 的用户
解题思路:
双指针
p指针用于记录位置,q指针寻找小于x的节点。
q指针找到<x的节点后,交换链表
"""
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
p, q = ListNode(0, next = head), head # p指针用于记录位置,q指针用于寻找<x的节点。为便于交换链表,寻找时,均使用指针的next来判断节点
start = p
while p and p.next and p.next.val < x: # 先移动p指针,直到p的下一个节点值大于x
p = p.next
q = p.next
while q and q.next:
if q.next.val < x: # 如果q指针指向的下一个节点值小于x, 则交换链表
p_next = p.next
q_next_next = q.next.next
p.next = q.next
q.next.next = p_next
q.next = q_next_next
p = p.next # 交换链表后,p指针向后移动一位
else: # q指针指向的下一个节点值>=x,则移动q指针寻找小于x的节点
q = q.next
return start.next
|
python
|
import logging
from typing import Any, Dict
import requests
LOG = logging.getLogger(__name__)
class Client:
CROSSWALK_ENDPOINT = '/crosswalks'
STATISTICS_ENDPOTIN = '/statistics'
TOKEN_ENDPOINT = '/login/access-token'
def __init__(self, base_url: str, username: str, passwd: str) -> None:
self.base_url = base_url
self.username = username
self.passwd = passwd
self.token = None
def _send_request(self,
endpoint: str,
method: str = 'get',
body: Any = None,
query_params: Dict[str, str] = None,
headers: Dict[str, str] = None,
) -> dict:
url = f"{self.base_url}{endpoint}"
if query_params:
params = "&".join(f'{key}={val}' for key, val in query_params.items())
url += f"?{params}"
LOG.debug("Send request to %s", url)
if method == 'get':
response = requests.get(url, headers=headers)
elif method == 'post':
response = requests.post(url, data=body, headers=headers)
elif method == 'delete':
response = requests.delete(url, data=body, headers=headers)
else:
raise ValueError(f'Invalid request method ({method})')
if not response.ok:
LOG.error("Got invalid response from backend: [%s] %s",
response.status_code, response.text)
response_data = response.json()
LOG.debug("Got response: %s", response_data)
return response_data
def get_all_crosswalks(self):
auth_header = self._prepare_auth_header()
return self._send_request(self.CROSSWALK_ENDPOINT, headers=auth_header)
def get_all_stats(self):
auth_header = self._prepare_auth_header()
return self._send_request(self.STATISTICS_ENDPOTIN, headers=auth_header)
def delete_crosswalk(self, name: str):
auth_header = self._prepare_auth_header()
return self._send_request(self.CROSSWALK_ENDPOINT + f"/{name}", headers=auth_header, method='delete')
def _get_token(self):
data = f'grant_type=&username={self.username}&password={self.passwd}&scope=&client_id=&client_secret='
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
LOG.info('Get token')
response = self._send_request(self.TOKEN_ENDPOINT,
method='post',
body=data,
headers=headers)
return response['access_token']
def _prepare_auth_header(self):
if not self.token:
self.token = self._get_token()
return {'Authorization': f'Bearer {self.token}'}
|
python
|
from tacred_enrichment.internal.ucca_enhancer import UccaEnhancer
from tacred_enrichment.internal.ucca_types import UccaParsedPassage
from tacred_enrichment.internal.dep_graph import Step, DepGraph
from tacred_enrichment.internal.ucca_types import is_terminal
class UccaEncoding(UccaEnhancer):
def enhance(self, tac, tac_to_ucca, ucca: UccaParsedPassage):
links = ucca.get_links()
graph = DepGraph(links, is_terminal)
terminals_to_ucca_encoding = {}
for terminal_on_path in ucca.terminals:
token_index = int(terminal_on_path.node_id.split('.')[1]) - 1
steps = graph.get_undirected_steps(terminal_on_path.node_id, graph.root())
terminals_to_ucca_encoding[token_index] = Step.get_dependency_representation(steps[1:]) if len(steps) > 1 else ''
return {'ucca_encodings':terminals_to_ucca_encoding}
|
python
|
from flask import jsonify
class InvalidSearchException(ValueError): pass
class InvalidRequestException(Exception):
def __init__(self, error_message, code=None):
self.error_message = error_message
self.code = code or 400
def response(self):
return jsonify({'error': self.error_message}), self.code
def error(message, code=None):
"""
Trigger an Exception that will short-circuit the Response cycle and return
a 400 "Bad request" with the given error message.
"""
raise InvalidRequestException(message, code=code)
|
python
|
from argparse import ArgumentParser
import pysam
def merge(input_path, output_path, custom_id='custom_id', line_length=80):
with open(output_path, 'w+') as out_f:
out_f.write(f'>{custom_id}\n')
data = ''
with pysam.FastxFile(input_path) as in_f:
for record in in_f:
print(f'Merging {record.name}')
data += record.sequence
for i in range(0, len(data), line_length):
chunk = data[i:i + line_length]
if len(chunk) == line_length:
out_f.write(chunk+'\n')
else:
data = chunk
if len(data) > 0: out_f.write(data+'\n')
def main():
parser = ArgumentParser(description='FASTA-merge: merge multiple FASTA sequences into one')
parser.add_argument('input_path', type=str,
help='str: input FASTA file')
parser.add_argument('output_path', type=str,
help='str: output FASTA file')
parser.add_argument('custom_id', type=str,
help='str: custom id for the resulting single sequence')
parser.add_argument('line_length', type=int, nargs='?',
help='int: line length (default=80)')
args = parser.parse_args()
input_path = args.input_path
output_path = args.output_path
custom_id = args.custom_id
line_length = args.line_length
if line_length == None: line_length = 80
merge(input_path, output_path, custom_id=custom_id, line_length=line_length)
if __name__ == '__main__':
main()
|
python
|
n=input()
if(len(n)<4):
print("NO")
else:
count=0
for i in range(0,len(n)):
if(n[i]=='4' or n[i]=='7'):
count=count+1
dig=0
flag=0
if(count==0):
print("NO")
else:
while count>0:
dig=count%10
if(dig!=4 and dig!=7):
flag=1
break
count=count//10
if(flag==0):
print("YES")
else:
print("NO")
|
python
|
# Generated by Django 2.2.3 on 2019-07-12 14:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('TeamXapp', '0047_auto_20190712_1504'),
]
operations = [
migrations.AlterField(
model_name='allmembers',
name='scrum_team_name',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='TeamXapp.ScrumTeam', verbose_name='Scrum team: '),
),
migrations.AlterField(
model_name='allmembers',
name='scrum_team_roles',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='TeamXapp.ScrumTeamRole', verbose_name='Scrum Team Roles: '),
),
migrations.AlterField(
model_name='leavecalendar',
name='leave_type',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='TeamXapp.LeaveStatus'),
),
migrations.AlterField(
model_name='scrumteam',
name='domain',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='TeamXapp.Domain', verbose_name='Domain'),
),
migrations.AlterField(
model_name='scrumteam',
name='scrum_master',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='TeamXapp.AllMembers', verbose_name='Scrum Master'),
),
migrations.AlterField(
model_name='scrumteam',
name='team_status',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='TeamXapp.ScrumTeamStatus', verbose_name='Team Status'),
),
migrations.AlterField(
model_name='scrumteam',
name='team_type',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='TeamXapp.ScrumTeamType', verbose_name='Team Type'),
),
]
|
python
|
import os
import numpy
import math
import cv2
from skimage import io
from skimage import color
import torch
from torch.utils.data import Dataset
from torchvision import transforms
from random import randint
class ClusterDataset(Dataset):
"""Camera localization dataset."""
def __cluster__(self, root_dir, num_experts):
'''
Clusters the dataset using hierarchical kMeans.
Initialization:
Put all images in one cluster.
Interate:
Pick largest cluster.
Split with kMeans and k=2.
Input for kMeans is the 3D median scene coordiante per image.
Terminate:
When number of target clusters has been reached.
Returns:
cam_centers: For each cluster the mean (not median) scene coordinate
labels: For each image the cluster ID
'''
print('Clustering the dataset ...')
# load scene coordinate ground truth
init_dir = root_dir + '/init/'
init_files = os.listdir(init_dir)
init_files = [init_dir + f for f in init_files]
init_files.sort()
cam_centers = torch.zeros((len(init_files), 3))
num_cam_clusters = num_experts
# Calculate median scene coordinate per image
for i, f in enumerate(init_files):
init_data = torch.load(f)
init_data = init_data.view(3, -1)
init_mask = init_data.sum(0) != 0
init_data = init_data[:,init_mask]
init_data = init_data.median(1)[0]
cam_centers[i] = init_data
cam_centers = cam_centers.numpy()
# setup kMEans
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.1)
flags = cv2.KMEANS_PP_CENTERS
# label of next cluster
label_counter = 0
# initialize list of clusters with all images
clusters = []
clusters.append((cam_centers, label_counter, numpy.zeros(3)))
# all images belong to cluster 0
labels = numpy.zeros(len(init_files))
# iterate kMeans with k=2
while len(clusters) < num_cam_clusters:
# select largest cluster (list is sorted)
cur_cluster = clusters.pop(0)
label_counter += 1
# split cluster
_, cur_labels, cur_centroids = cv2.kmeans(cur_cluster[0], 2, None, criteria, 10, flags)
# update cluster list
cur_mask = (cur_labels == 0)[:,0]
cur_cam_centers0 = cur_cluster[0][cur_mask,:]
clusters.append((cur_cam_centers0, cur_cluster[1], cur_centroids[0]))
cur_mask = (cur_labels == 1)[:,0]
cur_cam_centers1 = cur_cluster[0][cur_mask,:]
clusters.append((cur_cam_centers1, label_counter, cur_centroids[1]))
cluster_labels = labels[labels == cur_cluster[1]]
cluster_labels[cur_mask] = label_counter
labels[labels == cur_cluster[1]] = cluster_labels
#sort updated list
clusters = sorted(clusters, key = lambda cluster: cluster[0].shape[0], reverse = True)
cam_centers = torch.zeros(num_cam_clusters, 3)
cam_sizes = torch.zeros(num_cam_clusters, 1)
# output result
for cluster in clusters:
# recalculate cluster centers (is: mean of medians, we want: mean of means)
cam_num = cluster[0].shape[0]
cam_data = torch.zeros((cam_num, 3))
cam_count = 0
for i, f in enumerate(init_files):
if labels[i] == cluster[1]:
init_data = torch.load(f)
init_data = init_data.view(3, -1)
init_mask = init_data.sum(0) != 0
init_data = init_data[:,init_mask]
cam_data[cam_count] = init_data.sum(1) / init_mask.sum()
cam_count += 1
cam_centers[cluster[1]] = cam_data.mean(0)
cam_dists = cam_centers[cluster[1]].unsqueeze(0).expand(cam_num, 3)
cam_dists = cam_data - cam_dists
cam_dists = cam_dists.norm(dim=1)
cam_dists = cam_dists**2
cam_sizes[cluster[1]] = cam_dists.mean()
print("Cluster %i: %.1fm, %.1fm, %.1fm, images: %i" % (cluster[1], cam_centers[cluster[1]][0], cam_centers[cluster[1]][1], cam_centers[cluster[1]][2], cluster[0].shape[0]))
print('Done.')
return cam_centers, cam_sizes, labels
def __init__(self, root_dir, num_clusters, cluster = -1, training=True, imsize=480, softness=5):
'''Constructor.
Clusters the dataset, and creates lists of data files.
Parameters:
root_dir: Folder of the data (training or test).
expert: Select a specific cluster. Loads only data of this expert.
num_experts: Number of clusters for clustering.
training: Load and return ground truth scene coordinates (disabled for test).
'''
self.num_experts = num_clusters
self.cluster = cluster
self.training = training
self.imsize = imsize
self.softness = softness
with open('env_list.txt', 'r') as f:
environment = f.readlines()
if len(environment) > 1:
print("ERROR: Environment file contains more than one line. Clustering is not supported for more than one dataset.")
exit()
root_dir = environment[0].strip() + '/' + root_dir
rgb_dir = root_dir + '/rgb/'
pose_dir = root_dir + '/poses/'
calibration_dir = root_dir + '/calibration/'
init_dir = root_dir + '/init/'
seg_dir = root_dir + '/seg/'
self.rgb_files = os.listdir(rgb_dir)
self.rgb_files = [rgb_dir + f for f in self.rgb_files]
self.rgb_files.sort()
# statistics calculated over aachen day training set
img_mean = [0.3639, 0.3639, 0.3639]
img_std = [0.2074, 0.2074, 0.2074]
if training:
clr_jitter = transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=[0,0])
else:
clr_jitter = transforms.ColorJitter(saturation=[0,0])
self.image_transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize(self.imsize),
clr_jitter,
transforms.ToTensor(),
transforms.Normalize(
mean=img_mean,
std=img_std
)
])
self.pose_files = os.listdir(pose_dir)
self.pose_files = [pose_dir + f for f in self.pose_files]
self.pose_files.sort()
self.calibration_files = os.listdir(calibration_dir)
self.calibration_files = [calibration_dir + f for f in self.calibration_files]
self.calibration_files.sort()
if self.training:
self.init_files = os.listdir(init_dir)
self.init_files = [init_dir + f for f in self.init_files]
self.init_files.sort()
# cluster the dataset
self.cam_centers, self.cam_sizes, self.labels = self.__cluster__(root_dir, num_clusters)
print("Calculating ground truth gating probabilities.")
self.gating_probs = torch.zeros((len(self.init_files), num_clusters))
for i, f in enumerate(self.init_files):
init_data = torch.load(f)
init_data = init_data.view(3, -1)
init_mask = init_data.sum(0) != 0
init_data = init_data[:,init_mask]
init_data = init_data.sum(1) / init_mask.sum()
init_data = init_data.unsqueeze(0).expand(self.cam_centers.size())
init_data = init_data - self.cam_centers
init_data = init_data.norm(dim=1)
init_data = init_data**2
init_data = init_data / self.cam_sizes[:,0] / 2
init_data = torch.exp(-init_data * self.softness)
init_data /= torch.sqrt(2 * math.pi * self.cam_sizes[:,0])
init_data /= init_data.sum() + 0.0000001
self.gating_probs[i] = init_data
if cluster >= 0:
self.img_sampler = torch.distributions.categorical.Categorical(probs = self.gating_probs[:,self.cluster])
print("Done.")
def __len__(self):
'''Returns length of the dataset.'''
return len(self.rgb_files)
def get_file_name(self, idx):
return self.rgb_files[idx]
def __getitem__(self, idx):
'''Loads and returns the i th data item of the dataset.
Returns:
image: RGB iamge.
pose: ground truth camera pose.
init: ground truth scene coordinates.
seg: binary segmentation that masks clutter: people, sky, cars etc. Obtained via a off-the shelf semantic segmentation method.
focal_length: Focal length of the camera.
idx: Pass through of the data item index.
'''
if self.cluster >= 0:
idx = int(self.img_sampler.sample())
image = io.imread(self.rgb_files[idx])
if len(image.shape) < 3: # covnert gray scale images
image = color.gray2rgb(image)
# scale image and focallength correspondingly
image_scale = self.imsize / min(image.shape[0:2])
image = self.image_transform(image)
focallength = float(numpy.loadtxt(self.calibration_files[idx]))
focallength *= image_scale
gt_pose = numpy.loadtxt(self.pose_files[idx])
gt_pose = torch.from_numpy(gt_pose).float()
if self.training:
gt_coords = torch.load(self.init_files[idx])
else:
gt_coords = 0
return idx, image, focallength, gt_pose, gt_coords, -1
|
python
|
import pytest
from pretalx.common.forms.utils import get_help_text
@pytest.mark.parametrize('text,min_length,max_length,warning', (
('t', 1, 3, 't Please write between 1 and 3 characters.'),
('', 1, 3, 'Please write between 1 and 3 characters.'),
('t', 0, 3, 't Please write no more than 3 characters.'),
('t', 1, 0, 't Please write at least 1 characters.'),
))
def test_get_text_length_help_text(text, min_length, max_length, warning):
assert get_help_text(text, min_length, max_length) == warning
|
python
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
Provides a set of I/O routines.
.. include common links, assuming primary doc root is up one directory
.. include:: ../links.rst
"""
import os
import sys
import warnings
import gzip
import shutil
from packaging import version
import numpy
from astropy.io import fits
# These imports are largely just to make the versions available for
# writing to the header. See `initialize_header`
import scipy
import astropy
import sklearn
import pypeit
import time
from IPython import embed
def init_record_array(shape, dtype):
r"""
Utility function that initializes a record array using a provided
input data type. For example::
dtype = [ ('INDX', numpy.int, (2,) ),
('VALUE', numpy.float) ]
Defines two columns, one named `INDEX` with two integers per row and
the one named `VALUE` with a single float element per row. See
`numpy.recarray`_.
Args:
shape (:obj:`int`, :obj:`tuple`):
Shape of the output array.
dtype (:obj:`list`):
List of the tuples that define each element in the record
array.
Returns:
`numpy.recarray`: Zeroed record array
"""
return numpy.zeros(shape, dtype=dtype).view(numpy.recarray)
def rec_to_fits_type(rec_element):
"""
Return the string representation of a fits binary table data type
based on the provided record array element.
"""
n = 1 if len(rec_element[0].shape) == 0 else rec_element[0].size
if rec_element.dtype == numpy.bool:
return '{0}L'.format(n)
if rec_element.dtype == numpy.uint8:
return '{0}B'.format(n)
if rec_element.dtype == numpy.int16 or rec_element.dtype == numpy.uint16:
return '{0}I'.format(n)
if rec_element.dtype == numpy.int32 or rec_element.dtype == numpy.uint32:
return '{0}J'.format(n)
if rec_element.dtype == numpy.int64 or rec_element.dtype == numpy.uint64:
return '{0}K'.format(n)
if rec_element.dtype == numpy.float32:
return '{0}E'.format(n)
if rec_element.dtype == numpy.float64:
return '{0}D'.format(n)
# If it makes it here, assume its a string
l = int(rec_element.dtype.str[rec_element.dtype.str.find('U')+1:])
# return '{0}A'.format(l) if n==1 else '{0}A{1}'.format(l*n,l)
return '{0}A'.format(l*n)
def rec_to_fits_col_dim(rec_element):
"""
Return the string representation of the dimensions for the fits
table column based on the provided record array element.
The shape is inverted because the first element is supposed to be
the most rapidly varying; i.e. the shape is supposed to be written
as row-major, as opposed to the native column-major order in python.
"""
return None if len(rec_element[0].shape) == 1 else str(rec_element[0].shape[::-1])
def rec_to_bintable(arr, name=None, hdr=None):
"""
Construct an `astropy.io.fits.BinTableHDU` from a record array.
Args:
arr (`numpy.recarray`):
The data array to write to a binary table.
name (:obj:`str`, optional):
The name for the binary table extension.
hdr (`astropy.io.fits.Header`, optional):
Header for the BinTableHDU extension.
Returns:
`astropy.io.fits.BinTableHDU`: The binary fits table that can be
included in an `astropy.io.fits.HDUList` and written to disk.
"""
return fits.BinTableHDU.from_columns([fits.Column(name=n,
format=rec_to_fits_type(arr[n]),
dim=rec_to_fits_col_dim(arr[n]),
array=arr[n])
for n in arr.dtype.names], name=name, header=hdr)
def compress_file(ifile, overwrite=False, rm_original=True):
"""
Compress a file using gzip package.
Args:
ifile (:obj:`str`):
Name of file to compress. Output file with have the same
name with '.gz' appended.
overwrite (:obj:`bool`, optional):
Overwrite any existing file.
rm_original (:obj:`bool`, optional):
The method writes the compressed file such that both the
uncompressed and compressed file will exist when the
compression is finished. If this is True, the original
(uncompressed) file is removed.
Raises:
ValueError:
Raised if the file name already has a '.gz' extension or if
the file exists and `overwrite` is False.
"""
# Nominally check if the file is already compressed
if ifile.split('.')[-1] == 'gz':
raise ValueError('File appears to already have been compressed! {0}'.format(ifile))
# Construct the output file name and check if it exists
ofile = '{0}.gz'.format(ifile)
if os.path.isfile(ofile) and not overwrite:
raise FileExistsError('{0} exists! To overwrite, set overwrite=True.'.format(ofile))
# Compress the file
with open(ifile, 'rb') as f_in:
with gzip.open(ofile, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
if rm_original:
# Remove the uncompressed file
os.remove(ifile)
def parse_hdr_key_group(hdr, prefix='F'):
"""
Parse a group of fits header values grouped by a keyword prefix.
If the prefix is 'F', the header keywords are expected to be, e.g.,
'F1', 'F2', 'F3', etc. The list of values returned are then, e.g.,
[ hdr['F1'], hdr['F2'], hdr['F3'], ... ]. The function performs no
retyping, so the values in the returned list have whatever type they
had in the fits header.
Args:
hdr (`fits.Header`):
Astropy Header object
prefix (:obj:`str`, optional):
The prefix used for the header keywords.
Returns:
list: The list of header values ordered by their keyword index.
"""
values = {}
for k, v in hdr.items():
# Check if this header keyword starts with the required prefix
if k[:len(prefix)] == prefix:
try:
# Try to convert the keyword without the prefix into an
# integer; offseting to an array index.
i = int(k[len(prefix):])-1
except ValueError:
# Assume the value is some other random keyword that
# starts with the prefix but isn't part of the keyword
# group
continue
# Assume we've found a valid value; assign it and keep
# trolling the header
values[i] = v
# Convert from dictionary with integer keys to an appropriately
# sorted list
# JFH try/except added to deal with cases where no header cards were found with the desired
# prefix. I'm not sure returning an empty list is the desired behavior, but None will cause
# downstream things to crash.
try:
return [values[i] for i in range(max(values.keys())+1)]
except:
return []
def initialize_header(hdr=None):
"""
Initialize a FITS header.
Args:
hdr (`astropy.io.fits.Header`, optional):
Header object to update with basic summary
information. The object is modified in-place and also
returned. If None, an empty header is instantiated,
edited, and returned.
Returns:
`astropy.io.fits.Header`: The initialized (or edited)
fits header.
"""
# Add versioning; this hits the highlights but should it add
# the versions of all packages included in the requirements.txt
# file?
if hdr is None:
hdr = fits.Header()
hdr['VERSPYT'] = ('.'.join([ str(v) for v in sys.version_info[:3]]), 'Python version')
hdr['VERSNPY'] = (numpy.__version__, 'Numpy version')
hdr['VERSSCI'] = (scipy.__version__, 'Scipy version')
hdr['VERSAST'] = (astropy.__version__, 'Astropy version')
hdr['VERSSKL'] = (sklearn.__version__, 'Scikit-learn version')
hdr['VERSPYP'] = (pypeit.__version__, 'PypeIt version')
# Save the date of the reduction
hdr['DATE'] = (time.strftime('%Y-%m-%d',time.gmtime()), 'UTC date created')
# TODO: Anything else?
# Return
return hdr
def header_version_check(hdr, warning_only=True):
"""
Check the package versions in the header match the system versions.
.. note::
The header must contain the keywords written by
:func:`initialize_header`.
Args:
hdr (`astropy.io.fits.Header`):
The header to check
warning_only (:obj:`bool`, optional):
If the versions are discrepant, only throw a warning
instead of raising an exception.
Returns:
:obj:`bool`: Returns True if the check was successful, False
otherwise. If `warning_only` is False, the method will either
raise an exception or return True.
Raises:
ValueError:
Raised if `warning_only` is False and the system versions
are different from those logged in the header.
"""
# Compile the packages and versions to check
packages = ['python', 'numpy', 'scipy', 'astropy', 'sklearn', 'pypeit']
hdr_versions = [hdr['VERSPYT'], hdr['VERSNPY'], hdr['VERSSCI'], hdr['VERSAST'], hdr['VERSSKL'],
hdr['VERSPYP']]
sys_versions = ['.'.join([ str(v) for v in sys.version_info[:3]]), numpy.__version__,
scipy.__version__, astropy.__version__, sklearn.__version__,
pypeit.__version__]
# Run the check and either issue warnings or exceptions
all_identical = True
for package, hdr_version, sys_version in zip(packages, hdr_versions, sys_versions):
if version.parse(hdr_version) != version.parse(sys_version):
all_identical = False
msg = '{0} version used to create the file ({1}) '.format(package, hdr_version) \
+ 'does not match the current system version ({0})!'.format(sys_version)
if warning_only:
# TODO: I had to change pypeit/__init__.py to get these
# to show up. We eventually need to make pypmsgs play
# nice with warnings and other logging, or just give up
# on pypmsgs...
warnings.warn(msg)
else:
raise ValueError(msg)
# Return if all versions are identical
return all_identical
|
python
|
# stateio.py (flowsa)
# !/usr/bin/env python3
# coding=utf-8
"""
Supporting functions for accessing files from stateior via data commons.
https://github.com/USEPA/stateior
"""
import os
import pandas as pd
from esupy.processed_data_mgmt import download_from_remote, Paths,\
load_preprocessed_output
from flowsa.metadata import set_fb_meta
from flowsa.location import us_state_abbrev, apply_county_FIPS
from flowsa.flowbyfunctions import assign_fips_location_system
def parse_statior(*, source, year, config, **_):
"""parse_response_fxn for stateio make and use tables"""
# Prepare meta for downloading stateior datasets
name = config.get('datatype')
fname = f"{name}_{year}"
meta = set_fb_meta(fname, "")
meta.tool = 'stateio'
meta.ext = 'rds'
stateio_paths = Paths()
stateio_paths.local_path = os.path.realpath(stateio_paths.local_path +
"/stateio")
# Download and load the latest version from remote
download_from_remote(meta, stateio_paths)
states = load_preprocessed_output(meta, stateio_paths)
data_dict = {}
# uses rpy2
# this .rds is stored as a list of named dataframes by state
for state in us_state_abbrev.keys():
df = states.rx2(state)
df2 = df.melt(ignore_index=False, value_name = 'FlowAmount',
var_name = 'ActivityConsumedBy')
df2['ActivityProducedBy'] = df2.index
if source == 'stateio_Make_Summary':
# Adjust the index by removing the state: STATE.SECTOR
df2['ActivityProducedBy'] = df2[
'ActivityProducedBy'].str.split(".", expand=True)[1]
df2.reset_index(drop=True, inplace=True)
df2['State'] = state
data_dict[state] = df2
fba = pd.concat(data_dict, ignore_index=True)
fba.dropna(subset=['FlowAmount'], inplace=True)
# Gross Output
if 'GO' in source and 'ActivityConsumedBy' in fba.columns:
fba = fba.drop(columns=['ActivityConsumedBy'])
# Assign location
fba['County'] = ''
fba = apply_county_FIPS(fba)
fba = assign_fips_location_system(fba, '2015')
fba.drop(columns=['County'], inplace=True)
# Hardcoded data
fba['Year'] = year
fba['SourceName'] = source
fba['Class'] = 'Money'
fba['Unit'] = "USD"
fba['FlowName'] = f"USD{year}"
fba["FlowType"] = "TECHNOSPHERE_FLOW"
fba['DataReliability'] = 5 # tmp
fba['DataCollection'] = 5 # tmp
return fba
if __name__ == "__main__":
import flowsa
source = 'stateio_Industry_GO'
flowsa.flowbyactivity.main(year=2017, source=source)
fba = flowsa.getFlowByActivity(source, 2017)
|
python
|
from sys import argv
import json
finalOutput = {"result": ""}
outputFile = argv[3]
if_spark = argv[4]
reviewFile = argv[1]
businessFile = argv[2]
nCates = int(argv[5])
def no_spark():
def LOAD_FILE(filePath):
output = []
with open(filePath) as file:
for line in file:
output.append(json.loads(line))
return output
# nCates = 5
reviews = LOAD_FILE(reviewFile)
business = LOAD_FILE(businessFile)
def howManyKeys(dictIn):
counter = 0
for x in dictIn:
counter += 1
print(counter)
def transReviewToDict(listIn: list):
outputDict = {}
for line in listIn:
if line['business_id'] in outputDict:
outputDict[line['business_id']][line['review_id']] = line
else:
outputDict[line['business_id']] = {line['review_id']: line}
return outputDict
def transBusinessToDict(listIn: list):
outputDict = {}
for line in listIn:
outputDict[line['business_id']] = line
return outputDict
# Load the datasets
businessDict = transBusinessToDict(business)
reviewsDict = transReviewToDict(reviews)
def joinDatasets(reviews, business):
outputDict = {}
for line in reviews:
if line in business:
outputDict[line] = business[line]
outputDict[line]['reviews'] = reviews[line]
# business[line]['reviews'] = line
return outputDict
allDict = joinDatasets(reviewsDict, businessDict)
def countStars(dictIn: dict):
outputDict = {}
for line in dictIn:
# print(line)
cates = str(dictIn[line]['categories']).split(",")
stars = dictIn[line]['stars']
for w in cates:
w = w.strip()
if w in outputDict:
outputDict[w][0] += stars
outputDict[w][1] += 1
else:
outputDict[w] = [stars, 1]
return outputDict
def avgCatesStars(countedStars: dict):
# outputDict = {}
for cate in countedStars:
countedStars[cate] = countedStars[cate][0]/countedStars[cate][1]
return countedStars
def updateStarsByReview(allDict: dict):
for line in allDict:
reviewsOneBusiness = allDict[line]['reviews']
star = 0
for review in reviewsOneBusiness:
# pprint(review)
star += reviewsOneBusiness[review]['stars']
allDict[line]['stars'] = star/len(reviewsOneBusiness)
return allDict
allDictStarUpdated = updateStarsByReview(allDict)
finalCatesStar = avgCatesStars(countStars(allDictStarUpdated))
catesStarList = sorted(finalCatesStar.items(),
key=lambda t: (-t[1], t[0]), reverse=0)
outList = []
c = 0
for i in range(len(catesStarList)):
if c >= nCates:
break
c += 1
# , finalCatesStar[catesStarList[i][0]]])
outList.append(catesStarList[i])
return outList
def spark():
from pyspark import SparkContext as sc
from pyspark import SparkConf
from multiprocessing import cpu_count
cpuNum = cpu_count()
confSpark = SparkConf().setAppName(
"Task2_with_spark").setMaster(
"local[*]").set(
'spark.driver.memory', '12G')
sc = sc.getOrCreate(confSpark)
def transToDict(lineIn: str):
return json.loads(lineIn)
rddReviews = sc.textFile(reviewFile)
rddBusiness = sc.textFile(businessFile)
rddReviewsDict = rddReviews.map(transToDict)
rddBusinessDict = rddBusiness.map(transToDict)
def Map_extractIdAndCategories(line: dict):
cateList = []
cateStr = str(line['categories']).split(",")
for cate in cateStr:
cateList.append(cate.strip())
# return {"business_id":line['business_id'],"categories":cateList}
return (line['business_id'], cateList)
rddExtarctedBusinessDict = rddBusinessDict.map(Map_extractIdAndCategories)
def Map_emitBusinessIdAndStar(line: dict):
outputTuple = (line["business_id"], (float(line["stars"]), 1))
return outputTuple
def Reduce_countAvgStars(value1: tuple, value2: tuple):
return (value1[0]+value2[0], value1[1]+value2[1])
def Map_calcAvgStars(line: tuple):
outputTuple = (line[0], line[1][0]/line[1][1])
return outputTuple
def Reduce_joinStarsAndCategories(line1: tuple, line2: tuple):
outputTuple = (line1, line2)
return outputTuple
def Map_emitCategoriesWithStars(line: tuple):
if isinstance(line, float) or isinstance(line[1], float):
return []
elif len(line[1]) < 2:
return []
else:
outputList = []
stars = line[1][1]
cateList = line[1][0]
for x in cateList:
tupleO = (x, (stars, 1))
outputList.append(tupleO)
return outputList
def test(line):
if not isinstance(line[1][0], str):
return line
rddBusinessStarFromReviews = rddReviewsDict.map(
Map_emitBusinessIdAndStar).partitionBy(cpuNum, lambda line: hash(line[0]) % cpuNum)
rddBusinessStarFromReviews = rddBusinessStarFromReviews.reduceByKey(
Reduce_countAvgStars)
rddBusinessStarFromReviews = rddBusinessStarFromReviews.map(
Map_calcAvgStars)
rddFull = rddExtarctedBusinessDict.union(rddBusinessStarFromReviews)
rddFull = rddFull.reduceByKey(Reduce_joinStarsAndCategories) # .collect()
rddFull = rddFull.flatMap(Map_emitCategoriesWithStars) # .collect()
rddCategoires = rddFull.reduceByKey(Reduce_countAvgStars) # .collect()
rddCategoires = rddCategoires.filter(test) # .collect()
rddCategoires = rddCategoires.map(Map_calcAvgStars).collect()
rddCategoires.sort(key=lambda x: [-x[1], x[0]])
outputList = rddCategoires[0:nCates]
return outputList
def sparkOrNot(if_spark):
if if_spark == 'spark':
return spark()
elif if_spark == "no_spark":
return no_spark()
finalOutput["result"] = sparkOrNot(if_spark)
with open(outputFile, 'a') as outfile:
json.dump(finalOutput, outfile, ensure_ascii=False)
outfile.write('\n')
|
python
|
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import dj_database_url
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', 'please_override_me')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [
'localhost',
'ebu-breakfast.herokuapp.com',
]
# Application definition
INSTALLED_APPS = [
'channels',
'election.apps.ElectionConfig',
'api.apps.ApiConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'rest_framework',
'django_filters',
'knox',
'raven.contrib.django.raven_compat',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.locale.LocaleMiddleware',
]
ROOT_URLCONF = 'breakfast.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'templates'
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
ASGI_APPLICATION = 'breakfast.routing.application'
PASSWORD = 'ebujugend'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'breakfast',
}
}
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
LOGIN_URL = "./login"
LANGUAGES = (
('en', _('English')),
('de', _('German')),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
LANGUAGE_CODE = 'de'
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_L10N = True
USE_TZ = True
USE_X_FORWARDED_HOST = True
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MESSAGE_TAGS = {
messages.ERROR: 'danger'
}
FIXTURE_DIRS = [
'fixtures'
]
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
},
},
}
# Logging
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'propagate': True,
'level': 'INFO'
},
'election': {
'handlers': ['console'],
'propagate': True,
'level': 'DEBUG',
},
},
}
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'knox.auth.TokenAuthentication',
),
}
REST_KNOX = {
'USER_SERIALIZER': 'api.serializers.user.UserSerializer',
}
if not DEBUG:
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
RAVEN_CONFIG = {
'dsn': os.environ.get('SENTRY_DSN', ''),
'release': "2.0.0",
}
|
python
|
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from PIL import Image
import scipy.misc
import pandas as pd
import numpy as np
import random
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from glob import glob
from torch.utils.data import Dataset, DataLoader, random_split
import os
from os import listdir
root_dir = "img_data/"
train_file = os.path.join(root_dir, "train.csv")
val_file = os.path.join(root_dir, "val.csv")
label_colors_file = os.path.join(root_dir, "label_colors.txt")
label_colors_img = os.path.join(root_dir, "LabeledApproved_full/")
means = np.array([103.939, 116.779, 123.68]) / 255.
h, w = 720, 960
train_h = int(h * 2 / 3) # 480
train_w = int(w * 2 / 3) # 640
val_h = int(h/32) * 32 # 704
val_w = w # 960
num_class = 32
data_length = 70
total_pixel = h * w
class ReadDataset(Dataset):
def __init__(self, csv_file, phase, n_class=num_class, crop=True, flip_rate=0.5, scale=1.0):
self.data = pd.read_csv(csv_file)
self.means = means
self.n_class = n_class
self.scale = scale
self.flip_rate = flip_rate
self.crop = crop
if phase == 'train':
self.new_h = int(train_h * scale)
self.new_w = int(train_w * scale)
elif phase == 'val':
self.flip_rate = 0.
self.crop = False
self.new_h = val_h
self.new_w = val_w
def __len__(self):
return len(self.data)
#original code use self.data.ix[idx,0], 'ix' is derprecated, use 'loc'. Check https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html about how to use 'loc'
def __getitem__(self, idx):
img_name_ori = self.data.loc[idx,'img']
img_name = os.path.join(root_dir, img_name_ori)
img_pil = Image.open(img_name).convert('RGB')
w_ori,h_ori = img_pil.size
s_w, s_h = int(self.scale * w_ori), int(self.scale * h_ori)
assert s_w > 0 and s_h > 0, 'Scale needs to be positive'
img_pil = img_pil.resize((s_w, s_h),resample=0)
img = np.array(img_pil)
label_name = self.data.loc[idx, 'label']
label_name = os.path.join(root_dir, label_name)
label = np.load(label_name)
label_pil = Image.fromarray(label)
#use `resample=0` to avoid number larger than 31 (number of object classes)
label_pil = label_pil.resize((s_w, s_h), resample=0)
label = np.array(label_pil)
if self.crop:
h, w, _ = img.shape
top = random.randint(0, h - self.new_h)
left = random.randint(0, w - self.new_w)
img = img[top:top + self.new_h, left:left + self.new_w]
label = label[top:top + self.new_h, left:left + self.new_w]
#The fliplr() function is used to flip array in the left/right direction.
if random.random() < self.flip_rate:
img = np.fliplr(img)
label = np.fliplr(label)
# reduce mean
img = img[:, :, ::-1] # switch to BGR
img = np.transpose(img, (2, 0, 1)) / 255.
img[0] -= self.means[0]
img[1] -= self.means[1]
img[2] -= self.means[2]
# convert to tensor
img = torch.from_numpy(img.copy()).float()
img = img/255.0
label = torch.from_numpy(label.copy()).long()
sample = {'img': img, 'label': label, 'img_name':img_name_ori}
return sample
#every network class needs to inheritate nn.Module and has forward function
class DoubleConv(nn.Module):
def __init__(self,in_channels,out_channels, mid_channels=None):
super().__init__()
if not mid_channels:
mid_channels = out_channels
#about BatchNoram2d, https://pytorch.org/docs/stable/nn.html
#seems original paper didn't mention that
#About `inplace == true ` https://www.jianshu.com/p/8385aa74e2de
self.double_conv = nn.Sequential(
nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(mid_channels),
nn.ReLU(inplace=True),
nn.Conv2d(mid_channels, out_channels, kernel_size=3,padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
def forward(self,x):
return self.double_conv(x)
#`//` means devision and then floor
#Transpose is learning parameter while Up-sampling is no-learning parameters. Using Up-samling for faster inference or training because it does not require to update weight or compute gradient
class Up(nn.Module):
def __init__(self, in_channels, out_channels, bilinear=True):
super().__init__()
if bilinear:
self.up = nn.Upsample(scale_factor=2, mode='bilinear',align_corners=True)
self.conv = DoubleConv(in_channels,out_channels,in_channels // 2)
else:
self.up = nn.ConvTranspose2d(in_channels , in_channels // 2, kernel_size=2, stride=2)
self.conv = DoubleConv(in_channels, out_channels)
#x_f is the feedfoward network input, x_s is skipped connection layer
#1: upsample 2: padding so that two layer share the same size 3:connect two layer
def forward(self, x_f, x_s):
#first, upsample them
x_f = self.up(x_f)
#size()[0] is batch size, size()[1] is channel, size()[2] is height, [3] is width
#print(x_f.type(), x_s.type())
diff_y = x_s.size()[2] - x_f.size()[2]
diff_x = x_s.size()[3] - x_f.size()[3]
#make x_f and x_s the same size
x_f = F.pad(x_f, [diff_x//2, diff_x-diff_x//2,
diff_y//2, diff_y-diff_y//2])
#connect two layers
#print('shape of x_s and x_f ', x_s.shape, x_f.shape)
x = torch.cat([x_s,x_f], dim=1)
#print('in Up, the concatednated x size is ', x.shape)
return self.conv(x)
class Down(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.maxpool_conv = nn.Sequential(
nn.MaxPool2d(2),
DoubleConv(in_channels, out_channels)
)
def forward(self, x):
return self.maxpool_conv(x)
#output is 1x1 conv according tothe paper
class Out(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.out = nn.Conv2d(in_channels,out_channels,1)
def forward(self, x):
return self.out(x)
class UNet(nn.Module):
def __init__(self,n_channels, n_classes, bilinear=True):
super(UNet, self).__init__()
self.n_channels = n_channels
self.n_classes = n_classes
self.bilinear = bilinear
self.inp = DoubleConv(n_channels,64)
self.down1 = Down(64, 128)
self.down2 = Down(128,256)
self.down3 = Down(256,512)
factor = 2 if bilinear else 1
self.down4 = Down(512,1024//factor)
self.up1 = Up(1024,512//factor, bilinear)
self.up2 = Up(512,256//factor, bilinear)
self.up3 = Up(256,128//factor, bilinear)
self.up4 = Up(128,64)
self.outc = Out(64,n_classes)
def forward(self, x):
x0 = self.inp(x)
x1 = self.down1(x0)
x2 = self.down2(x1)
x3 = self.down3(x2)
x4 = self.down4(x3)
x = self.up1(x4,x3)
x = self.up2(x,x2)
x = self.up3(x,x1)
x = self.up4(x,x0)
return self.outc(x)
def parse_label():
# change label to class index
f = open(label_colors_file, "r").read().split("\n")[:-1] # ignore the last empty line
all_color = []
for idx, line in enumerate(f):
label = line.split()[-1]
color = tuple([int(x) for x in line.split()[:-1]])
all_color.append(color)
print(label, color, idx)
return all_color
if __name__ == '__main__':
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('use device ',device)
net = UNet(3,num_class)
net = net.float()
net = net.to(device=device)
batch_size = 1
val_data = ReadDataset(csv_file=val_file, phase='val')
val_data_loader = DataLoader(val_data, batch_size=batch_size, shuffle=True, num_workers=8, pin_memory=True)
Model_Path = './unet_model.pth'
net.load_state_dict(torch.load(Model_Path))
correct = 0
total = 0
all_color = parse_label()
img_show_time = 10
print('prediction_groundtruth comparison image will refresh after',img_show_time, 'seconds')
with torch.no_grad():
for data in val_data_loader:
img = data['img']
mask = data['label']
img_name = data['img_name']
img = img.to(device=device, dtype=torch.float32)
#print(img_name)
outputs = net(img.float())
outputs = outputs.data.cpu().numpy()
pred = outputs.transpose(0, 2, 3, 1).reshape(-1, num_class).argmax(axis=1).reshape(batch_size, h, w)
#print(pred[0].dtype)
#print(mask[0].dtype)
# f = plt.figure()
# f.add_subplot(1,2,1)
# plt.imshow(mask[0])
# f.add_subplot(1,2,2)
# plt.imshow(pred[0])
acc_counter = 0
for batch_num in range(batch_size):
for i in range(h):
for j in range(w):
if mask[batch_num][i][j] == pred[batch_num][i][j]:
acc_counter = acc_counter + 1
print('current image batch accuracy is ', acc_counter/(batch_size*total_pixel) * 100.0, '%')
img_np = np.zeros((h, w, 3), dtype=np.uint8)
for batch_num in range(batch_size):
for i in range(h):
for j in range(w):
color = all_color[pred[batch_num, i,j]]
img_np[i,j,0] = color[0]
img_np[i,j,1] = color[1]
img_np[i,j,2] = color[2]
oimg = Image.fromarray(img_np, 'RGB')
#original image
gt_img_path = os.path.join(root_dir, img_name[0])
gt_img = Image.open(gt_img_path)
#split_path[0] image folder name, split_path[1] image name
split_path = os.path.split(img_name[0])
#only got image name, split it with 'png'
split_path = split_path[1].split('.')
#in the labeled folder, image name has two more chars '_L'
split_path = split_path[0] + '_L.png'
gt_label_path = os.path.join(label_colors_img,split_path)
gt_label = Image.open(gt_label_path)
f = plt.figure()
f.add_subplot(1,3,1)
plt.imshow(oimg)
f.add_subplot(1,3,2)
plt.imshow(gt_img)
f.add_subplot(1,3,3)
plt.imshow(gt_label)
plt.pause(img_show_time)
plt.close()
|
python
|
"""
Define some reference aggregates based on *exact* site names
"""
import logging
import pandas as pd
from solarforecastarbiter import datamodel
from solarforecastarbiter.io import api
logger = logging.getLogger('reference_aggregates')
REF_AGGREGATES = [
{
'name': 'NOAA SURFRAD Average GHI',
'description': 'Average GHI across all SURFRAD sites',
'variable': 'ghi',
'aggregate_type': 'mean',
'interval_length': pd.Timedelta('1h'),
'interval_label': 'ending',
'timezone': 'Etc/GMT+6',
'observations': [
{
'site': 'NOAA SURFRAD Bondville IL',
'observation': 'Bondville IL ghi',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Table Mountain Boulder CO',
'observation': 'Table Mountain Boulder CO ghi',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Desert Rock NV',
'observation': 'Desert Rock NV ghi',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Fort Peck MT',
'observation': 'Fort Peck MT ghi',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Goodwin Creek MS',
'observation': 'Goodwin Creek MS ghi',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Penn State Univ PA',
'observation': 'Penn State Univ PA ghi',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Sioux Falls SD',
'observation': 'Sioux Falls SD ghi',
'from': '2017-01-01T00:00Z',
'until': None
},
]
}, {
'name': 'NOAA SURFRAD Average DNI',
'description': 'Average DNI across all SURFRAD sites',
'variable': 'dni',
'aggregate_type': 'mean',
'interval_length': pd.Timedelta('1h'),
'interval_label': 'ending',
'timezone': 'Etc/GMT+6',
'observations': [
{
'site': 'NOAA SURFRAD Bondville IL',
'observation': 'Bondville IL dni',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Table Mountain Boulder CO',
'observation': 'Table Mountain Boulder CO dni',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Desert Rock NV',
'observation': 'Desert Rock NV dni',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Fort Peck MT',
'observation': 'Fort Peck MT dni',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Goodwin Creek MS',
'observation': 'Goodwin Creek MS dni',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Penn State Univ PA',
'observation': 'Penn State Univ PA dni',
'from': '2017-01-01T00:00Z',
'until': None
},
{
'site': 'NOAA SURFRAD Sioux Falls SD',
'observation': 'Sioux Falls SD dni',
'from': '2017-01-01T00:00Z',
'until': None
},
]
}, {
'name': 'UO SRML Portland PV',
'description': 'Sum of a number of small PV systems in Portland, OR',
'variable': 'ac_power',
'aggregate_type': 'sum',
'interval_length': pd.Timedelta('1h'),
'interval_label': 'ending',
'timezone': 'Etc/GMT+8',
'observations': [
{
'site': 'UO SRML Portland OR PV 15 deg tilt',
'observation': 'Portland OR PV 15 deg tilt ac_power Unisolar',
'from': '2019-01-01T08:00Z',
'until': None,
},
{
'site': 'UO SRML Portland OR PV 30 deg tilt',
'observation': 'Portland OR PV 30 deg tilt ac_power Evergreen',
'from': '2019-01-01T08:00Z',
'until': None,
},
{
'site': 'UO SRML Portland OR PV 30 deg tilt',
'observation': 'Portland OR PV 30 deg tilt ac_power Photowatt',
'from': '2019-01-01T08:00Z',
'until': None,
},
{
'site': 'UO SRML Portland OR PV 30 deg tilt',
'observation': 'Portland OR PV 30 deg tilt ac_power Kaneka',
'from': '2019-01-01T08:00Z',
'until': None,
},
{
'site': 'UO SRML Portland OR PV 30 deg tilt',
'observation': 'Portland OR PV 30 deg tilt ac_power Sanyo',
'from': '2019-01-01T08:00Z',
'until': None,
},
]
}
]
def generate_aggregate(observations, agg_def):
"""Generate an aggregate object.
Parameters
----------
observations: list of datamodel.Observation
agg_def: dict
Text metadata to create a datamodel.Aggregate.
'observation' field names will be matched against names
of datamodel.Observation in ``observations``.
Returns
-------
datamodel.Aggregate
Raises
------
ValueError
If an observation does not exist in the API for an aggregate
or multiple observations match the given name and site name.
"""
agg_obs = []
limited_obs = list(filter(lambda x: x.variable == agg_def['variable'],
observations))
# go through each agg_dev.observations[*] and find the Observation
# from the API corresponding to the site name and observation name
# to make AggregateObservations and Aggregate
for obs in agg_def['observations']:
candidates = list(filter(
lambda x: x.name == obs['observation'] and
x.site.name == obs['site'],
limited_obs
))
if len(candidates) == 0:
raise ValueError(
f'No observations match site: {obs["site"]},'
f' name: {obs["observation"]}')
elif len(candidates) > 1:
raise ValueError(
f'Multiple observations match site: {obs["site"]},'
f' name: {obs["observation"]}'
)
else:
agg_obs.append(
datamodel.AggregateObservation(
observation=candidates[0],
effective_from=pd.Timestamp(obs['from']),
effective_until=(
None if obs.get('until') is None
else pd.Timestamp(obs['until'])),
observation_deleted_at=(
None if obs.get('deleted_at') is None
else pd.Timestamp(obs['deleted_at'])
)
)
)
agg_dict = agg_def.copy()
agg_dict['observations'] = tuple(agg_obs)
agg = datamodel.Aggregate(**agg_dict)
return agg
def make_reference_aggregates(token, provider, base_url,
aggregates=None):
"""Create the reference aggregates in the API.
Parameters
----------
token: str
Access token for the API
provider: str
Provider name to filter all API observations on
base_url: str
URL of the API to list objects and create aggregate at
aggregates: list or None
List of dicts that describes each aggregate. Defaults to
REF_AGGREGATES if None.
Raises
------
ValueError
If an observation does not exist in the API for an aggregate
or multiple observations match the given name and site name.
"""
session = api.APISession(token, base_url=base_url)
observations = list(filter(lambda x: x.provider == provider,
session.list_observations()))
existing_aggregates = {ag.name for ag in session.list_aggregates()}
if aggregates is None:
aggregates = REF_AGGREGATES
for agg_def in aggregates:
if agg_def['name'] in existing_aggregates:
logger.warning('Aggregate %s already exists', agg_def['name'])
# TODO: update the aggregate if the definition has changed
continue
logger.info('Creating aggregate %s', agg_def['name'])
agg = generate_aggregate(observations, agg_def)
# allow create to raise any API errors
session.create_aggregate(agg)
|
python
|
import sys
import unittest
import dask.array as da
import dask.distributed as dd
import numpy as np
import xarray as xr
# Import from directory structure if coverage test, or from installed
# packages otherwise
if "--cov" in str(sys.argv):
from src.geocat.comp import heat_index
else:
from geocat.comp import heat_index
class Test_heat_index(unittest.TestCase):
@classmethod
def setUpClass(cls):
# set up ground truths
cls.ncl_gt_1 = [
137.36142, 135.86795, 104.684456, 131.25621, 105.39449, 79.78999,
83.57511, 59.965, 30.
]
cls.ncl_gt_2 = [
68.585, 76.13114, 75.12854, 99.43573, 104.93261, 93.73293,
104.328705, 123.23398, 150.34001, 106.87023
]
cls.t1 = np.array([104, 100, 92, 92, 86, 80, 80, 60, 30])
cls.rh1 = np.array([55, 65, 60, 90, 90, 40, 75, 90, 50])
cls.t2 = np.array([70, 75, 80, 85, 90, 95, 100, 105, 110, 115])
cls.rh2 = np.array([10, 75, 15, 80, 65, 25, 30, 40, 50, 5])
# make client to reference in subsequent tests
cls.client = dd.Client()
def test_numpy_input(self):
assert np.allclose(heat_index(self.t1, self.rh1, False),
self.ncl_gt_1,
atol=0.005)
def test_multi_dimensional_input(self):
assert np.allclose(heat_index(self.t2.reshape(2, 5),
self.rh2.reshape(2, 5), True),
np.asarray(self.ncl_gt_2).reshape(2, 5),
atol=0.005)
def test_alt_coef(self):
assert np.allclose(heat_index(self.t2, self.rh2, True),
self.ncl_gt_2,
atol=0.005)
def test_float_input(self):
assert np.allclose(heat_index(80, 75), 83.5751, atol=0.005)
def test_list_input(self):
assert np.allclose(heat_index(self.t1.tolist(), self.rh1.tolist()),
self.ncl_gt_1,
atol=0.005)
def test_xarray_input(self):
t = xr.DataArray(self.t1)
rh = xr.DataArray(self.rh1)
assert np.allclose(heat_index(t, rh), self.ncl_gt_1, atol=0.005)
def test_alternate_xarray_tag(self):
t = xr.DataArray([15, 20])
rh = xr.DataArray([15, 20])
out = heat_index(t, rh)
assert out.tag == "NCL: heat_index_nws; (Steadman+t)*0.5"
def test_rh_warning(self):
self.assertWarns(UserWarning, heat_index, [50, 80, 90], [0.1, 0.2, 0.5])
def test_rh_valid(self):
self.assertRaises(ValueError, heat_index, [50, 80, 90], [-1, 101, 50])
def test_dask_unchunked_input(self):
t = da.from_array(self.t1)
rh = da.from_array(self.rh1)
out = self.client.submit(heat_index, t, rh).result()
assert np.allclose(out, self.ncl_gt_1, atol=0.005)
def test_dask_chunked_input(self):
t = da.from_array(self.t1, chunks='auto')
rh = da.from_array(self.rh1, chunks='auto')
out = self.client.submit(heat_index, t, rh).result()
assert np.allclose(out, self.ncl_gt_1, atol=0.005)
|
python
|
# INPUT
N = int(input())
A = [int(input()) for _ in range(N)]
# PROCESSES
"""
Critical observation:
To reach a value $V$, we must have come from a value SMALLER than $V$ AND that is before it.
Assuming that ALL values before $V$ have an optimal solution, we can find the optimal solution for $V$.
Define the DP table as `dp[i]`, where `i` is the index of the element. The value of `dp[i]` represents the length of
the longest rising subsequence that ENDS at index `i`.
The base case is `dp[0] = 1` because if we end at index 0, the optimal solution is to take the first element.
The transition is as follows:
dp[i] = (Maximum of `dp[j]` for all `j < i` and where `array[j] < array[i]`) + 1
As stated above, we must have come from an element that is SMALLER than the current element, hence the condition of
`array[j] < array[i]`. We find the maximum of all `dp[j]` (i.e. longest rising length) in order to find the maximum
for this current element. We add 1 to the maximum as we are including the current element.
"""
dp = [None] * N # Make a list with `N` spaces so that we can store all of the states
dp[0] = 1 # The base case
for i in range(1, N): # We don't have to process the case where `i = 0` because that's the base case
curr_max = 1 # Set to 1 initially, representing the case where we JUST take this element itself
for j in range(i): # Up to but not including i
# Check if the current element is bigger than this element
if A[i] > A[j]:
# Get the DP solution for that element
possible_sol = dp[j] + 1 # Remember to add 1 for the current element!
# Update maximum as necessary
if possible_sol > curr_max:
curr_max = possible_sol
# Update DP table
dp[i] = curr_max
# Now we have computed all longest maximal rising subsequece lengths that end at every index, we find the longest such
# subsequence by using the `max` function
answer = max(dp)
# OUTPUT
print(answer)
|
python
|
""" Simple mutually-recursive coroutines with asyncio. Using asyncio.ensure_future
instead of yield from allows the coroutine to exit and merely schedules the next
call with the event loop, allowing infinite mutual recursion. """
import asyncio
@asyncio.coroutine
def a(n):
print("A: {}".format(n))
asyncio.async(b(n+1)) # asyncio.ensure_future in Python 3.4.4
@asyncio.coroutine
def b(n):
print("B: {}".format(n))
asyncio.async(a(n+1)) # asyncio.ensure_future in Python 3.4.4
loop = asyncio.get_event_loop()
asyncio.async(a(0))
loop.run_forever()
loop.close()
|
python
|
from __future__ import unicode_literals
from collections import OrderedDict
from django import forms
from django.forms.widgets import Textarea
from django.utils.translation import ugettext_lazy as _
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
mark_safe_lazy = lazy(mark_safe, str)
from apps.forms.fields import DateWidget, DSRadioSelect, DSStackedRadioSelect
from apps.forms.forms import (
YESNO_CHOICES,
to_bool,
BaseStageForm,
SplitStageForm)
from .fields import ERROR_MESSAGES
from .validators import (
is_date_in_past,
is_date_in_future,
is_date_in_last_28_days,
is_date_in_next_6_months,
is_urn_valid,
is_urn_welsh,
is_valid_contact_number)
def reorder_fields(fields, order):
"""Convert dict to OrderedDictionary, sorted and filtered by order"""
for key, v in fields.copy().items():
if key not in order:
del fields[key]
return OrderedDict(sorted(fields.items(), key=lambda k: order.index(k[0])))
class URNEntryForm(BaseStageForm):
"""URN entry form"""
urn = forms.CharField(
widget=forms.TextInput(attrs={"class": "form-control"}),
label=_("What is your Unique Reference Number (URN)?"),
required=True,
validators=[is_urn_valid, is_urn_welsh],
help_text=_("On page 1 of the notice, usually at the top."),
error_messages={
"required": ERROR_MESSAGES["URN_REQUIRED"],
"is_urn_valid": ERROR_MESSAGES["URN_INVALID"],
"is_urn_not_used": ERROR_MESSAGES['URN_ALREADY_USED'],
"is_urn_welsh": ERROR_MESSAGES['URN_NOT_WELSH']})
class AuthForm(BaseStageForm):
"""Auth form"""
def __init__(self, *args, **kwargs):
self.auth_field = kwargs.pop("auth_field", "DOB")
super(AuthForm, self).__init__(*args, **kwargs)
if self.auth_field == "DOB":
del self.fields["postcode"]
elif self.auth_field == "PostCode":
del self.fields["date_of_birth"]
number_of_charges = forms.IntegerField(
label=_("Number of offences"),
help_text=_("How many offences are listed on your notice?"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"maxlength": "2",
"class": "form-control-inline",
"size": "2"}),
min_value=1, max_value=10,
error_messages={
"required": ERROR_MESSAGES["NUMBER_OF_CHARGES_REQUIRED"]})
postcode = forms.CharField(
widget=forms.TextInput(attrs={"class": "form-control"}),
label=_("Postcode"),
required=True,
help_text=_("As written on the notice we sent you"),
error_messages={
"required": ERROR_MESSAGES["POSTCODE_REQUIRED"]})
date_of_birth = forms.DateField(
widget=DateWidget,
required=True,
validators=[is_date_in_past],
label=_("Date of birth"),
help_text=mark_safe_lazy(_("For example, 27 03 2007 <br />DD MM YY")),
error_messages={
"required": ERROR_MESSAGES["DATE_OF_BIRTH_REQUIRED"],
"invalid": ERROR_MESSAGES["DATE_OF_BIRTH_INVALID"],
"is_date_in_past": ERROR_MESSAGES["DATE_OF_BIRTH_IN_FUTURE"]})
class NoticeTypeForm(BaseStageForm):
"""Notice type form"""
SJP_CHOICES = ((True, _("Single Justice Procedure Notice")),
(False, _("Something else")))
sjp = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
coerce=to_bool,
choices=SJP_CHOICES,
label=_("What is the title at the very top of the page?"),
error_messages={
"required": ERROR_MESSAGES["NOTICE_TYPE_REQUIRED"]})
class BaseCaseForm(BaseStageForm):
"""Base case form"""
PLEA_MADE_BY_CHOICES = (
("Defendant", _("The person named in the notice")),
("Company representative", _("Pleading on behalf of a company")))
number_of_charges = forms.IntegerField(
label=_("Number of offences"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"maxlength": "2",
"class": "form-control-inline",
"size": "2"}),
help_text=_("How many offences are listed on your notice?"),
min_value=1,
max_value=10,
error_messages={
"required": ERROR_MESSAGES["NUMBER_OF_CHARGES_REQUIRED"]})
plea_made_by = forms.TypedChoiceField(
required=True,
widget=DSRadioSelect,
choices=PLEA_MADE_BY_CHOICES,
label=_("Are you? (plea made by)"),
help_text=_("Choose one of the following options:"),
error_messages={"required": ERROR_MESSAGES["PLEA_MADE_BY_REQUIRED"]})
class CaseForm(BaseCaseForm):
"""Case form"""
date_of_hearing = forms.DateField(
widget=DateWidget,
validators=[is_date_in_future, is_date_in_next_6_months],
required=True,
label=_("Court hearing date"),
help_text=_(
"On page 1 of the notice, near the top. <br>For example, 30/07/2014"),
error_messages={
"required": ERROR_MESSAGES["HEARING_DATE_REQUIRED"],
"invalid": ERROR_MESSAGES["HEARING_DATE_INVALID"],
"is_date_in_future": ERROR_MESSAGES["HEARING_DATE_PASSED"],
"is_date_in_next_6_months": ERROR_MESSAGES["HEARING_DATE_INCORRECT"]})
def __init__(self, *args, **kwargs):
super(CaseForm, self).__init__(*args, **kwargs)
fields_order = ["urn", "date_of_hearing", "number_of_charges", "plea_made_by"]
self.fields = reorder_fields(self.fields, fields_order)
class SJPCaseForm(BaseCaseForm):
"""SJP case form"""
posting_date = forms.DateField(
widget=DateWidget,
validators=[is_date_in_past, is_date_in_last_28_days],
required=True,
label=_("Posting date"),
help_text=_(
"On page 1 of the notice, near the top. <br>For example, 30/07/2014"),
error_messages={
"required": ERROR_MESSAGES["POSTING_DATE_REQUIRED"],
"invalid": ERROR_MESSAGES["POSTING_DATE_INVALID"],
"is_date_in_past": ERROR_MESSAGES["POSTING_DATE_IN_FUTURE"],
"is_date_in_last_28_days": ERROR_MESSAGES["POSTING_DATE_INCORRECT"]})
def __init__(self, *args, **kwargs):
super(SJPCaseForm, self).__init__(*args, **kwargs)
fields_order = ["urn", "posting_date", "number_of_charges", "plea_made_by"]
self.fields = reorder_fields(self.fields, fields_order)
class YourDetailsForm(BaseStageForm):
"""Your details form"""
dependencies = {
"updated_address": {
"field": "correct_address",
"value": "False"
},
"no_ni_number_reason": {
"field": "have_ni_number",
"value": "False"
},
"ni_number": {
"field": "have_ni_number",
"value": "True"
},
"driving_licence_number": {
"field": "have_driving_licence_number",
"value": "True"
}
}
first_name = forms.CharField(
widget=forms.TextInput(attrs={
"class": "form-control"}),
max_length=100,
required=True,
label=_("First name"),
error_messages={
"required": ERROR_MESSAGES["FIRST_NAME_REQUIRED"]})
middle_name = forms.CharField(
widget=forms.TextInput(attrs={
"class": "form-control"}),
max_length=100,
required=False,
label=_("Middle name"))
last_name = forms.CharField(
widget=forms.TextInput(attrs={
"class": "form-control"}),
max_length=100,
required=True,
label=_("Last name"),
error_messages={
"required": ERROR_MESSAGES["LAST_NAME_REQUIRED"]})
correct_address = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
coerce=to_bool,
choices=YESNO_CHOICES["Ydy/Nac ydy"],
label=_(
"Is your address correct on page 1 of the notice we sent to you?"),
error_messages={
"required": ERROR_MESSAGES["CORRECT_ADDRESS_REQUIRED"]})
updated_address = forms.CharField(
widget=forms.Textarea(attrs={
"rows": "4",
"class": "form-control"}),
required=False,
label="",
help_text=_("If no, tell us your correct address here:"),
error_messages={
"required": ERROR_MESSAGES["UPDATED_ADDRESS_REQUIRED"]})
contact_number = forms.CharField(
widget=forms.TextInput(attrs={"type": "tel", "class": "form-control"}),
required=True,
max_length=30,
validators=[is_valid_contact_number],
label=_("Contact number"),
help_text=_("Landline or mobile number."),
error_messages={
"required": ERROR_MESSAGES["CONTACT_NUMBER_REQUIRED"],
"invalid": ERROR_MESSAGES["CONTACT_NUMBER_INVALID"]})
date_of_birth = forms.DateField(
widget=DateWidget,
required=True,
validators=[is_date_in_past],
label=_("Date of birth"),
error_messages={
"required": ERROR_MESSAGES["DATE_OF_BIRTH_REQUIRED"],
"invalid": ERROR_MESSAGES["DATE_OF_BIRTH_INVALID"],
"is_date_in_past": ERROR_MESSAGES["DATE_OF_BIRTH_IN_FUTURE"]})
email = forms.EmailField(
widget=forms.TextInput(attrs={
"type": "email",
"class": "form-control"}),
required=True,
label=_("Email address"),
help_text=_(
"We'll automatically email you a copy of your plea"),
error_messages={
"required": ERROR_MESSAGES["UPDATES_EMAIL_REQUIRED"],
"invalid": ERROR_MESSAGES["EMAIL_ADDRESS_INVALID"]})
have_ni_number = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
coerce=to_bool,
choices=YESNO_CHOICES["Oes/Nac oes"],
label=_("Do you have a National Insurance number?"),
help_text=mark_safe_lazy(_(
"It's on your National Insurance card, benefit letter, payslip or P60 - for example, 'QQ 12 34 56 C'. "
"<a href='https://www.gov.uk/lost-national-insurance-number' target='_blank'>Find a lost "
"national insurance number</a>"
)),
error_messages={
"required": ERROR_MESSAGES["HAVE_NI_NUMBER_REQUIRED"]})
ni_number = forms.CharField(
widget=forms.TextInput(attrs={"class": "form-control"}),
required=True,
label="",
help_text=_(
"If yes, enter it here."),
error_messages={
"required": ERROR_MESSAGES["NI_NUMBER_REQUIRED"]})
no_ni_number_reason = forms.CharField(
widget=forms.Textarea(attrs={
"rows": "4",
"class": "form-control"}),
required=False,
label="",
help_text=_(
"If no, please provide a valid reason"),
error_messages={
"required": ERROR_MESSAGES["NI_NUMBER_REASON"]}
)
have_driving_licence_number = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
coerce=to_bool,
choices=YESNO_CHOICES["Oes/Nac oes"],
label=_("Do you have a UK driving licence?"),
help_text=mark_safe_lazy(_(
"Entering your UK driving licence number means you don't have "
"to send your licence to the court. "
"<a href='https://www.viewdrivingrecord.service.gov.uk/driving-record/personal-details' target='_blank'>"
"View your driving licence information</a>")),
error_messages={
"required": ERROR_MESSAGES["HAVE_DRIVING_LICENCE_NUMBER_REQUIRED"]})
driving_licence_number = forms.CharField(
widget=forms.TextInput(
attrs={"class": "form-control"}),
required=True,
label="",
help_text=_(
"If yes, enter it here. Your driving licence number is in "
"section 5 of your driving licence photocard."),
error_messages={
"required": ERROR_MESSAGES["DRIVING_LICENCE_NUMBER_REQUIRED"]})
def __init__(self, *args, **kwargs):
exclude_dob = kwargs.pop("exclude_dob", False)
super(YourDetailsForm, self).__init__(*args, **kwargs)
if exclude_dob:
del self.fields["date_of_birth"]
class CompanyDetailsForm(BaseStageForm):
"""Company details form"""
dependencies = {
"updated_address": {
"field": "correct_address",
"value": "False"
}
}
COMPANY_POSITION_CHOICES = (
("Director", _("director")),
("Company secretary", _("company secretary")),
("Company solicitor", _("company solicitor")))
company_name = forms.CharField(
label=_("Company name"),
widget=forms.TextInput(attrs={
"class": "form-control"}),
max_length=100,
required=True,
help_text=_("As written on page 1 of the notice we sent you."),
error_messages={
"required": ERROR_MESSAGES["COMPANY_NAME_REQUIRED"]})
correct_address = forms.TypedChoiceField(
widget=DSRadioSelect,
coerce=to_bool,
choices=YESNO_CHOICES["Ydy/Nac ydy"],
required=True,
label=_(
"Is the company's address correct on page 1 of the notice we "
"sent to you?"),
error_messages={
"required": ERROR_MESSAGES["COMPANY_CORRECT_ADDRESS_REQUIRED"]})
updated_address = forms.CharField(
widget=forms.Textarea(attrs={
"rows": "4",
"class": "form-control"}),
label="",
required=False,
help_text=_("If no, tell us the correct company address here:"),
error_messages={"required": ERROR_MESSAGES["COMPANY_UPDATED_ADDRESS_REQUIRED"]})
first_name = forms.CharField(
label=_("Your first name"),
widget=forms.TextInput(attrs={
"class": "form-control"}),
required=True,
error_messages={
"required": ERROR_MESSAGES["FIRST_NAME_REQUIRED"]})
last_name = forms.CharField(
label=_("Your last name"),
widget=forms.TextInput(attrs={
"class": "form-control"}),
required=True,
error_messages={
"required": ERROR_MESSAGES["LAST_NAME_REQUIRED"]})
position_in_company = forms.ChoiceField(
label=_("Your position in the company"),
choices=COMPANY_POSITION_CHOICES,
widget=DSRadioSelect,
required=True,
error_messages={
"required": ERROR_MESSAGES["POSITION_REQUIRED"]})
contact_number = forms.CharField(
label=_("Contact number"),
widget=forms.TextInput(attrs={
"type": "tel",
"class": "form-control"}),
max_length=30,
validators=[is_valid_contact_number],
required=True,
help_text=_("Office or mobile number."),
error_messages={
"required": ERROR_MESSAGES["COMPANY_CONTACT_NUMBER_REQUIRED"],
"invalid": ERROR_MESSAGES["CONTACT_NUMBER_INVALID"]})
email = forms.EmailField(
widget=forms.TextInput(attrs={
"type": "email",
"class": "form-control"}),
required=True,
label=_("Work email address"),
help_text=_(
"We'll automatically email you a copy of your plea"),
error_messages={
"required": ERROR_MESSAGES["UPDATES_EMAIL_REQUIRED"],
"invalid": ERROR_MESSAGES["EMAIL_ADDRESS_INVALID"]})
class YourStatusForm(BaseStageForm):
"""Your status form"""
YOU_ARE_CHOICES = (
("Employed", _("Employed")),
("Employed and also receiving benefits", _("Employed and also receiving benefits")),
("Self-employed", _("Self-employed")),
("Self-employed and also receiving benefits", _("Self-employed and also receiving benefits")),
("Receiving out of work benefits", _("Receiving out of work benefits")),
("Other", _("Other")))
you_are = forms.ChoiceField(
label=_("Are you? (employment status)"),
choices=YOU_ARE_CHOICES,
widget=DSRadioSelect,
error_messages={
"required": ERROR_MESSAGES["EMPLOYMENT_STATUS_REQUIRED"]})
class YourEmploymentForm(BaseStageForm):
"""Your employmet form"""
PERIOD_CHOICES = (
("Weekly", _("Weekly")),
("Fortnightly", _("Fortnightly")),
("Monthly", _("Monthly")),)
pay_period = forms.ChoiceField(
widget=DSRadioSelect,
choices=PERIOD_CHOICES,
label=_("How often do you get paid from your employer?"),
error_messages={
"required": ERROR_MESSAGES["PAY_PERIOD_REQUIRED"]})
pay_amount = forms.DecimalField(
label=_("What is your take home pay (after tax)?"),
localize=True,
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["PAY_AMOUNT_REQUIRED"]})
class YourSelfEmploymentForm(BaseStageForm):
"""Your self employment form"""
PERIOD_CHOICES = (
("Weekly", _("Weekly")),
("Fortnightly", _("Fortnightly")),
("Monthly", _("Monthly")),
("Other", _("Other")),)
pay_period = forms.ChoiceField(
widget=DSRadioSelect,
choices=PERIOD_CHOICES,
label=_("How often do you get paid?"),
error_messages={
"required": ERROR_MESSAGES["PAY_PERIOD_REQUIRED"]})
pay_amount = forms.DecimalField(
label=_("What is your take home pay (after tax)?"),
localize=True,
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["PAY_AMOUNT_REQUIRED"]})
class YourOutOfWorkBenefitsForm(BaseStageForm):
"""Your out of work benefit form"""
BENEFIT_TYPE_CHOICES = (
("Contributory Jobseeker's Allowance", _("Contributory Jobseeker's Allowance")),
("Income-based Jobseekers Allowance", _("Income-based Jobseekers Allowance")),
("Universal Credit", _("Universal Credit")),
("Other", _("Other")))
PERIOD_CHOICES = (
("Weekly", _("Weekly")),
("Fortnightly", _("Fortnightly")),
("Monthly", _("Monthly")),
("Other", _("Other")),)
benefit_type = forms.ChoiceField(
widget=DSRadioSelect,
choices=BENEFIT_TYPE_CHOICES,
label=_("Which out of work benefit do you receive?"),
error_messages={
"required": ERROR_MESSAGES["BENEFIT_TYPE_REQUIRED"]})
pay_period = forms.ChoiceField(
widget=DSRadioSelect,
choices=PERIOD_CHOICES,
label=_("How often is your benefit paid?"),
error_messages={
"required": ERROR_MESSAGES["BENEFIT_PAY_PERIOD_REQUIRED"]})
pay_amount = forms.DecimalField(
label=_("How much is your benefit payment?"),
localize=True,
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["BENEFIT_PAY_AMOUNT_REQUIRED"]})
class AboutYourIncomeForm(BaseStageForm):
"""About your income form"""
PERIOD_CHOICES = (
("Weekly", _("Weekly")),
("Fortnightly", _("Fortnightly")),
("Monthly", _("Monthly")),
("Other", _("Other")),)
income_source = forms.CharField(
label=_("What is the source of your main income?"),
help_text=_("For example, student loan, pension or investments."),
widget=forms.TextInput(attrs={
"class": "form-control"}),
error_messages={
"required": ERROR_MESSAGES["INCOME_SOURCE_REQUIRED"]})
pay_period = forms.ChoiceField(
widget=DSRadioSelect,
choices=PERIOD_CHOICES,
label=_("How often is your main income paid?"),
error_messages={
"required": ERROR_MESSAGES["INCOME_PAY_PERIOD_REQUIRED"]})
pay_amount = forms.DecimalField(
label=_("How much is your take home income (after tax)?"),
localize=True,
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["PAY_AMOUNT_REQUIRED"]})
pension_credit = forms.TypedChoiceField(
label=_("Do you receive Pension Credit?"),
widget=DSRadioSelect,
choices=YESNO_CHOICES["Ydw/Nac ydw"],
coerce=to_bool,
error_messages={
"required": ERROR_MESSAGES["PENSION_CREDIT_REQUIRED"]})
class YourBenefitsForm(BaseStageForm):
"""Your benefits form"""
BENEFIT_TYPE_CHOICES = (
(
"Contributory Employment and Support Allowance",
_("Contributory Employment and Support Allowance")),
(
"Income-related Employment and Support Allowance",
_("Income-related Employment and Support Allowance")),
(
"Income Support",
_("Income Support")),
(
"Universal Credit",
_("Universal Credit")),
(
"Other",
_("Other")))
PERIOD_CHOICES = (
("Weekly", _("Weekly")),
("Fortnightly", _("Fortnightly")),
("Monthly", _("Monthly")))
benefit_type = forms.ChoiceField(
label=_("Which benefit do you receive?"),
widget=DSRadioSelect,
choices=BENEFIT_TYPE_CHOICES,
error_messages={
"required": ERROR_MESSAGES["BENEFITS_TYPE_REQUIRED"]})
pay_period = forms.ChoiceField(
label=_("How often is your benefit paid?"),
widget=DSRadioSelect,
choices=PERIOD_CHOICES,
error_messages={
"required": ERROR_MESSAGES["BENEFIT_PAY_PERIOD_REQUIRED"]})
pay_amount = forms.DecimalField(
label=_("How much is your benefit payment?"),
localize=True,
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["BENEFIT_PAY_AMOUNT_REQUIRED"]})
class YourPensionCreditForm(BaseStageForm):
"""Your pension credit form"""
PERIOD_CHOICES = (
("Weekly", _("Weekly")),
("Fortnightly", _("Fortnightly")),
("Monthly", _("Monthly")))
pay_period = forms.ChoiceField(
label=_("How often is your Pension Credit paid?"),
widget=DSRadioSelect,
choices=PERIOD_CHOICES,
error_messages={
"required": ERROR_MESSAGES["PENSION_CREDIT_PERIOD_REQUIRED"]})
pay_amount = forms.DecimalField(
label=_("How much is your Pension Credit payment?"),
localize=True,
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["PENSION_CREDIT_AMOUNT_REQUIRED"]})
class YourIncomeForm(BaseStageForm):
"""Your income form"""
hardship = forms.TypedChoiceField(
label=_("Would paying a fine cause you financial problems?"),
widget=DSRadioSelect,
choices=YESNO_CHOICES["Byddai/Na fyddai"],
coerce=to_bool,
error_messages={
"required": ERROR_MESSAGES["HARDSHIP_REQUIRED"]})
class HardshipForm(BaseStageForm):
"""Hardship form"""
hardship_details = forms.CharField(
label=_("How would paying a fine cause you financial problems?"),
help_text=_("Why you think the court should allow you to pay your fine in instalments:"),
widget=forms.Textarea(attrs={
"cols": 45,
"rows": 5,
"class": "form-control"}),
required=True,
error_messages={
"required": ERROR_MESSAGES["HARDSHIP_DETAILS_REQUIRED"]})
class HouseholdExpensesForm(BaseStageForm):
"""Household expenses form"""
household_accommodation = forms.DecimalField(
min_value=0,
decimal_places=2,
localize=True,
required=False,
label=_("Accommodation"),
help_text=_("Rent, mortgage or lodgings"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["HOUSEHOLD_ACCOMMODATION_REQUIRED"],
"invalid": ERROR_MESSAGES["HOUSEHOLD_ACCOMMODATION_INVALID"],
"min_value": ERROR_MESSAGES["HOUSEHOLD_ACCOMMODATION_MIN"]})
household_utility_bills = forms.DecimalField(
min_value=0,
decimal_places=2,
localize=True,
required=False,
label=_("Utility bills"),
help_text=_("Gas, water, electricity etc"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["HOUSEHOLD_UTILITY_BILLS_REQUIRED"],
"invalid": ERROR_MESSAGES["HOUSEHOLD_UTILITY_BILLS_INVALID"],
"min_value": ERROR_MESSAGES["HOUSEHOLD_UTILITY_BILLS_MIN"]})
household_insurance = forms.DecimalField(
min_value=0,
decimal_places=2,
localize=True,
required=False,
label=_("Insurance"),
help_text=_("Home, life insurance etc"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["HOUSEHOLD_INSURANCE_REQUIRED"],
"invalid": ERROR_MESSAGES["HOUSEHOLD_INSURANCE_INVALID"],
"min_value": ERROR_MESSAGES["HOUSEHOLD_INSURANCE_MIN"]})
household_council_tax = forms.DecimalField(
min_value=0,
decimal_places=2,
localize=True,
required=False,
label=_("Council tax"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["HOUSEHOLD_COUNCIL_TAX_REQUIRED"],
"invalid": ERROR_MESSAGES["HOUSEHOLD_COUNCIL_TAX_INVALID"],
"min_value": ERROR_MESSAGES["HOUSEHOLD_COUNCIL_TAX_MIN"]})
other_bill_payers = forms.TypedChoiceField(
widget=DSRadioSelect,
label=_("Does anyone else contribute to these bills?"),
choices=YESNO_CHOICES["Oes/Nac oes"],
coerce=to_bool,
error_messages={
"required": ERROR_MESSAGES["OTHER_BILL_PAYERS_REQUIRED"]})
class OtherExpensesForm(BaseStageForm):
"""Other expenses form"""
dependencies = {
"other_not_listed_details": {
"field": "other_not_listed",
"value": "True"
},
"other_not_listed_amount": {
"field": "other_not_listed",
"value": "True"
}
}
other_tv_subscription = forms.DecimalField(
min_value=0,
decimal_places=2,
localize=True,
required=False,
label=_("Television subscription"),
help_text=_("TV licence, satellite etc"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["OTHER_TV_SUBSCRIPTION_REQUIRED"],
"invalid": ERROR_MESSAGES["OTHER_TV_SUBSCRIPTION_INVALID"],
"min_value": ERROR_MESSAGES["OTHER_TV_SUBSCRIPTION_MIN"]})
other_travel_expenses = forms.DecimalField(
min_value=0,
decimal_places=2,
localize=True,
required=False,
label=_("Travel expenses"),
help_text=_("Fuel, car, public transport etc"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["OTHER_TRAVEL_EXPENSES_REQUIRED"],
"invalid": ERROR_MESSAGES["OTHER_TRAVEL_EXPENSES_INVALID"],
"min_value": ERROR_MESSAGES["OTHER_TRAVEL_EXPENSES_MIN"]})
other_telephone = forms.DecimalField(
min_value=0,
decimal_places=2,
localize=True,
required=False,
label=_("Telephone"),
help_text=_("Landline and/or mobile"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["OTHER_TELEPHONE_REQUIRED"],
"invalid": ERROR_MESSAGES["OTHER_TELEPHONE_INVALID"],
"min_value": ERROR_MESSAGES["OTHER_TELEPHONE_MIN"]})
other_loan_repayments = forms.DecimalField(
min_value=0,
decimal_places=2,
localize=True,
required=False,
label=_("Loan repayments"),
help_text=_("Credit card, bank etc"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["OTHER_LOAN_REPAYMENTS_REQUIRED"],
"invalid": ERROR_MESSAGES["OTHER_LOAN_REPAYMENTS_INVALID"],
"min_value": ERROR_MESSAGES["OTHER_LOAN_REPAYMENTS_MIN"]})
other_court_payments = forms.DecimalField(
min_value=0,
decimal_places=2,
localize=True,
required=False,
label=_("County court orders"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["OTHER_COURT_PAYMENTS_REQUIRED"],
"invalid": ERROR_MESSAGES["OTHER_COURT_PAYMENTS_INVALID"],
"min_value": ERROR_MESSAGES["OTHER_COURT_PAYMENTS_MIN"]})
other_child_maintenance = forms.DecimalField(
min_value=0,
decimal_places=2,
localize=True,
required=False,
label=_("Child maintenance"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["OTHER_CHILD_MAINTENANCE_REQUIRED"],
"invalid": ERROR_MESSAGES["OTHER_CHILD_MAINTENANCE_INVALID"],
"min_value": ERROR_MESSAGES["OTHER_CHILD_MAINTENANCE_MIN"]})
other_not_listed = forms.TypedChoiceField(
widget=DSRadioSelect,
choices=YESNO_CHOICES["Oes/Nac oes"],
coerce=to_bool,
label=_("Any other expenses that are not listed above?"),
help_text=_(
"Other significant expenses you think the court should know about. "
"For example, childcare"),
error_messages={
"required": ERROR_MESSAGES["OTHER_NOT_LISTED_REQUIRED"]})
other_not_listed_details = forms.CharField(
label="",
help_text=_("If yes, tell us here"),
widget=forms.Textarea(attrs={
"cols": 45,
"rows": 4,
"class": "form-control"}),
required=True,
error_messages={
"required": ERROR_MESSAGES["OTHER_NOT_LISTED_DETAILS_REQUIRED"]})
other_not_listed_amount = forms.DecimalField(
min_value=0,
decimal_places=2,
localize=True,
required=False,
label=_("Monthly total of your other significant expenses"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"class": "form-control-inline"}),
error_messages={
"required": ERROR_MESSAGES["OTHER_NOT_LISTED_AMOUNT_REQUIRED"],
"invalid": ERROR_MESSAGES["OTHER_NOT_LISTED_AMOUNT_INVALID"],
"min_value": ERROR_MESSAGES["OTHER_NOT_LISTED_AMOUNT_MIN"]})
class CompanyFinancesForm(SplitStageForm):
"""Company finances form"""
dependencies = {
"number_of_employees": {
"field": "trading_period"
},
"gross_turnover": {
"field": "trading_period"
},
"net_turnover": {
"field": "trading_period"
}
}
split_form_options = {
"trigger": "trading_period",
"nojs_only": True
}
trading_period = forms.TypedChoiceField(
required=True,
widget=DSRadioSelect,
choices=YESNO_CHOICES["Ydy/Nac ydy"],
coerce=to_bool,
label=_("Has the company been trading for more than 12 months?"),
error_messages={
"required": ERROR_MESSAGES["COMPANY_TRADING_PERIOD"]})
number_of_employees = forms.IntegerField(
label=_("Number of employees"),
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"maxlength": "5",
"class": "form-control-inline"}),
min_value=1,
max_value=10000,
localize=True,
error_messages={
"required": ERROR_MESSAGES["COMPANY_NUMBER_EMPLOYEES"]})
gross_turnover = forms.DecimalField(
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"maxlength": "10",
"class": "form-control-inline"}),
max_digits=10,
decimal_places=2,
localize=True,
label=_("Gross turnover"),
help_text=_("For example, 150000"),
error_messages={
"required": ERROR_MESSAGES["COMPANY_GROSS_TURNOVER"]})
net_turnover = forms.DecimalField(
widget=forms.TextInput(attrs={
"pattern": "[0-9]*",
"maxlength": "10",
"class": "form-control-inline"}),
label=_("Net turnover"),
help_text=_("For example, 110000"),
max_digits=10,
decimal_places=2,
localize=True,
error_messages={
"required": ERROR_MESSAGES["COMPANY_NET_TURNOVER"]})
def __init__(self, *args, **kwargs):
super(CompanyFinancesForm, self).__init__(*args, **kwargs)
if self.data.get("trading_period") == "False":
self.fields["gross_turnover"].error_messages.update({
"required": ERROR_MESSAGES["COMPANY_GROSS_TURNOVER_PROJECTED"]})
self.fields["net_turnover"].error_messages.update({
"required": ERROR_MESSAGES["COMPANY_NET_TURNOVER_PROJECTED"]})
else:
self.fields["gross_turnover"].error_messages.update({
"required": ERROR_MESSAGES["COMPANY_GROSS_TURNOVER"]})
self.fields["net_turnover"].error_messages.update({
"required": ERROR_MESSAGES["COMPANY_NET_TURNOVER"]})
class ConfirmationForm(BaseStageForm):
"""Confirmation stage form"""
understand = forms.BooleanField(
required=True,
error_messages={
"required": ERROR_MESSAGES["UNDERSTAND_REQUIRED"]})
class BasePleaForm(SplitStageForm):
"""Base form for pleas"""
split_form_options = {
"trigger": "guilty",
"nojs_only": True
}
guilty_extra = forms.CharField(
label=_("Mitigation"),
widget=Textarea(attrs={
"class": "form-control",
"rows": "4"}),
help_text=_("Is there something you would like the court to consider?"),
required=False,
max_length=5000)
not_guilty_extra = forms.CharField(
label=_("Not guilty because?"),
widget=Textarea(attrs={
"class": "form-control",
"rows": "4"}),
help_text=_("Why do you believe you are not guilty?"),
max_length=5000,
error_messages={
"required": ERROR_MESSAGES["NOT_GUILTY_REQUIRED"]})
interpreter_needed = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
choices=YESNO_CHOICES["Oes/Nac oes"],
coerce=to_bool,
label=_("Do you need an interpreter in court?"),
error_messages={
"required": ERROR_MESSAGES["INTERPRETER_NEEDED_REQUIRED"]})
interpreter_language = forms.CharField(
widget=forms.TextInput(attrs={
"class": "form-control"}),
max_length=100,
required=True,
label="",
help_text=_("If yes, tell us which language (include sign language):"),
error_messages={
"required": ERROR_MESSAGES["INTERPRETER_LANGUAGE_REQUIRED"]})
interpreter_needed_guilty_court = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
choices=YESNO_CHOICES["Oes/Nac oes"],
coerce=to_bool,
label=_("Do you need an interpreter in court?"),
error_messages={
"required": ERROR_MESSAGES["INTERPRETER_NEEDED_REQUIRED"]})
interpreter_language_guilty_court = forms.CharField(
widget=forms.TextInput(attrs={
"class": "form-control"}),
max_length=100,
required=True,
label="",
help_text=_("If yes, tell us which language (include sign language):"),
error_messages={
"required": ERROR_MESSAGES["INTERPRETER_LANGUAGE_REQUIRED"]})
hearing_language = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
choices=YESNO_CHOICES["Saesneg/Cymraeg"],
coerce=to_bool,
label=_("If there is a hearing, which language do you wish to speak?"),
error_messages={
"required": ERROR_MESSAGES["HEARING_LANGUAGE_REQUIRED"]})
documentation_language = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
choices=YESNO_CHOICES["Saesneg/Cymraeg"],
coerce=to_bool,
label=_("Please state in which language you wish to receive any further documentation?"),
error_messages={
"required": ERROR_MESSAGES["DOCUMENTATION_LANGUAGE_REQUIRED"]})
disagree_with_evidence = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
choices=YESNO_CHOICES["Ydw/Nac ydw"],
coerce=to_bool,
label=_(
"Do you disagree with any evidence from a witness statement in "
"the notice we sent to you?"),
error_messages={
"required": ERROR_MESSAGES["DISAGREE_WITH_EVIDENCE_REQUIRED"]})
disagree_with_evidence_details = forms.CharField(
label="",
widget=Textarea(attrs={
"class": "form-control",
"rows": "3"}),
help_text=_(
"If yes, tell us the name of the witness (on the top left of the "
"statement) and what you disagree with:"),
max_length=5000,
error_messages={
"required": ERROR_MESSAGES["DISAGREE_WITH_EVIDENCE_DETAILS_REQUIRED"]})
witness_needed = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
choices=YESNO_CHOICES["Hoffwn/Na hoffwn"],
coerce=to_bool,
label=_("Do you want to call a defence witness?"),
help_text=_("Someone who can give evidence in court supporting your case."),
error_messages={
"required": ERROR_MESSAGES["WITNESS_NEEDED_REQUIRED"]})
witness_details = forms.CharField(
label="",
widget=Textarea(attrs={
"class": "form-control",
"rows": "3"}),
help_text=_(
"If yes, tell us the name, address and date of birth of any "
"witnesses you want to call to support your case:"),
max_length=5000,
error_messages={
"required": ERROR_MESSAGES["WITNESS_DETAILS_REQUIRED"]})
witness_interpreter_needed = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
choices=YESNO_CHOICES["Oes/Nac oes"],
coerce=to_bool,
label=_("Does your witness need an interpreter in court?"),
error_messages={
"required": ERROR_MESSAGES["WITNESS_INTERPRETER_NEEDED_REQUIRED"]})
witness_interpreter_language = forms.CharField(
widget=forms.TextInput(attrs={
"class": "form-control"}),
max_length=100,
required=True,
label="",
help_text=_("If yes, tell us which language (include sign language):"),
error_messages={
"required": ERROR_MESSAGES["WITNESS_INTERPRETER_LANGUAGE_REQUIRED"]})
def __init__(self, *args, **kwargs):
welsh_questions = kwargs.pop("welsh_questions", False)
super(BasePleaForm, self).__init__(*args, **kwargs)
if not welsh_questions:
del self.fields["hearing_language"]
del self.fields["documentation_language"]
class PleaForm(BasePleaForm):
"""Plea form"""
PLEA_CHOICES = (
('guilty_no_court', _('Guilty - I want the case to be dealt with in my absence')), ('guilty_court', _('Guilty - I want to attend court in person')),
('not_guilty', _("Not guilty - Pleading not guilty to this charge means we'll send details of a date for you to come to court for a trial.")),
)
dependencies = OrderedDict([
("not_guilty_extra", {"field": "guilty", "value": "not_guilty"}),
("interpreter_needed", {"field": "guilty", "value": "not_guilty"}),
("interpreter_language", {"field": "interpreter_needed", "value": "True"}),
("interpreter_needed_guilty_court", {"field": "guilty", "value": "guilty_court"}),
("interpreter_language_guilty_court", {"field": "interpreter_needed_guilty_court", "value": "True"}),
("disagree_with_evidence", {"field": "guilty", "value": "not_guilty"}),
("disagree_with_evidence_details", {"field": "disagree_with_evidence", "value": "True"}),
("witness_needed", {"field": "guilty", "value": "not_guilty"}),
("witness_details", {"field": "witness_needed", "value": "True"}),
("witness_interpreter_needed", {"field": "witness_needed", "value": "True"}),
("witness_interpreter_language", {"field": "witness_interpreter_needed", "value": "True"}),
("hearing_language", {"field": "guilty", "value": "not_guilty|guilty_court"}),
("documentation_language", {"field": "guilty", "value": "not_guilty|guilty_court"}),
])
guilty = forms.ChoiceField(
choices=PLEA_CHOICES,
widget=DSStackedRadioSelect,
required=True,
error_messages={
"required": ERROR_MESSAGES["PLEA_REQUIRED"]})
class SJPPleaForm(BasePleaForm):
"""SJP form"""
PLEA_CHOICES = (
('guilty_no_court', _('Guilty - I want the case to be dealt with in my absence')), ('guilty_court', _('Guilty - I want to attend court in person')),
('not_guilty', _("Not guilty - Pleading not guilty to this charge means you do not come to court on the hearing date in your requisition pack - we'll send details of a new hearing date.")),
)
dependencies = OrderedDict([
("sjp_interpreter_needed", {"field": "guilty", "value": "guilty_court"}),
("sjp_interpreter_language", {"field": "sjp_interpreter_needed", "value": "True"}),
("not_guilty_extra", {"field": "guilty", "value": "not_guilty"}),
("interpreter_needed", {"field": "guilty", "value": "not_guilty"}),
("interpreter_language", {"field": "interpreter_needed", "value": "True"}),
("disagree_with_evidence", {"field": "guilty", "value": "not_guilty"}),
("disagree_with_evidence_details", {"field": "disagree_with_evidence", "value": "True"}),
("witness_needed", {"field": "guilty", "value": "not_guilty"}),
("witness_details", {"field": "witness_needed", "value": "True"}),
("witness_interpreter_needed", {"field": "witness_needed", "value": "True"}),
("witness_interpreter_language", {"field": "witness_interpreter_needed", "value": "True"}),
("hearing_language", {"field": "guilty", "value": "not_guilty|guilty_court"}),
("documentation_language", {"field": "guilty", "value": "not_guilty|guilty_court"}),
])
guilty = forms.ChoiceField(
choices=PLEA_CHOICES,
widget=DSStackedRadioSelect,
required=True,
error_messages={
"required": ERROR_MESSAGES["PLEA_REQUIRED"]})
come_to_court = forms.TypedChoiceField(
widget=DSRadioSelect,
required=False,
choices=YESNO_CHOICES["Hoffwn/Na hoffwn"],
coerce=to_bool,
label=_("Do you want to come to court to plead guilty?"),
error_messages={
"required": ERROR_MESSAGES["COME_TO_COURT_REQUIRED"]})
sjp_interpreter_needed = forms.TypedChoiceField(
widget=DSRadioSelect,
required=True,
choices=YESNO_CHOICES["Oes/Nac oes"],
coerce=to_bool,
label=_("Do you need an interpreter in court?"),
error_messages={
"required": ERROR_MESSAGES["INTERPRETER_NEEDED_REQUIRED"]})
sjp_interpreter_language = forms.CharField(
widget=forms.TextInput(attrs={
"class": "form-control"}),
max_length=100,
required=True,
label="",
help_text=_("If yes, tell us which language (include sign language):"),
error_messages={
"required": ERROR_MESSAGES["INTERPRETER_LANGUAGE_REQUIRED"]})
def __init__(self, *args, **kwargs):
super(SJPPleaForm, self).__init__(*args, **kwargs)
fields_order = [
"split_form",
"guilty",
"come_to_court",
"sjp_interpreter_needed",
"sjp_interpreter_language",
"guilty_extra",
"not_guilty_extra",
"interpreter_needed",
"interpreter_language",
"disagree_with_evidence",
"disagree_with_evidence_details",
"witness_needed",
"witness_details",
"witness_interpreter_needed",
"witness_interpreter_language",
"hearing_language",
"documentation_language"
]
self.fields = reorder_fields(self.fields, fields_order)
class CourtFinderForm(forms.Form):
"""Courtfinder form"""
urn = forms.CharField(
widget=forms.TextInput(attrs={
"class": "form-control"}),
label=_("Unique reference number (URN)"),
required=True,
help_text=_("On page 1, usually at the top."),
error_messages={
"required": ERROR_MESSAGES["URN_REQUIRED"],
"is_urn_valid": ERROR_MESSAGES["URN_INCORRECT"]})
|
python
|
"""
Just another Python API for Travis CI (API).
A module which provides the tests of our requester module.
Author:
Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom
Project link:
https://github.com/funilrys/PyTravisCI
Project documentation:
https://pytravisci.readthedocs.io/en/latest/
License
::
MIT License
Copyright (c) 2019, 2020 Nissar Chababy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import json
import secrets
from unittest import TestCase
from unittest import main as launch_tests
from unittest.mock import patch
import requests
from PyTravisCI.__about__ import __version__
from PyTravisCI.exceptions import TravisCIError
from PyTravisCI.requester import Requester
class RequesterTest(TestCase):
"""
Provides the tests of the requester class.
"""
# pylint: disable=too-many-public-methods
def test_default_header(self) -> None:
"""
Tests if the expected header is set.
"""
expected_api_version = "3"
expected_user_agent = f"PyTravisCI/{__version__}"
expected = {
"Travis-API-Version": expected_api_version,
"User-Agent": expected_user_agent,
}
requester = Requester()
actual = requester.session.headers
self.assertDictContainsSubset(expected, actual)
def test_authorization_header(self) -> None:
"""
Tests if the authorization header is correctly set.
"""
given_token = secrets.token_urlsafe(16)
expected = {"Authorization": f"token {given_token}"}
requester = Requester()
requester.set_authorization(given_token)
actual = requester.session.headers
self.assertDictContainsSubset(expected, actual)
def test_authorization_header_non_string(self) -> None:
"""
Tests that the method which let us communicate the token
raises an exception if a non-string value is given.
"""
given = True
requester = Requester()
self.assertRaises(TypeError, lambda: requester.set_authorization(given))
def test_set_base_url(self) -> None:
"""
Tests of the method which let us communicate the base url.
"""
given_base_url = "https://example.org/api"
expected = "https://example.org/api"
requester = Requester()
requester.set_base_url(given_base_url)
actual = requester.base_url
self.assertEqual(expected, actual)
def test_set_base_url_ends_with_with_slash(self) -> None:
"""
Tests of the method which let us communicate the base url for the case
that a slash is given at the end of the URL.
"""
given_base_url = "https://example.org/api/"
expected = "https://example.org/api"
requester = Requester()
requester.set_base_url(given_base_url)
actual = requester.base_url
self.assertEqual(expected, actual)
def test_set_base_url_non_string(self) -> None:
"""
Tests of the method which let us communicate the base url for the case
that a non-string is given.
"""
given = True
requester = Requester()
self.assertRaises(TypeError, lambda: requester.set_base_url(given))
def test_bind_endpoint_to_base_url(self) -> None:
"""
Tests of the method which let us bind an endpoint with the previously
given base url.
"""
given_base_url = "https://example.org/api"
given_endpoint = "hello/world"
expected = "https://example.org/api/hello/world"
requester = Requester()
requester.set_base_url(given_base_url)
actual = requester.bind_endpoint_to_base_url(given_endpoint)
self.assertEqual(expected, actual)
def test_bind_endpoint_to_base_url_endpoint_starts_with_slash(self) -> None:
"""
Tests of the method which let us bind an endpoint with the previously
given base url for the case that the given endpoint starts with a slash.
"""
given_base_url = "https://example.org/api"
given_endpoint = "/hello/world"
expected = "https://example.org/api/hello/world"
requester = Requester()
requester.set_base_url(given_base_url)
actual = requester.bind_endpoint_to_base_url(given_endpoint)
self.assertEqual(expected, actual)
def test_bind_endpoint_to_base_url_endpoint_not_string(self) -> None:
"""
Tests of the method which let us bind an endpoint with the previouly
given base url for the case that the given endpoint is a non-string.
"""
given_base_url = "https://example.org/api"
given_endpoint = True
requester = Requester()
requester.set_base_url(given_base_url)
self.assertRaises(
TypeError, lambda: requester.bind_endpoint_to_base_url(given_endpoint)
)
def test_is_error(self) -> None:
"""
Tests of the method which checks if the API response is an error.
"""
expected = True
given = {
"@type": "error",
"error_type": "not_found",
"error_message": "repository not found (or insufficient access)",
"resource_type": "repository",
}
actual = Requester.is_error(given)
self.assertEqual(expected, actual)
def test_is_error_not_error(self) -> None:
"""
Tests of the method whixh checks if the API response is an error for the
case that a normal resource type is given.
"""
expected = False
given = {
"@type": "user",
"@href": "/user/4549848944894848948949",
"@representation": "standard",
"@permissions": {"read": True, "sync": True},
"id": 4549848944894848948949,
"login": "foobar",
"name": "Foo Bar",
"github_id": 1148942198798789784897949849484523106,
"vcs_id": "1148942198798789784897949849484523106",
"vcs_type": "GithubUser",
"avatar_url": None,
"education": False,
"allow_migration": False,
"email": "[email protected]",
"is_syncing": False,
"synced_at": "2020-10-14T14:53:08Z",
"recently_signed_up": False,
"secure_user_hash": None,
}
actual = Requester.is_error(given)
self.assertEqual(expected, actual)
def test_get_error_message(self) -> None:
"""
Tests of the method which let us get the actual error message.
"""
given = {
"@type": "error",
"error_type": "not_found",
"error_message": "repository not found (or insufficient access)",
"resource_type": "repository",
}
expected = "repository not found (or insufficient access)"
actual = Requester.get_error_message(given)
self.assertEqual(expected, actual)
def test_get_error_message_not_error(self) -> None:
"""
Tests of the method which let us get the actual error message for the
case that no error is actually given.
"""
given = {
"@type": "user",
"@href": "/user/4549848944894848948949",
"@representation": "standard",
"@permissions": {"read": True, "sync": True},
"id": 4549848944894848948949,
"login": "foobar",
"name": "Foo Bar",
"github_id": 1148942198798789784897949849484523106,
"vcs_id": "1148942198798789784897949849484523106",
"vcs_type": "GithubUser",
"avatar_url": None,
"education": False,
"allow_migration": False,
"email": "[email protected]",
"is_syncing": False,
"synced_at": "2020-10-14T14:53:08Z",
"recently_signed_up": False,
"secure_user_hash": None,
}
expected = None
actual = Requester.get_error_message(given)
self.assertEqual(expected, actual)
def test_get_error_message_already_checked(self) -> None:
"""
Tests of the method which let us get the actual error message for the
case that we already know that it is an error.
"""
given = {
"@type": "error",
"error_type": "not_found",
"error_message": "repository not found (or insufficient access)",
"resource_type": "repository",
}
expected = "repository not found (or insufficient access)"
actual = Requester.get_error_message(given, already_checked=True)
self.assertEqual(expected, actual)
def test_get_error_message_fake_already_checked(self) -> None:
"""
Tests of the method which let us get the actual error message for the
case that we "already know" that it is an error but it was just fake.
"""
given = {
"@type": "user",
"@href": "/user/4549848944894848948949",
"@representation": "standard",
"@permissions": {"read": True, "sync": True},
"id": 4549848944894848948949,
"login": "foobar",
"name": "Foo Bar",
"github_id": 1148942198798789784897949849484523106,
"vcs_id": "1148942198798789784897949849484523106",
"vcs_type": "GithubUser",
"avatar_url": None,
"education": False,
"allow_migration": False,
"email": "[email protected]",
"is_syncing": False,
"synced_at": "2020-10-14T14:53:08Z",
"recently_signed_up": False,
"secure_user_hash": None,
}
self.assertRaises(
KeyError, lambda: Requester.get_error_message(given, already_checked=True)
)
def test_get_error_type(self) -> None:
"""
Tests of the method which let us get the actual error type.
"""
given = {
"@type": "error",
"error_type": "not_found",
"error_message": "repository not found (or insufficient access)",
"resource_type": "repository",
}
expected = "not_found"
actual = Requester.get_error_type(given)
self.assertEqual(expected, actual)
def test_get_error_type_not_error(self) -> None:
"""
Tests of the method which let us get the actual error type for the
case that no error is actually given.
"""
given = {
"@type": "user",
"@href": "/user/4549848944894848948949",
"@representation": "standard",
"@permissions": {"read": True, "sync": True},
"id": 4549848944894848948949,
"login": "foobar",
"name": "Foo Bar",
"github_id": 1148942198798789784897949849484523106,
"vcs_id": "1148942198798789784897949849484523106",
"vcs_type": "GithubUser",
"avatar_url": None,
"education": False,
"allow_migration": False,
"email": "[email protected]",
"is_syncing": False,
"synced_at": "2020-10-14T14:53:08Z",
"recently_signed_up": False,
"secure_user_hash": None,
}
expected = None
actual = Requester.get_error_type(given)
self.assertEqual(expected, actual)
def test_get_error_type_already_checked(self) -> None:
"""
Tests of the method which let us get the actual error type for the
case that we already know that it is an error.
"""
given = {
"@type": "error",
"error_type": "not_found",
"error_message": "repository not found (or insufficient access)",
"resource_type": "repository",
}
expected = "not_found"
actual = Requester.get_error_type(given, already_checked=True)
self.assertEqual(expected, actual)
def test_get_error_type_fake_already_checked(self) -> None:
"""
Tests of the method which let us get the actual error type for the
case that we "already know" that it is an error but it was just fake.
"""
given = {
"@type": "user",
"@href": "/user/4549848944894848948949",
"@representation": "standard",
"@permissions": {"read": True, "sync": True},
"id": 4549848944894848948949,
"login": "foobar",
"name": "Foo Bar",
"github_id": 1148942198798789784897949849484523106,
"vcs_id": "1148942198798789784897949849484523106",
"vcs_type": "GithubUser",
"avatar_url": None,
"education": False,
"allow_migration": False,
"email": "[email protected]",
"is_syncing": False,
"synced_at": "2020-10-14T14:53:08Z",
"recently_signed_up": False,
"secure_user_hash": None,
}
self.assertRaises(
KeyError, lambda: Requester.get_error_type(given, already_checked=True)
)
def test_raise_if_error(self) -> None:
"""
Tests of the method which actually raises the exception when the
API response is an error.
"""
given = {
"@type": "error",
"error_type": "not_found",
"error_message": "repository not found (or insufficient access)",
"resource_type": "repository",
}
fake_response = requests.Response()
fake_response.url = "https://example.org"
self.assertRaises(
TravisCIError, lambda: Requester.raise_if_error(fake_response, given)
)
def test_raise_if_error_not_error(self) -> None:
"""
Tests of the method which actually raises the exception when the
API response is an error, but for the case that no error
is given (in the api_response)
"""
given = {
"@type": "user",
"@href": "/user/4549848944894848948949",
"@representation": "standard",
"@permissions": {"read": True, "sync": True},
"id": 4549848944894848948949,
"login": "foobar",
"name": "Foo Bar",
"github_id": 1148942198798789784897949849484523106,
"vcs_id": "1148942198798789784897949849484523106",
"vcs_type": "GithubUser",
"avatar_url": None,
"education": False,
"allow_migration": False,
"email": "[email protected]",
"is_syncing": False,
"synced_at": "2020-10-14T14:53:08Z",
"recently_signed_up": False,
"secure_user_hash": None,
}
expected = None
fake_response = requests.Response()
fake_response.url = "https://example.org"
actual = Requester.raise_if_error(fake_response, given)
self.assertEqual(expected, actual)
@patch.object(requests.Session, "get")
def test_request_factory(self, mock_session_get):
"""
Tests of the request factory.
"""
given_base_url = "https://example.org/api/"
given_endpoint = "hello/world"
response = {
"@type": "user",
"@href": "/user/4549848944894848948949",
"@representation": "standard",
"@permissions": {"read": True, "sync": True},
"id": 4549848944894848948949,
"login": "foobar",
"name": "Foo Bar",
"github_id": 1148942198798789784897949849484523106,
"vcs_id": "1148942198798789784897949849484523106",
"vcs_type": "GithubUser",
"avatar_url": None,
"education": False,
"allow_migration": False,
"email": "[email protected]",
"is_syncing": False,
"synced_at": "2020-10-14T14:53:08Z",
"recently_signed_up": False,
"secure_user_hash": None,
}
requester = Requester()
requester.set_base_url(given_base_url)
mock_session_get.return_value.headers = dict()
mock_session_get.return_value.status_code = 200
mock_session_get.return_value.url = "https://example.org/api/hello/world"
mock_session_get.return_value.json.return_value = response
expected = response
actual = requester.get(given_endpoint)
self.assertEqual(expected, actual)
@patch.object(requests.Session, "get")
def test_request_factory_no_json_response(self, mock_session_get):
"""
Tests of the request factory for the case that no JSON is given as response.
"""
given_base_url = "https://example.org/api/"
given_endpoint = "hello/world"
response = {
"@type": "user",
"@href": "/user/4549848944894848948949",
"@representation": "standard",
"@permissions": {"read": True, "sync": True},
"id": 4549848944894848948949,
"login": "foobar",
"name": "Foo Bar",
"github_id": 1148942198798789784897949849484523106,
"vcs_id": "1148942198798789784897949849484523106",
"vcs_type": "GithubUser",
"avatar_url": None,
"education": False,
"allow_migration": False,
"email": "[email protected]",
"is_syncing": False,
"synced_at": "2020-10-14T14:53:08Z",
"recently_signed_up": False,
"secure_user_hash": None,
}
requester = Requester()
requester.set_base_url(given_base_url)
mock_session_get.return_value.headers = dict()
mock_session_get.return_value.status_code = 200
mock_session_get.return_value.url = "https://example.org/api/hello/world"
mock_session_get.return_value.text = json.dumps(response)
mock_session_get.return_value.json.side_effect = json.decoder.JSONDecodeError(
"hello", "world", 33
)
self.assertRaises(TravisCIError, lambda: requester.get(given_endpoint))
@patch.object(requests.Session, "get")
def test_request_factory_empty_esponse(self, mock_session_get):
"""
Tests of the request factory for the case that an empty response is
given (back).
"""
given_base_url = "https://example.org/api/"
given_endpoint = "hello/world"
requester = Requester()
requester.set_base_url(given_base_url)
mock_session_get.return_value.status_code = 200
mock_session_get.return_value.headers = dict()
mock_session_get.return_value.url = "https://example.org/api/hello/world"
mock_session_get.return_value.text = ""
mock_session_get.return_value.json.side_effect = json.decoder.JSONDecodeError(
"hello", "world", 33
)
self.assertRaises(TravisCIError, lambda: requester.get(given_endpoint))
if __name__ == "__main__":
launch_tests()
|
python
|
#!/usr/bin/env python
from __future__ import print_function, division, absolute_import
import sys
from channelfinder import ChannelFinderClient, Channel, Property, Tag
import aphla as ap
#GET http://channelfinder.nsls2.bnl.gov:8080/ChannelFinder/resources/resources/channels?~name=SR*
cfsurl = 'http://web01.nsls2.bnl.gov:8080/ChannelFinder'
#cfinput = {
# 'BaseURL': cfsurl,
# 'username': conf.username,
# 'password': conf.password}
def download_cfs(cfsurl, **cfinput):
cf = ChannelFinderClient(BaseURL = cfsurl)
chs = cf.find(**cfinput)
ret = chanData.ChannelFinderData()
for ch in chs:
pv = ch.Name
prpt = dict([(p.Name, p.Value) for p in ch.Properties])
tags = [t.Name for t in ch.Tags]
ret.update(pv = pv, properties = prpt, tags = tags)
return ret
def print_kv(k, v):
s = ''
if len(v[0]) == 0 and len(v[1]) == 0: return
elif len(v[1]) == 0:
for p,vv in v[0].items():
if vv is None: continue
s = s + "{0}={1}, ".format(p, vv)
if s:
print(k, s[:-2])
elif len(v[0]) == 0:
print(k,)
for p in v[1]:
print("%s," % p,)
print("")
else:
print(k,)
for p,vv in v[0].items():
print("%s=%s" % (str(p), str(vv)),)
for p in v[1]:
print("%s," % p)
print("")
if __name__ == "__main__":
if len(sys.argv) < 2:
print(sys.argv[0], "us_nsls2_cfs.csv")
sys.exit(0)
cfa1 = ap.ChannelFinderAgent()
cfa1.importCsv(sys.argv[1])
cfa2 = ap.ChannelFinderAgent()
cfa2.downloadCfs(cfsurl, tagName='aphla.*')
print("<<<< local - CFS")
for k, v in (cfa1 - cfa2).items():
print_kv(k, v)
print("--------------")
for k, v in (cfa2 - cfa1).items():
print_kv(k, v)
print(">>>> CFS - local")
|
python
|
from django.db import models
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
class PinCard(models.Model):
token = models.CharField(max_length=32, db_index=True, editable=False)
display_number = models.CharField(max_length=20, editable=False)
expiry_month = models.PositiveSmallIntegerField()
expiry_year = models.PositiveSmallIntegerField()
scheme = models.CharField(max_length=20, editable=False)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
address_line1 = models.CharField(max_length=255)
address_line2 = models.CharField(max_length=255, blank=True)
address_city = models.CharField(max_length=255)
address_postcode = models.CharField(max_length=20)
address_state = models.CharField(max_length=255)
address_country = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, related_name='pin_cards', blank=True, null=True)
class Meta:
app_label = 'billing'
def __unicode__(self):
return 'Card %s' % self.display_number
class PinCustomer(models.Model):
token = models.CharField(unique=True, max_length=32)
card = models.ForeignKey(PinCard, related_name='customers')
email = models.EmailField()
created_at = models.DateTimeField()
user = models.ForeignKey(User, related_name='pin_customers', blank=True, null=True)
class Meta:
app_label = 'billing'
def __unicode__(self):
return 'Customer %s' % self.email
class PinCharge(models.Model):
token = models.CharField(unique=True, max_length=32, editable=False)
card = models.ForeignKey(PinCard, related_name='charges', editable=False)
customer = models.ForeignKey(PinCustomer, related_name='customers', null=True, blank=True, editable=False)
success = models.BooleanField()
amount = models.DecimalField(max_digits=16, decimal_places=2)
currency = models.CharField(max_length=3)
description = models.CharField(max_length=255)
email = models.EmailField()
ip_address = models.GenericIPAddressField(blank=True, null=True)
created_at = models.DateTimeField()
status_message = models.CharField(max_length=255)
error_message = models.CharField(max_length=255)
user = models.ForeignKey(User, related_name='pin_charges', blank=True, null=True)
class Meta:
app_label = 'billing'
def __unicode__(self):
return 'Charge %s' % self.email
class PinRefund(models.Model):
token = models.CharField(unique=True, max_length=32)
charge = models.ForeignKey(PinCharge, related_name='refunds')
success = models.BooleanField()
amount = models.DecimalField(max_digits=16, decimal_places=2)
currency = models.CharField(max_length=3)
created_at = models.DateTimeField()
status_message = models.CharField(max_length=255)
error_message = models.CharField(max_length=255)
user = models.ForeignKey(User, related_name='pin_refunds', blank=True, null=True)
class Meta:
app_label = 'billing'
def __unicode__(self):
return 'Refund %s' % self.charge.email
|
python
|
#!/usr/bin/env python
"""The setup script."""
from setuptools import (
find_packages,
setup,
)
from authz import __version__
with open('README.md') as readme_file:
readme = readme_file.read()
requirements = ["casbin==1.9.3"]
test_requirements = ['pytest>=3', ]
setup(
author="Ezequiel Grondona",
author_email='[email protected]',
python_requires='>=3.6',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
description="Authorization middleware for GraphQL.",
install_requires=requirements,
license="MIT license",
long_description=readme,
long_description_content_type='text/markdown',
include_package_data=True,
keywords='graphql',
name='graphql-authz',
packages=find_packages(include=['authz', 'authz.*']),
test_suite='tests',
tests_require=test_requirements,
url='https://github.com/Checho3388/graphql-authz',
version=__version__,
zip_safe=False,
)
|
python
|
real = float(input('Quanto você tem na Carteira? R$'))
dolar = real / 5.11
euro = real / 5.76
print('Com R${:.2f} você pode comprar U$${:.2f} e €{:.2f} '.format(real, dolar, euro))
|
python
|
def fib(n):
if (n==0):
return 0
elif (n==1):
return 1
else:
x = fib(n-1) + fib(n-2)
return x
print(fib(6))
|
python
|
#!/usr/bin/python
from hashlib import sha1
from subprocess import check_output
import hmac
import json
import os
import sys
# Due to |hmac.compare_digest| is new in python 2.7.7, in order to be
# compatible with other 2.7.x version, we use a similar implementation of
# |compare_digest| to the Python implementation.
#
# See: http://stackoverflow.com/questions/18168819
def compare_digest(x, y):
if not (isinstance(x, bytes) and isinstance(y, bytes)):
raise TypeError("both inputs should be instances of bytes")
if len(x) != len(y):
return False
result = 0
for a, b in zip(x, y):
result |= int(a, 16) ^ int(b, 16)
return result == 0
def verify_signature(payload_body):
x_hub_signature = os.getenv("HTTP_X_HUB_SIGNATURE")
if not x_hub_signature:
return False
sha_name, signature = x_hub_signature.split('=')
if sha_name != 'sha1':
return False
# Never hardcode the token into real product, but now we are finishing
# homework.
SECRET_TOKEN = 'nQLr1TFpNvheiPPw9FnsUYD8vSeEV79L'
mac = hmac.new(SECRET_TOKEN, msg=payload_body, digestmod=sha1)
return compare_digest(mac.hexdigest(), signature)
print 'Content-Type: application/json\n\n'
result = {}
event = os.getenv('HTTP_X_GITHUB_EVENT')
if event != 'push':
result['success'] = False
else:
payload_body = sys.stdin.read()
result['success'] = verify_signature(payload_body)
if result['success']:
path = os.path.dirname(os.path.realpath(__file__))
out = check_output(["git", "pull"], cwd=path)
result['out'] = out
print json.dumps(result)
|
python
|
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'ix4hnvelil^q36!(bg#)_+q=vkf4yk)@bh64&0qc2z*zy5^kdz'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'user',
'job',
'ckeditor',
'django_filters',
'widget_tweaks',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
AUTH_USER_MODEL = 'user.User'
CKEDITOR_CONFIGS = {
'default': {
'toolbar_YourCustomToolbarConfig': [
{'name': 'basicstyles',
'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},
{'name': 'clipboard', 'items': ['Undo', 'Redo']},
{'name': 'paragraph',
'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', '-',
'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']},
'/',
{'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
{'name': 'colors', 'items': ['TextColor', 'BGColor']},
{'name': 'tools', 'items': ['Maximize']},
{'name': 'links', 'items': ['Link', 'Unlink']},
{'name': 'insert',
'items': ['HorizontalRule', 'Smiley', 'SpecialChar']},
{'name': 'document', 'items': ['Preview', ]},
],
'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here
'height': 350,
'width': 1000,
'tabSpaces': 4,
}
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'jobland.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'jobland.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Dhaka'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static-files"),
]
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
# Email settings
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_HOST = 'smtp.gmail.com'
# EMAIL_PORT = '587'
# EMAIL_HOST_USER = '[email protected]'
# EMAIL_HOST_PASSWORD = "asdfASDF123"
# EMAIL_USE_TLS = True # for security
|
python
|
import io
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import time
class Analyzer:
'''Controls plotting of different object properties'''
def __init__(self):
self.plot_number = 1
self.xdata = []
self.reactors = []
self.reactor_number = 0
self.start_time = 0
@property
def stream_names(self):
return {'Reactor': ['plot']}
def get_plot(self, name, simulation_state, start_plotting, restart_plots):
if(restart_plots):
self.xdata = []
self.reactors = []
self.reactor_number = 0
self.start_time = simulation_state.time
if(start_plotting):
return self.plot_reactors(simulation_state)
return None
def plot_reactors(self,simulation_state):
'''Plots reactor concentrations as received from simulation
Parameters
----------
simulation_state : protobuf object
Contains a time stamp and object properties
Returns
-------
callable
Callable that retrieves contents of the output file
'''
if(len(simulation_state.kinetics) == 0):
self.reactor_number = 0
return None
if(self.reactor_number != len(simulation_state.kinetics)):
self.reactor_number = len(simulation_state.kinetics)
self.start_time = simulation_state.time
self.xdata = []
self.reactors = []
x = (simulation_state.time - self.start_time)*0.04 #display time in seconds(considering ~25fps)
self.xdata.append(x)
for i in range(len(simulation_state.kinetics)):
y = simulation_state.kinetics[i].mole_fraction
if(len(self.reactors) == i):#add one if we're out of space
self.reactors.append([[] for j in range(len(y))])
for j in range(len(y)):#reactors stores the concentrations of each species of reactant in each reactor over time
self.reactors[i][j].append(y[j])#append this time step's molefrac to the respective reactor/species
if(simulation_state.time % 25 == 0):
fig, axes = plt.subplots(len(simulation_state.kinetics), 1, sharex = True, sharey = True, squeeze=False) #overlay all the plots
fig.text(0.5, 0.04, 'Time Elapsed (s)', ha='center', va='center')
fig.text(0.01, 0.5, 'Concentration (mol/L)', ha='center', va='center', rotation='vertical')
labels = ['A', 'B', 'C', 'D']
colors = ['red', 'blue', 'green', 'purple']
linestyles = ['-', ':', '-', ':']
i = 0
for i,ax in enumerate(axes[:,0]):
#self.reactors[i] = [[] for j in range(len(y))]
for j in range(len(y)):
#print(self.xdata, ydata[:,j])
ax.plot(self.xdata, self.reactors[i][j], color = colors[j], label = labels[j], ls=linestyles[j])
plt.legend(loc='upper right')
with io.BytesIO() as output:
fig.savefig(output, format='jpg')
plt.clf()
return output.getvalue()
|
python
|
from ..gl import AGLObject, GLHelper
from ...debugging import Debug, LogLevel
from ...constants import _NP_UBYTE
from ...autoslot import Slots
from OpenGL import GL
import numpy as np
import time
class TextureData(Slots):
__slots__ = ("__weakref__", )
def __init__(self, width: int, height: int):
self.width: int = width
self.height: int = height
self.data: memoryview = None
self.format: GL.GLenum = GL.GL_RGB
self.filepath: str = ""
class TextureSpec(Slots):
__slots__ = ("__weakref__", )
def __init__(self):
self.mipmaps: int = 3
self.minFilter: GL.GLenum = GL.GL_LINEAR_MIPMAP_LINEAR
self.magFilter: GL.GLenum = GL.GL_LINEAR
self.wrapMode: GL.GLenum = GL.GL_REPEAT
self.compress: bool = True
class Texture(AGLObject):
_InternalFormat = GL.GL_RGBA8
_CompressedInternalFormat = GL.GL_COMPRESSED_RGBA
_CompressionEnabled = False
def __init__(self, tData: TextureData, tSpec: TextureSpec):
start = time.perf_counter()
super().__init__()
self.width = tData.width
self.height = tData.height
self.filepath = tData.filepath
self.specification = tSpec
self._id = GLHelper.CreateTexture(GL.GL_TEXTURE_2D)
_format = Texture._CompressedInternalFormat if tSpec.compress else Texture._InternalFormat
if not Texture._CompressionEnabled:
_format = Texture._InternalFormat
GL.glTextureStorage2D(self._id, tSpec.mipmaps, _format, tData.width, tData.height)
GL.glTextureParameteri(self._id, GL.GL_TEXTURE_WRAP_S, tSpec.wrapMode)
GL.glTextureParameteri(self._id, GL.GL_TEXTURE_WRAP_T, tSpec.wrapMode)
GL.glTextureParameteri(self._id, GL.GL_TEXTURE_MIN_FILTER, tSpec.minFilter)
GL.glTextureParameteri(self._id, GL.GL_TEXTURE_MAG_FILTER, tSpec.magFilter)
GL.glTextureSubImage2D(self._id, 0, 0, 0, tData.width, tData.height, tData.format, GL.GL_UNSIGNED_BYTE, tData.data.obj)
GL.glGenerateTextureMipmap(self._id)
tData.data.release()
Debug.GetGLError()
Debug.Log(f"Texture (id: {self._id}) initialized in {time.perf_counter() - start} seconds.", LogLevel.Info)
def BindToUnit(self, slot) -> None:
GL.glBindTextureUnit(slot, self._id)
def Delete(self, removeRef: bool) -> None:
super().Delete(removeRef)
GL.glDeleteTextures(1, [self._id])
@classmethod
def CreateWhiteTexture(cls):
tData = TextureData(1, 1)
tData.data = memoryview(np.array([255, 255, 255, 255], dtype=_NP_UBYTE))
tData.format = GL.GL_RGBA
spec = TextureSpec()
spec.minFilter = GL.GL_NEAREST
spec.magFilter = GL.GL_NEAREST
spec.mipmaps = 1
spec.compress = False
return cls(tData, spec)
|
python
|
# This is a work in progress - see Demos/win32gui_menu.py
# win32gui_struct.py - helpers for working with various win32gui structures.
# As win32gui is "light-weight", it does not define objects for all possible
# win32 structures - in general, "buffer" objects are passed around - it is
# the callers responsibility to pack the buffer in the correct format.
#
# This module defines some helpers for the commonly used structures.
#
# In general, each structure has 3 functions:
#
# buffer, extras = PackSTRUCTURE(items, ...)
# item, ... = UnpackSTRUCTURE(buffer)
# buffer, extras = EmtpySTRUCTURE(...)
#
# 'extras' is always items that must be held along with the buffer, as the
# buffer refers to these object's memory.
# For structures that support a 'mask', this mask is hidden from the user - if
# 'None' is passed, the mask flag will not be set, or on return, None will
# be returned for the value if the mask is not set.
#
# NOTE: I considered making these structures look like real classes, and
# support 'attributes' etc - however, ctypes already has a good structure
# mechanism - I think it makes more sense to support ctype structures
# at the win32gui level, then there will be no need for this module at all.
# XXX - the above makes sense in terms of what is built and passed to
# win32gui (ie, the Pack* functions) - but doesn't make as much sense for
# the Unpack* functions, where the aim is user convenience.
import win32gui
import win32con
import struct
import array
import commctrl
import pywintypes
# Generic WM_NOTIFY unpacking
def UnpackWMNOTIFY(lparam):
format = "iii"
buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam)
hwndFrom, idFrom, code = struct.unpack(format, buf)
return hwndFrom, idFrom, code
# MENUITEMINFO struct
# http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/Resources/Menus/MenuReference/MenuStructures/MENUITEMINFO.asp
# We use the struct module to pack and unpack strings as MENUITEMINFO
# structures. We also have special handling for the 'fMask' item in that
# structure to avoid the caller needing to explicitly check validity
# (None is used if the mask excludes/should exclude the value)
menuitem_fmt = '5i5PiP'
def PackMENUITEMINFO(fType=None, fState=None, wID=None, hSubMenu=None,
hbmpChecked=None, hbmpUnchecked=None, dwItemData=None,
text=None, hbmpItem=None, dwTypeData=None):
# 'extras' are objects the caller must keep a reference to (as their
# memory is used) for the lifetime of the INFO item.
extras = []
# ack - dwItemData and dwTypeData were confused for a while...
assert dwItemData is None or dwTypeData is None, \
"sorry - these were confused - you probably want dwItemData"
# if we are a long way past 209, then we can nuke the above...
if dwTypeData is not None:
import warnings
warnings.warn("PackMENUITEMINFO: please use dwItemData instead of dwTypeData")
if dwItemData is None:
dwItemData = dwTypeData or 0
fMask = 0
if fType is None: fType = 0
else: fMask |= win32con.MIIM_FTYPE
if fState is None: fState = 0
else: fMask |= win32con.MIIM_STATE
if wID is None: wID = 0
else: fMask |= win32con.MIIM_ID
if hSubMenu is None: hSubMenu = 0
else: fMask |= win32con.MIIM_SUBMENU
if hbmpChecked is None:
assert hbmpUnchecked is None, \
"neither or both checkmark bmps must be given"
hbmpChecked = hbmpUnchecked = 0
else:
assert hbmpUnchecked is not None, \
"neither or both checkmark bmps must be given"
fMask |= win32con.MIIM_CHECKMARKS
if dwItemData is None: dwItemData = 0
else: fMask |= win32con.MIIM_DATA
if hbmpItem is None: hbmpItem = 0
else: fMask |= win32con.MIIM_BITMAP
if text is not None:
fMask |= win32con.MIIM_STRING
if isinstance(text, unicode):
text = text.encode("mbcs")
str_buf = array.array("c", text+'\0')
cch = len(str_buf)
# We are taking address of strbuf - it must not die until windows
# has finished with our structure.
lptext = str_buf.buffer_info()[0]
extras.append(str_buf)
else:
lptext = 0
cch = 0
# Create the struct.
# 'P' format does not accept PyHANDLE's !
item = struct.pack(
menuitem_fmt,
struct.calcsize(menuitem_fmt), # cbSize
fMask,
fType,
fState,
wID,
long(hSubMenu),
long(hbmpChecked),
long(hbmpUnchecked),
dwItemData,
lptext,
cch,
long(hbmpItem)
)
# Now copy the string to a writable buffer, so that the result
# could be passed to a 'Get' function
return array.array("c", item), extras
def UnpackMENUITEMINFO(s):
(cb,
fMask,
fType,
fState,
wID,
hSubMenu,
hbmpChecked,
hbmpUnchecked,
dwItemData,
lptext,
cch,
hbmpItem) = struct.unpack(menuitem_fmt, s)
assert cb==len(s)
if fMask & win32con.MIIM_FTYPE==0: fType = None
if fMask & win32con.MIIM_STATE==0: fState = None
if fMask & win32con.MIIM_ID==0: wID = None
if fMask & win32con.MIIM_SUBMENU==0: hSubMenu = None
if fMask & win32con.MIIM_CHECKMARKS==0: hbmpChecked = hbmpUnchecked = None
if fMask & win32con.MIIM_DATA==0: dwItemData = None
if fMask & win32con.MIIM_BITMAP==0: hbmpItem = None
if fMask & win32con.MIIM_STRING:
text = win32gui.PyGetString(lptext, cch)
else:
text = None
return fType, fState, wID, hSubMenu, hbmpChecked, hbmpUnchecked, \
dwItemData, text, hbmpItem
def EmptyMENUITEMINFO(mask = None, text_buf_size=512):
extra = []
if mask is None:
mask = win32con.MIIM_BITMAP | win32con.MIIM_CHECKMARKS | \
win32con.MIIM_DATA | win32con.MIIM_FTYPE | \
win32con.MIIM_ID | win32con.MIIM_STATE | \
win32con.MIIM_STRING | win32con.MIIM_SUBMENU
# Note: No MIIM_TYPE - this screws win2k/98.
if mask & win32con.MIIM_STRING:
text_buffer = array.array("c", "\0" * text_buf_size)
extra.append(text_buffer)
text_addr, text_len = text_buffer.buffer_info()
else:
text_addr = text_len = 0
buf = struct.pack(
menuitem_fmt,
struct.calcsize(menuitem_fmt), # cbSize
mask,
0, #fType,
0, #fState,
0, #wID,
0, #hSubMenu,
0, #hbmpChecked,
0, #hbmpUnchecked,
0, #dwItemData,
text_addr,
text_len,
0, #hbmpItem
)
return array.array("c", buf), extra
# MENUINFO struct
menuinfo_fmt = '7i'
def PackMENUINFO(dwStyle = None, cyMax = None,
hbrBack = None, dwContextHelpID = None, dwMenuData = None,
fMask = 0):
if dwStyle is None: dwStyle = 0
else: fMask |= win32con.MIM_STYLE
if cyMax is None: cyMax = 0
else: fMask |= win32con.MIM_MAXHEIGHT
if hbrBack is None: hbrBack = 0
else: fMask |= win32con.MIM_BACKGROUND
if dwContextHelpID is None: dwContextHelpID = 0
else: fMask |= win32con.MIM_HELPID
if dwMenuData is None: dwMenuData = 0
else: fMask |= win32con.MIM_MENUDATA
# Create the struct.
item = struct.pack(
menuinfo_fmt,
struct.calcsize(menuinfo_fmt), # cbSize
fMask,
dwStyle,
cyMax,
hbrBack,
dwContextHelpID,
dwMenuData)
return array.array("c", item)
def UnpackMENUINFO(s):
(cb,
fMask,
dwStyle,
cyMax,
hbrBack,
dwContextHelpID,
dwMenuData) = struct.unpack(menuinfo_fmt, s)
assert cb==len(s)
if fMask & win32con.MIM_STYLE==0: dwStyle = None
if fMask & win32con.MIM_MAXHEIGHT==0: cyMax = None
if fMask & win32con.MIM_BACKGROUND==0: hbrBack = None
if fMask & win32con.MIM_HELPID==0: dwContextHelpID = None
if fMask & win32con.MIM_MENUDATA==0: dwMenuData = None
return dwStyle, cyMax, hbrBack, dwContextHelpID, dwMenuData
def EmptyMENUINFO(mask = None):
if mask is None:
mask = win32con.MIM_STYLE | win32con.MIM_MAXHEIGHT| \
win32con.MIM_BACKGROUND | win32con.MIM_HELPID | \
win32con.MIM_MENUDATA
buf = struct.pack(
menuinfo_fmt,
struct.calcsize(menuinfo_fmt), # cbSize
mask,
0, #dwStyle
0, #cyMax
0, #hbrBack,
0, #dwContextHelpID,
0, #dwMenuData,
)
return array.array("c", buf)
##########################################################################
#
# Tree View structure support - TVITEM, TVINSERTSTRUCT and TVDISPINFO
#
##########################################################################
# XXX - Note that the following implementation of TreeView structures is ripped
# XXX - from the SpamBayes project. It may not quite work correctly yet - I
# XXX - intend checking them later - but having them is better than not at all!
# Helpers for the ugly win32 structure packing/unpacking
# XXX - Note that functions using _GetMaskAndVal run 3x faster if they are
# 'inlined' into the function - see PackLVITEM. If the profiler points at
# _GetMaskAndVal(), you should nuke it (patches welcome once they have been
# tested)
def _GetMaskAndVal(val, default, mask, flag):
if val is None:
return mask, default
else:
if flag is not None:
mask |= flag
return mask, val
def PackTVINSERTSTRUCT(parent, insertAfter, tvitem):
tvitem_buf, extra = PackTVITEM(*tvitem)
tvitem_buf = tvitem_buf.tostring()
format = "ii%ds" % len(tvitem_buf)
return struct.pack(format, parent, insertAfter, tvitem_buf), extra
def PackTVITEM(hitem, state, stateMask, text, image, selimage, citems, param):
extra = [] # objects we must keep references to
mask = 0
mask, hitem = _GetMaskAndVal(hitem, 0, mask, commctrl.TVIF_HANDLE)
mask, state = _GetMaskAndVal(state, 0, mask, commctrl.TVIF_STATE)
if not mask & commctrl.TVIF_STATE:
stateMask = 0
mask, text = _GetMaskAndVal(text, None, mask, commctrl.TVIF_TEXT)
mask, image = _GetMaskAndVal(image, 0, mask, commctrl.TVIF_IMAGE)
mask, selimage = _GetMaskAndVal(selimage, 0, mask, commctrl.TVIF_SELECTEDIMAGE)
mask, citems = _GetMaskAndVal(citems, 0, mask, commctrl.TVIF_CHILDREN)
mask, param = _GetMaskAndVal(param, 0, mask, commctrl.TVIF_PARAM)
if text is None:
text_addr = text_len = 0
else:
if isinstance(text, unicode):
text = text.encode("mbcs")
text_buffer = array.array("c", text+"\0")
extra.append(text_buffer)
text_addr, text_len = text_buffer.buffer_info()
format = "iiiiiiiiii"
buf = struct.pack(format,
mask, hitem,
state, stateMask,
text_addr, text_len, # text
image, selimage,
citems, param)
return array.array("c", buf), extra
# Make a new buffer suitable for querying hitem's attributes.
def EmptyTVITEM(hitem, mask = None, text_buf_size=512):
extra = [] # objects we must keep references to
if mask is None:
mask = commctrl.TVIF_HANDLE | commctrl.TVIF_STATE | commctrl.TVIF_TEXT | \
commctrl.TVIF_IMAGE | commctrl.TVIF_SELECTEDIMAGE | \
commctrl.TVIF_CHILDREN | commctrl.TVIF_PARAM
if mask & commctrl.TVIF_TEXT:
text_buffer = array.array("c", "\0" * text_buf_size)
extra.append(text_buffer)
text_addr, text_len = text_buffer.buffer_info()
else:
text_addr = text_len = 0
format = "iiiiiiiiii"
buf = struct.pack(format,
mask, hitem,
0, 0,
text_addr, text_len, # text
0, 0,
0, 0)
return array.array("c", buf), extra
def UnpackTVITEM(buffer):
item_mask, item_hItem, item_state, item_stateMask, \
item_textptr, item_cchText, item_image, item_selimage, \
item_cChildren, item_param = struct.unpack("10i", buffer)
# ensure only items listed by the mask are valid (except we assume the
# handle is always valid - some notifications (eg, TVN_ENDLABELEDIT) set a
# mask that doesn't include the handle, but the docs explicity say it is.)
if not (item_mask & commctrl.TVIF_TEXT): item_textptr = item_cchText = None
if not (item_mask & commctrl.TVIF_CHILDREN): item_cChildren = None
if not (item_mask & commctrl.TVIF_IMAGE): item_image = None
if not (item_mask & commctrl.TVIF_PARAM): item_param = None
if not (item_mask & commctrl.TVIF_SELECTEDIMAGE): item_selimage = None
if not (item_mask & commctrl.TVIF_STATE): item_state = item_stateMask = None
if item_textptr:
text = win32gui.PyGetString(item_textptr)
else:
text = None
return item_hItem, item_state, item_stateMask, \
text, item_image, item_selimage, \
item_cChildren, item_param
# Unpack the lparm from a "TVNOTIFY" message
def UnpackTVNOTIFY(lparam):
format = "iiii40s40s"
buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam)
hwndFrom, id, code, action, buf_old, buf_new \
= struct.unpack(format, buf)
item_old = UnpackTVITEM(buf_old)
item_new = UnpackTVITEM(buf_new)
return hwndFrom, id, code, action, item_old, item_new
def UnpackTVDISPINFO(lparam):
format = "iii40s"
buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam)
hwndFrom, id, code, buf_item = struct.unpack(format, buf)
item = UnpackTVITEM(buf_item)
return hwndFrom, id, code, item
#
# List view items
def PackLVITEM(item=None, subItem=None, state=None, stateMask=None, text=None, image=None, param=None, indent=None):
extra = [] # objects we must keep references to
mask = 0
# _GetMaskAndVal adds quite a bit of overhead to this function.
if item is None: item = 0 # No mask for item
if subItem is None: subItem = 0 # No mask for sibItem
if state is None:
state = 0
stateMask = 0
else:
mask |= commctrl.LVIF_STATE
if stateMask is None: stateMask = state
if image is None: image = 0
else: mask |= commctrl.LVIF_IMAGE
if param is None: param = 0
else: mask |= commctrl.LVIF_PARAM
if indent is None: indent = 0
else: mask |= commctrl.LVIF_INDENT
if text is None:
text_addr = text_len = 0
else:
mask |= commctrl.LVIF_TEXT
if isinstance(text, unicode):
text = text.encode("mbcs")
text_buffer = array.array("c", text+"\0")
extra.append(text_buffer)
text_addr, text_len = text_buffer.buffer_info()
format = "iiiiiiiiii"
buf = struct.pack(format,
mask, item, subItem,
state, stateMask,
text_addr, text_len, # text
image, param, indent)
return array.array("c", buf), extra
def UnpackLVITEM(buffer):
item_mask, item_item, item_subItem, \
item_state, item_stateMask, \
item_textptr, item_cchText, item_image, \
item_param, item_indent = struct.unpack("10i", buffer)
# ensure only items listed by the mask are valid
if not (item_mask & commctrl.LVIF_TEXT): item_textptr = item_cchText = None
if not (item_mask & commctrl.LVIF_IMAGE): item_image = None
if not (item_mask & commctrl.LVIF_PARAM): item_param = None
if not (item_mask & commctrl.LVIF_INDENT): item_indent = None
if not (item_mask & commctrl.LVIF_STATE): item_state = item_stateMask = None
if item_textptr:
text = win32gui.PyGetString(item_textptr)
else:
text = None
return item_item, item_subItem, item_state, item_stateMask, \
text, item_image, item_param, item_indent
# Unpack an "LVNOTIFY" message
def UnpackLVDISPINFO(lparam):
format = "iii40s"
buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam)
hwndFrom, id, code, buf_item = struct.unpack(format, buf)
item = UnpackLVITEM(buf_item)
return hwndFrom, id, code, item
def UnpackLVNOTIFY(lparam):
format = "3i8i"
buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam)
hwndFrom, id, code, item, subitem, newstate, oldstate, \
changed, pt_x, pt_y, lparam = struct.unpack(format, buf)
return hwndFrom, id, code, item, subitem, newstate, oldstate, \
changed, (pt_x, pt_y), lparam
# Make a new buffer suitable for querying an items attributes.
def EmptyLVITEM(item, subitem, mask = None, text_buf_size=512):
extra = [] # objects we must keep references to
if mask is None:
mask = commctrl.LVIF_IMAGE | commctrl.LVIF_INDENT | commctrl.LVIF_TEXT | \
commctrl.LVIF_PARAM | commctrl.LVIF_STATE
if mask & commctrl.LVIF_TEXT:
text_buffer = array.array("c", "\0" * text_buf_size)
extra.append(text_buffer)
text_addr, text_len = text_buffer.buffer_info()
else:
text_addr = text_len = 0
format = "iiiiiiiiii"
buf = struct.pack(format,
mask, item, subitem,
0, 0,
text_addr, text_len, # text
0, 0, 0)
return array.array("c", buf), extra
# List view column structure
def PackLVCOLUMN(fmt=None, cx=None, text=None, subItem=None, image=None, order=None):
extra = [] # objects we must keep references to
mask = 0
mask, fmt = _GetMaskAndVal(fmt, 0, mask, commctrl.LVCF_FMT)
mask, cx = _GetMaskAndVal(cx, 0, mask, commctrl.LVCF_WIDTH)
mask, text = _GetMaskAndVal(text, None, mask, commctrl.LVCF_TEXT)
mask, subItem = _GetMaskAndVal(subItem, 0, mask, commctrl.LVCF_SUBITEM)
mask, image = _GetMaskAndVal(image, 0, mask, commctrl.LVCF_IMAGE)
mask, order= _GetMaskAndVal(order, 0, mask, commctrl.LVCF_ORDER)
if text is None:
text_addr = text_len = 0
else:
if isinstance(text, unicode):
text = text.encode("mbcs")
text_buffer = array.array("c", text+"\0")
extra.append(text_buffer)
text_addr, text_len = text_buffer.buffer_info()
format = "iiiiiiii"
buf = struct.pack(format,
mask, fmt, cx,
text_addr, text_len, # text
subItem, image, order)
return array.array("c", buf), extra
def UnpackLVCOLUMN(lparam):
format = "iiiiiiii"
mask, fmt, cx, text_addr, text_size, subItem, image, order = \
struct.unpack(format, lparam)
# ensure only items listed by the mask are valid
if not (mask & commctrl.LVCF_FMT): fmt = None
if not (mask & commctrl.LVCF_WIDTH): cx = None
if not (mask & commctrl.LVCF_TEXT): text_addr = text_size = None
if not (mask & commctrl.LVCF_SUBITEM): subItem = None
if not (mask & commctrl.LVCF_IMAGE): image = None
if not (mask & commctrl.LVCF_ORDER): order = None
if text_addr:
text = win32gui.PyGetString(text_addr)
else:
text = None
return fmt, cx, text, subItem, image, order
# Make a new buffer suitable for querying an items attributes.
def EmptyLVCOLUMN(mask = None, text_buf_size=512):
extra = [] # objects we must keep references to
if mask is None:
mask = commctrl.LVCF_FMT | commctrl.LVCF_WIDTH | commctrl.LVCF_TEXT | \
commctrl.LVCF_SUBITEM | commctrl.LVCF_IMAGE | commctrl.LVCF_ORDER
if mask & commctrl.LVCF_TEXT:
text_buffer = array.array("c", "\0" * text_buf_size)
extra.append(text_buffer)
text_addr, text_len = text_buffer.buffer_info()
else:
text_addr = text_len = 0
format = "iiiiiiii"
buf = struct.pack(format,
mask, 0, 0,
text_addr, text_len, # text
0, 0, 0)
return array.array("c", buf), extra
# List view hit-test.
def PackLVHITTEST(pt):
format = "iiiii"
buf = struct.pack(format,
pt[0], pt[1],
0, 0, 0)
return array.array("c", buf), None
def UnpackLVHITTEST(buf):
format = "iiiii"
x, y, flags, item, subitem = struct.unpack(format, buf)
return (x,y), flags, item, subitem
def PackHDITEM(cxy = None, text = None, hbm = None, fmt = None,
param = None, image = None, order = None):
extra = [] # objects we must keep references to
mask = 0
mask, cxy = _GetMaskAndVal(cxy, 0, mask, commctrl.HDI_HEIGHT)
mask, text = _GetMaskAndVal(text, None, mask, commctrl.LVCF_TEXT)
mask, hbm = _GetMaskAndVal(hbm, 0, mask, commctrl.HDI_BITMAP)
mask, fmt = _GetMaskAndVal(fmt, 0, mask, commctrl.HDI_FORMAT)
mask, param = _GetMaskAndVal(param, 0, mask, commctrl.HDI_LPARAM)
mask, image = _GetMaskAndVal(image, 0, mask, commctrl.HDI_IMAGE)
mask, order = _GetMaskAndVal(order, 0, mask, commctrl.HDI_ORDER)
if text is None:
text_addr = text_len = 0
else:
if isinstance(text, unicode):
text = text.encode("mbcs")
text_buffer = array.array("c", text+"\0")
extra.append(text_buffer)
text_addr, text_len = text_buffer.buffer_info()
format = "iiiiiiiiiii"
buf = struct.pack(format,
mask, cxy, text_addr, hbm, text_len,
fmt, param, image, order, 0, 0)
return array.array("c", buf), extra
# Device notification stuff
# Generic function for packing a DEV_BROADCAST_* structure - generally used
# by the other PackDEV_BROADCAST_* functions in this module.
def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=''):
# It seems a requirement is 4 byte alignment, even for the 'BYTE data[1]'
# field (eg, that would make DEV_BROADCAST_HANDLE 41 bytes, but we must
# be 44.
extra_data += '\0' * (4-len(extra_data)%4)
format = "iii" + rest_fmt
full_size = struct.calcsize(format) + len(extra_data)
data = (full_size, devicetype, 0) + rest_data
return struct.pack(format, *data) + extra_data
def PackDEV_BROADCAST_HANDLE(handle, hdevnotify=0, guid="\0"*16, name_offset=0, data="\0"):
return PackDEV_BROADCAST(win32con.DBT_DEVTYP_HANDLE, "PP16sl",
(long(handle), long(hdevnotify), str(buffer(guid)), name_offset),
data)
def PackDEV_BROADCAST_DEVICEINTERFACE(classguid, name=""):
rest_fmt = "16s%ds" % len(name)
# str(buffer(iid)) hoops necessary to get the raw IID bytes.
rest_data = (str(buffer(pywintypes.IID(classguid))), name)
return PackDEV_BROADCAST(win32con.DBT_DEVTYP_DEVICEINTERFACE, rest_fmt, rest_data)
# An object returned by UnpackDEV_BROADCAST.
class DEV_BROADCAST_INFO:
def __init__(self, devicetype, **kw):
self.devicetype = devicetype
self.__dict__.update(kw)
def __str__(self):
return "DEV_BROADCAST_INFO:" + str(self.__dict__)
# Support for unpacking the 'lparam'
def UnpackDEV_BROADCAST(lparam):
# guard for 0 here, otherwise PyMakeBuffer will create a new buffer.
if lparam == 0:
return None
hdr_size = struct.calcsize("iii")
hdr_buf = win32gui.PyMakeBuffer(hdr_size, lparam)
size, devtype, reserved = struct.unpack("iii", hdr_buf)
rest = win32gui.PyMakeBuffer(size-hdr_size, lparam+hdr_size)
extra = x = {}
if devtype == win32con.DBT_DEVTYP_HANDLE:
# 2 handles, a GUID, a LONG and possibly an array following...
fmt = "PP16sl"
x['handle'], x['hdevnotify'], guid_bytes, x['nameoffset'] = \
struct.unpack(fmt, rest[:struct.calcsize(fmt)])
x['eventguid'] = pywintypes.IID(guid_bytes, True)
elif devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE:
# guid, null-terminated name
x['classguid'] = pywintypes.IID(rest[:16], 1)
name = rest[16:]
if '\0' in name:
name = name.split('\0', 1)[0]
x['name'] = name
elif devtype == win32con.DBT_DEVTYP_VOLUME:
# int mask and flags
x['unitmask'], x['flags'] = struct.unpack("II", rest[:struct.calcsize("II")])
else:
raise NotImplementedError("unknown device type %d" % (devtype,))
return DEV_BROADCAST_INFO(devtype, **extra)
|
python
|
import numpy as np
from numba import njit
@njit
def linspace(x1,x2,n):
'''
Jit compiled version of numpy.linspace().
'''
x = np.zeros(n)
x[0] = x1
x[-1] = x2
for i in range(1,n-1):
x[i] = x[0] + i*(x2-x1)/(n-1)
return x
@njit
def trapezoid(x,y):
'''
Jit compiled version of scipy.integrate.cumulative_trapezoid().
Assumes initial=0.
'''
integrand = np.zeros(len(x))
for i in range(1, len(x)):
integrand[i] = integrand[i-1] + (x[i]-x[i-1])*0.5*(y[i]+y[i-1])
return integrand
@njit
def jit_polyval(poly, x):
'''
Jit compiled version of np.polyval().
'''
n = len(poly)
y = np.ones(len(x))*poly[-1]
exponent = n-1
for i in range(n-1):
y = poly[i] *x**exponent + y
exponent -= 1
return y
def polyval(poly,x):
if not hasattr(x, '__iter__'):
y = float(jit_polyval(poly,np.array([x])))
else:
y = jit_polyval(poly,x)
return y
|
python
|
from setuptools import setup, find_packages
setup(
name='k8sfoams',
version='1.0.2',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
url='https://github.com/mmpyro/k8s-pod-foamtree',
description='K8s pod foamtree visualizer',
author="Michal Marszalek",
author_email="[email protected]",
license='Apache 2.0',
scripts=['k8sfoams'],
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'attrs==21.2.0',
'bandit==1.7.0',
'bitmath==1.3.3.1',
'cachetools==4.2.2',
'certifi==2021.5.30',
'chardet==4.0.0',
'click==8.0.1',
'flake8==3.9.2',
'flask==2.0.1',
'gitdb==4.0.7',
'gitpython==3.1.18',
'google-auth==1.32.1',
'gunicorn==20.1.0',
'idna==2.10',
'iniconfig==1.1.1',
'itsdangerous==2.0.1',
'jinja2==3.0.1',
'kubernetes==17.17.0',
'markupsafe==2.0.1',
'mccabe==0.6.1',
'mock==4.0.3',
'mypy==0.910',
'mypy-extensions==0.4.3',
'oauthlib==3.1.1',
'packaging==21.0',
'pbr==5.6.0',
'pluggy==0.13.1',
'py==1.10.0',
'pyasn1==0.4.8',
'pyasn1-modules==0.2.8',
'pycodestyle==2.7.0',
'pydash==5.0.1',
'pyflakes==2.3.1',
'pyparsing==2.4.7',
'pytest==6.2.4',
'python-dateutil==2.8.1',
'pyyaml==5.4.1',
'requests==2.25.1',
'requests-oauthlib==1.3.0',
'rsa==4.7.2',
'six==1.16.0',
'smmap==4.0.0',
'stevedore==3.3.0',
'toml==0.10.2',
'typing-extensions==3.10.0.0',
'urllib3==1.26.6',
'websocket-client==1.1.0',
'werkzeug==2.0.1',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Scientific/Engineering :: Visualization',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3.8',
],
keywords = ['foamtree', 'k8s', 'visualization']
)
|
python
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2019 Andreas Bunkahle
# Copyright (c) 2019 Bohdan Horbeshko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import numpy as np
import os
from pkg_resources import parse_version
from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO
from enum import Enum
from builtins import bytes
version = "1.3"
"""
Version history:
1.3: Additional flag for BGR2RGB conversion, by default this flag is set and a BGR2RGB color conversion
takes place, better time optimization of color table mapping
1.2: Bug fix for multiple frame gif images, pixel error in frames fixed
1.1: single frame and multiple frame gif images are now supported
1.0: first release just for still single images
"""
if parse_version(ks_version) < parse_version('0.7'):
raise Exception("Incompatible Kaitai Struct Python API: 0.7 or later is required, but you have %s" % (ks_version))
class Gif(KaitaiStruct):
"""GIF (Graphics Interchange Format) is an image file format, developed
in 1987. It became popular in 1990s as one of the main image formats
used in World Wide Web.
GIF format allows encoding of palette-based images up to 256 colors
(each of the colors can be chosen from a 24-bit RGB
colorspace). Image data stream uses LZW (Lempel–Ziv–Welch) lossless
compression.
Over the years, several version of the format were published and
several extensions to it were made, namely, a popular Netscape
extension that allows to store several images in one file, switching
between them, which produces crude form of animation.
Structurally, format consists of several mandatory headers and then
a stream of blocks follows. Blocks can carry additional
metainformation or image data.
"""
class BlockType(Enum):
extension = 33
local_image_descriptor = 44
end_of_file = 59
class ExtensionLabel(Enum):
graphic_control = 249
comment = 254
application = 255
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.hdr = self._root.Header(self._io, self, self._root)
self.logical_screen_descriptor = self._root.LogicalScreenDescriptorStruct(self._io, self, self._root)
if self.logical_screen_descriptor.has_color_table:
self._raw_global_color_table = self._io.read_bytes((self.logical_screen_descriptor.color_table_size * 3))
io = KaitaiStream(BytesIO(self._raw_global_color_table))
self.global_color_table = self._root.ColorTable(io, self, self._root)
self.blocks = []
i = 0
while True:
_ = self._root.Block(self._io, self, self._root)
self.blocks.append(_)
if ((self._io.is_eof()) or (_.block_type == self._root.BlockType.end_of_file)) :
break
i += 1
class ImageData(KaitaiStruct):
"""
.. seealso::
- section 22 - https://www.w3.org/Graphics/GIF/spec-gif89a.txt
"""
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.lzw_min_code_size = self._io.read_u1()
self.subblocks = self._root.Subblocks(self._io, self, self._root)
class ColorTableEntry(KaitaiStruct):
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.red = self._io.read_u1()
self.green = self._io.read_u1()
self.blue = self._io.read_u1()
class LogicalScreenDescriptorStruct(KaitaiStruct):
"""
.. seealso::
- section 18 - https://www.w3.org/Graphics/GIF/spec-gif89a.txt
"""
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.screen_width = self._io.read_u2le()
self.screen_height = self._io.read_u2le()
self.flags = self._io.read_u1()
self.bg_color_index = self._io.read_u1()
self.pixel_aspect_ratio = self._io.read_u1()
@property
def has_color_table(self):
if hasattr(self, '_m_has_color_table'):
return self._m_has_color_table if hasattr(self, '_m_has_color_table') else None
self._m_has_color_table = (self.flags & 128) != 0
return self._m_has_color_table if hasattr(self, '_m_has_color_table') else None
@property
def color_table_size(self):
if hasattr(self, '_m_color_table_size'):
return self._m_color_table_size if hasattr(self, '_m_color_table_size') else None
self._m_color_table_size = (2 << (self.flags & 7))
return self._m_color_table_size if hasattr(self, '_m_color_table_size') else None
class LocalImageDescriptor(KaitaiStruct):
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.left = self._io.read_u2le()
self.top = self._io.read_u2le()
self.width = self._io.read_u2le()
self.height = self._io.read_u2le()
self.flags = self._io.read_u1()
if self.has_color_table:
self._raw_local_color_table = self._io.read_bytes((self.color_table_size * 3))
io = KaitaiStream(BytesIO(self._raw_local_color_table))
self.local_color_table = self._root.ColorTable(io, self, self._root)
self.image_data = self._root.ImageData(self._io, self, self._root)
@property
def has_color_table(self):
if hasattr(self, '_m_has_color_table'):
return self._m_has_color_table if hasattr(self, '_m_has_color_table') else None
self._m_has_color_table = (self.flags & 128) != 0
return self._m_has_color_table if hasattr(self, '_m_has_color_table') else None
@property
def has_interlace(self):
if hasattr(self, '_m_has_interlace'):
return self._m_has_interlace if hasattr(self, '_m_has_interlace') else None
self._m_has_interlace = (self.flags & 64) != 0
return self._m_has_interlace if hasattr(self, '_m_has_interlace') else None
@property
def has_sorted_color_table(self):
if hasattr(self, '_m_has_sorted_color_table'):
return self._m_has_sorted_color_table if hasattr(self, '_m_has_sorted_color_table') else None
self._m_has_sorted_color_table = (self.flags & 32) != 0
return self._m_has_sorted_color_table if hasattr(self, '_m_has_sorted_color_table') else None
@property
def color_table_size(self):
if hasattr(self, '_m_color_table_size'):
return self._m_color_table_size if hasattr(self, '_m_color_table_size') else None
self._m_color_table_size = (2 << (self.flags & 7))
return self._m_color_table_size if hasattr(self, '_m_color_table_size') else None
class Block(KaitaiStruct):
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.block_type = self._root.BlockType(self._io.read_u1())
_on = self.block_type
if _on == self._root.BlockType.extension:
self.body = self._root.Extension(self._io, self, self._root)
elif _on == self._root.BlockType.local_image_descriptor:
self.body = self._root.LocalImageDescriptor(self._io, self, self._root)
class ColorTable(KaitaiStruct):
"""
.. seealso::
- section 19 - https://www.w3.org/Graphics/GIF/spec-gif89a.txt
"""
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.entries = []
i = 0
while not self._io.is_eof():
self.entries.append(self._root.ColorTableEntry(self._io, self, self._root))
i += 1
class Header(KaitaiStruct):
"""
.. seealso::
- section 17 - https://www.w3.org/Graphics/GIF/spec-gif89a.txt
"""
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.magic = self._io.ensure_fixed_contents(b"\x47\x49\x46")
self.version = (self._io.read_bytes(3)).decode(u"ASCII")
class ExtGraphicControl(KaitaiStruct):
"""
.. seealso::
- section 23 - https://www.w3.org/Graphics/GIF/spec-gif89a.txt
"""
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.block_size = self._io.ensure_fixed_contents(b"\x04")
self.flags = self._io.read_u1()
self.delay_time = self._io.read_u2le()
self.transparent_idx = self._io.read_u1()
self.terminator = self._io.ensure_fixed_contents(b"\x00")
@property
def transparent_color_flag(self):
if hasattr(self, '_m_transparent_color_flag'):
return self._m_transparent_color_flag if hasattr(self, '_m_transparent_color_flag') else None
self._m_transparent_color_flag = (self.flags & 1) != 0
return self._m_transparent_color_flag if hasattr(self, '_m_transparent_color_flag') else None
@property
def user_input_flag(self):
if hasattr(self, '_m_user_input_flag'):
return self._m_user_input_flag if hasattr(self, '_m_user_input_flag') else None
self._m_user_input_flag = (self.flags & 2) != 0
return self._m_user_input_flag if hasattr(self, '_m_user_input_flag') else None
class Subblock(KaitaiStruct):
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.num_bytes = self._io.read_u1()
self.bytes = self._io.read_bytes(self.num_bytes)
class ExtApplication(KaitaiStruct):
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.application_id = self._root.Subblock(self._io, self, self._root)
self.subblocks = []
i = 0
while True:
_ = self._root.Subblock(self._io, self, self._root)
self.subblocks.append(_)
if _.num_bytes == 0:
break
i += 1
class Subblocks(KaitaiStruct):
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.entries = []
i = 0
while True:
_ = self._root.Subblock(self._io, self, self._root)
self.entries.append(_)
if _.num_bytes == 0:
break
i += 1
class Extension(KaitaiStruct):
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self._read()
def _read(self):
self.label = self._root.ExtensionLabel(self._io.read_u1())
_on = self.label
if _on == self._root.ExtensionLabel.application:
self.body = self._root.ExtApplication(self._io, self, self._root)
elif _on == self._root.ExtensionLabel.comment:
self.body = self._root.Subblocks(self._io, self, self._root)
elif _on == self._root.ExtensionLabel.graphic_control:
self.body = self._root.ExtGraphicControl(self._io, self, self._root)
else:
self.body = self._root.Subblocks(self._io, self, self._root)
#================================================================
# Bit-level operations
#================================================================
class BitReader(object):
'''Reads bits from a byte string'''
__slots__ = [
"_str",
"_ptr",
"_len",
]
#------------------------------------------------
# Construction
#------------------------------------------------
def __init__(self, byte_string):
'''Initialize the reader with a complete byte string'''
if not isinstance(byte_string, bytes):
raise TypeError("Requires bytelike object")
self._str = bytes(byte_string)
self._ptr = 0
self._len = len(byte_string) * 8
#------------------------------------------------
# Bit operations
#------------------------------------------------
def read(self, amount):
'''Read bits from the byte string and returns int'''
#--- Initialize indices ---
byte_start, start = divmod(self._ptr, 8)
byte_end, end = divmod(min(self._ptr+amount, self._len), 8)
#Error check
if byte_start > self._len:
return 0
#--- Read bits ---
if byte_start == byte_end:
#Reading from one byte
byte = self._str[byte_start]
if start:
byte >>= start
byte &= ~(-1 << (end - start))
#Adjust pointer
self._ptr = (byte_end << 3) | end
bit_str = byte
else:
#Reading from many bytes
bit_str = 0
bit_index = 0
i = byte_start
#Read remaining piece of the start
if start:
bit_str |= self._str[i] >> start
bit_index += (8 - start)
i += 1
#Grab entire bytes if necessary
while i < byte_end:
bit_str |= (self._str[i] << bit_index)
bit_index += 8
i += 1
#Read beginning piece of end byte
if end:
byte = self._str[i] & (~(-1 << end))
bit_str |= (byte << bit_index)
bit_index += end
#--- Update pointer ---
self._ptr = (byte_end << 3) | end
return bit_str
def cvtColor(image):
"converts color from BGR to RGB and BGRA to RGBA and vice versa"
if len(image.shape)>=3:
np8_image = image.astype(np.uint8)
if image.shape[2] == 3:
b, g, r = np.dsplit(np8_image, np8_image.shape[-1])
return np.dstack([r, g, b])
elif image.shape[2] == 4:
b, g, r, a = np.dsplit(np8_image, np8_image.shape[-1])
return np.dstack([r, g, b, a])
return image
#================================================================
# LZW compression algorithms
#================================================================
def lzw_decompress(raw_bytes, lzw_min):
'''Decompress the LZW data and yields output'''
#Initialize streams
code_in = BitReader(raw_bytes)
idx_out = []
#Set up bit reading
bit_size = lzw_min + 1
bit_inc = (1 << (bit_size)) - 1
#Initialize special codes
CLEAR = 1 << lzw_min
END = CLEAR + 1
code_table_len = END + 1
#Begin reading codes
code_last = -1
while code_last != END:
#Get the next code id
code_id = code_in.read(bit_size)
#Check the next code
if code_id == CLEAR:
#Reset size readers
bit_size = lzw_min + 1
bit_inc = (1 << (bit_size)) - 1
code_last = -1
#Clear the code table
code_table = [-1] * code_table_len
for x in range(code_table_len):
code_table[x] = (x,)
elif code_id == END:
#End parsing
break
elif code_id < len(code_table) and code_table[code_id] is not None:
current = code_table[code_id]
#Table has code_id - output code
idx_out.extend(current)
k = (current[0],)
elif code_last not in (-1, CLEAR, END):
previous = code_table[code_last]
#Code not in table
k = (previous[0],)
idx_out.extend(previous + k)
#Check increasing the bit size
if len(code_table) == bit_inc and bit_size < 12:
bit_size += 1
bit_inc = (1 << (bit_size)) - 1
#Update the code table with previous + k
if code_last not in (-1, CLEAR, END):
code_table.append(code_table[code_last] + k)
code_last = code_id
return idx_out
def paste(mother, child, x, y):
"Pastes the numpy image child into the numpy image mother at position (x, y)"
size = mother.shape
csize = child.shape
if y+csize[0]<0 or x+csize[1]<0 or y>size[0] or x>size[1]: return mother
sel = [int(y), int(x), csize[0], csize[1]]
csel = [0, 0, csize[0], csize[1]]
if y<0:
sel[0] = 0
sel[2] = csel[2] + y
csel[0] = -y
elif y+sel[2]>=size[0]:
sel[2] = int(size[0])
csel[2] = size[0]-y
else:
sel[2] = sel[0] + sel[2]
if x<0:
sel[1] = 0
sel[3] = csel[3] + x
csel[1] = -x
elif x+sel[3]>=size[1]:
sel[3] = int(size[1])
csel[3] = size[1]-x
else:
sel[3] = sel[1] + sel[3]
childpart = child[csel[0]:csel[2], csel[1]:csel[3]]
mother[sel[0]:sel[2], sel[1]:sel[3]] = childpart
return mother
def convert(gif_filename, BGR2RGB=True):
"""converts an image specified by its filename gif_filename to a numpy image
if BGR2RGB is True (default) there will also be a color conversion from BGR to RGB"""
if not os.path.isfile(gif_filename):
raise IOError("File does not exist")
frames = []
frames_specs = []
image_specs = {}
gifread = open(gif_filename, "rb")
raw = gifread.read()
gifread.close()
# print(len(raw))
image_specs["Length"] = len(raw)
data = Gif(KaitaiStream(BytesIO(raw)))
# print("Header", data.hdr.magic, data.hdr.version)
image_specs["Header"] = str(data.hdr.magic).replace("b'", "").strip("'") + " " + str(data.hdr.version)
lsd = data.logical_screen_descriptor
image_width = lsd.screen_width
image_height = lsd.screen_height
# print("Color table size", repr(lsd.color_table_size), "Has color table", lsd.has_color_table, "Image width", image_width, "image height", image_height, "Flags", lsd.flags, "Background color", lsd.bg_color_index, "Pixel aspect ratio", lsd.pixel_aspect_ratio)
image_specs["Color table size"] = lsd.color_table_size
image_specs["Color table existing"] = lsd.has_color_table
image_specs["Image Size"] = image_width, image_height
image_specs["Flags"] = lsd.flags
image_specs["Background Color"] = lsd.bg_color_index
image_specs["Pixel Aspect Ratio"] = lsd.pixel_aspect_ratio
# print("Color table length", len(data.global_color_table.entries))
image_specs["Color table length"] = len(data.global_color_table.entries)
gcte = data.global_color_table.entries
color_table = []
for i in range(len(gcte)):
color_table.append((gcte[i].red, gcte[i].green, gcte[i].blue))
# print("Color table values", color_table)
image_specs["Color table values"] = color_table
# print(len(data.blocks))
image_specs["Data Blocks count"] = len(data.blocks)
frames = []
exts = []
first_frame = True
for i in range(len(data.blocks)):
# print("Block_type", data.blocks[i].block_type, "block_count:", i)
if data.blocks[i].block_type == Gif.BlockType.local_image_descriptor:
imgdata = data.blocks[i].body.image_data
left = data.blocks[i].body.left
top = data.blocks[i].body.top
width = data.blocks[i].body.width
height = data.blocks[i].body.height
flags = data.blocks[i].body.flags
has_color_table = data.blocks[i].body.has_color_table
if has_color_table:
local_color_table = data.blocks[i].body.local_color_table
lzw_min = imgdata.lzw_min_code_size
if exts == []:
exts.append({})
exts[-1]["left"] = left
exts[-1]["top"] = top
exts[-1]["width"] = width
exts[-1]["height"] = height
exts[-1]["flags1"] = flags
exts[-1]["has_color_table"] = has_color_table
if has_color_table:
exts[-1]["local_color_table"] = local_color_table
exts[-1]["lzw_min"] = lzw_min
all_bytes = b""
alle = 0
for j in range(len(imgdata.subblocks.entries)):
# print(imgdata.subblocks.entries[i].num_bytes, sep=" ", end=", ")
block_len = imgdata.subblocks.entries[j].num_bytes
alle = alle + block_len
# print(len(imgdata.subblocks.entries[i].bytes), repr(imgdata.subblocks.entries[i].bytes))
all_bytes = all_bytes + imgdata.subblocks.entries[j].bytes
# print("alle", alle)
# print(len(all_bytes))
# print("single frame attr at block no.:", i, left, top, width, height, flags, has_color_table, lzw_min)
# if has_color_table:
# print(local_color_table)
uncompressed = lzw_decompress(all_bytes, lzw_min)
np_len = len(uncompressed)
# print("Uncompressed image: type/length, image_data[:100]", type(uncompressed), np_len, uncompressed[:100])
if len(color_table[0])==1:
np_image = np.zeros((np_len), dtype=np.uint8)
channels = 1
elif len(color_table[0])==2:
np_image = np.zeros((np_len*2), dtype=np.uint8)
channels = 2
elif len(color_table[0])==3:
np_image = np.zeros((np_len*3), dtype=np.uint8)
channels = 3
elif len(color_table[0])==4:
np_image = np.zeros((np_len*4), dtype=np.uint8)
channels = 4
if has_color_table:
np_image = np.array([local_color_table[byt] if byt != exts[-1]['transparent_idx'] else (254, 0, 254) for byt in uncompressed])
else:
np_image = np.array([color_table[byt] if byt != exts[-1]['transparent_idx'] else (254, 0, 254) for byt in uncompressed])
# print("image_height, image_width, channels", image_height, image_width, channels)
np_image = np.reshape(np_image, (height, width, channels))
# print(np_image.shape, np_image[329-height,329-width,0])
if BGR2RGB:
if channels == 3 or channels == 4:
np_image = cvtColor(np_image)
else:
np_image = np_image.astype(np.uint8)
else:
np_image = np_image.astype(np.uint8)
if len(exts) > 1:
displace_flags = (exts[-2]['flags'] >> 2) & 7
if displace_flags == 2:
first_frame = True
if first_frame:
first_frame = False
frame1 = np_image.copy()
else:
old_frame = frames[-1].copy()
if has_color_table:
if BGR2RGB:
transp_idx = local_color_table[exts[-1]['transparent_idx']][::-1] # RGB -> BGR
else:
transp_idx = local_color_table[exts[-1]['transparent_idx']] # RGB -> RGB
else:
if BGR2RGB:
transp_idx = color_table[exts[-1]['transparent_idx']][::-1] # RGB -> BGR
else:
transp_idx = color_table[exts[-1]['transparent_idx']] # RGB -> RGB
transp_idx = np.array(transp_idx)
# cv2.imshow("old_frame", old_frame)
new_frame = paste(frame1.copy(), np_image, exts[-1]['left'], exts[-1]['top'])
# cv2.imshow("new_frame", new_frame)
f = np.all((new_frame==transp_idx), axis=-1)
flattened_image = np.reshape(new_frame, (new_frame.shape[0]*new_frame.shape[1], channels))
old_flattened_image = np.reshape(old_frame, (old_frame.shape[0]*old_frame.shape[1], channels))
f = np.reshape(f, (old_frame.shape[0]*old_frame.shape[1], 1))
np_image = np.array([old_flattened_image[i] if j else flattened_image[i] for i, j in enumerate(f)])
np_image = np.reshape(np_image, (old_frame.shape[0], old_frame.shape[1], channels))
# cv2.imshow("last_frame", np_image)
# cv2.waitKey()
frames.append(np_image)
elif data.blocks[i].block_type == Gif.BlockType.extension:
label = data.blocks[i].body.label
# print("label of extension", label)
if label == Gif.ExtensionLabel.graphic_control:
body = data.blocks[i].body.body
# print("body, label of extension", body, label)
block_size = data.blocks[i].body.body.block_size
flags = data.blocks[i].body.body.flags
delay_time = data.blocks[i].body.body.delay_time
transparent_idx = data.blocks[i].body.body.transparent_idx
terminator = data.blocks[i].body.body.terminator
frame_count = len(frames)
ext_dict = {"block_size": block_size, "flags": flags, "delay_time": delay_time, "transparent_idx": transparent_idx, "terminator": terminator}
exts.append(ext_dict)
# print(i, "block_size, flags, delay_time, transparent_idx, terminator", block_size, flags, delay_time, transparent_idx, terminator)
elif label == Gif.ExtensionLabel.application:
application_id = data.blocks[i].body.body.application_id
subblocks = data.blocks[i].body.body.subblocks
image_specs["application_id"] = application_id.bytes
for k in range(len(subblocks)):
image_specs["application_subblocks"+str(k)] = subblocks[k].bytes
elif label == Gif.ExtensionLabel.comment:
subblocks = data.blocks[i].body.body
image_specs["comment"] = b"".join([b.bytes for b in subblocks.entries])
else: # data.blocks[i].block_type == Gif.BlockType.end_of_file
pass
return frames, exts, image_specs
if __name__ == '__main__':
import cv2
images = "Images/hopper.gif", "Images/audrey.gif", "Images/Rotating_earth.gif", "Images/testcolors.gif"
for image in images:
frames, exts, image_specs = convert(image)
print()
print("Image:", image)
print()
print("len frames", len(frames))
print("len exts", len(exts))
print("exts:", exts)
print("image_specs:", image_specs)
for i in range(len(frames)):
cv2.imshow("np_image", frames[i])
print(exts[i])
k = cv2.waitKey(0)
if k == 27:
break
cv2.destroyWindow("np_image")
|
python
|
import threading
import datetime
from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan
import pandas as pd
import numpy as np
import time
from functools import reduce
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
import dash_html_components as html
import model.queries as qrs
from model.DataLoader import SiteDataLoader
class SiteReport(object):
def __init__(self):
self.sobj = SiteDataLoader()
self.sites = self.sobj.sites
def generateIPTable(self, site, test_method, df):
ipv6 = len(df[(df['is_ipv6']==True)])
ipv4 = len(df[(df['is_ipv6']==False)])
return html.Table(
# Header
[html.Tr([html.Th(f"{test_method.capitalize()} hosts", colSpan='4', className=f"{test_method}-head")]) ] +
# Body
[html.Tr([
html.Td([col], colSpan='2', className='ipv-type') for col in ['IPv4', 'IPv6']
]) ] +
[html.Tr([
html.Td([col], colSpan='2', className='ipv-count') for col in [ipv4, ipv6]
]) ],
className='ip-table'
)
def get2dayValue(self, dff, site, test_type):
val = dff['day_val']
if (len(val.values) > 0) and (val.isnull().values.any() == False):
if test_type == 'throughput':
return round(dff['day_val'].values[0]/1e+6, 2)
return dff['day_val'].values[0]
else: return 'N/A'
def getChangeVals(self, dfm, direction, site):
if len(dfm[['day-2', 'day-1', 'day']].values) > 0:
vals = dfm[['day-2', 'day-1', 'day']].values[0]
data = dfm[['day-2', 'day-1', 'day']]
vals = list(data.applymap(lambda x: "+"+str(x) if x>0 else x).values[0])
vals.insert(0, direction)
return vals
else: return [direction, 'N/A', 'N/A', 'N/A']
def getUnit(self, test_type):
if (test_type in ['packetloss', 'retransmits']):
return 'packets'
elif (test_type == 'throughput'):
return 'MBps'
elif (test_type == 'owd'):
return 'ms'
def generateTable(self, site, test_type, df, dates):
# there is no value for the first day of the period since
# there is no data for the previous day to comapre with
dates[0] = ''
meas_type = (test_type).upper()
dfin = df[df['direction']=='IN']
dfout = df[df['direction']=='OUT']
ch_in = self.getChangeVals(dfin, 'IN', site)
ch_out = self.getChangeVals(dfout, 'OUT', site)
val_in = self.get2dayValue(dfin, site, test_type)
val_out = self.get2dayValue(dfout, site, test_type)
unit = self.getUnit(test_type)
return html.Table(
# Header
[html.Tr([html.Th(f"{meas_type} ({unit})", colSpan='4', className=f"{test_type}-tests")]) ] +
# Body
[html.Tr([
html.Td([col], colSpan='2', className='inout-type') for col in ['TODAY IN', 'TODAY OUT']
]) ] +
[html.Tr([
html.Td(val_in, colSpan='2', className='inout-value'),
html.Td(val_out, colSpan='2', className='inout-value')
]) ]+
[html.Tr(
html.Td('Change over the past 3 days (%)', colSpan='4', className='change-title'),
) ] +
[html.Tr([
html.Td(col) for col in dates
], className='change-values') ] +
[html.Tr([
html.Td(col) for col in ch_in
], className='change-values') ] +
[html.Tr([
html.Td(col) for col in ch_out
], className='change-values') ], className=f'{test_type}'
)
def createCard(self, site):
sobj = self.sobj
return dbc.Card(
dbc.CardBody(
[
dbc.Row([
dbc.Col([
html.H4(site, id=f"{site}-title", className='site-title')
], width=12)
], justify="left"),
dbc.Row([
dbc.Col([
self.generateIPTable(site, 'latency', sobj.genData.latency_df_related_only[sobj.latency_df_related_only['site']==site]),
self.generateTable(site, 'packetloss', sobj.pls_data[sobj.pls_data['site']==site], sobj.pls_dates),
], width=6, className='left'),
dbc.Col([
self.generateIPTable(site, 'throughput', sobj.genData.throughput_df_related_only[sobj.throughput_df_related_only['site']==site]),
self.generateTable(site, 'throughput', sobj.thp_data[sobj.thp_data['site']==site], sobj.thp_dates)
], width=6, className='right'),
]),
dbc.Row([
dbc.Col([
self.generateTable(site, 'owd', sobj.owd_data[sobj.owd_data['site']==site], sobj.owd_dates)
], width=6, className='left'),
dbc.Col([
self.generateTable(site, 'retransmits', sobj.rtm_data[sobj.rtm_data['site']==site], sobj.rtm_dates)
], width=6, className='right'),
])
]
), id=str(site+'-card')
)
|
python
|
largura = float(input('Qual a largura da parede? '))
altura = float(input('Qual a altura da parede? '))
area = largura*altura
qtd_tinta = area/2
print(qtd_tinta)
|
python
|
import os
from unittest.mock import call
import numpy as np
import pytest
import sparse
from histolab.slide import Slide
from histolab.tiler import RandomTiler, Tiler
from histolab.types import CoordinatePair
from ..unitutil import (
ANY,
PILImageMock,
SparseArrayMock,
function_mock,
initializer_mock,
method_mock,
property_mock,
)
class Describe_RandomTiler(object):
def it_constructs_from_args(self, request):
_init = initializer_mock(request, RandomTiler)
random_tiler = RandomTiler((512, 512), 10, 2, 7, True, "", ".png", 1e4)
_init.assert_called_once_with(ANY, (512, 512), 10, 2, 7, True, "", ".png", 1e4)
assert isinstance(random_tiler, RandomTiler)
assert isinstance(random_tiler, Tiler)
def but_it_has_wrong_tile_size_value(self, request):
with pytest.raises(ValueError) as err:
RandomTiler((512, -1), 10, 0)
assert isinstance(err.value, ValueError)
assert str(err.value) == "Tile size must be greater than 0 ((512, -1))"
def or_it_has_not_available_level_value(self, request, tmpdir):
tmp_path_ = tmpdir.mkdir("myslide")
image = PILImageMock.DIMS_50X50_RGB_RANDOM_COLOR
image.save(os.path.join(tmp_path_, "mywsi.png"), "PNG")
slide_path = os.path.join(tmp_path_, "mywsi.png")
slide = Slide(slide_path, "processed")
random_tiler = RandomTiler((512, 512), 10, 3)
with pytest.raises(ValueError) as err:
random_tiler.extract(slide)
assert isinstance(err.value, ValueError)
assert str(err.value) == "Level 3 not available. Number of available levels: 1"
def or_it_has_negative_level_value(self, request):
with pytest.raises(ValueError) as err:
RandomTiler((512, 512), 10, -1)
assert isinstance(err.value, ValueError)
assert str(err.value) == "Level cannot be negative (-1)"
def or_it_has_wrong_max_iter(self, request):
with pytest.raises(ValueError) as err:
RandomTiler((512, 512), 10, 0, max_iter=3)
assert isinstance(err.value, ValueError)
assert (
str(err.value)
== "The maximum number of iterations (3) must be grater than or equal to the maximum number of tiles (10)."
)
def or_it_has_wrong_seed(self, request, tmpdir):
tmp_path_ = tmpdir.mkdir("myslide")
image = PILImageMock.DIMS_50X50_RGB_RANDOM_COLOR
image.save(os.path.join(tmp_path_, "mywsi.png"), "PNG")
slide_path = os.path.join(tmp_path_, "mywsi.png")
slide = Slide(slide_path, "processed")
random_tiler = RandomTiler((512, 512), 10, 0, seed=-1)
with pytest.raises(ValueError) as err:
random_tiler.extract(slide)
assert isinstance(err.value, ValueError)
assert str(err.value) == "Seed must be between 0 and 2**32 - 1"
@pytest.mark.parametrize("tile_size", ((512, 512), (128, 128), (10, 10)))
def it_knows_its_tile_size(self, request, tile_size):
random_tiler = RandomTiler(tile_size, 10, 0)
tile_size_ = random_tiler.tile_size
assert type(tile_size_) == tuple
assert tile_size_ == tile_size
@pytest.mark.parametrize("max_iter", (1000, 10, 3000))
def it_knows_its_max_iter(self, request, max_iter):
random_tiler = RandomTiler((128, 128), 10, 0, max_iter=max_iter)
max_iter_ = random_tiler.max_iter
assert type(max_iter_) == int
assert max_iter_ == max_iter
def it_knows_its_tile_filename(self, request, tile_filename_fixture):
(
tile_size,
n_tiles,
level,
seed,
check_tissue,
prefix,
suffix,
tile_coords,
tiles_counter,
expected_filename,
) = tile_filename_fixture
random_tiler = RandomTiler(
tile_size, n_tiles, level, seed, check_tissue, prefix, suffix
)
_filename = random_tiler._tile_filename(tile_coords, tiles_counter)
assert type(_filename) == str
assert _filename == expected_filename
def it_can_generate_random_coordinates(self, request, tmpdir):
tmp_path_ = tmpdir.mkdir("myslide")
image = PILImageMock.DIMS_500X500_RGBA_COLOR_155_249_240
image.save(os.path.join(tmp_path_, "mywsi.png"), "PNG")
slide_path = os.path.join(tmp_path_, "mywsi.png")
slide = Slide(slide_path, "processed")
_box_mask_lvl = method_mock(request, RandomTiler, "box_mask_lvl")
_box_mask_lvl.return_value = SparseArrayMock.ONES_500X500_BOOL
_tile_size = property_mock(request, RandomTiler, "tile_size")
_tile_size.return_value = (128, 128)
_np_random_choice1 = function_mock(request, "numpy.random.choice")
_np_random_choice1.return_value = 0
_np_random_choice2 = function_mock(request, "numpy.random.choice")
_np_random_choice2.return_value = 0
_scale_coordinates = function_mock(request, "histolab.tiler.scale_coordinates")
random_tiler = RandomTiler((128, 128), 10, 0)
random_tiler._random_tile_coordinates(slide)
_box_mask_lvl.assert_called_once_with(random_tiler, slide)
_tile_size.assert_has_calls([call((128, 128))])
_scale_coordinates.assert_called_once_with(
reference_coords=CoordinatePair(x_ul=0, y_ul=0, x_br=128, y_br=128),
reference_size=(500, 500),
target_size=(500, 500),
)
@pytest.mark.parametrize(
"check_tissue, expected_box",
(
(False, SparseArrayMock.ONES_500X500_BOOL),
(True, SparseArrayMock.RANDOM_500X500_BOOL),
),
)
def it_knows_its_box_mask(self, request, tmpdir, check_tissue, expected_box):
tmp_path_ = tmpdir.mkdir("myslide")
image = PILImageMock.DIMS_500X500_RGBA_COLOR_155_249_240
image.save(os.path.join(tmp_path_, "mywsi.png"), "PNG")
slide_path = os.path.join(tmp_path_, "mywsi.png")
slide = Slide(slide_path, "processed")
_biggest_tissue_box_mask = property_mock(
request, Slide, "biggest_tissue_box_mask"
)
if check_tissue:
_biggest_tissue_box_mask.return_value = expected_box
random_tiler = RandomTiler((128, 128), 10, 0, check_tissue=check_tissue)
box_mask = random_tiler.box_mask(slide)
if check_tissue:
_biggest_tissue_box_mask.assert_called_once_with()
assert type(box_mask) == sparse._coo.core.COO
np.testing.assert_array_almost_equal(box_mask.todense(), expected_box.todense())
# fixtures -------------------------------------------------------
@pytest.fixture(
params=(
(
(512, 512),
10,
3,
7,
True,
"",
".png",
CoordinatePair(0, 512, 0, 512),
3,
"tile_3_level3_0-512-0-512.png",
),
(
(512, 512),
10,
0,
7,
True,
"folder/",
".png",
CoordinatePair(4, 127, 4, 127),
10,
"folder/tile_10_level0_4-127-4-127.png",
),
)
)
def tile_filename_fixture(self, request):
(
tile_size,
n_tiles,
level,
seed,
check_tissue,
prefix,
suffix,
tile_coords,
tiles_counter,
expected_filename,
) = request.param
return (
tile_size,
n_tiles,
level,
seed,
check_tissue,
prefix,
suffix,
tile_coords,
tiles_counter,
expected_filename,
)
|
python
|
import numpy as np
import pandas as pd
import talib as ta
from cryptotrader.utils import safe_div
def price_relative(obs, period=1):
prices = obs.xs('open', level=1, axis=1).astype(np.float64)
price_relative = prices.apply(ta.ROCR, timeperiod=period, raw=True).fillna(1.0)
return price_relative
def momentum(obs, period=14):
prices = obs.xs('open', level=1, axis=1).astype(np.float64)
# mean_volume = obs.xs('volume', level=1, axis=1).astype(np.float64).apply(lambda x: safe_div(x[-period:-1].sum(),
# x[-int(2 * period):-period].sum()), raw=True)
mom = prices.apply(ta.MOM, timeperiod=period, raw=True).fillna(0.0)
return 1 + safe_div(mom, prices.iloc[-period])# * mean_volume
def tsf(ts, period=14):
tsf = ts.apply(ta.TSF, timeperiod=period, raw=True).fillna(0.0)
return tsf
class OLS(object):
def __init__(self, X, Y):
self.fit(X, Y)
def fit(self, X, Y):
self.ls_coef_ = np.cov(X, Y)[0, 1] / np.var(X)
self.ls_intercept = Y.mean() - self.ls_coef_ * X.mean()
def predict(self, X):
return self.ls_coef_ * X + self.ls_intercept
|
python
|
"""
@author : Krypton Byte
"""
import requests
def igdownload(url):
req=requests.get(url, params={"__a":1})
if ('graphql' in req.text):
media=req.json()["graphql"]["shortcode_media"]
if media.get("is_video"):
return {"status": True,"result":[{"type":"video", "url":media["video_url"]}]}
elif media.get("edge_sidecar_to_children"): #multiple media
med={"status":True, "result":[]}
for i in media["edge_sidecar_to_children"]["edges"]:
med["result"].append( {"type":"video","url":i["node"]["video_url"]} if i["node"]["is_video"] else {"type":"image","url":i["node"]["display_resources"][-1]["src"]})
return med
else: #1 media
return {"status":True,"result":[{"type":"image","url":media["display_resources"][-1]["src"]}]}
else:
return {"status":False}
def igstalker(user):
stalk=requests.get(f"https://www.instagram.com/{user}/",params={"__a":1}).json()
if stalk:
userProperty=stalk["graphql"]["user"]
return {
"pic":userProperty["profile_pic_url_hd"],
"username":userProperty["username"],
"follower":userProperty["edge_followed_by"]["count"],
"following":userProperty["edge_follow"]["count"],
"bio":userProperty["biography"],
"post":userProperty["edge_owner_to_timeline_media"]["count"]
}
else:
return {}
|
python
|
import requests
from bs4 import BeautifulSoup
#https://en.wikipedia.org/wiki/List_of_companies_operating_trains_in_the_United_Kingdom
def main():
urlList = ['https://twitter.com/ScotRail','https://twitter.com/LDNOverground','https://twitter.com/AvantiWestCoast','https://twitter.com/c2c_Rail','https://twitter.com/CalSleeper',
'https://twitter.com/chilternrailway','https://twitter.com/CrossCountryUK','https://twitter.com/EastMidRailway','https://twitter.com/Eurostar','https://twitter.com/TLRailUK',
'https://twitter.com/SouthernRailUK','https://twitter.com/GNRailUK','https://twitter.com/GatwickExpress','https://twitter.com/GC_Rail','https://twitter.com/greateranglia',
'https://twitter.com/GWRHelp','https://twitter.com/HeathrowExpress','https://twitter.com/Hull_Trains','https://twitter.com/LNER','https://twitter.com/merseyrail',
'https://twitter.com/northernassist','https://twitter.com/Se_Railway','https://twitter.com/sw_help','https://twitter.com/TfLRail','https://twitter.com/TPExpressTrains',
'https://twitter.com/tfwrail','https://twitter.com/WestMidRailway']
for url in urlList:
# logoUrl = getImageUrl(url)
x = url.split("/")
name = x[3]
print(name + ".jpg")
# getImageFromUrl(logoUrl, name)
def getImageUrl(url):
r = requests.get(url)
html = r.text
soup = BeautifulSoup(html, 'html.parser')
images = soup.find('img', class_="ProfileAvatar-image")
logoUrl = images['src']
return logoUrl
def getImageFromUrl(url, name):
response = requests.get(url)
if response.status_code == 200:
with open("imgs/{0}.jpg".format(name), 'wb') as f:
f.write(response.content)
if __name__ == "__main__":
main()
|
python
|
# coding: utf-8
nms = ['void',
'Front bumper skin',
'Rear bumper skin',
'Front bumper grille',
'network',
'Hood',
'Front fog lamp',
'Headlamp',
'Front windshield',
'Roof panel',
'Front fender',
'Rear fender',
'Front door shell outer plate',
'Rear door shell outer plate',
'Door glass front',
'Door glass rear',
'Rearview mirror assembly',
'Tires front',
'Tires rear',
'Wheel',
'Luggage cover',
'Rocker outer plate ',
'Rear lamp',
'Rear windshield',
'External spare tire cover',
'Wheel trim cover',
'Front Fender Turn Signal',
'A pillar',
'Rear side glass',
'Front side glass',
'License plate front',
'License plate rear']
import matplotlib.pyplot as plt
from torchvision.utils import make_grid
def decode_seg_map_sequence(label_masks, dataset='coco'):
rgb_masks = []
for label_mask in label_masks:
rgb_mask = decode_segmap(label_mask, dataset)
rgb_masks.append(rgb_mask)
rgb_masks = torch.from_numpy(np.array(rgb_masks).transpose([0, 3, 1, 2]))
return rgb_masks
def decode_segmap(label_mask, dataset, plot=False):
if dataset == 'pascal' or dataset == 'coco':
n_classes = 32
label_colours = get_pascal_labels()
else:
raise NotImplementedError
r = label_mask.copy()
g = label_mask.copy()
b = label_mask.copy()
for ll in range(0, n_classes):
r[label_mask == ll] = label_colours[ll, 0]
g[label_mask == ll] = label_colours[ll, 1]
b[label_mask == ll] = label_colours[ll, 2]
rgb = np.zeros((label_mask.shape[0], label_mask.shape[1], 3))
rgb[:, :, 0] = r / 255.0
rgb[:, :, 1] = g / 255.0
rgb[:, :, 2] = b / 255.0
if plot:
plt.imshow(rgb)
plt.show()
else:
return rgb
def encode_segmap(mask):
mask = mask.astype(int)
label_mask = np.zeros((mask.shape[0], mask.shape[1]), dtype=np.int16)
for ii, label in enumerate(get_pascal_labels()):
label_mask[np.where(np.all(mask == label, axis=-1))[:2]] = ii
label_mask = label_mask.astype(int)
return label_mask
def get_pascal_labels():
return np.asarray([[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],
[0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],
[64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0],
[64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128],
[0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0],
[0, 64, 128], [128, 64, 128], [0, 192, 128], [128, 192, 128],
[0, 0, 64], [0, 0, 192], [128, 0, 64], [128, 0, 192],
[0, 128, 64], [0, 128, 192], [128, 128, 64], [128, 128, 192]])
from fastai.vision import *
#from modeling.sync_batchnorm.replicate import patch_replication_callback
#from modeling.deeplab import *
import matplotlib, time, os
# In[4]:
#torch.cuda.set_device(1)
# In[5]:
start_time = time.time()
print(os.getcwd())
learn = load_learner('G:\\yzh\\zcm','512_deeplab_5.pkl')
# In[6]:
image = open_image('img.jpg')
tfm_image = image.apply_tfms(tfms=None,size=512,)#resize_method=ResizeMethod.PAD,padding_mode='zeros')
# In[20]:
pred = learn.predict(tfm_image)
# In[21]:
"""record = np.zeros((512,512,3))
for i in range(512):
for j in range(512):
record[i,j,:] = rgbList[p[i][j]]
"""
output = pred[2].unsqueeze(0)
grid_image = make_grid(decode_seg_map_sequence(torch.max(output[:3], 1)[1].detach().cpu().numpy()), 3, normalize=False, range=(0, 255))
grid_image = grid_image.numpy()
grid_image = np.moveaxis(grid_image,0,2)
matplotlib.image.imsave('predict.png', grid_image)
# In[22]:
print('ljsdjflkjkldsjkl', time.time() - start_time)
|
python
|
import httpretty
from tests import FulcrumTestCase
class MembershipTest(FulcrumTestCase):
@httpretty.activate
def test_search(self):
httpretty.register_uri(httpretty.GET, self.api_root + '/memberships',
body='{"memberships": [{"id": 1},{"id": 2}], "total_count": 2, "current_page": 1, "total_pages": 1, "per_page": 20000}',
status=200)
memberships = self.fulcrum_api.memberships.search()
self.assertIsInstance(memberships, dict)
self.assertEqual(len(memberships['memberships']), 2)
|
python
|
import pytest
from picorss.src.domain import entities
@pytest.fixture()
def rss_page() -> entities.RssPage:
return entities.RssPage(url="https://example.com")
def test_rss_page_has_url(rss_page: entities.RssPage) -> None:
assert rss_page.url
|
python
|
def process(self):
self.edit("LATIN")
self.replace("CAPITAL LETTER D WITH SMALL LETTER Z", "Dz")
self.replace("CAPITAL LETTER DZ", "DZ")
self.edit("AFRICAN", "african")
self.edit("WITH LONG RIGHT LEG", "long", "right", "leg")
self.edit('LETTER YR', "yr")
self.edit("CAPITAL LETTER O WITH MIDDLE TILDE", "Obar")
self.edit("CAPITAL LETTER SMALL Q WITH HOOK TAIL", "Qsmallhooktail")
self.edit("LETTER REVERSED ESH LOOP", "eshreversedloop")
self.edit("CAPITAL LETTER L WITH SMALL LETTER J", "Lj")
self.edit("CAPITAL LETTER N WITH SMALL LETTER J", "Nj")
self.edit("LETTER INVERTED GLOTTAL STOP WITH STROKE", "glottalinvertedstroke")
self.edit("LETTER TWO WITH STROKE", "twostroke")
self.edit("CAPITAL LETTER LJ", "LJ")
self.edit("CAPITAL LETTER NJ", "NJ")
self.edit("CAPITAL LETTER AE WITH", "AE")
self.edit("CAPITAL LETTER WYNN", "Wynn")
self.edit("LETTER WYNN", "wynn")
self.edit("WITH PALATAL", "palatal")
self.edit("DENTAL", "dental")
self.edit("LATERAL", "lateral")
self.edit("ALVEOLAR", "alveolar")
self.edit("RETROFLEX", "retroflex")
self.replace("LETTER CLICK", "click")
self.forceScriptPrefix("latin", "CAPITAL LETTER GAMMA", "Gamma")
self.forceScriptPrefix("latin", "CAPITAL LETTER IOTA", "Iota")
self.forceScriptPrefix("latin", "CAPITAL LETTER UPSILON", "Upsilon")
self.processAs("Helper Diacritics")
self.processAs("Helper Shapes")
self.handleCase()
self.compress()
if __name__ == "__main__":
from glyphNameFormatter.exporters import printRange
printRange("Latin Extended-B")
|
python
|
#!/usr/bin/env python3
# Write a program that computes typical stats
# Count, Min, Max, Mean, Std. Dev, Median
# No, you cannot import the stats library!
import sys
import math
units = []
#Create your list of integers/floating-point numnbers making sure to covert from strings
for i in sys.argv[1:]:
units.append(float(i))
print('Count:',len(units))
units.sort()
print('Minimum:',units[0])
print('Maximum:',units[-1])
#Using our list of mubers, we want to compute various stats
mean = 0
for j in range(len(units)):
mean = mean + units[j]
print('Mean:',mean/len(units))
rmean = (mean/len(units))
standard = 0
for std in range(len(units)):
standard = (units[std]-rmean)**2 + standard
print('Std.dev:',math.sqrt(standard/len(units)))
for i in units:
mid = len(units)//2
if len(units) % 2 == 1:
median = units[mid]
else:
median = (units[mid]+units[mid-1])/2
print('Median:',median)
"""
python3 stats.py 3 1 4 1 5
Count: 5
Minimum: 1.0
Maximum: 5.0
Mean: 2.800
Std. dev: 1.600
Median 3.000
"""
|
python
|
"""
Copyright (c) 2014, Samsung Electronics Co.,Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of Samsung Electronics Co.,Ltd..
"""
"""
udt4py - libudt4 Cython-ish wrapper.
URL: https://github.com/vmarkovtsev/udt4py
Original author: Vadim Markovtsev <[email protected]>
libudt4 is (c)2001 - 2011, The Board of Trustees of the University of Illinois.
libudt4 URL: http://udt.sourceforge.net/
"""
"""
UDTEpoll tests.
"""
import threading
import time
import unittest
from udt4py import UDTSocket, UDTException, UDTEpoll
class UDTEpollTest(unittest.TestCase):
def testEpoll(self):
self.socket = UDTSocket()
self.socket.bind("0.0.0.0:7015")
self.socket.listen()
other_thread = threading.Thread(target=self.otherConnect)
other_thread.start()
sock, _ = self.socket.accept()
poll = UDTEpoll()
poll.add(sock)
rs = []
while len(rs) == 0:
rs, ws, _, _ = poll.wait()
self.assertEqual(sock, rs[0])
self.assertEqual(sock, ws[0])
msg = bytearray(5)
sock.recv(msg)
def otherConnect(self):
sock = UDTSocket()
sock.connect("127.0.0.1:7015")
self.assertEqual(UDTSocket.Status.CONNECTED, sock.status)
sock.send(b"hello")
if __name__ == "__main__":
unittest.main()
|
python
|
import os
from config.config import get_config
import shutil
def main():
config = get_config()
if not os.path.exists(config.dataset):
print(f"[!] No dataset in {config.dataset}")
return
for image_transfer in os.listdir(config.dataset):
print(image_transfer)
if not '2' in image_transfer:
continue
from_style, to_style = image_transfer.split('2')
if not os.path.exists(os.path.join(config.dataset, from_style)):
a_num = 1000000
os.makedirs(os.path.join(config.dataset, from_style))
else:
a_num = int('1' + str(os.listdir(os.path.join(config.dataset, from_style))[-1].split('.')[0]))
if not os.path.exists((os.path.join(config.dataset, to_style))):
b_num = 1000000
os.makedirs(os.path.join(config.dataset, to_style))
else:
b_num = int('1' + str(os.listdir(os.path.join(config.dataset, from_style))[-1].split('.')[0]))
num = 0
for image_dir in os.listdir(os.path.join(config.dataset, image_transfer)):
_from = os.path.join(config.dataset, image_transfer, image_dir)
if image_dir.endswith('A'):
num = a_num
_to = os.path.join(config.dataset, from_style)
elif image_dir.endswith('B'):
num = b_num
_to = os.path.join(config.dataset, to_style)
else:
print("[!] unknown dataset format")
return
step = 0
total_step = len(os.listdir(_from))
for image in os.listdir(_from):
to_name = str(num)[1:] + '.' + str(image).split(".")[1]
num += 1
step += 1
shutil.move(os.path.join(_from, image), os.path.join(_to, to_name))
if step % 100 == 0:
print(f"[*] [{step}/{total_step}] move image from {_from} to {_to}")
if image_dir.endswith('A'):
a_num = num
elif image_dir.endswith('B'):
b_num = num
shutil.rmtree(os.path.join(config.dataset, image_transfer))
if __name__ == '__main__':
main()
|
python
|
'''
Created on 2020-02-13
@author: wf
'''
from flask import Flask
from flask import render_template
from flask import request
from dgs.diagrams import Generators,Generator,Example
import os
from flask.helpers import send_from_directory
import argparse
import sys
from pydevd_file_utils import setup_client_server_paths
scriptdir=os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__,static_url_path='',static_folder=scriptdir+'/../web', template_folder=scriptdir+'/../templates')
@app.route('/')
def home():
return index()
def index(err=None,gen=None,alias='dot',outputType='png',source="",message="",genResult=None):
""" render index page with the given parameters"""
return render_template('index.html',outputType=outputType,gen=gen,alias=alias,gens=Generators.generators(),err=err, message=message, source=source,genResult=genResult)
@app.route('/example/<generator>')
def example(generator):
""" get the given example generator """
txt=Example.get(generator)
return txt
@app.route('/check/<generator>')
def check(generator):
gen=Generators.get(generator)
if gen is not None:
return gen.getHtmlInfo()
else:
return "%s is not a valid generator" % generator
@app.route('/render/<outputType>/<crc32>', methods=['GET'])
def render(outputType,crc32):
# allow extension ending for direct rendering e.g. in wikis
ext="."+outputType
if crc32.endswith(ext):
crc32=crc32[:-len(ext)]
outputDirectory=Generator.getOutputDirectory()
filename="%s.%s" % (crc32,outputType)
return send_from_directory(outputDirectory,filename)
def getParam(name):
value=request.form.get(name)
if value is None:
value=request.args.get(name)
return value
@app.route('/render', methods=['POST'])
def renderForWikiExtension():
""" endpoint for diagrams extension"""
generator=getParam('generator')
source=getParam('source')
targetFormat=getParam('types')
if targetFormat is None or targetFormat=="None":
targetFormat="png"
gen=Generators.get(generator)
# use for DOS attack prevention
ip=request.remote_addr
result=gen.generate('dot',source,targetFormat)
# force SSL
json=result.asJson(request.base_url.replace('http:','https:'))
return json
@app.route('/diagrams', methods=['GET', 'POST']) #allow both GET and POST requests
def form_example():
err=None
alias="graphviz"
outputType='png';
genResult=None
message=""
source=None
gen=None
if request.method == 'POST':
try:
source = request.form.get('source')
alias=request.form.get('generator')
generatorId=Generators.generatorIdForAlias(alias)
outputType=request.form.get('outputType')
gen=Generators.get(generatorId)
if gen is None:
raise Exception("invalid generator %s",generatorId)
genResult=gen.generate(alias,source,outputType,useCached=True)
if not genResult.isValid():
raise Exception("could not generate %s for %s",outputType,generatorId)
except Exception as ex:
err=ex
return index(err=err, message=message,source=source,gen=gen,alias=alias,outputType=outputType,genResult=genResult)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Diagrams rendering webservice")
parser.add_argument('--debug',
action='store_true',
help="run in debug mode")
parser.add_argument('--port',
type=int,
default=5003,
help="the port to use")
parser.add_argument('--host',
default="0.0.0.0",
help="the host to serve for")
parser.add_argument('--debugServer',
help="remote debug Server")
parser.add_argument('--debugPort',type=int,
help="remote debug Port",default=5678)
parser.add_argument('--debugPathMapping',nargs='+',help="remote debug Server path mapping - needs two arguments 1st: remotePath 2nd: local Path")
args=parser.parse_args(sys.argv[1:])
if args.debugServer:
import pydevd
print (args.debugPathMapping,flush=True)
if args.debugPathMapping:
if len(args.debugPathMapping)==2:
remotePath=args.debugPathMapping[0] # path on the remote debugger side
localPath=args.debugPathMapping[1] # path on the local machine where the code runs
MY_PATHS_FROM_ECLIPSE_TO_PYTHON = [
(remotePath, localPath),
]
setup_client_server_paths(MY_PATHS_FROM_ECLIPSE_TO_PYTHON)
#os.environ["PATHS_FROM_ECLIPSE_TO_PYTHON"]='[["%s", "%s"]]' % (remotePath,localPath)
#print("trying to debug with PATHS_FROM_ECLIPSE_TO_PYTHON=%s" % os.environ["PATHS_FROM_ECLIPSE_TO_PYTHON"]);
pydevd.settrace(args.debugServer, port=args.debugPort,stdoutToServer=True, stderrToServer=True)
app.run(debug=args.debug,port=args.port,host=args.host)
|
python
|
import boto3
import codecs
import xmltodict
import re
class Example:
'''Represents a single source line and all corresponding target lines
we would like a Turker to evaluate.
'''
def __init__(self, source_line, key):
self.source_line = source_line # The single source line
self.target_lines = [] # List of all possible responses.
self.key = key # This should be something short and unique.
# for each target_line, contains a list of the ranking that line was assigned
# This is not used for 2-choice evaluation
self.ranks = []
self.workers = []
self.hits = []
# This is used for 2-choice evaluation
self.votes = []
def source_line_utterances(self):
'''The source line could actualy consist of multiple tab-separatted utterances.
Retrive these as a list.
'''
return self.source_line.split('\t')
def add_target_line(self, target_line):
self.target_lines.append(target_line)
self.ranks.append([])
def __str__(self):
return "source='%s', targets='%s', votes='%s'" % (self.source_line, str(self.target_lines), str(self.votes))
def process_source_and_responses(source_file, target_files):
'''Read the source file and target files into a list of example objects.
'''
examples = []
# with open(source_file, 'r') as s_f:
with codecs.open(source_file, 'r', encoding="utf-8") as s_f:
source_lines = s_f.readlines()
for idx, line in enumerate(source_lines):
example = Example(line.strip(), "ex-%03d" % (idx))
examples.append(example)
all_target_lines = []
for target_file in target_files:
# with open(target_file, 'r') as t_f:
with codecs.open(target_file, 'r', encoding="utf-8") as t_f:
target_lines_for_file = t_f.readlines()
for idx, line in enumerate(target_lines_for_file):
examples[idx].add_target_line(line.strip())
return examples
def create_mturk_client(run_in_sandbox):
'''Create the AMT client, which is used to post and read from HITs'''
aws_access_key, aws_secret_access_key = read_keys_from_file()
if run_in_sandbox:
endpoint_url = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com'
else:
endpoint_url = 'https://mturk-requester.us-east-1.amazonaws.com'
mturk = boto3.client(
'mturk',
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_access_key,
region_name='us-east-1',
endpoint_url = endpoint_url,
)
return mturk
def read_keys_from_file(filename='accessKeys.csv'):
'''Readers Amazon credentials from the csv file that can be downloaded from Amazon'''
with open(filename, 'r') as f:
f.readline()
aws_access_key, aws_secret_access_key = f.readline().strip().split(',')
return aws_access_key, aws_secret_access_key
def process_amt_hit_responses(worker_results_list, examples_dict, invert=False):
''' Processes the worker_results_list and adds the vote information
to each Example in the examples_dict
If invert is True, set votes for first target to 1 and votes for 2nd target to 0
'''
for worker_results in worker_results_list:
if worker_results['NumResults'] > 0:
for assignment in worker_results['Assignments']:
xml_doc = xmltodict.parse(assignment['Answer'])
# This code assumes there are multiple fields in HIT layout
for answer_field in xml_doc['QuestionFormAnswers']['Answer']:
if type(answer_field) == str:
continue
try:
input_field = answer_field['QuestionIdentifier']
rank = int(answer_field['FreeText'])
worker_id = assignment['WorkerId']
hit_id = assignment['HITId']
except Exception as e:
import pdb; pdb.set_trace()
print(e)
parsed = re.search(r'(ex-\d+)-target-(.+)', input_field)
example_key = parsed.group(1)
target_index_or_tie = parsed.group(2)
example = examples_dict[example_key]
if 'tie' in target_index_or_tie:
example.votes.append(-1)
else:
target_index = int(target_index_or_tie)
if invert:
target_index = 0 if target_index == 1 else 1
example.votes.append(target_index)
example.workers.append(worker_id)
example.hits.append(hit_id)
|
python
|
def inputMatrix(m,n, vektori = False):
if vektori:
border = "border-right: 2px solid black; border-left: 2px solid black; border-top: none; border-bottom: none;"
else:
border = "border: none;"
tmp = ""
tmp+= """
<div class="container">
<div style="border-left: 2px solid black; border-right: 2px solid black; display: inline-block">
"""
for i in range(m):
for j in range(n):
tmp+= """
<input type="text" name="%s" style="width: 30px; height: 30px; %s text-align: center"/>""" % (i, border)# 1 px dotted grey"/>""" % i
tmp+= "<br>\n"
tmp+="""
</div>
"""
tmp+="""
<div class="row">
<input type="submit" value="Unesi Vektore">
</div>
</div>
"""
return tmp
def outputMatrix(a, vektori = False):
m,n = a.shape
if vektori:
border = "border-right: 2px solid black; border-left: 2px solid black; border-top: none; border-bottom: none;"
else:
border = "border: none:"
tmp = ""
tmp+= """
<div class="container">
<div style="border-left: 2px solid black; border-right: 2px solid black; display: inline-block">
"""
for i in range(m):
for j in range(n):
tmp+= """
<label style="width: 30px; height: 30px; %s text-align: center"> %s </label>""" % (border, "{0:.1f}".format(a[i,j]))# 1 px dotted grey"/>""" % i
tmp+= "<br>\n"
tmp+="""
</div>
"""
tmp+="""
</div>
"""
return tmp
def textMat(a, tekst, vektori = False):
m,n = a.shape
if vektori:
border = "border-right: 2px solid black; border-left: 2px solid black; border-top: none; border-bottom: none;"
else:
border = "border: none:"
tmp = ""
tmp+= """
<div class="container">"""
tmp += """
<div class="row">
<h3><span class="label label-default"> %s </span></h1>
</div>""" % tekst
tmp+= """
<div style="border-left: 2px solid black; border-right: 2px solid black; display: inline-block">
"""
for i in range(m):
for j in range(n):
tmp+= """
<label style="width: 30px; height: 30px; %s text-align: center"> %s </label>""" % (border, "{0:.1f}".format(a[i,j]))# 1 px dotted grey"/>""" % i
tmp+= "<br>\n"
tmp+="""
</div>
"""
tmp+="""
</div>
"""
return tmp
|
python
|
from django.contrib import admin
from .models import Trailer
# Register your models here.
admin.site.register(Trailer)
|
python
|
from sklearn.datasets import load_breast_cancer
dataset=load_breast_cancer()
x=dataset.data
y=dataset.target
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
from logistic_regression import LogisticRegression
clf=LogisticRegression(lr=0.01,n_iters=1000)
clf.fit(x_train,y_train)
y_pre=clf.predict(x_test)
print(y_pre)
|
python
|
# En este ejercicio se nos solicitó:
# 1.- El retorno total y anualizado de tres stocks: SPY, VWO y QQQ entre 2015 y 2021 (ambos inclusive)
# 2.- Graficar el retorno acumulado de los stocks indicados durante ese mismo período
# Para ambos ejercicios se nos indicó que utilizáramos la free API key de Alpha Vantage
import requests
import pandas as pd
import numpy as np
import math
# URL genérica = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={SYMBOL}&outputsize=full&apikey=7M2JKVOWY1ZE0IFW&datatype=csv'
# Sustituir {SYMBOL} por el ticker correspondiente
tickers = ['SPY', 'VWO', 'QQQ']
print('\n','*' * 110, "\n", '*', ' ' * 106, '*')
print(' * \033[1mNOTA BENE.\033[0m A efectos de una comparación sin sesgos deberíamos incluir los eventuales divivendos de *')
print(' * cada acción/activo, sin embargo a efectos de calcular la volatilidad y riesgo/beneficio se utiliza el *')
print(' * indicador "Close" y no "Adjusted Close" que además es un indicador Premium en la API de AlphaVantage. *')
print(' * Por lo anterior, toda conclusión derivada de estos cálculos debe ser contrastada con el dato mencionado *')
print(' *', ' ' * 106, '*', '\n','*' * 110, '\n')
def constructor_URL(ticker):
URL = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' + ticker + '&outputsize=full&apikey=7M2JKVOWY1ZE0IFW&datatype=csv'
return URL
riesgo_beneficio = {} # Creamos un diccionario vacío para almacenar los nombres de activos y su respectivo riesgo-beneficio
df_retorno_diario = pd.DataFrame() # Creamos un dataframe vacío al que luego insertaremos columnas
for ticker in tickers:
# Proceso de carga y manipulación de datos
df = pd.read_csv(constructor_URL(ticker)) # Cargamos el CSV en un Dataframe en Pandas
df = df.iloc[::-1] # Invertimos el orden del Dataframe para poder trabajarlo correctamente (de la fecha más antigua a la más reciente)
df['Ret_Log'] = np.log(df['close'] / df['close'].shift(1)).dropna() # Calculamos el retorno logarítmico usando el precio de cierre
df.drop(['high', 'low', 'volume'], axis = 1, inplace = True) # Eliminamos las columnas que no utilizaremos
df.drop(df[df['timestamp'] < '2015-01-01'].index, inplace = True) # Eliminamos todas las fechas anteriores al 1 de enero de 2015
df.drop(df[df['timestamp'] > '2021-12-31'].index, inplace = True) # Eliminamos todas las fechas posteriores al 31 de diciembre de 2021
# Cálculos para obtener la información requerida
df['Volatilidad'] = df['Ret_Log'].rolling(window=252).std() * np.sqrt(252) * 100 # Calculamos la volatilidad usando la desviación estándar y pandas rolling
volat_promedio = round(df['Volatilidad'].mean(), 2) # Cálculo de la volatilidad promedio durante el período
retorno_total = round((df['close'].iloc[-1] - df['open'].iloc[0]) / df['open'].iloc[0], 4) # Cálculo del retorno total durante el período
retorno_porcentual = round(retorno_total * 100, 2) # Retorno total del período en términos porcentuales (pregunta 1, parte 1)
retorno_anualizado = round((((1 + retorno_total)**(1/7)) - 1) * 100, 2) # Cálculo del retorno anualizado = ((1 + retorno_total)^(1/años) - 1)
df_retorno_diario[ticker] = df['close'].pct_change()[1:] #El retorno acumulado se calcula mediante la variación porcentual diaria
riesgo_beneficio[ticker] = retorno_anualizado / volat_promedio
print("El retorno total de {} entre 2015-01-01 y 2021-12-31 es: {}%".format(ticker, retorno_porcentual))
print("La volatilidad anual promedio de {} es: {}%".format(ticker, volat_promedio))
print("El retorno anualizado de {} es: {}%\n".format(ticker, retorno_anualizado))
if ticker == tickers[-1]: #En la última iteración, ya con todos los datos, indicamos la probable mejor opción y se genera el gráfico
for llave, valor in riesgo_beneficio.items():
print("El cociente beneficio/volatilidad de {} es {}".format(llave, round(valor, 2)))
print("La mejor relación beneficio vs. volatilidad (retorno vs. riesgo) la tiene la tiene:", max(riesgo_beneficio, key=riesgo_beneficio.get),"\n")
df2 = df['timestamp'].iloc[1:]
df_retorno_diario.set_index(df2, inplace = True) #Reemplazamos el índice del DataFrame retorno diario con las fechas
df3 = df_retorno_diario.add(1).cumprod().sub(1) # Aplicación de la fórmula de Retornos Acumulados
df3.plot(title = "Serie Temporal de Retornos Acumulados", ylabel = "Retorno Acumulado (ganancia por cada US$ invertido)", xlabel = "Fecha", rot = 45, figsize=(12,8))
|
python
|
# Aula 13 (Estrutura de Repetição for)
from time import sleep
for c in range(10, -1, -1):
print(c)
sleep(1)
print('BOOM!')
|
python
|
# Collaborators: https://www.decodeschool.com/Python-Programming/Branching-Statements/Divisible-by-3-or-not-in-python#:~:text=Program%20Explanation,3%20using%20print()%20method.
#
for x in range (2, 51):
if x % 3==0:
print ("{} is divisible by 3".format(x))
else:
print ("{} is not divisible by 3".format(x))
|
python
|
import argparse
import os
from watermark_add_dct import do_singleRun_dct
from watermark_add_dwt import do_singleRun_dwt
from image_utils import encoding
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="main")
# general options
parser.add_argument(
"--inFolder",
type=str,
default="./kodak_imgs/",
help="Input Folder (default: ./kodak_imgs/).",
)
parser.add_argument(
"--outFolder",
type=str,
default="./tmp/",
help="Output Folder (default: ./tmp/).",
)
parser.add_argument(
"--imgSrc",
type=str,
required=True,
help="File name of input image (i.e. kodim23.png).",
)
parser.add_argument(
"--imgWtr",
type=str,
required=True,
help="File name of watermark image (i.e. kodim23.png).",
)
parser.add_argument(
"--method",
type=str,
required=True,
help="Encoding/decoding method [ADD_DCT/ADD_DWT].",
)
parser.add_argument(
"--comp",
type=encoding,
choices=list(encoding),
required=True,
)
args = parser.parse_args()
print("args:\n{}".format(args))
if not os.path.exists(args.outFolder):
os.makedirs(args.outFolder)
if args.method == "ADD_DCT":
results = do_singleRun_dct(
args.inFolder,
args.imgSrc,
args.imgWtr,
args.method,
args.comp,
args.outFolder
)
else:
results = do_singleRun_dwt(
args.inFolder,
args.imgSrc,
args.imgWtr,
args.method,
args.comp,
args.outFolder
)
print("results:\n{}".format(results))
|
python
|
"""Filters that are used in jobfunnel's filter() method or as intermediate
filters to reduce un-necessesary scraping
Paul McInnis 2020
"""
import logging
from collections import namedtuple
from copy import deepcopy
from datetime import datetime
from typing import Dict, List, Optional, Tuple
import nltk
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from jobfunnel.backend import Job
from jobfunnel.backend.tools import Logger
from jobfunnel.resources import (DEFAULT_MAX_TFIDF_SIMILARITY,
MIN_JOBS_TO_PERFORM_SIMILARITY_SEARCH,
DuplicateType, Remoteness)
DuplicatedJob = namedtuple(
'DuplicatedJob', ['original', 'duplicate', 'type'],
)
class JobFilter(Logger):
"""Class Used by JobFunnel and BaseScraper to filter collections of jobs
TODO: make more configurable, maybe with a FilterBank class.
"""
def __init__(self, user_block_jobs_dict: Optional[Dict[str, str]] = None,
duplicate_jobs_dict: Optional[Dict[str, str]] = None,
blocked_company_names_list: Optional[List[str]] = None,
max_job_date: Optional[datetime] = None,
max_similarity: float = DEFAULT_MAX_TFIDF_SIMILARITY,
desired_remoteness: Remoteness = Remoteness.ANY,
min_tfidf_corpus_size:
int = MIN_JOBS_TO_PERFORM_SIMILARITY_SEARCH,
log_level: int = logging.INFO,
log_file: str = None) -> None:
"""Init
TODO: need a config for this
Args:
user_block_jobs_dict (Optional[Dict[str, str]], optional): dict
containing user's blocked jobs. Defaults to None.
duplicate_jobs_dict (Optional[Dict[str, str]], optional): dict
containing duplicate jobs, detected by content. Defaults to None
blocked_company_names_list (Optional[List[str]], optional): list of
company names disallowed from results. Defaults to None.
max_job_date (Optional[datetime], optional): maximium date that a
job can be scraped. Defaults to None.
desired_remoteness (Remoteness, optional): The desired level of
work-remoteness. ANY will impart no restriction.
log_level (Optional[int], optional): log level. Defaults to INFO.
log_file (Optional[str], optional): log file, Defaults to None.
"""
super().__init__(
level=log_level,
file_path=log_file,
)
self.user_block_jobs_dict = user_block_jobs_dict or {}
self.duplicate_jobs_dict = duplicate_jobs_dict or {}
self.blocked_company_names_list = blocked_company_names_list or []
self.max_job_date = max_job_date
self.max_similarity = max_similarity
self.desired_remoteness = desired_remoteness
self.min_tfidf_corpus_size = min_tfidf_corpus_size
# Retrieve stopwords if not already downloaded
try:
stopwords = nltk.corpus.stopwords.words('english')
except LookupError:
nltk.download('stopwords', quiet=True)
stopwords = nltk.corpus.stopwords.words('english')
# Init vectorizer
self.vectorizer = TfidfVectorizer(
strip_accents='unicode',
lowercase=True,
analyzer='word',
stop_words=stopwords,
)
def filter(self, jobs_dict: Dict[str, Job],
remove_existing_duplicate_keys: bool = True) -> Dict[str, Job]:
"""Filter jobs that fail numerous tests, possibly including duplication
Arguments:
remove_existing_duplicate_keys: pass True to remove jobs if their
ID was previously detected to be a duplicate via TFIDF cosine
similarity
NOTE: if you remove duplicates before processesing them into updates
you will retain potentially stale job information.
Returns:
jobs_dict with all filtered items removed.
"""
return {
key_id: job for key_id, job in jobs_dict.items()
if not self.filterable(
job, check_existing_duplicates=remove_existing_duplicate_keys
)
}
def filterable(self, job: Job,
check_existing_duplicates: bool = True) -> bool:
"""Filter jobs out using all our available filters
NOTE: this allows job to be partially initialized
NOTE: if a job has UNKNOWN remoteness, we will include it anyways
TODO: we should probably add some logging to this?
Arguments:
check_existing_duplicates: pass True to check if ID was previously
detected to be a duplicate via TFIDF cosine similarity
Returns:
True if the job should be removed from incoming data, else False
"""
return bool(
job.status and job.is_remove_status
or (job.company in self.blocked_company_names_list)
or (job.post_date and self.max_job_date
and job.is_old(self.max_job_date))
or (job.key_id and self.user_block_jobs_dict
and job.key_id in self.user_block_jobs_dict)
or (check_existing_duplicates and self.is_duplicate(job))
or (job.remoteness != Remoteness.UNKNOWN
and self.desired_remoteness != Remoteness.ANY
and job.remoteness != self.desired_remoteness)
)
def is_duplicate(self, job: Job) -> bool:
"""Return true if passed Job has key_id and it is in our duplicates list
"""
return bool(job.key_id and self.duplicate_jobs_dict
and job.key_id in self.duplicate_jobs_dict)
def find_duplicates(self, existing_jobs_dict: Dict[str, Job],
incoming_jobs_dict: Dict[str, Job],
) -> List[DuplicatedJob]:
"""Remove all known duplicates from jobs_dict and update original data
TODO: find duplicates by content within existing jobs
Args:
existing_jobs_dict (Dict[str, Job]): dict of jobs keyed by key_id.
incoming_jobs_dict (Dict[str, Job]): dict of new jobs by key_id.
Returns:
Dict[str, Job]: jobs dict with all jobs keyed by known-duplicate
key_ids removed, and their originals updated.
"""
duplicate_jobs_list = [] # type: List[DuplicatedJob]
filt_existing_jobs_dict = deepcopy(existing_jobs_dict)
filt_incoming_jobs_dict = {} # type: Dict[str, Job]
# Look for matches by key id only
for key_id, incoming_job in incoming_jobs_dict.items():
# The key-ids are a direct match between existing and new
if key_id in existing_jobs_dict:
self.logger.debug(
f"Identified duplicate {key_id} between incoming data "
"and existing data."
)
duplicate_jobs_list.append(
DuplicatedJob(
original=existing_jobs_dict[key_id],
duplicate=incoming_job,
type=DuplicateType.KEY_ID,
)
)
# The key id is a known-duplicate we detected via content match
# NOTE: original and duplicate have the same key id.
elif key_id in self.duplicate_jobs_dict:
self.logger.debug(
f"Identified existing content-matched duplicate {key_id} "
"in incoming data."
)
duplicate_jobs_list.append(
DuplicatedJob(
original=None, # TODO: load ref from duplicates dict
duplicate=incoming_job,
type=DuplicateType.EXISTING_TFIDF,
)
)
else:
# This key_id is not duplicate, we can use it for TFIDF
filt_incoming_jobs_dict[key_id] = deepcopy(incoming_job)
# Run the tfidf vectorizer if we have enough jobs left after removing
# key duplicates
if (len(filt_incoming_jobs_dict.keys())
+ len(filt_existing_jobs_dict.keys()) < self.min_tfidf_corpus_size):
self.logger.warning(
"Skipping content-similarity filter because there are fewer than "
f"{self.min_tfidf_corpus_size} jobs."
)
elif filt_incoming_jobs_dict:
duplicate_jobs_list.extend(
self.tfidf_filter(
incoming_jobs_dict=filt_incoming_jobs_dict,
existing_jobs_dict=filt_existing_jobs_dict,
)
)
else:
self.logger.warning(
"Skipping content-similarity filter because there are no "
"incoming jobs"
)
# Update duplicates list with more JSON-friendly entries
# TODO: we should retain a reference to the original job's contents
self.duplicate_jobs_dict.update({
j.duplicate.key_id: j.duplicate.as_json_entry
for j in duplicate_jobs_list
})
return duplicate_jobs_list
def tfidf_filter(self, incoming_jobs_dict: Dict[str, dict],
existing_jobs_dict: Dict[str, dict],
) -> List[DuplicatedJob]:
"""Fit a tfidf vectorizer to a corpus of Job.DESCRIPTIONs and identify
duplicate jobs by cosine-similarity.
NOTE/WARNING: if you are running this method, you should have already
removed any duplicates by key_id
NOTE: this only uses job descriptions to do the content matching.
NOTE: it is recommended that you have at least around 25 ish Jobs.
TODO: need to handle existing_jobs_dict = None
TODO: have this raise an exception if there are too few words.
TODO: we should consider caching the transformed corpus.
Args:
incoming_jobs_dict (Dict[str, dict]): dict of jobs containing
potential duplicates (i.e jobs we just scraped)
existing_jobs_dict (Dict[str, dict]): the existing jobs dict
(i.e. Master CSV)
Raises:
ValueError: incoming_jobs_dict contains no job descriptions
Returns:
List[DuplicatedJob]: list of new duplicate Jobs and their existing
Jobs found via content matching (for use in JobFunnel).
"""
def __dict_to_ids_and_words(jobs_dict: Dict[str, Job],
is_incoming: bool = False,
) -> Tuple[List[str], List[str]]:
"""Get query words and ids as lists + prefilter
NOTE: this is just a convenience method since we do this 2x
TODO: consider moving this once/if we change iteration
"""
ids = [] # type: List[str]
words = [] # type: List[str]
filt_job_dict = {} # type: Dict[str, Job]
for job in jobs_dict.values():
if is_incoming and job.key_id in self.duplicate_jobs_dict:
# NOTE: we should never see this for incoming jobs.
# we will see it for existing jobs since duplicates can
# share a key_id.
raise ValueError(
"Attempting to run TFIDF with existing duplicate "
f"{job.key_id}"
)
elif not len(job.description):
self.logger.debug(
f"Removing {job.key_id} from scrape result, empty "
"description."
)
else:
ids.append(job.key_id)
words.append(job.description)
# NOTE: We want to leave changing incoming_jobs_dict in
# place till the end or we will break usage of
# Job.update_if_newer()
filt_job_dict[job.key_id] = job
# TODO: assert on length of contents of the lists as well
if not words:
raise ValueError(
"No data to fit, are your job descriptions all empty?"
)
return ids, words, filt_job_dict
query_ids, query_words, filt_incoming_jobs_dict = \
__dict_to_ids_and_words(incoming_jobs_dict, is_incoming=True)
# Calculate corpus and format query data for TFIDF calculation
corpus = [] # type: List[str]
if existing_jobs_dict:
self.logger.debug("Running TFIDF on incoming vs existing data.")
reference_ids, reference_words, filt_existing_jobs_dict = \
__dict_to_ids_and_words(existing_jobs_dict, is_incoming=False)
corpus = query_words + reference_words
else:
self.logger.debug("Running TFIDF on incoming data only.")
reference_ids = query_ids,
reference_words = query_words
filt_existing_jobs_dict = filt_incoming_jobs_dict
corpus = query_words
# Provide a warning if we have few words.
# TODO: warning should reflect actual corpus size
if len(corpus) < self.min_tfidf_corpus_size:
self.logger.warning(
"It is not recommended to use this filter with less than "
f"{self.min_tfidf_corpus_size} jobs"
)
# Fit vectorizer to entire corpus
self.vectorizer.fit(corpus)
# Calculate cosine similarity between reference and current blurbs
# This is a list of the similarity between that query job and all the
# TODO: impl. in a more efficient way since fit() does the transform too
similarities_per_query = cosine_similarity(
self.vectorizer.transform(query_words),
self.vectorizer.transform(reference_words)
if existing_jobs_dict else None,
)
# Find Duplicate jobs by similarity score
# NOTE: multiple jobs can be determined to be a duplicate of same job!
# TODO: traverse this so we look at max similarity for original vs query
# currently it's the other way around so we can look at multi-matching
# original jobs but not multiple matching queries for our original job.
new_duplicate_jobs_list = [] # type: List[DuplicatedJob]
for query_similarities, query_id in zip(similarities_per_query,
query_ids):
# Identify the jobs in existing_jobs_dict that our query is a
# duplicate of
# TODO: handle if everything is highly similar!
similar_indeces = np.where(
query_similarities >= self.max_similarity
)[0]
if similar_indeces.size > 0:
# TODO: capture if more jobs are similar by content match
top_similar_job = np.argmax(query_similarities[similar_indeces])
self.logger.debug(
f"Identified incoming job {query_id} as new duplicate by "
"contents of existing job "
f"{reference_ids[top_similar_job]}"
)
new_duplicate_jobs_list.append(
DuplicatedJob(
original=filt_existing_jobs_dict[
reference_ids[top_similar_job]],
duplicate=filt_incoming_jobs_dict[query_id],
type=DuplicateType.NEW_TFIDF,
)
)
if not new_duplicate_jobs_list:
self.logger.debug("Found no duplicates by content-matching.")
# returns a list of newly-detected duplicate Jobs
return new_duplicate_jobs_list
|
python
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .ctdet import CtdetTrainer
from .exdet import ExdetTrainer
train_factory = {
'exdet': ExdetTrainer,
'ctdet': CtdetTrainer,
}
|
python
|
p1 = int(input('digite o primeiro termo:'))
r = int(input('digite a razõ da P.A'))
d= p1 + (10-1) * r
for c in range(p1-1,d,r):
print(c)
|
python
|
import factory
import time
import random
from spaceone.core import utils
class MetricFactory(factory.DictFactory):
key = factory.LazyAttribute(lambda o: utils.generate_id('metric'))
name = factory.LazyAttribute(lambda o: utils.random_string())
unit = {
'x': 'Datetime',
'y': 'Count'
}
chart_type = 'line'
chart_option = {}
class MetricsFactory(factory.DictFactory):
metrics = factory.List([
factory.SubFactory(MetricFactory) for _ in range(5)
])
available_resources = {
utils.generate_id('server'): True,
utils.generate_id('server'): True,
utils.generate_id('server'): True,
utils.generate_id('server'): False,
utils.generate_id('server'): False
}
domain_id = utils.generate_id('domain')
class MetricDataFactory(factory.DictFactory):
labels = factory.List([
int(time.time()) for _ in range(10)
])
resource_values = {
utils.generate_id('server'): [random.randint(0, 20) for _ in range(10)],
utils.generate_id('server'): [random.randint(0, 20) for _ in range(10)],
utils.generate_id('server'): [random.randint(0, 20) for _ in range(10)]
}
domain_id = utils.generate_id('domain')
|
python
|
# Copyright © 2019 Province of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module holds non-party registration validation for rules not covered by the schema.
Validation includes verifying delete collateral ID's and timestamps.
"""
from ppr_api.models import utils as model_utils
COURT_ORDER_INVALID = 'CourtOrderInformation is not allowed with a base registration type of {}.\n'
COURT_ORDER_MISSING = 'Required courtOrderInformation is missing.\n'
COURT_ORDER_INVALID_DATE = 'Invalid courtOrderInformation.orderDate: the value must be between the base ' + \
'registration date and the current system date.\n'
AUTHORIZATION_INVALID = 'Authorization Received indicator is required with this registration.\n'
DELETE_MISSING_ID_VEHICLE = 'Required vehicleId missing in delete Vehicle Collateral.\n'
DELETE_MISSING_ID_GENERAL = 'Required collateralId missing in delete General Collateral.\n'
DELETE_INVALID_ID_VEHICLE = 'Invalid vehicleId {} in delete Vehicle Collateral.\n'
DELETE_INVALID_ID_GENERAL = 'Invalid collateralId {} in delete General Collateral.\n'
LI_NOT_ALLOWED = 'Life Infinite is not allowed with this registration type.\n'
RENEWAL_INVALID = 'Renewal registration is now allowed: the base registration has an infinite life.\n'
LIFE_MISSING = 'Either Life Years or Life Infinite is required with this registration type.\n'
LIFE_INVALID = 'Only one of Life Years or Life Infinite is allowed.\n'
def validate_registration(json_data, financing_statement=None):
"""Perform all registration data validation checks not covered by schema validation."""
error_msg = ''
if 'authorizationReceived' not in json_data or not json_data['authorizationReceived']:
error_msg += AUTHORIZATION_INVALID
error_msg += validate_collateral_ids(json_data, financing_statement)
return error_msg
def validate_renewal(json_data, financing_statement):
"""Perform all renewal registration data validation checks not covered by schema validation."""
error_msg = ''
if 'authorizationReceived' not in json_data or not json_data['authorizationReceived']:
error_msg += AUTHORIZATION_INVALID
if not financing_statement:
return error_msg
error_msg += validate_life(json_data, financing_statement)
if model_utils.REG_TYPE_REPAIRER_LIEN == financing_statement.registration[0].registration_type:
if 'courtOrderInformation' not in json_data:
error_msg += COURT_ORDER_MISSING
elif 'orderDate' in json_data['courtOrderInformation'] and \
len(json_data['courtOrderInformation']['orderDate']) >= 10:
co_date = json_data['courtOrderInformation']['orderDate']
# order date must be between base registration date and current date.
if not model_utils.valid_court_order_date(financing_statement.registration[0].registration_ts, co_date):
error_msg += COURT_ORDER_INVALID_DATE
elif 'courtOrderInformation' in json_data:
error_msg += COURT_ORDER_INVALID.format(financing_statement.registration[0].registration_type)
return error_msg
def validate_collateral_ids(json_data, financing_statement=None):
"""Check amendment, change registration delete collateral ID's are valid."""
error_msg = ''
# Check delete vehicle ID's
if 'deleteVehicleCollateral' in json_data:
for collateral in json_data['deleteVehicleCollateral']:
if 'vehicleId' not in collateral:
error_msg += DELETE_MISSING_ID_VEHICLE
elif financing_statement:
collateral_id = collateral['vehicleId']
existing = find_vehicle_collateral_by_id(collateral_id, financing_statement.vehicle_collateral)
if not existing:
error_msg += DELETE_INVALID_ID_VEHICLE.format(str(collateral_id))
# Check delete general collateral ID's.
# Removed: with th "add only" model the check on delete general collateral ID is no longer required.
# if 'deleteGeneralCollateral' in json_data:
# for collateral in json_data['deleteGeneralCollateral']:
# if 'collateralId' not in collateral:
# error_msg += DELETE_MISSING_ID_GENERAL
# elif financing_statement:
# collateral_id = collateral['collateralId']
# existing = find_general_collateral_by_id(collateral_id, financing_statement.general_collateral)
# if not existing:
# error_msg += DELETE_INVALID_ID_GENERAL.format(str(collateral_id))
return error_msg
def find_vehicle_collateral_by_id(vehicle_id: int, vehicle_collateral):
"""Search existing list of vehicle_collateral objects for a matching vehicle id."""
collateral = None
if vehicle_id and vehicle_collateral:
for v_collateral in vehicle_collateral:
if v_collateral.id == vehicle_id and not v_collateral.registration_id_end:
collateral = v_collateral
return collateral
def find_general_collateral_by_id(collateral_id: int, general_collateral):
"""Search existing list of general_collateral objects for a matching collateral id."""
collateral = None
if collateral_id and general_collateral:
for g_collateral in general_collateral:
if g_collateral.id == collateral_id and not g_collateral.registration_id_end:
collateral = g_collateral
return collateral
def validate_life(json_data, financing_statement):
"""Validate renewal lifeYears and lifeInfinite by registration type."""
error_msg = ''
reg_type = financing_statement.registration[0].registration_type
if financing_statement.life == model_utils.LIFE_INFINITE:
error_msg += RENEWAL_INVALID
elif reg_type == model_utils.REG_TYPE_REPAIRER_LIEN and 'lifeInfinite' in json_data and json_data['lifeInfinite']:
error_msg += LI_NOT_ALLOWED
elif reg_type != model_utils.REG_TYPE_REPAIRER_LIEN and 'lifeYears' not in json_data and \
'lifeInfinite' not in json_data:
error_msg += LIFE_MISSING
elif json_data.get('lifeYears', -1) > 0 and json_data.get('lifeInfinite'):
error_msg += LIFE_INVALID
return error_msg
|
python
|
import lasagne
from lasagne.regularization import regularize_network_params, l2, l1
import time
import theano
import numpy as np
from theano.tensor import *
import theano.tensor as T
import gc
import sys
sys.setrecursionlimit(50000)
#then import my own modules
import seqHelper
import lasagneModelsFingerprints
#get my files
expr_filename = '../../data/csv_files/logSolubilityTest.csv'
fingerprint_filename = '../../data/temp/logSolubilityInput_withRDKITidx.pkl'
#set some hyperparameters
batch_size = 100
learning_rate = 0.001
num_epochs = 500
random_seed = int(time.time())
output_dim = 1
input_index_dim = 6
l2_regularization_lambda = 0.0001
final_layer_type = lasagne.nonlinearities.linear
start_time = str(time.ctime()).replace(':','-').replace(' ','_')
#this is the dimension of the output fingerprint
fingerprint_dim = 265
#this is the dimension of the hiddens of the fingerprint
#the length of the list determines the number of layers for the molecule conv net
fingerprint_network_architecture=[500]*5
# for a neural net on the final output, make this number > 0
final_neural_net = 1000
#otherwise, set it to 0 if just a linear layer is desired
#final_neural_net = 0
#then make the name of the output to save for testing
neural_net_present = 'True'
if fingerprint_network_architecture == []:
neural_net_present = 'False'
if expr_filename == 'data/logSolubilityTest.csv':
test_type = 'solubility'
progress_filename = 'output/CNN_fingerprint_visual_context_NN-'+neural_net_present+'_'+start_time+'.csv'
#read in our molecule data
smiles_to_measurement,smiles_to_atom_info,smiles_to_bond_info,\
smiles_to_atom_neighbors,smiles_to_bond_neighbors,smiles_to_atom_mask,\
smiles_to_rdkit_list,max_atom_len,max_bond_len,num_atom_features,num_bond_features\
= seqHelper.read_in_data(expr_filename,fingerprint_filename)
#then get some variables ready to set up my model
experiment_names = smiles_to_measurement.keys()
#get my random training and test set
test_num = int(float(len(experiment_names))*0.2)
train_num = int(float(len(experiment_names))*0.8)
test_list, train_list = seqHelper.gen_rand_train_test_data(experiment_names, test_num, random_seed)
#define my theano variables
input_atom = ftensor3('input_atom')
input_atom_index = itensor3('input_atom_index')
input_bonds = ftensor3('input_bonds')
input_bond_index = itensor3('input_mask_attn')
input_mask = fmatrix('input_mask_attn')
target_vals = fvector('output_data')
#get my model output
cnn_model = lasagneModelsFingerprints.buildVisualCNNfingerprint(input_atom, input_bonds, \
input_atom_index, input_bond_index, input_mask, max_atom_len, max_bond_len, num_atom_features, \
num_bond_features, input_index_dim, fingerprint_dim, batch_size, output_dim, final_layer_type, \
fingerprint_network_architecture, final_neural_net)
#count the number of parameters in the model and initialize progress file
print "Number of parameters:",lasagne.layers.count_params(cnn_model['output'])
OUTPUT = open(progress_filename, 'w')
OUTPUT.write("NUM_PARAMS,"+str(lasagne.layers.count_params(cnn_model['output']))+'\n')
OUTPUT.write("EPOCH,RMSE,MSE\n")
OUTPUT.close()
#mulitply our training predictions and visualizations by 1.0
# this makes it so these numbers are part of the theano graph but not changed in value
# in this way, theano doesn't complain at me for unused variables
context_output_train = lasagne.layers.get_output(cnn_model['output'],deterministic=False)
train_prediction = context_output_train[0] * 1.0
visual_predictions_train = context_output_train[1] * 1.0
train_prediction = train_prediction.flatten()
train_loss = lasagne.objectives.squared_error(target_vals,train_prediction)
#get our loss and our cost
l2_loss = regularize_network_params(cnn_model['output'],l2)
train_cost = T.mean(train_loss) + l2_loss*l2_regularization_lambda
#then get our parameters and update from lasagne
params = lasagne.layers.get_all_params(cnn_model['output'], trainable=True)
updates = lasagne.updates.adam(train_cost, params, learning_rate=learning_rate)
#then get the outputs for the test and multiply them by 1.0 like above
context_output_test = lasagne.layers.get_output(cnn_model['output'],deterministic=True)
test_predicition = context_output_test[0] * 1.0
visual_predictions_test = context_output_test[1] * 1.0
test_predicition = test_predicition.flatten()
test_cost = lasagne.objectives.squared_error(target_vals,test_predicition)
#then define my theano functions for train and test
train_func = theano.function([input_atom,input_bonds,input_atom_index,\
input_bond_index,input_mask,target_vals], [train_prediction,train_cost,visual_predictions_train],\
updates=updates, allow_input_downcast=True)
test_func = theano.function([input_atom,input_bonds,input_atom_index,\
input_bond_index,input_mask,target_vals], [test_predicition,test_cost,visual_predictions_test], allow_input_downcast=True)
print "compiled functions"
#then run through my epochs
for epoch in xrange(num_epochs):
#get my minibatch
expr_list_of_lists_train = seqHelper.gen_batch_list_of_lists(train_list,batch_size,(random_seed+epoch))
#run through my training minibatches
for counter,experiment_list in enumerate(expr_list_of_lists_train):
x_atom,x_bonds,x_atom_index,x_bond_index,x_mask,y_val = seqHelper.gen_batch_XY_reg(experiment_list,\
smiles_to_measurement,smiles_to_atom_info,smiles_to_bond_info,\
smiles_to_atom_neighbors,smiles_to_bond_neighbors,smiles_to_atom_mask)
train_prediction,train_error,train_viz = train_func(x_atom,x_bonds,x_atom_index,x_bond_index,x_mask,y_val)
test_error_list = []
if epoch % 1 == 0:
expr_list_of_lists_test = seqHelper.gen_batch_list_of_lists(test_list,batch_size,(random_seed+epoch))
#then run through the test data
OUTPUTVIZ = open('output/Chemotype_predictions_NN-'+neural_net_present+'_'+start_time+'.csv', 'w')
for experiment_list in expr_list_of_lists_test:
x_atom,x_bonds,x_atom_index,x_bond_index,x_mask,y_val = seqHelper.gen_batch_XY_reg(experiment_list,\
smiles_to_measurement,smiles_to_atom_info,smiles_to_bond_info,\
smiles_to_atom_neighbors,smiles_to_bond_neighbors,smiles_to_atom_mask)
#do the prediction
test_prediction,test_error_output,test_viz = test_func(x_atom,x_bonds,x_atom_index,x_bond_index,x_mask,y_val)
#add the error to the error list
test_error_list += test_error_output.tolist()
#write out my visual predictions
seqHelper.write_out_predictions_cnn(experiment_list,x_mask,smiles_to_rdkit_list,\
test_viz, test_prediction.tolist(), OUTPUTVIZ)
print "##########################################"
print "EPOCH:\t"+str(epoch+1)+"\tRMSE\t",np.sqrt(np.mean(test_error_list)),'\tMSE\t',np.mean(test_error_list)
print "##########################################"
#then also do the visualizations for the training data
for experiment_list in expr_list_of_lists_train:
x_atom,x_bonds,x_atom_index,x_bond_index,x_mask,y_val = seqHelper.gen_batch_XY_reg(experiment_list,\
smiles_to_measurement,smiles_to_atom_info,smiles_to_bond_info,\
smiles_to_atom_neighbors,smiles_to_bond_neighbors,smiles_to_atom_mask)
test_prediction,test_error_output,test_viz = test_func(x_atom,x_bonds,x_atom_index,x_bond_index,x_mask,y_val)
seqHelper.write_out_predictions_cnn(experiment_list, x_mask, smiles_to_rdkit_list, \
test_viz, test_prediction.tolist(), OUTPUTVIZ)
OUTPUTVIZ.close()
#then write out my progress
OUTPUT = open(progress_filename, 'a')
OUTPUT.write(str(epoch)+","+str(np.sqrt(np.mean(test_error_list)))+','+str(np.mean(test_error_list))+'\n')
OUTPUT.close()
|
python
|
"""Profile model."""
# Django
from django.db import models
# Utilities
from feelit.utils.models import FeelitModel
class Profile(FeelitModel):
""" Profile model.
Profile holds user's public data like bio, posts and stats.
"""
user = models.OneToOneField('users.User', on_delete=models.CASCADE)
biography = models.TextField(max_length=250)
picture = models.ImageField(
'profile picture',
upload_to='users/pictures',
blank=True,
null=True
)
# Stats
profile_rating = models.FloatField(
default=0.0,
help_text="Feelings overall rating based on post results")
def __str__(self):
"""Return user's str representation."""
return str(self.user)
|
python
|
import re
ncr_replacements = {
0x00: 0xFFFD,
0x0D: 0x000D,
0x80: 0x20AC,
0x81: 0x0081,
0x81: 0x0081,
0x82: 0x201A,
0x83: 0x0192,
0x84: 0x201E,
0x85: 0x2026,
0x86: 0x2020,
0x87: 0x2021,
0x88: 0x02C6,
0x89: 0x2030,
0x8A: 0x0160,
0x8B: 0x2039,
0x8C: 0x0152,
0x8D: 0x008D,
0x8E: 0x017D,
0x8F: 0x008F,
0x90: 0x0090,
0x91: 0x2018,
0x92: 0x2019,
0x93: 0x201C,
0x94: 0x201D,
0x95: 0x2022,
0x96: 0x2013,
0x97: 0x2014,
0x98: 0x02DC,
0x99: 0x2122,
0x9A: 0x0161,
0x9B: 0x203A,
0x9C: 0x0153,
0x9D: 0x009D,
0x9E: 0x017E,
0x9F: 0x0178,
}
LT = '<'
AMP = '&'
SLASH = '/'
cdata_tags = ('script', 'style')
class InvalidNumCharRefReplacer(object):
""" Replaces invalid numeric character references in HTML.
In the wild you can find HTML containing numeric character
references where the numbers are not valid Unicode characters.
Most often the numbers are windows-1252 characters.
So we replace this invalid characters as best we can.
Note that the Python 3 html.parser.HTMLParser also does this
and so does the html5lib HTML parser.
"""
def __init__(self, fp):
self.fp = fp
self.clean = ''
self.dirty = ''
self.cdata_tag = None
def read(self, size=None):
while True:
dirty = self.fp.read(size)
eof = (size is None or not dirty)
dirty = self.dirty + dirty
clean, self.dirty, self.cdata_tag = clean_ncr(dirty,
eof,
self.cdata_tag)
self.clean += clean
if eof:
assert not self.dirty
data = self.clean
self.clean = ''
return data
elif len(self.clean) >= size:
data = self.clean[:size]
self.clean = self.clean[size:]
return data
def clean_ncr(dirty, eof, cdata_tag=None):
# We scan 'dirty' for incorrect numeric character references.
# As we scan, we append 'clean' sections to 'parts'.
parts = []
clean_start = clean_end = 0
assert not cdata_tag or cdata_tag == cdata_tag.lower().strip()
end_token = {
AMP: end_char_ref,
LT: end_tag,
}
while True:
if cdata_tag:
# ignore char refs inside <script> or <style> tags.
# just looking for </script> or </style>
begin_token = begin_tag
else:
begin_token = begin_tag_or_char_ref
begin = begin_token.search(dirty, clean_end)
if not begin:
# now we know there are not more tokens in this chunk
clean_end = len(dirty)
break
token = end_token[begin.group()].search(dirty, begin.end())
if not token:
# We haven't seen the end of this token yet,
# we may be called again, but with more data (if !eof).
break
if begin.group() == LT:
if token.group('slash') and cdata_tag:
tag = token.group('tag')
if tag and tag.lower() == cdata_tag:
cdata_tag = None
elif not token.group('comment'):
tag = token.group('tag')
tag = tag and tag.lower()
if not cdata_tag and tag and tag in cdata_tags:
cdata_tag = tag
else:
assert begin.group() == AMP
assert not cdata_tag
ncr = token.group(1)
if ncr:
if ncr.lower().startswith('x'):
code_point = int(ncr[1:], 16)
else:
code_point = int(ncr, 10)
if code_point in ncr_replacements:
# append clean section
parts.append(dirty[clean_start:begin.start()])
ncr = '&#x%0X' % ncr_replacements[code_point]
parts.append(ncr)
# next clean section starts here
clean_start = token.end()
# everything up to this position is now clean
clean_end = token.end()
if eof:
parts.append(dirty[clean_start:])
else:
parts.append(dirty[clean_start:clean_end])
return ''.join(parts), dirty[clean_end:], cdata_tag
#
# When scanning for the begining of tokens we look just one character
# at a time so that we don't have to worry about partial buffering.
begin_tag = re.compile(LT)
begin_tag_or_char_ref = re.compile('[<&]', re.I)
end_tag = re.compile('(?P<comment>!--)|(?P<slash>/?)\s*(?P<tag>[a-z]+)(?=[^a-z])', re.I)
end_char_ref = re.compile('[^#]|#(x[0-9A-F]+|[0-9]+)', re.I)
def replace_invalid_ncr(fp):
return InvalidNumCharRefReplacer(fp)
|
python
|
"""The Twinkly API client."""
import logging
from typing import Any
from aiohttp import ClientResponseError, ClientSession
from .const import (
EP_BRIGHTNESS,
EP_COLOR,
EP_DEVICE_INFO,
EP_LOGIN,
EP_MODE,
EP_TIMEOUT,
EP_VERIFY,
)
_LOGGER = logging.getLogger(__name__)
class TwinklyClient:
"""Client of the Twinkly API."""
def __init__(self, host: str, session: ClientSession = None):
"""Initialize a TwinklyClient."""
self._host = host
self._base_url = "http://" + host + "/xled/v1/"
self._token = None
self._session = (
session
if session
else ClientSession(raise_for_status=True, timeout=EP_TIMEOUT)
)
self._is_on = False
self._brightness = 0
self._is_available = False
@property
def host(self) -> str:
"""Get the host used by this client."""
return self._host
async def get_device_info(self) -> Any:
"""Retrieve the device information."""
return await self.__send_request(EP_DEVICE_INFO)
async def get_is_on(self) -> bool:
"""Get a boolean which indicates the current state of the device."""
return await self.get_mode() != "off"
async def set_is_on(self, is_on: bool) -> None:
"""Turn the device on / off."""
await self.__send_request(EP_MODE, {"mode": "movie" if is_on else "off"})
async def get_mode(self) -> str:
"""Get the current mode of the device (off,color,demo,effect,movie,playlist,rt)."""
return (await self.__send_request(EP_MODE))["mode"]
async def set_mode(self, mode: str) -> None:
"""Set the device mode (off,color,demo,effect,movie,playlist,rt)"""
await self.__send_request(EP_MODE, {"mode": mode})
async def get_brightness(self) -> int:
"""Get the current brightness of the device, between 0 and 100."""
brightness = await self.__send_request(EP_BRIGHTNESS)
return int(brightness["value"]) if brightness["mode"] == "enabled" else 100
async def set_brightness(self, brightness: int) -> None:
"""Set the brightness of the device."""
await self.__send_request(EP_BRIGHTNESS, {"value": brightness, "type": "A"})
async def get_color(self) -> dict:
"""Get the current color, dict of h,s,v,r,g,b,w ints"""
response_data = await self.__send_request(EP_COLOR)
return response_data
async def set_color(
self,
hue: int = None,
saturation: int = None,
value: int = None,
red: int = None,
green: int = None,
blue: int = None,
white: int = None
) -> None:
"""Set the color of the device."""
# Only include set keys
payload = {
k: v for k, v in {
"hue": hue,
"saturation": saturation,
"value": value,
"red": red,
"green": green,
"blue": blue,
"white": white
}.items() if v is not None
}
await self.__send_request(EP_COLOR, payload)
async def __send_request(
self, endpoint: str, data: Any = None, retry: int = 1
) -> Any:
"""Send an authenticated request with auto retry if not yet auth."""
if self._token is None:
await self.__auth()
try:
response = await self._session.request(
method="GET" if data is None else "POST",
url=self._base_url + endpoint,
json=data,
headers={"X-Auth-Token": self._token},
raise_for_status=True,
timeout=EP_TIMEOUT,
)
result = await response.json() if data is None else None
return result
except ClientResponseError as err:
if err.code == 401 and retry > 0:
self._token = None
return await self.__send_request(endpoint, data, retry - 1)
raise
async def __auth(self) -> None:
"""Authenticate to the device."""
_LOGGER.info("Authenticating to '%s'", self._host)
# Login to the device using a hard-coded challenge
login_response = await self._session.post(
url=self._base_url + EP_LOGIN,
json={"challenge": "Uswkc0TgJDmwl5jrsyaYSwY8fqeLJ1ihBLAwYcuADEo="},
raise_for_status=True,
timeout=EP_TIMEOUT,
)
login_result = await login_response.json()
_LOGGER.debug("Successfully logged-in to '%s'", self._host)
# Get the token, but do not store it until it gets verified
token = login_result["authentication_token"]
# Verify the token is valid
await self._session.post(
url=self._base_url + EP_VERIFY,
headers={"X-Auth-Token": token},
raise_for_status=True,
timeout=EP_TIMEOUT,
)
_LOGGER.debug("Successfully verified token to '%s'", self._host)
self._token = token
|
python
|
"""add private column to group
Revision ID: 9612aba86eb2
Revises: 789ac8c2844f
Create Date: 2021-06-06 10:31:28.453405
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "9612aba86eb2"
down_revision = "789ac8c2844f"
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("group", sa.Column("private", sa.Boolean(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("group", "private")
# ### end Alembic commands ###
|
python
|
from stormberry.config import Config
import signal
import sys
import stormberry.logging
from stormberry.station import WeatherStation
from stormberry.plugin import ISensorPlugin, IRepositoryPlugin, IDisplayPlugin, PluginDataManager
from stormberry.plugin.manager import get_plugin_manager
class SignalHandling(object):
"""
Does graceful signal handling for heartbeat.
"""
def __init__(self, station):
self.station = station
def __enter__(self):
signal.signal(signal.SIGQUIT, self.station.stop_station)
signal.signal(signal.SIGTERM, self.station.stop_station)
signal.signal(signal.SIGINT, self.station.stop_station)
def __exit__(self, type, value, traceback):
# Ideally this would restore the original
# signal handlers, but that isn't functionality
# that's needed right now, so we'll do nothing.
pass
def main():
config = Config()
try:
logdir = config.get("GENERAL", "LOGDIR")
except:
logdir = "/tmp"
filehandler, termhandler = stormberry.logging.setup_handlers(logdir, "stormberry-station.log")
stormberry_logger = stormberry.logging.setup_logging(config, "stormberry-station", [filehandler, termhandler])
yapsy_logger = stormberry.logging.setup_logging(config, "yapsy", [filehandler, termhandler])
plugin_manager = get_plugin_manager(config)
plugins = plugin_manager.getAllPlugins()
plugin_names = str([x.plugin_object.__class__.__name__ for x in plugins])
stormberry_logger.info("Loaded %d plugins: %s" % (len(plugins), plugin_names))
plugin_data_manager = PluginDataManager()
try:
station = WeatherStation(plugin_manager, config, plugin_data_manager, stormberry_logger)
station.prepare_sensors()
station.prepare_repositories()
station.prepare_displays()
stormberry_logger.info('Successfully initialized sensors')
with SignalHandling(station) as sh:
station.start_station()
stormberry_logger.info('Weather Station successfully launched')
signal.pause()
except Exception as e:
stormberry_logger.critical(e)
station.stop_station()
sys.exit(0)
|
python
|
from use_cases.encryption.makeEncryptString import *
from use_cases.encryption.makeDecryptString import *
from use_cases.encryption.makeCreateKeyPair import *
|
python
|
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import json
from datetime import datetime, timedelta
from ... import IoTLiveScenarioTest
from ...settings import DynamoSettings, ENV_SET_TEST_IOTHUB_BASIC
settings = DynamoSettings(ENV_SET_TEST_IOTHUB_BASIC)
LIVE_HUB = settings.env.azext_iot_testhub
LIVE_RG = settings.env.azext_iot_testrg
class TestIoTHubJobs(IoTLiveScenarioTest):
def __init__(self, test_case):
super(TestIoTHubJobs, self).__init__(test_case, LIVE_HUB, LIVE_RG)
job_count = 3
self.job_ids = self.generate_job_names(job_count)
def test_jobs(self):
device_count = 2
device_ids_twin_tags = self.generate_device_names(device_count)
device_ids_twin_props = self.generate_device_names(device_count)
for device_id in device_ids_twin_tags + device_ids_twin_props:
self.cmd(
"iot hub device-identity create -d {} -n {} -g {}".format(
device_id, LIVE_HUB, LIVE_RG
)
)
# Focus is on scheduleUpdateTwin jobs until we improve JIT device simulation
# Update twin tags scenario
self.kwargs[
"twin_patch_tags"
] = '{"tags": {"deviceClass": "Class1, Class2, Class3"}}'
query_condition = "deviceId in ['{}']".format("','".join(device_ids_twin_tags))
self.cmd(
"iot hub job create --job-id {} --job-type {} -q \"{}\" --twin-patch '{}' -n {} -g {} --ttl 300 --wait".format(
self.job_ids[0],
"scheduleUpdateTwin",
query_condition,
"{twin_patch_tags}",
LIVE_HUB,
LIVE_RG,
),
checks=[
self.check("jobId", self.job_ids[0]),
self.check("queryCondition", query_condition),
self.check("status", "completed"),
self.check("updateTwin.etag", "*"),
self.check(
"updateTwin.tags",
json.loads(self.kwargs["twin_patch_tags"])["tags"],
),
self.check("type", "scheduleUpdateTwin"),
],
)
for device_id in device_ids_twin_tags:
self.cmd(
"iot hub device-twin show -d {} -n {} -g {}".format(
device_id, LIVE_HUB, LIVE_RG
),
checks=[
self.check(
"tags", json.loads(self.kwargs["twin_patch_tags"])["tags"]
)
],
)
# Update twin desired properties, using connection string
self.kwargs[
"twin_patch_props"
] = '{"properties": {"desired": {"arbitrary": "value"}}}'
query_condition = "deviceId in ['{}']".format("','".join(device_ids_twin_props))
self.cmd(
"iot hub job create --job-id {} --job-type {} -q \"{}\" --twin-patch '{}' --login '{}' --ttl 300 --wait".format(
self.job_ids[1],
"scheduleUpdateTwin",
query_condition,
"{twin_patch_props}",
self.connection_string,
),
checks=[
self.check("jobId", self.job_ids[1]),
self.check("queryCondition", query_condition),
self.check("status", "completed"),
self.check("updateTwin.etag", "*"),
self.check(
"updateTwin.properties",
json.loads(self.kwargs["twin_patch_props"])["properties"],
),
self.check("type", "scheduleUpdateTwin"),
],
)
# Error - omit queryCondition when scheduleUpdateTwin or scheduleDeviceMethod
self.cmd(
"iot hub job create --job-id {} --job-type {} --twin-patch '{}' -n {}".format(
self.job_ids[1], "scheduleUpdateTwin", "{twin_patch_props}", LIVE_HUB
),
expect_failure=True,
)
self.cmd(
"iot hub job create --job-id {} --job-type {} --twin-patch '{}' -n {}".format(
self.job_ids[1], "scheduleDeviceMethod", "{twin_patch_props}", LIVE_HUB
),
expect_failure=True,
)
# Error - omit twin patch when scheduleUpdateTwin
self.cmd(
"iot hub job create --job-id {} --job-type {} -q '*' -n {}".format(
self.job_ids[1], "scheduleUpdateTwin", LIVE_HUB
),
expect_failure=True,
)
# Error - omit method name when scheduleDeviceMethod
self.cmd(
"iot hub job create --job-id {} --job-type {} -q '*' -n {}".format(
self.job_ids[1], "scheduleDeviceMethod", LIVE_HUB
),
expect_failure=True,
)
# Show Job tests
# Using --wait when creating effectively uses show
self.cmd(
"iot hub job show --job-id {} -n {} -g {}".format(
self.job_ids[0], LIVE_HUB, LIVE_RG
),
checks=[
self.check("jobId", self.job_ids[0]),
self.check("type", "scheduleUpdateTwin"),
],
)
# With connection string
self.cmd(
"iot hub job show --job-id {} --login {}".format(
self.job_ids[1], self.connection_string
),
checks=[
self.check("jobId", self.job_ids[1]),
self.check("type", "scheduleUpdateTwin"),
],
)
# Error - Show non-existant job
self.cmd(
"iot hub job show --job-id notarealjobid -n {} -g {}".format(
LIVE_HUB, LIVE_RG
),
expect_failure=True,
)
# Cancel Job test
# Create job to be cancelled - scheduled +7 days from now.
scheduled_time_iso = (datetime.utcnow() + timedelta(days=6)).isoformat()
self.cmd(
"iot hub job create --job-id {} --job-type {} -q \"{}\" --twin-patch '{}' --start '{}' -n {} -g {}".format(
self.job_ids[2],
"scheduleUpdateTwin",
query_condition,
"{twin_patch_tags}",
scheduled_time_iso,
LIVE_HUB,
LIVE_RG,
),
checks=[self.check("jobId", self.job_ids[2])],
)
self.cmd(
"iot hub job cancel --job-id {} -n {} -g {}".format(
self.job_ids[2], LIVE_HUB, LIVE_RG
),
checks=[
self.check("jobId", self.job_ids[2]),
self.check("status", "cancelled"),
],
)
# Error - Cancel non-existant job
self.cmd(
"iot hub job cancel --job-id notarealjobid -n {} -g {}".format(
LIVE_HUB, LIVE_RG
),
expect_failure=True,
)
# List Job tests
# You can't explictly delete a job/job history so check for existance
job_result_set = self.cmd(
"iot hub job list -n {} -g {}".format(LIVE_HUB, LIVE_RG)
).get_output_in_json()
self.validate_job_list(jobs_set=job_result_set)
# List Jobs - with connection string
job_result_set_cs = self.cmd(
"iot hub job list --login {}".format(self.connection_string)
).get_output_in_json()
self.validate_job_list(jobs_set=job_result_set_cs)
def validate_job_list(self, jobs_set):
filtered_job_ids_result = {}
for job in jobs_set:
filtered_job_ids_result[job["jobId"]] = True
for job_id in self.job_ids:
assert job_id in filtered_job_ids_result
|
python
|
import abc
class Policy(object, metaclass=abc.ABCMeta):
"""
General policy interface.
"""
@abc.abstractmethod
def get_action(self, observation):
"""
:param observation:
:return: action, debug_dictionary
"""
pass
def reset(self):
pass
class ExplorationPolicy(Policy, metaclass=abc.ABCMeta):
def set_num_steps_total(self, t):
pass
|
python
|
import os
os.chdir("Python/Logging")
# log_settings changes sys.excepthook to log_settings.log_exceptions, so
# importing log_settings is sufficient to capture uncaught exceptions to the
# log file, meanwhile they are also (still) printed to stdout
import log_settings
# adds 'Starting new program!' with timestamp to the log file
log_settings.log_message("Starting new program!")
def divide(num1: int, num2: int) -> float:
log_settings.log_message(f"Attempting to divide {num1} by {num2}")
try:
return num1 / num2
except ZeroDivisionError as e:
# Caught exceptions can be added as a log message:
log_settings.log_exception(e)
# Normal behaviour:
print(divide(10, 3))
# Caught error:
print(divide(10, 0))
# Uncaught error:
print(divide(10 / "x"))
|
python
|
class IBSException(Exception):
pass
#TODO: This doesn't make sense for negative numbers, should they even be allowed?
class NumericValue():
""" To store a number which can be read to/from LE or BE """
def __init__(self, value):
self.value = value
@classmethod
def FromLEBytes(cls, databytes):
""" Construct from array of bytes in LE order """
value = sum([(databytes[n] << n*8) for n in range(len(databytes))])
return cls(value)
@classmethod
def FromBEBytes(cls, databytes):
""" Construct from array of bytes in BE order """
value = sum([(databytes[n] << n*8) for n in reversed(range(len(databytes)))])
return cls(value)
def AsLEBytes(self, nBytes = 4):
""" Returns a list of nBytes bytes in Little-Endian order """
return [(self.value >> (n * 8) & 0xFF) for n in range(nBytes)]
def AsBEBytes(self, nBytes = 4):
""" Returns a list of nBytes bytes in Big-Endian order """
return [(self.value >> (n * 8) & 0xFF) for n in reversed(range(nBytes))]
def AsString(self):
""" Returns the value as a string with hex and decimal representation"""
return '0x{value1:08X} ({value2})'.format(value1 = self.value, value2 = self.value)
def Value(self):
return self.value
class IBSID():
""" Represents a CAN ID in ISOBUS communication """
def __init__(self, da, sa, pgn, prio=6):
self.da = da
self.sa = sa
self.pgn = pgn
self.prio = prio
def GetCANID(self):
""" Return the CAN ID as a 29 bit identifier """
canid = 0
if ((self.pgn >> 8) & 0xFF) < 0xEF:
# PDU1
canid = (((self.prio & 0x7) << 26)
| ((self.pgn & 0xFF00) << 8)
| ((self.da & 0xFF) << 8)
| (self.sa & 0xFF))
else :
# PDU2
canid = (((self.prio & 0x7) << 26)
| ((self.pgn & 0xFFFF) << 8)
| (self.sa & 0xFF))
return canid
@classmethod
def FromCANID(cls, canid):
""" Get values from 29 bit identifier """
prio = (canid >> 26) & 0x7
sa = canid & 0xFF
pgn = 0
da = 0xFF
if ((canid >> 16) & 0xFF) <= 0xEF:
#Destination specific
pgn = (canid >> 8) & 0xFF00
da = (canid >> 8) & 0xFF
else:
#Broadcast
pgn = (canid >> 8) & 0xFFFF
return cls(da, sa, pgn, prio)
|
python
|
from pyrocko import automap
import math
import shutil
from pyrocko import model, gmtpy
from pyrocko.moment_tensor import magnitude_to_moment as mag2mom
from pyrocko.moment_tensor import to6
from pyrocko.guts import Object, Float, String, List
class ArrayMap(automap.Map):
stations = List.T(model.Station.T(), optional=True)
station_label_mapping = List.T(String.T(), optional=True)
event = model.Event.T(optional=True)
def __init__(
self, stations=None, station_label_mapping=None, event=None, *args, **kwargs
):
automap.Map.__init__(self)
self.stations = stations
self.station_label_mapping = station_label_mapping
self.event = event
def save(
self,
outpath,
resolution=75.0,
oversample=2.0,
size=None,
width=None,
height=None,
):
self.draw_labels()
self.draw_axes()
self.draw_cities()
size_factor = 9.0
if self.show_topo and self.show_topo_scale:
self._draw_topo_scale()
if self.stations:
lats = [s.lat for s in self.stations]
lons = [s.lon for s in self.stations]
self.gmt.psxy(in_columns=(lons, lats), S="t10p", G="black", *self.jxyr)
for i_station, s in enumerate(self.stations):
label = self.station_label_mapping.get(i_station, str(s.station))
self.add_label(s.lat, s.lon, label)
if self.event:
e = self.event
if e.moment_tensor:
if e.magnitude is None:
e.magnitude = e.moment_tensor.magnitude
size_cm = (
math.sqrt(math.sqrt(mag2mom(e.magnitude) / 100e17)) * size_factor
)
m = e.moment_tensor
data = (
e.lon,
e.lat,
10,
m.strike1,
m.dip1,
m.rake1,
1,
0,
0,
"M %1.1f" % e.magnitude,
)
if True:
self.gmt.psmeca(
S="%s%g" % ("a", size_cm * 2.0),
G="red",
# W='thinnest,%i/%i/%i' % darken(gmtpy.color_tup(colors[e.cluster])),
# L='thinnest,%i/%i/%i' % darken(gmtpy.color_tup(colors[e.cluster])),
in_rows=[data],
*self.jxyr
)
gmt = self._gmt
if outpath.endswith(".eps"):
tmppath = gmt.tempfilename() + ".eps"
elif outpath.endswith(".ps"):
tmppath = gmt.tempfilename() + ".ps"
else:
tmppath = gmt.tempfilename() + ".pdf"
gmt.save(tmppath)
if any(outpath.endswith(x) for x in (".eps", ".ps", ".pdf")):
shutil.copy(tmppath, outpath)
else:
convert_graph(
tmppath,
outpath,
resolution=resolution,
oversample=oversample,
size=size,
width=width,
height=height,
)
|
python
|
import sys
import json
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
class Fetcher:
'''
The crawler class used for retrieving information from sodexo's menu page
Note:
Blitman Commons is not yet included in sodexo's page. The class should throw an error if blm is at request
Attributes:
url (str): link to the corresponding menu page of the target dinning hall
'''
def __init__(self, target):
'''
Args:
target (str): Shortened name of the dinning hall
Returns:
None
Raises:
ValueError: If `target` is a not expected dinning hall name
'''
if target.lower() == 'cms':
self.url = 'https://menus.sodexomyway.com/BiteMenu/Menu?menuId=15465&locationId=76929001&whereami=http://rensselaerdining.com/dining-near-me/commons-dining-hall'
elif target.lower() == 'sage':
self.url = 'https://menus.sodexomyway.com/BiteMenu/Menu?menuId=15285&locationId=76929002&whereami=http://rensselaerdining.com/dining-near-me/russell-sage'
elif target.lower() == 'barh':
self.url = 'https://menus.sodexomyway.com/BiteMenu/Menu?menuId=667&locationId=76929003&whereami=http://rensselaerdining.com/dining-near-me/barh-dining-hall'
elif target.lower() == 'blm':
self.url = '' # blitman commons is currently not on RPI's official menu
else:
raise ValueError(f'Target dinning hall ({target}) is not valid')
self.target = target
self.driver = webdriver.Chrome()
def crawl(self):
'''
Raises:
raise RuntimeError if there is no data for the target dinning hall
Returns:
Packed json file with information from the target dinning hall
'''
# open url
self.driver.get(self.url)
source_code = self.driver.find_element_by_xpath("//*").get_attribute("outerHTML")
soup = BeautifulSoup(source_code, 'html.parser')
self.menu = {
"breakfast": None,
"lunch": None,
"dinner": None
}
self.menu["breakfast"] = soup.find_all(class_="breakfast")
self.menu["lunch"] = soup.find_all(class_="lunch")
self.menu["dinner"] = soup.find_all(class_="dinner")
# TODO: Structure out the data in self.menu and return
pass
# Load the data that PHP sent us
try:
data = json.loads(sys.argv[1])
except json.JSONDecodeError:
print("ERROR decoding JSON")
sys.exit(1)
# Generate some data to send to PHP
result = {'res': '', 'menu': '', 'img': ''}
# Send it to stdout (to PHP)
print(json.dumps(result))
|
python
|
import math
def round_up(n, multiple):
"""
can be used to ensure that you have next multiple if you need an int, but have a float
n = number to check
multiple = number you'd like to round up to
EX:
num_ranks = 64
num_ios = 26252
this is not an even number if you divide
returns the next multiple (upper)
"""
return math.ceil(n / (multiple + 0.0)) * multiple
|
python
|
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
packages=["mushr_rhc_ros"], package_dir={"": "src"}
)
setup(install_requires=["numpy", "torch", "networkx", "scipy", "sklearn"], **setup_args)
|
python
|
# Copyright 2018 Google, Inc.,
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Environment that runs OpenAI Gym games."""
import threading
import time
import gym
import numpy as np
import sonnet as snt
import tensorflow as tf
from vaeseq import util
class Environment(snt.RNNCore):
"""Plays a batch of games."""
def __init__(self, hparams, name=None):
super(Environment, self).__init__(name=name)
self._hparams = hparams
self._games = {}
self._games_lock = threading.Lock()
self._next_id = 1
self._id_lock = threading.Lock()
self._step_time = None
self._render_thread = None
@property
def output_size(self):
return dict(output=tf.TensorShape(self._hparams.game_output_size),
score=tf.TensorShape([]),
game_over=tf.TensorShape([]))
@property
def output_dtype(self):
return dict(output=tf.float32,
score=tf.float32,
game_over=tf.float32)
@property
def state_size(self):
"""The state is a game ID, or 0 if the game is over."""
return tf.TensorShape([])
@property
def state_dtype(self):
"""The state is a game ID, or 0 if the game is over."""
return tf.int64
def initial_state(self, batch_size):
def _make_games(batch_size):
"""Produces a serialized batch of randomized games."""
with self._id_lock:
first_id = self._next_id
self._next_id += batch_size
game_ids = range(first_id, self._next_id)
updates = []
for game_id in game_ids:
game = gym.make(self._hparams.game)
game.reset()
updates.append((game_id, game))
with self._games_lock:
self._games.update(updates)
return np.asarray(game_ids, dtype=np.int64)
state, = tf.py_func(_make_games, [batch_size], [tf.int64])
state.set_shape([None])
return state
def _build(self, input_, state):
actions = tf.distributions.Categorical(logits=input_).sample()
def _step_games(actions, state):
"""Take a step in a single game."""
score = np.zeros(len(state), dtype=np.float32)
output = np.zeros([len(state)] + self._hparams.game_output_size,
dtype=np.float32)
games = [None] * len(state)
with self._games_lock:
for i, game_id in enumerate(state):
if game_id:
games[i] = self._games[game_id]
finished_games = []
for i, game in enumerate(games):
if game is None:
continue
output[i], score[i], game_over, _ = game.step(actions[i])
if game_over:
finished_games.append(state[i])
state[i] = 0
if finished_games:
with self._games_lock:
for game_id in finished_games:
del self._games[game_id]
if self._render_thread is not None:
time.sleep(0.1)
return output, score, state
output, score, state = tf.py_func(
_step_games, [actions, state],
[tf.float32, tf.float32, tf.int64])
output = dict(output=output, score=score,
game_over=2. * tf.to_float(tf.equal(state, 0)) - 1.)
# Fix up the inferred shapes.
util.set_tensor_shapes(output, self.output_size, add_batch_dims=1)
util.set_tensor_shapes(state, self.state_size, add_batch_dims=1)
return output, state
def start_render_thread(self):
if self._render_thread is not None:
return self._render_thread
self._render_thread = threading.Thread(target=self._render_games_loop)
self._render_thread.start()
def stop_render_thread(self):
if self._render_thread is None:
return
tmp = self._render_thread
self._render_thread = None
tmp.join()
def _render_games_loop(self):
while (self._render_thread is not None and
threading.current_thread().ident == self._render_thread.ident):
with self._games_lock:
games = list(self._games.values())
for game in games:
game.render()
time.sleep(0.05)
|
python
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import ctypes
from mxnet.test_utils import *
import os
import time
import argparse
from mxnet.base import check_call, _LIB
parser = argparse.ArgumentParser(description="Benchmark cast storage operators",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--num-omp-threads', type=int, default=1, help='number of omp threads to set in MXNet')
args = parser.parse_args()
def measure_cost(repeat, f, *args, **kwargs):
start = time.time()
results = []
for i in range(repeat):
(f(*args, **kwargs)).wait_to_read()
end = time.time()
diff = end - start
return diff / repeat
def run_cast_storage_synthetic():
def dense_to_sparse(m, n, density, ctx, repeat, stype):
set_default_device(ctx)
data_shape = (m, n)
dns_data = rand_ndarray(data_shape, stype, density).tostype('default')
dns_data.wait_to_read()
# do one warm up run, verify correctness
assert same(mx.nd.cast_storage(dns_data, stype).asnumpy(), dns_data.asnumpy())
# start benchmarking
cost = measure_cost(repeat, mx.nd.cast_storage, dns_data, stype)
results = '{:10.1f} {:>10} {:8d} {:8d} {:10.2f}'.format(density*100, str(ctx), m, n, cost*1000)
print(results)
check_call(_LIB.MXSetNumOMPThreads(ctypes.c_int(args.num_omp_threads)))
# params
# m number of rows
# n number of columns
# density density of the matrix
# num_repeat number of benchmark runs to average over
# contexts mx.cpu(), mx.gpu()
# note: benchmark different contexts separately; to benchmark cpu, compile without CUDA
# benchmarks dns_to_csr, dns_to_rsp
m = [ 512, 512]
n = [50000, 100000]
density = [1.00, 0.80, 0.60, 0.40, 0.20, 0.10, 0.05, 0.02, 0.01]
num_repeat = 10
contexts = [mx.gpu()]
benchmarks = ["dns_to_csr", "dns_to_rsp"]
# run benchmark
for b in benchmarks:
stype = ''
print("==================================================")
if b is "dns_to_csr":
stype = 'csr'
print(" cast_storage benchmark: dense to csr, size m x n ")
elif b is "dns_to_rsp":
stype = 'row_sparse'
print(" cast_storage benchmark: dense to rsp, size m x n ")
else:
print("invalid benchmark: %s" %b)
continue
print("==================================================")
headline = '{:>10} {:>10} {:>8} {:>8} {:>10}'.format('density(%)', 'context', 'm', 'n', 'time(ms)')
print(headline)
for i in range(len(n)):
for ctx in contexts:
for den in density:
dense_to_sparse(m[i], n[i], den, ctx, num_repeat, stype)
print("")
print("")
if __name__ == "__main__":
run_cast_storage_synthetic()
|
python
|
from nltk.stem.porter import PorterStemmer
from nltk.tokenize import word_tokenize
import random
from tqdm import tqdm
from summariser.ngram_vector.base import Sentence
from summariser.ngram_vector.state_type import *
from utils.data_helpers import *
# from summariser.utils.data_helpers import *
class Vectoriser:
def __init__(self,docs,sum_len=100,no_stop_words=True,stem=True,block=1,base=200,lang='english'):
self.docs = docs
self.without_stopwords = no_stop_words
self.stem = stem
self.block_num = block
self.base_length = base
self.language = lang
self.sum_token_length = sum_len
self.stemmer = PorterStemmer()
self.stoplist = set(stopwords.words(self.language))
self.sim_scores = {}
self.stemmed_sentences_list = []
self.load_data()
def sample_random_summaries(self,num):
act_list = []
for ii in tqdm(range(num), desc='generating samples for memory replay'):
state = State(self.sum_token_length, self.base_length, len(self.sentences),self.block_num, self.language)
while state.available_sents != [0]:
new_id = random.choice(state.available_sents)
if new_id == 0: continue
if new_id > 0 and len(self.sentences[new_id-1].untokenized_form.split(' ')) > self.sum_token_length: continue
state.updateState(new_id-1,self.sentences)
actions = state.historical_actions
act_list.append(actions)
return act_list
def getSummaryVectors(self,summary_acts_list):
vector_list = []
for act_list in summary_acts_list:
state = State(self.sum_token_length, self.base_length, len(self.sentences), self.block_num, self.language)
for i, act in enumerate(act_list):
state.updateState(act, self.sentences, read=True)
vector = state.getSelfVector(self.top_ngrams_list, self.sentences)
vector_list.append(vector)
return vector_list
def sent2tokens(self, sent_str):
if self.without_stopwords and self.stem:
return sent2stokens_wostop(sent_str, self.stemmer, self.stoplist, self.language)
elif self.without_stopwords == False and self.stem:
return sent2stokens(sent_str, self.stemmer, self.language)
elif self.without_stopwords and self.stem == False:
return sent2tokens_wostop(sent_str, self.stoplist, self.language)
else: # both false
return sent2tokens(sent_str, self.language)
def load_data(self):
self.sentences = []
for doc_id, doc in enumerate(self.docs):
doc_name, doc_sents = doc
doc_tokens_list = []
for sent_id, sent_text in enumerate(doc_sents):
token_sent = word_tokenize(sent_text, self.language)
current_sent = Sentence(token_sent, doc_id, sent_id + 1)
untokenized_form = untokenize(token_sent)
current_sent.untokenized_form = untokenized_form
current_sent.length = len(untokenized_form.split(' '))
self.sentences.append(current_sent)
sent_tokens = self.sent2tokens(untokenized_form)
doc_tokens_list.extend(sent_tokens)
stemmed_form = ' '.join(sent_tokens)
self.stemmed_sentences_list.append(stemmed_form)
#print('total sentence num: ' + str(len(self.sentences)))
self.state_length_computer = StateLengthComputer(self.block_num, self.base_length, len(self.sentences))
self.top_ngrams_num = self.state_length_computer.getStatesLength(self.block_num)
self.vec_length = self.state_length_computer.getTotalLength()
sent_list = []
for sent in self.sentences:
sent_list.append(sent.untokenized_form)
self.top_ngrams_list = getTopNgrams(sent_list, self.stemmer, self.language,
self.stoplist, 2, self.top_ngrams_num)
|
python
|
# coding: utf-8
# In[7]:
import numpy as np
#toy example of fixImages_stackocclusions
#a = np.arange(16).reshape(4, 2, 2)
#b = a + 2
#print("a")
#print(a)
#print(2*'\n')
#print("b")
#print(b)
#print(2*'\n')
#print("stack_axis = 0")
#print(np.stack((a,b), axis=0))
#print(2*'\n')
#print("stack_axis = 1")
#print(np.stack((a,b), axis=1))
#print(2*'\n')
#This is exactly what we need:
#print("stack_axis = 2")
#print(np.stack((a,b), axis=2))
# In[19]:
#fixImages_stackocclusions function
#Stack each image along with all of its occulusions!
#This function is more useful for display purposes!
#n = 3
#n1 = n2 = 4
#imgs = np.arange(n*n1*n2).reshape(n,n1,n2)
#print(imgs)
#print(2*'\n')
#print(imgs[0]) #first image
#print(imgs[1]) #second image
#print(imgs[2]) #third image
#strides = [1, 1]
#patch_size = [2, 2]
def fixImages_stackOcclusions(imgs, strides, patch_size):
strides1 = strides[0] #stride along columns
strides2 = strides[1] #stride along rows
w = patch_size[0] #width of the patch
h = patch_size[1] #height of the patch
#
n = imgs.shape[0] # total number of images that belong to imgs
n1 = imgs.shape[1] # the first dimension of each image
n2 = imgs.shape[2] # the second dimension of each image
GivenImages_stackOcclusions = [] #initializing a list for storing occluded images
iter_columns = range(0, n1-w+strides1, strides1) #iterator along columns object
iter_rows = range(0, n2-h+strides2, strides2) #iterator along rows object
#total number of possible occlusions in each dimension
num_rows = len(iter_columns) #total number of iterations along columns
num_columns = len(iter_rows) #total number of iterations along rows
#we want the moving patch to act simultaneously
#on all the images that belong to imgs at once:
for i in iter_columns:
for j in iter_rows:
occluded_imgs = imgs.copy()
if i == iter_columns[-1]:
occluded_imgs[:,i:n2+1, j:j+h] = 0
#print(range(i, n2), range(j, j+h))
#print(occluded_imgs)
#print(2*'\n')
GivenImages_stackOcclusions.append(occluded_imgs)
elif j == iter_rows[-1]:
occluded_imgs[:,i:i+w, j:n1+1] = 0
#print(range(i, i+w), range(j,n1))
#print(occluded_imgs)
#print(2*'\n')
GivenImages_stackOcclusions.append(occluded_imgs)
else:
occluded_imgs[:,i:i+w, j:j+h] = 0
#print(range(i, i+w), range(j,j+w))
#print(occluded_imgs)
#print(2*'\n')
GivenImages_stackOcclusions.append(occluded_imgs)
#print(len(GivenImages_stackOcclusions))
#print(num_rows*num_columns)
#print(GivenImages_stackOcclusions)
#If were to stack each image along with all of its occulusions then this would have been what we wanted!
#print('axis=1')
#print(np.stack(GivenImages_stackOcclusions, axis=1))
stack_occlusions_array = np.stack(GivenImages_stackOcclusions, axis=1)
print("stack_occlusions_array's shape: ", stack_occlusions_array.shape)
return stack_occlusions_array
#stack_occlusions_array = fixImages_stackOcclusions(imgs, strides, patch_size)
#print("stack_occlusions_array")
#print(stack_occlusions_array)
# In[20]:
#fixOcclusions_stackImages
# but given an occlusion located in a particular area in the image, for all images in our digitClass
#we want to list that particular occlusion for all the images in our digitClass
#n = 3
#n1 = n2 = 4
#imgs = np.arange(n*n1*n2).reshape(n,n1,n2)
#print(imgs)
#print(2*'\n')
#print(imgs[0]) #first image
#print(imgs[1]) #second image
#print(imgs[2]) #third image
#strides = [1, 1]
#patch_size = [2, 2]
#for each fixed occlusion, we are stacking the occluded images with that particular occlusion
#in a single entry of a list
def fixOcclusions_stackImages(imgs, strides, patch_size):
strides1 = strides[0] #stride along columns
strides2 = strides[1] #stride along rows
w = patch_size[0] #width of the patch
h = patch_size[1] #height of the patch
#
n = imgs.shape[0] # total number of images that belong to imgs
n1 = imgs.shape[1] # the first dimension of each image
n2 = imgs.shape[2] # the second dimension of each image
givenOcclusions_stackImages = [] #initializing a list for storing occluded images
iter_columns = range(0, n1-w+strides1, strides1) #iterator along columns object
iter_rows = range(0, n2-h+strides2, strides2) #iterator along rows object
#total number of possible occlusions in each dimension
num_rows = len(iter_columns) #total number of iterations along columns
num_columns = len(iter_rows) #total number of iterations along rows
#we want the moving patch to act simultaneously
#on all the images that belong to imgs at once:
for i in iter_columns:
for j in iter_rows:
occluded_imgs = imgs.copy()
if i == iter_columns[-1]:
occluded_imgs[:,i:n2+1, j:j+h] = 0
#print(range(i, n2), range(j, j+h))
#print(occluded_imgs)
#print(2*'\n')
givenOcclusions_stackImages.append(occluded_imgs)
elif j == iter_rows[-1]:
occluded_imgs[:,i:i+w, j:n1+1] = 0
#print(range(i, i+w), range(j,n1))
#print(occluded_imgs)
#print(2*'\n')
givenOcclusions_stackImages.append(occluded_imgs)
else:
occluded_imgs[:,i:i+w, j:j+h] = 0
#print(range(i, i+w), range(j,j+w))
#print(occluded_imgs)
#print(2*'\n')
givenOcclusions_stackImages.append(occluded_imgs)
return givenOcclusions_stackImages
#givenOcclusions_stackImages = fixOcclusions_stackImages(imgs, strides, patch_size)
#print(len(givenOcclusions_stackImages))
#print(num_rows*num_columns)
#print(givenOcclusions_stackImages)
#done!
|
python
|
# Copyright 2020 Antonio Macaluso
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from qml_Utils import *
X, y = datasets.make_blobs(n_samples=10, centers=[[0.2, 0.8], [0.7, 0.1]],
n_features=2, center_box=(0, 1),
cluster_std=0.2, random_state=5432)
# pad the vectors to size 2^2 with constant values
padding = 0.3 * np.ones((len(X), 1))
X_pad = np.c_[np.c_[X, padding], np.zeros((len(X), 1))]
normalization = np.sqrt(np.sum(X_pad ** 2, -1))
X_norm = (X_pad.T / normalization).T
best_param = [[np.array([[[ 0.01762722, -0.05147767, 0.00978738],
[ 0.02240893, 0.01867558, -0.00977278]]]),
np.array([[[ 5.60373788e-03, -1.11406652e+00, -1.03218852e-03],
[ 4.10598502e-03, 1.44043571e-03, 1.45427351e-02]]]),
3.4785004378680453],
-0.7936398118318136]
parameters = best_param[0]
bias = best_param[1]
features = np.array([get_angles(x) for x in X_norm])
qiskit.IBMQ.load_account()
predictions_qml_sim = []
predictions_qml_real = []
for f in features:
# f = features[1]
device = qml.device("default.qubit", wires=5)
pred_sim = test_qSLP_qml(f, best_param, dev= device)[0]
predictions_qml_sim.append(pred_sim)
device = qml.device('qiskit.ibmq', wires=5, backend='ibmq_santiago')
pred_real = test_qSLP_qml(f, best_param, dev= device)[0]
predictions_qml_real.append(pred_real)
# row = f.tolist()
# row.append(pred_sim)
# row.append(pred_real)
# row = pd.Series(row)
data_test = pd.concat([pd.Series(predictions_qml_sim),
pd.Series(predictions_qml_real)],
axis=1)
data_test.to_csv('data_test.csv')
data_test = pd.concat([pd.Series(predictions_qml_sim),
pd.Series(predictions_qml_real),pd.Series(y)], axis=1)
data_test.to_csv('data_test.csv')
predictions_qasm = []
predictions_qml = []
for f in features:
# f = features[1]
device = qml.device("qiskit.aer", wires=5, backend='qasm_simulator')
pred_qasm = test_qSLP_qml(f, best_param, dev= device)[0]
predictions_qasm.append(pred_qasm)
device = qml.device("default.qubit", wires=5)
pred_qml = test_qSLP_qml(f, best_param, dev= device)[0]
predictions_qml.append(pred_qml)
data_test_qasm = pd.concat([pd.Series(predictions_qasm),
pd.Series(predictions_qml)],
axis=1)
data_test_qasm.to_csv('data_test_qasm.csv', index=False)
data_test_qasm = pd.concat([pd.Series(predictions_qml_sim),
pd.Series(predictions_qml_real),pd.Series(y)],
axis=1)
data_test_qasm.to_csv('data_test_qasm.csv', index = False)
# provider = qiskit.IBMQ.get_provider(group='open')
# ibmq_ourense = provider.get_backend('ibmq_ourense')
#
# backend = IBMQ.backends(operational=True, simulator=False)[2]
# pred = test_qSLP_qml(f, best_param)[0]
|
python
|
# Generated by Django 3.0.3 on 2020-09-10 12:25
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sequence', '0026_sequence_coordinates_ele'),
]
operations = [
migrations.AddField(
model_name='image',
name='ele',
field=models.FloatField(default=0),
),
migrations.AddField(
model_name='image',
name='point',
field=django.contrib.gis.db.models.fields.PointField(blank=True, null=True, srid=4326),
),
]
|
python
|
# -*- coding: utf-8 -*-
"""Query web services."""
import gzip
import logging
from ._bouth23 import bstream, s
from ._exceptions import ISBNLibHTTPError, ISBNLibURLError
from ..config import options
# pylint: disable=import-error
# pylint: disable=wrong-import-order
# pylint: disable=no-name-in-module
try: # pragma: no cover
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
except ImportError: # pragma: no cover
from urllib import urlencode
from urllib2 import Request, urlopen, HTTPError, URLError
UA = 'isbnlib (gzip)'
LOGGER = logging.getLogger(__name__)
# pylint: disable=too-few-public-methods
# pylint: disable=useless-object-inheritance
class WEBService(object):
"""Class to query web services."""
def __init__(self, url, user_agent=UA, values=None, appheaders=None):
"""Initialize main properties."""
# TODO(use urllib.quote to the non-ascii part?)
self._url = url
# headers to accept gzipped content
headers = {'Accept-Encoding': 'gzip', 'User-Agent': user_agent}
# add more user provided headers
if appheaders: # pragma: no cover
headers.update(appheaders)
# if 'data' it does a POST request (data must be urlencoded)
data = urlencode(values).encode('utf8') if values else None
self._request = Request(url, data, headers=headers)
def response(self):
"""Check errors on response."""
try:
response = urlopen(self._request,
timeout=options.get('URLOPEN_TIMEOUT'))
LOGGER.debug('Request headers:\n%s', self._request.header_items())
except HTTPError as e: # pragma: no cover
LOGGER.critical('ISBNLibHTTPError for %s with code %s [%s]',
self._url, e.code, e.msg)
if e.code in (401, 403, 429):
raise ISBNLibHTTPError('%s Are you making many requests?' %
e.code)
if e.code in (502, 504):
raise ISBNLibHTTPError('%s Service temporarily unavailable!' %
e.code)
raise ISBNLibHTTPError('(%s) %s' % (e.code, e.msg))
except URLError as e: # pragma: no cover
LOGGER.critical('ISBNLibURLError for %s with reason %s', self._url,
e.reason)
raise ISBNLibURLError(e.reason)
return response if response else None
def data(self):
"""Return the uncompressed data."""
res = self.response()
LOGGER.debug('Response headers:\n%s', res.info())
if res.info().get('Content-Encoding') == 'gzip':
buf = bstream(res.read())
f = gzip.GzipFile(fileobj=buf)
data = f.read()
else: # pragma: no cover
data = res.read()
return s(data)
def query(url, user_agent=UA, values=None, appheaders=None):
"""Query to a web service."""
service = WEBService(url,
user_agent=user_agent,
values=values,
appheaders=appheaders)
data = service.data()
LOGGER.debug('Raw data from service:\n%s', data)
return data
|
python
|
# Copyright 2014, Sandia Corporation. Under the terms of Contract
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain
# rights in this software.
"""Functionality for managing scene graphs.
Note that the scenegraph is an internal implementation detail for developers
adding new functionality to Toyplot, casual Toyplot users will never need to
work with it.
"""
import collections
##########################################################################
# AdjacencyList
class AdjacencyList(object):
"""Adjaceny list representation for a directed graph."""
def __init__(self):
self._targets = collections.defaultdict(list)
def add_edge(self, source, target):
"""Add a directed edge from `source` to `target`."""
self._targets[source].append(target)
def remove_edge(self, source, target):
"""Remove the directed edge from `source` to `target`, if it exists."""
self._targets[source].remove(target)
def sources(self, target):
"""Return nodes that are connected to `target` via incoming edges."""
return [source for source, targets in self._targets.items() if target in targets]
def targets(self, source):
"""Return nodes are connected to `source` via outgoing edges."""
return self._targets.get(source, [])
##########################################################################
# SceneGraph
class SceneGraph(object):
"""Collection of graphs representing semantic relationships among a (small number) of canvas objects.
"""
def __init__(self):
self._relationships = {}
def __repr__(self):
result = "<toyplot.scenegraph.SceneGraph at 0x{:x}>".format(id(self))
for relationship, graph in self._relationships.items():
result += "\n Relationship: {}".format(relationship)
for source, targets in graph._targets.items():
result += "\n {!r} ->".format(source)
for target in targets:
result += "\n {!r}".format(target)
return result
def add_edge(self, source, relationship, target):
"""Add an edge of type `relationship` from `source` to `target`.
"""
if not isinstance(relationship, str):
raise ValueError("Relationship must be a string.")
if relationship not in self._relationships:
self._relationships[relationship] = AdjacencyList()
self._relationships[relationship].add_edge(source, target)
def remove_edge(self, source, relationship, target):
"""Remove an edge of type `relationship` from `source` to `target`, if one exists.
"""
if not isinstance(relationship, str):
raise ValueError("Relationship must be a string.")
if relationship not in self._relationships:
return
self._relationships[relationship].remove_edge(source, target)
def sources(self, relationship, target):
"""Return nodes that are connected to `target` via incoming edges of type `relationship`, if any."""
if not isinstance(relationship, str):
raise ValueError("Relationship must be a string.")
if relationship not in self._relationships:
return []
return self._relationships[relationship].sources(target)
def source(self, relationship, target):
"""Return a single node that is connected to `target` via an incoming edge of type `relationship`.
Raises an exception if there isn't exactly one incoming edge of type `relationship`.
"""
if not isinstance(relationship, str):
raise ValueError("Relationship must be a string.")
result = self.sources(relationship, target)
if len(result) != 1:
raise RuntimeError("Expected one source, found {}.".format(len(result)))
return result[0]
def targets(self, source, relationship):
"""Return nodes are connected to `source` via outgoing edges of type `relationship`."""
if not isinstance(relationship, str):
raise ValueError("Relationship must be a string.")
if relationship not in self._relationships:
return []
return self._relationships[relationship].targets(source)
|
python
|
__all__ = ["analysis", "data", "geometry", "io", "util"]
|
python
|
# coding: utf-8
#
from tornado.web import RequestHandler
from tornado.escape import json_decode
class BaseRequestHandler(RequestHandler):
pass
class IndexHandler(BaseRequestHandler):
def get(self):
self.write("Hello ATX-Storage")
|
python
|
import os
from Crypto.Protocol.KDF import scrypt
KEY_LENGTH = 32
N = 2**16 ##meant for ram
R = 10
P = 10
import binascii
import bcrypt
from loguru import logger
def generate_bcrypt(password):
if isinstance(password, str):
password = password.encode()
hashed =bcrypt.hashpw(password, bcrypt.gensalt())
return hashed
def check_bcrypt(password: str, hashed_password: str):
if isinstance(password, str):
password = password.encode()
if isinstance(hashed_password, str):
hashed_password = hashed_password.encode()
logger.warning(password)
logger.warning(hashed_password)
if bcrypt.checkpw(password, hashed_password):
return True
return False
def generate_scrypt_key(password, salt=None):
##return bytes of keys, returns list in case of keys > 1
##returns hex encoded salt and key byte array
if not salt:
salt = os.urandom(16)
keys = scrypt(password, salt, KEY_LENGTH, N, R, P, 1)
return keys, salt.hex()
|
python
|
# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
app_name = 'url_shorter'
urlpatterns = [
url(r'user_url_list/', views.UserURLListView.as_view(), name="user_url_list"),
url(r'user_url_create/', views.UserURLCreateView.as_view(), name="user_url_create"),
url(r'user_url_detail/(?P<short_url>[\w.@+-]+)/', views.UserURLDetailView.as_view(), name='user_url_detail'),
url(r'user_url_redirect/(?P<short_url>[\w.@+-]+)/', views.UserURLRedirectView.as_view(), name="user_url_redirect"),
url(r'url_create/', views.URLCreateView.as_view(), name="url_create"),
url(r'url_detail/(?P<short_url>[\w.@+-]+)/', views.URLDetailView.as_view(), name='url_detail'),
url(r'url_redirect/(?P<short_url>[\w.@+-]+)/', views.URLRedirectView.as_view(), name="url_redirect"),
url(r'', TemplateView.as_view(template_name="url_shorter/base.html")),
]
|
python
|
#!/usr/bin/python3
#coding=utf-8
"""
A flask based server for calculating.
@author: vincent cheung
@file: server.py
"""
from flask import Flask,render_template,request,redirect,url_for
from flask import send_file, Response
import os
import sys
sys.path.append('../')
from calculate import *
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
# Get the upload file
f = request.files['file']
# Read the upload CSV file
# TODO: Check File funtion not yet implemented
df = pd.read_csv(f, encoding='utf-8')
## Header like
head_str = u'序号,日期,市内交通费人民币,市内交通费港币,长途交通费人民币,长途交通费港币,餐费人民币,餐费港币,其他费用人民币,其他费用港币'
head_str_list = head_str.split(',')
#### Check upload file
if len(head_str_list) != df.shape[1]:
return 'Wrong file, please re-upload'
for i,j in zip(df.head(0),head_str_list):
if i != j:
return 'Wrong file, please re-upload'
#### Start process upload file
## Replace Nan to zero
df.fillna(0.0, inplace=True)
data={'日期':[],'市内交通费':[],'长途交通费':[],'餐费':[],'其他费用':[],'备注':[]}
## Iterate each record in df
for index, row in df.iterrows():
date = row[u'日期']
print ('Processing record on date:{}'.format(date))
rate, info_str = get_rate(date)
# Calculate the CNY seperately.
# Summup according to the items in K3 ERP system.
local_fee = row[u'市内交通费港币']/100.0*rate + row[u'市内交通费人民币']
traverse_fee = row[u'长途交通费港币']/100.0*rate + row[u'长途交通费人民币']
meal_fee = row[u'餐费港币']/100.0*rate + row[u'餐费人民币']
other_fee = row[u'其他费用港币']/100.0*rate + row[u'其他费用人民币']
# Collect data
data['日期'].append(date)
data['市内交通费'].append(local_fee)
data['长途交通费'].append(traverse_fee)
data['餐费'].append(meal_fee)
data['其他费用'].append(other_fee)
data['备注'].append(info_str)
## Sleep for 0.05 seconds in case of BOC server error
# TODO: May cause error while the input dataframe is too big, which cause the http link broken
time.sleep(0.05)
## Save resutls in csv format
frame = pd.DataFrame(data, columns=['日期', '市内交通费', '长途交通费','餐费','其他费用','备注'])
csv_buf = frame.to_csv(encoding='utf-8', float_format='%.2f')
## Return for download
file_name = 'results.csv'
response = Response(csv_buf, mimetype='text/csv')
response.headers["Content-Disposition"] = "attachment; filename=results.csv;"
return response
return render_template('index.html')
@app.route('/template.csv', methods=['POST', 'GET'])
def csv():
## Return file for download
return send_file('template.csv')
if __name__ == '__main__':
app.run(debug=True)
|
python
|
if ((True and True) or (not True and True)) and \
(True or True):
pass
|
python
|
value = '382d817119a18844865d880255a8221d90601ad164e8a8e1dd8a48f45846152255f839e09ab176154244faa95513d16e5e314078a97fdb8bb6da8d5615225695225674a4001a9177fb112277c45e17f85753c504d7187ed3cd43b107803827e09502559bf164292affe8aaa8e88ac898f9447119a188448692070056a2628864e6d7105edc5866b9b9b6ebcad6dc3982952a7674a62015025695225674a400d8715efb112277c45edb799f9728355c586f95b002e8aa815b83df3704571b99b6346426bd9862920721751857cb38f69bb3dee18ce1793bc857e27f74a400dd8a48d971bc15d07f521921b80948a86a8eb70457d1138279a796b8fbc43d9801e8ead669c8dcb10781788b5fe91097bad104d9ab952190a15ae706b50477b8dbe4d3cd437119c12842a42190e1a868aeb76446588d52b1078057e27cf7c65fa84aae5b8bbf6b88c19b9176a94a8eb7045778513712f1679b655d9c0255e88ac889b882b8f104711ba1dbabd7120520e188e195225655a802c184a0282affa86a8eb70457120542f7187658515f154244548a4212074278e7c6d3cd4595283e3d9a61d8ad56ba294878c5e69502551bf162487886280aff7b3309' # noqa
"""
This sequence has been encrypted with a cipher that works as follows:
key = {unknown 4-byte value}
#define SCR_WIDTH 24
#define SCR_LOOPS 3
for (int eggs = {each 3-byte tuple in plaintext})
{
unsigned int i, roll = 7;
for (i=0; i<SCR_LOOPS; i++) {
eggs ^= (key[eggs&0x3]<<8);
eggs = (eggs<<roll)|(eggs>>(SCR_WIDTH-roll));
eggs &= ((1<<SCR_WIDTH)-1);
}
print eggs;
}
"""
|
python
|
from taichi.misc.util import *
from taichi.two_d import *
from taichi import get_asset_path
if __name__ == '__main__':
scale = 8
res = (80 * scale, 40 * scale)
async = True
if async:
simulator = MPMSimulator(
res=res,
simulation_time=30,
frame_dt=1e-1,
base_delta_t=1e-6,
async=True,
strength_dt_mul=6)
else:
simulator = MPMSimulator(
res=res, simulation_time=30, frame_dt=1e-1, base_delta_t=1e-3)
simulator.add_event(-1,
lambda s: s.add_particles_texture(Vector(1, 0.60), 1.8, get_asset_path('textures/asyncmpm.png'),
'ep'))
levelset = simulator.create_levelset()
levelset.add_polygon([(0.05, 0.05), (1, 0.4), (1.95, 0.05), (1.95, 0.95),
(0.05, 0.95)], True)
levelset.set_friction(0)
simulator.set_levelset(levelset)
window = SimulationWindow(
1280,
simulator,
color_schemes['bw'],
levelset_supersampling=2,
show_images=True,
show_stat=False)
|
python
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
import sys
con = lite.connect('Database.db')
with con:
cur = con.cursor()
#Create data for the user table
cur.execute("CREATE TABLE users(UserId INT, UserName TEXT, Password TEXT)")
cur.execute("INSERT INTO users VALUES(1,'Admin','0cef1fb10f60529028a71f58e54ed07b')")
cur.execute("INSERT INTO users VALUES(2,'User','022b5ac7ea72a5ee3bfc6b3eb461f2fc')")
cur.execute("INSERT INTO users VALUES(3,'Guest','94ca112be7fc3f3934c45c6809875168')")
cur.execute("INSERT INTO users VALUES(4,'Plebian','0cbdc7572ff7d07cc6807a5b102a3b93')")
#Create some data for pageinformation
cur.execute("CREATE TABLE pages(pageId INT, title TEXT, content TEXT)")
cur.execute("INSERT INTO pages VALUES(1,'The Dashboard','So, here we are. After a lot of hard work and hassle here we have the dashboard finally up and running. Please take note of this message since it will be updated a lot!')")
cur.execute("INSERT INTO pages VALUES(2,'Seccond page','why is there a seccond page, we are going to update the first one right?')")
#Create some data for messaging
cur.execute("CREATE TABLE messages(messageId INT, name TEXT, message TEXT, link TEXT, [timestamp] timestamp )")
cur.execute("INSERT INTO messages VALUES(1,'Jack Sparrow','Bring me them treasure', 'https://www.google.nl/search?q=pirate+treasure&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjHncGMn6DaAhVBJsAKHeJUCpsQ_AUICigB&biw=1303&bih=879#imgrc=vHC7-cQ7t5N1IM:', '2012-12-25 16:59:59')")
cur.execute("INSERT INTO messages VALUES(2,'C. Ash', 'Can we please stay on topic and serious?', '', '2012-12-25 18:21:17')")
con.commit()
#con.close()
|
python
|
import itertools
import logging
import os.path
import sys
import time
import click
import pychromecast
from pychromecast.error import PyChromecastError
import pylast
import toml
logger = logging.getLogger(__name__)
# Default set of apps to scrobble from.
APP_WHITELIST = ['Spotify', 'Google Play Music', 'SoundCloud', 'Plex', 'YouTube Music']
SCROBBLE_THRESHOLD_PCT = 0.50
SCROBBLE_THRESHOLD_SECS = 120
UNSUPPORTED_MODES = {'MultizoneLeader'}
POLL_INTERVAL = 5.0
RECONNECT_INTERVAL = 15
class ChromecastNotFoundException(Exception):
pass
class ScrobbleListener(object):
'''
Tracks state of media playing on a single Chromecast device and
logs to {last,libre}.fm when scrobble threshholds are hit
'''
def __init__(self, config, cast_name, available_devices=None):
self.cast_name = cast_name
self.cast_config = config.get('chromecast', {})
self.app_whitelist = self.cast_config.get('app_whitelist', APP_WHITELIST)
self.last_scrobbled = {}
self.current_track = {}
self.current_time = 0
self.last_poll = time.time()
self._connect_chromecast(available_devices)
if not self.cast:
raise ChromecastNotFoundException()
self.scrobblers = []
if 'lastfm' in config:
self.scrobblers.append(pylast.LastFMNetwork(
api_key=config['lastfm']['api_key'],
api_secret=config['lastfm']['api_secret'],
username=config['lastfm']['user_name'],
password_hash=pylast.md5(config['lastfm']['password'])))
if 'librefm' in config:
self.scrobblers.append(pylast.LibreFMNetwork(
session_key=config['librefm']['session_key'],
username=config['librefm']['user_name'],
password_hash=pylast.md5(config['librefm']['password'])
))
self.estimate_spotify_timestamp = self.cast_config.get(
'estimate_spotify_timestamp', True)
def poll(self):
''' Helper for `_poll` to handle errors and reconnects. '''
try:
if not self.cast:
click.echo('Reconnecting to cast device `%s`...' % self.cast_name)
self._connect_chromecast()
else:
self._poll()
# This could happen due to network hiccups, Chromecast
# restarting, race conditions, etc...
except (PyChromecastError, pylast.NetworkError):
logger.info('poll(%s) failed', self.cast_name, exc_info=True)
self.cast = None
def _poll(self):
''' Updates internal media state, can trigger scrobble. '''
current_app = self.cast.app_display_name
# Only certain applications make sense to scrobble.
if current_app not in self.app_whitelist:
return
# Certain operating modes do not support the
# `media_controller.update_status()` call. Placing a device into a cast
# group is one such case. When running in this config, the cast.app_id
# is reported as 'MultizoneLeader'. Ensure we skip.
if self.cast.app_id in UNSUPPORTED_MODES:
return
# This can raise an exception when device is part of a multizone group
# (apparently `app_id` isn't sufficient)
try:
self.cast.media_controller.update_status()
except pychromecast.error.UnsupportedNamespace:
return
status = self.cast.media_controller.status
# Ignore when the player is paused.
if not status.player_is_playing:
return
# Triggered when we poll in between songs (see issue #6)
if status.current_time is None or status.duration is None or \
status.duration <= 0:
return
# Triggered when song is repeated and starting again after the first
# time
if status.duration < self.current_time:
self.last_scrobbled = {}
self.current_track = {}
self.current_time = 0
# Spotify doesn't reliably report timestamps (see #20, #27),
# so we estimate the current time as best we can
last_poll, self.last_poll = (self.last_poll, time.time())
if self.estimate_spotify_timestamp and current_app == 'Spotify':
self.current_time += time.time() - last_poll
else:
self.current_time = status.current_time
# We know music is playing, want to check what to update
self._on_media_controller_status(current_app, status)
def _connect_chromecast(self, available_devices=None):
''' Attempt to (re)connect to cast device named in `__init__`. '''
self.cast = None
if not available_devices:
available_devices = pychromecast.get_chromecasts(tries=1)
matching_devices = [
c for c in available_devices
if c.device.friendly_name == self.cast_name
]
if not matching_devices:
click.echo('Could not connect to device "%s"' % self.cast_name)
return
if len(matching_devices) > 1:
click.echo('WARNING: Multiple devices available. Choosing first.')
self.cast = matching_devices[0]
# Wait for the device to be available
self.cast.wait()
click.echo('Using chromecast: %s' % self.cast.device.friendly_name)
def _on_media_controller_status(self, app, status):
''' Handle a status object returned from MediaController '''
meta = {
'artist': status.artist if status.artist else status.album_artist,
'album': status.album_name,
'title': status.title,
}
# Filter out ads from free-tier Spotify (see #49)
if app == 'Spotify':
# First party ads have 'Spotify' as the artist
is_spotify_ad = meta['artist'] == 'Spotify'
# Third party ads have title 'Advertisement' and an empty
# album.
is_3p_ad = meta['title'] == 'Advertisement' and not meta['album']
if is_spotify_ad or is_3p_ad:
return
# Only need to update the now playing once for each track
if meta != self.current_track:
self._log_now_playing(meta)
self.current_track = meta
# Only scrobble if track has played 50% through (or 120 seconds,
# whichever comes first).
#
# Don't scrobble the same thing over and over
hit_threshold = self.current_time > SCROBBLE_THRESHOLD_SECS or \
(self.current_time / status.duration) >= SCROBBLE_THRESHOLD_PCT
if meta != self.last_scrobbled and hit_threshold:
self._log_scrobble(meta)
def _log_now_playing(self, track_meta):
''' Update the "now playing" track on user's profile. '''
for scrobbler in self.scrobblers:
try:
scrobbler.update_now_playing(**track_meta)
except (pylast.NetworkError, pylast.MalformedResponseError) as exc:
click.echo('Failed to update now playing for {}: {}'.format(
scrobbler.name, str(exc)))
logger.info('_log_now_playing(%s) failed', scrobbler.name,
exc_info=True)
# First time this track has been seen, so reset the estimated
# current time if we're using the spotify hack
if self.cast.app_display_name == 'Spotify' and \
self.estimate_spotify_timestamp:
# Assume the track did not start in sync with the poll interval
self.current_time = POLL_INTERVAL / 2
def _log_scrobble(self, track_meta):
''' Scrobble current track to user's profile. '''
click.echo('Scrobbling: {artist} - {title} [{album}]'.format(**track_meta))
for scrobbler in self.scrobblers:
try:
scrobbler.scrobble(timestamp=int(time.time()), **track_meta)
except (pylast.NetworkError, pylast.MalformedResponseError) as exc:
click.echo('Failed to scrobble to {}: {}'.format(
scrobbler.name, str(exc)))
logger.info('_log_scrobble(%s) failed', scrobbler.name,
exc_info=True)
self.last_scrobbled = track_meta
def load_config(path):
''' Parse config at given absolute path and check for required keys. '''
config = toml.load(path)
if 'lastfm' in config:
for k in ['api_key', 'api_secret', 'user_name', 'password']:
assert k in config['lastfm'], 'Missing required lastfm option: %s' % k
if 'librefm' in config:
for k in ['password', 'user_name', 'session_key']:
assert k in config['librefm'], 'Missing required librefm option: %s' % k
return config
def config_wizard():
''' Text User Interface to generate initial lastcast.toml config. '''
config = {'chromecast': {}}
if click.confirm('Set up last.fm account?', default=True):
click.echo('''
You'll need to create a last.fm API application first. Do so here:
http://www.last.fm/api/account/create
What you fill in doesn't matter at all, just make sure to save the API
Key and Shared Secret.
''')
config['lastfm'] = {
key: click.prompt(key, type=str, hide_input=hidden)
for (key, hidden) in [('user_name', False),
('password', True),
('api_key', False),
('api_secret', True)]
}
if click.confirm('Set up Libre.fm account?'):
libre_conf = {
key: click.prompt(key, type=str, hide_input=hidden)
for (key, hidden) in [('user_name', False),
('password', True)]
}
libre = pylast.LibreFMNetwork(
username=libre_conf['user_name'],
password_hash=pylast.md5(libre_conf['password']))
skg = pylast.SessionKeyGenerator(libre)
url = skg.get_web_auth_url()
click.echo('''Please grant lastcast access to your Libre.fm account:
%s
''' % url)
click.echo('Hit enter when ready')
click.getchar()
libre_conf['session_key'] = skg.get_web_auth_session_key(url)
config['librefm'] = libre_conf
available = [
cc.device.friendly_name for cc in
pychromecast.get_chromecasts()
]
if len(available) == 1:
config['chromecast']['devices'] = [available[0]]
if len(available) > 1 or click.confirm('Manually specify cast device?', default=True):
click.echo('\n\nAvailable cast devices: %s' % ', '.join(available))
device_names = click.prompt('Which device(s) should be used? (comma separated)')
device_names = [d.strip() for d in device_names.split(',') if d.strip != '']
config['chromecast']['devices'] = device_names
click.echo('\n\nDefault chromecast apps to scrobble from: %s' %
', '.join(APP_WHITELIST))
apps = click.prompt('Comma separated apps [blank for default]',
default='', show_default=False)
apps = [app.strip() for app in apps.split(',') if app.strip() != '']
if apps:
config['chromecast']['app_whitelist'] = apps
generated = toml.dumps(config)
click.echo('Generated config:\n\n%s' % generated)
if click.confirm('Write to ~/.lastcast.toml?', default=True):
with open(os.path.expanduser('~/.lastcast.toml'), 'w') as fp:
fp.write(generated)
def connect_to_devices(config, device_names, available):
'''
Attempt to connect to each named device, returning
ScrobbleListners and names of devices that couldn't be found.
'''
listeners = []
missing_devices = []
for name in device_names:
try:
listeners.append(ScrobbleListener(config, name, available_devices=available))
except ChromecastNotFoundException:
missing_devices.append(name)
return listeners, missing_devices
@click.command()
@click.option('--config', required=False, help='Config file location')
@click.option('--wizard', is_flag=True, help='Generate a lastcast config.')
@click.option('--verbose', is_flag=True, help='Enable debug logging.')
def main(config, wizard, verbose):
if verbose:
logger.setLevel('DEBUG')
else:
# pychromecast is by default pretty noisy about caught exceptions
logging.getLogger('pychromecast').setLevel('CRITICAL')
if wizard:
return config_wizard()
paths = [config] if config else ['./lastcast.toml', '~/.lastcast.toml']
for path in paths:
path = os.path.expanduser(path)
if os.path.exists(path):
config = load_config(path)
break
else:
click.echo('Config file not found!\n\nUse --wizard to create a config')
sys.exit(1)
cast_config = config.get('chromecast', {})
device_names = cast_config.get('devices', [])
# `name` is the legacy parameter name, supporting it for now.
if not device_names and 'name' in cast_config:
device_names = [cast_config['name']]
if not device_names:
click.echo('Need to specify either `devices` or `name` in '
'`[chromecast]` config block!')
sys.exit(1)
available = pychromecast.get_chromecasts()
listeners, missing = connect_to_devices(config, device_names, available)
retry_missing = cast_config.get('retry_missing', False)
if cast_config.get('ignore_missing', False) and missing:
click.echo('Continuing without missing devices: %s' % ', '.join(missing))
missing = []
if missing and not retry_missing:
click.echo('Failed to connect to %s. Exiting' % ', '.join(missing))
click.echo('Available devices: %s' % ', '.join([
d.device.friendly_name for d in available
]))
sys.exit(1)
for i in itertools.count():
for listener in listeners:
listener.poll()
# If we have any devices missing, periodically try to connect to them
if retry_missing and missing and i % RECONNECT_INTERVAL == 0:
click.echo('Retrying missing devices: %s' % ', '.join(missing))
available = pychromecast.get_chromecasts(tries=1)
new_devices, missing = connect_to_devices(config, missing, available)
listeners.extend(new_devices)
time.sleep(POLL_INTERVAL)
if __name__ == '__main__':
main()
|
python
|
from this_is_a_package import a_module
a_module.say_hello("ITC")
|
python
|
# coding: utf-8
"""
CMS Audit Logs
Use this endpoint to query audit logs of CMS changes that occurred on your HubSpot account. # noqa: E501
The version of the OpenAPI document: v3
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from hubspot.cms.audit_logs.configuration import Configuration
class PublicAuditLog(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
"object_id": "str",
"user_id": "str",
"timestamp": "datetime",
"object_name": "str",
"full_name": "str",
"event": "str",
"object_type": "str",
}
attribute_map = {
"object_id": "objectId",
"user_id": "userId",
"timestamp": "timestamp",
"object_name": "objectName",
"full_name": "fullName",
"event": "event",
"object_type": "objectType",
}
def __init__(
self,
object_id=None,
user_id=None,
timestamp=None,
object_name=None,
full_name=None,
event=None,
object_type=None,
local_vars_configuration=None,
): # noqa: E501
"""PublicAuditLog - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._object_id = None
self._user_id = None
self._timestamp = None
self._object_name = None
self._full_name = None
self._event = None
self._object_type = None
self.discriminator = None
self.object_id = object_id
self.user_id = user_id
self.timestamp = timestamp
self.object_name = object_name
self.full_name = full_name
self.event = event
self.object_type = object_type
@property
def object_id(self):
"""Gets the object_id of this PublicAuditLog. # noqa: E501
The ID of the object. # noqa: E501
:return: The object_id of this PublicAuditLog. # noqa: E501
:rtype: str
"""
return self._object_id
@object_id.setter
def object_id(self, object_id):
"""Sets the object_id of this PublicAuditLog.
The ID of the object. # noqa: E501
:param object_id: The object_id of this PublicAuditLog. # noqa: E501
:type: str
"""
if (
self.local_vars_configuration.client_side_validation and object_id is None
): # noqa: E501
raise ValueError(
"Invalid value for `object_id`, must not be `None`"
) # noqa: E501
self._object_id = object_id
@property
def user_id(self):
"""Gets the user_id of this PublicAuditLog. # noqa: E501
The ID of the user who caused the event. # noqa: E501
:return: The user_id of this PublicAuditLog. # noqa: E501
:rtype: str
"""
return self._user_id
@user_id.setter
def user_id(self, user_id):
"""Sets the user_id of this PublicAuditLog.
The ID of the user who caused the event. # noqa: E501
:param user_id: The user_id of this PublicAuditLog. # noqa: E501
:type: str
"""
if (
self.local_vars_configuration.client_side_validation and user_id is None
): # noqa: E501
raise ValueError(
"Invalid value for `user_id`, must not be `None`"
) # noqa: E501
self._user_id = user_id
@property
def timestamp(self):
"""Gets the timestamp of this PublicAuditLog. # noqa: E501
The timestamp at which the event occurred. # noqa: E501
:return: The timestamp of this PublicAuditLog. # noqa: E501
:rtype: datetime
"""
return self._timestamp
@timestamp.setter
def timestamp(self, timestamp):
"""Sets the timestamp of this PublicAuditLog.
The timestamp at which the event occurred. # noqa: E501
:param timestamp: The timestamp of this PublicAuditLog. # noqa: E501
:type: datetime
"""
if (
self.local_vars_configuration.client_side_validation and timestamp is None
): # noqa: E501
raise ValueError(
"Invalid value for `timestamp`, must not be `None`"
) # noqa: E501
self._timestamp = timestamp
@property
def object_name(self):
"""Gets the object_name of this PublicAuditLog. # noqa: E501
The internal name of the object in HubSpot. # noqa: E501
:return: The object_name of this PublicAuditLog. # noqa: E501
:rtype: str
"""
return self._object_name
@object_name.setter
def object_name(self, object_name):
"""Sets the object_name of this PublicAuditLog.
The internal name of the object in HubSpot. # noqa: E501
:param object_name: The object_name of this PublicAuditLog. # noqa: E501
:type: str
"""
if (
self.local_vars_configuration.client_side_validation and object_name is None
): # noqa: E501
raise ValueError(
"Invalid value for `object_name`, must not be `None`"
) # noqa: E501
self._object_name = object_name
@property
def full_name(self):
"""Gets the full_name of this PublicAuditLog. # noqa: E501
The name of the user who caused the event. # noqa: E501
:return: The full_name of this PublicAuditLog. # noqa: E501
:rtype: str
"""
return self._full_name
@full_name.setter
def full_name(self, full_name):
"""Sets the full_name of this PublicAuditLog.
The name of the user who caused the event. # noqa: E501
:param full_name: The full_name of this PublicAuditLog. # noqa: E501
:type: str
"""
if (
self.local_vars_configuration.client_side_validation and full_name is None
): # noqa: E501
raise ValueError(
"Invalid value for `full_name`, must not be `None`"
) # noqa: E501
self._full_name = full_name
@property
def event(self):
"""Gets the event of this PublicAuditLog. # noqa: E501
The type of event that took place (CREATED, UPDATED, PUBLISHED, DELETED, UNPUBLISHED). # noqa: E501
:return: The event of this PublicAuditLog. # noqa: E501
:rtype: str
"""
return self._event
@event.setter
def event(self, event):
"""Sets the event of this PublicAuditLog.
The type of event that took place (CREATED, UPDATED, PUBLISHED, DELETED, UNPUBLISHED). # noqa: E501
:param event: The event of this PublicAuditLog. # noqa: E501
:type: str
"""
if (
self.local_vars_configuration.client_side_validation and event is None
): # noqa: E501
raise ValueError(
"Invalid value for `event`, must not be `None`"
) # noqa: E501
allowed_values = [
"CREATED",
"UPDATED",
"PUBLISHED",
"DELETED",
"UNPUBLISHED",
] # noqa: E501
if (
self.local_vars_configuration.client_side_validation
and event not in allowed_values
): # noqa: E501
raise ValueError(
"Invalid value for `event` ({0}), must be one of {1}".format( # noqa: E501
event, allowed_values
)
)
self._event = event
@property
def object_type(self):
"""Gets the object_type of this PublicAuditLog. # noqa: E501
The type of the object (BLOG, LANDING_PAGE, DOMAIN, HUBDB_TABLE etc.) # noqa: E501
:return: The object_type of this PublicAuditLog. # noqa: E501
:rtype: str
"""
return self._object_type
@object_type.setter
def object_type(self, object_type):
"""Sets the object_type of this PublicAuditLog.
The type of the object (BLOG, LANDING_PAGE, DOMAIN, HUBDB_TABLE etc.) # noqa: E501
:param object_type: The object_type of this PublicAuditLog. # noqa: E501
:type: str
"""
if (
self.local_vars_configuration.client_side_validation and object_type is None
): # noqa: E501
raise ValueError(
"Invalid value for `object_type`, must not be `None`"
) # noqa: E501
allowed_values = [
"BLOG",
"BLOG_POST",
"LANDING_PAGE",
"WEBSITE_PAGE",
"TEMPLATE",
"MODULE",
"GLOBAL_MODULE",
"SERVERLESS_FUNCTION",
"DOMAIN",
"URL_MAPPING",
"EMAIL",
"CONTENT_SETTINGS",
"HUBDB_TABLE",
"KNOWLEDGE_BASE_ARTICLE",
"KNOWLEDGE_BASE",
"THEME",
"CSS",
"JS",
] # noqa: E501
if (
self.local_vars_configuration.client_side_validation
and object_type not in allowed_values
): # noqa: E501
raise ValueError(
"Invalid value for `object_type` ({0}), must be one of {1}".format( # noqa: E501
object_type, allowed_values
)
)
self._object_type = object_type
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PublicAuditLog):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, PublicAuditLog):
return True
return self.to_dict() != other.to_dict()
|
python
|
import numpy as np
import time
# Number of random numbers to be generated
nran = 1024
# Generate a random number from the normal distribution
result = [np.random.bytes(nran*nran) for x in range(nran)]
print(len(result), "======>>> random numbers")
# Wait for tsleep seconds
tsleep = 40
print("I am sleeping for {0} seconds so you can check the resources usage".format(tsleep))
time.sleep(tsleep)
|
python
|
# Example of using StagingAreaCallback for GPU prefetch on a simple convnet
# model on CIFAR10 dataset.
#
# https://gist.github.com/bzamecnik/b9dbd50cdc195d54513cd2f9dfb7e21b
import math
from keras.layers import Dense, Input, Conv2D, MaxPooling2D, Dropout, Flatten
from keras.models import Model
from keras.utils import to_categorical
import numpy as np
from keras_tf_multigpu.callbacks import StagingAreaCallback, SamplesPerSec
from keras_tf_multigpu.examples.datasets import create_synth_cifar10
np.random.seed(42)
def make_convnet(input, num_classes):
x = Conv2D(32, (3, 3), padding='same', activation='relu')(input)
x = Conv2D(32, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Dropout(0.25)(x)
x = Conv2D(64, (3, 3), padding='same', activation='relu')(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Dropout(0.25)(x)
x = Flatten()(x)
x = Dense(512, activation='relu')(x)
x = Dropout(0.5)(x)
output = Dense(num_classes, activation='softmax')(x)
return output
def make_plain_model(input_shape, num_classes):
input = Input(shape=input_shape)
model = Model(inputs=input, outputs=make_convnet(input, num_classes))
model.compile(optimizer='sgd', loss='categorical_crossentropy')
return model
def make_tensor_model(staging_area_callback, num_classes):
input = Input(tensor=staging_area_callback.input_tensor)
model = Model(inputs=input, outputs=make_convnet(input, num_classes))
model.compile(optimizer='sgd', loss='categorical_crossentropy',
target_tensors=[staging_area_callback.target_tensor],
fetches=staging_area_callback.extra_ops)
return model
num_classes = 10
dataset_size = 50000
batch_size = 2048
epochs = 5
x_train, y_train = create_synth_cifar10(dataset_size)
x_train = x_train.astype('float32')
y_train = y_train.astype('float32')
# last batch might be smaller
steps_per_epoch = int(math.ceil(len(x_train) / batch_size))
gauge = SamplesPerSec(batch_size)
staging_area_callback = StagingAreaCallback(x_train, y_train, batch_size)
print('training plain model:')
plain_model = make_plain_model(x_train.shape[1:], num_classes)
plain_model.fit(x_train, y_train, batch_size, epochs=epochs, callbacks=[gauge])
print('training pipelined model:')
pipelined_model = make_tensor_model(staging_area_callback, num_classes)
pipelined_model.fit(steps_per_epoch=steps_per_epoch, epochs=epochs,
callbacks=[staging_area_callback, gauge])
|
python
|
from requests import get
READ_SUCCESS_CODE = 200
class ConfigurationGateway(object):
def __init__(self, url, executables_path, repositories_path, results_key):
self.url = url
self.executables_path = executables_path
self.repositories_path = repositories_path
self.results_key = results_key
@staticmethod
def request(uri, key=None):
response = get(uri)
result = []
if response.status_code == READ_SUCCESS_CODE:
result = response.json()
if key:
result = result.get(key)
return result
def build_uri(self, path):
return '{}/{}'.format(self.url, path)
@property
def executables_uri(self):
return self.build_uri(self.executables_path)
@property
def repositories_uri(self):
return self.build_uri(self.repositories_path)
def get_executables_metadata(self):
return ConfigurationGateway.request(self.executables_uri)
def get_repositories(self):
return ConfigurationGateway.request(self.repositories_uri, key=self.results_key)
|
python
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.