from __future__ import print_function
from typing import Optional
from time import sleep
from pymba import Vimba
from pymba import Frame

vimba = None
def FrameCallback(frame: Frame, delay: Optional[int] = 10) -> None:
    bShowFrameInfos = True
    if bShowFrameInfos == True:
        print('Frame ID:%d' %(frame.data.frameID), end=" ")
        print('Size: %d' %(len(frame.buffer_data())), end=" " )
        print("Format:%s" %(frame.pixel_format))
        # print('Status: %s' % (frame.receiveStatus)) -- no such feature up to now
    print(".", end="")

def init_cameras():
    global vimba
    # vimba object
    vimba = Vimba()
    # Start vimba system
    vimba.startup()
    vmFactory = vimba.camera_ids()
    # Get connected cameras
    cams = [vimba.camera(id) for id in vmFactory]
    if len(cams) == 0:
        raise OSError("No camera present.")
    for idx, device in enumerate(vmFactory):
        print("Device {} ID: {}".format(idx, device))
    # Open cameras and print information
    for idx, cam in enumerate(cams):
        try:
            cam.open()
            cam.arm(mode='Continuous', callback=FrameCallback)
            cam.start_frame_acquisition()
        except VimbaException as e:
            if e.error_code == VimbaException.ERR_TIMEOUT:
                print(e)
                cam.disarm()
                cam.arm('Continuous')
            elif e.error_code == VimbaException.ERR_DEVICE_NOT_OPENED:
                print(e)
                cam.open()
                cam.arm(mode='Continuous', callback=FrameCallback)
    return cams

def main():
    global vimba
    cams = init_cameras()
    sleep(2)
    for cam in cams:
        cam.disarm()
        cam.close()
    vimba.shutdown()
    print("Exit Program...")

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import sorl.thumbnail.fields
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('fundraising', '0014_donation_receipt_email'),
    ]

    operations = [
        migrations.AlterField(
            model_name='djangohero',
            name='logo',
            field=sorl.thumbnail.fields.ImageField(upload_to='fundraising/logos/', blank=True),
            preserve_default=True,
        ),
    ]


import random

questions_data = [
	{
	'question' : 'What year it is today?',
	'options' : {'a' : 2009 , 'b' : 2002 , 'c' : 2015 , 'd' : 2020},
	'answer' : 'd'
	},
	{
	'question' : 'What is cube of 9?',
	'options' : {'a' : 729 , 'b' : 1000 , 'c' : 2132 , 'd' : 2020},
	'answer' : 'a'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is value of postfix expression 542*+3-?',
	'options' : {'a' : 10 , 'b' : 29 , 'c' : 15 , 'd' : 12},
	'answer' : 'a'
	},
	{
	'question' : 'What is not a prime number?',
	'options' : {'a' : 329 , 'b' : 669 , 'c' : 571 , 'd' : 129},
	'answer' : 'c'
	},
	{
	'question' : 'Suppose a C program has floating constant 1.414, whats the best way to convert this as "float" data type?',
	'options' : {'a' : '(float)1.414' , 'b' : 'float(1.414)' , 'c' : '1.414f or 1.414F', 'd' : 'None of the above'},
	'answer' : 'c'
	},
	{
	'question' : 'What is the value of expression 2**2**3**1',
	'options' : {'a' : 64 , 'b' : 256 , 'c' : 24 , 'd' : 'None of the above'},
	'answer' : 'b'
	},
	{
	'question' : 'In python,what is the value of round(12.5) - round(11.5)?',
	'options' : {'a' : 0 , 'b' : 2 , 'c' : 1 , 'd' : 'Error'},
	'answer' : 'c'
	},
	{
	'question' : "What is output for −raining'. find('z') ?",
	'options' : {'a' : '-1' , 'b' : 'TypeError' , 'c' : "''" , 'd' : 'Not Found'},
	'answer' : 'a'
	},
	{
	'question' : 'What command is used to insert 6 in a list ‘‘L’’ at 3rd position ?',
	'options' : {'a' : 'L.insert(2,5)' , 'b' : 'L.insert(3,6)' , 'c' : 'L.add(3,6)' , 'd' : 'L.append(2,6)'},
	'answer' : 'a'
	},
	{
	'question' : 'All keyworkds in Python are in:',
	'options' : {'a' : 'Uppercase' , 'b' : 'Lowercase' , 'c' : 'Capitalized' , 'd' : 'None of the above'},
	'answer' : 'd'
	},
	{
	'question' : 'Which operator has the highest precedance in python?',
	'options' : {'a' : 'Multiplication', 'b' : 'Exponential' , 'c' : 'Parantheses' , 'd' : 'Integer division'},
	'answer' : 'c'
	},
	{
	'question' : 'What is return type of id function?',
	'options' : {'a' : 'int' , 'b' : 'float' , 'c' : 'bool' , 'd' : 'dict'},
	'answer' : 'a'
	},
	{
	'question' : 'Select the reserve keyword in python:',
	'options' : {'a' : 'else' , 'b' : 'lambda' , 'c' : 'raise' , 'd' : 'All of the above'},
	'answer' : 'd'
	},
	{
	'question' : 'What is capital of India?',
	'options' : {'a' : "New Delhi" , 'b' : "you HOme" , 'c' : "Mumbai" , 'd' : "kashmir"},
	'answer' : 'a'
	},
	{
	'question' : 'how many colors are there in a rainbow?',
	'options' : {'a' : 9 , 'b' : 7 , 'c' : 261 , 'd' : 999},
	'answer' : 'b'
	},
	{
	'question' : 'What color is an orange?',
	'options' : {'a' : "blue" , 'b' : "yellow" , 'c' : "red+yellow" , 'd' : "black"},
	'answer' : 'c'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
	{
	'question' : 'What is not a perfect square?',
	'options' : {'a' : 9 , 'b' : 20 , 'c' : 625 , 'd' : 25},
	'answer' : 'b'
	},
]

data = questions_data

def getQuestion():
	global data
	if(len(data) < 1):
		data = questions_data
	question = random.choice(data)
	data.pop(data.index(question))
	return question
	#,questions_data.index(question)

"""
options = []
value = "No"
question = "What year it is today?"
for i in questions_data:
	if question in i.values():
		value = "YES"
		for j in i['options'].values():
			options.append(j)

print(options)
print(value)"""


import numpy as np

data = np.load('../data/datasets/resampled_X_lattices.npy')

def transform_2d(X_3d_lattices = data):

	X_3d_shape = X_3d_lattices.shape
	n,X,Y,Z = X_3d_shape
	assert X == Y == Z

	X_2d_xy_transform = np.zeros((n,X,Y,1))
	X_2d_yz_transform = np.zeros((n,Y,Z,1))
	X_2d_xz_transform = np.zeros((n,X,Z,1))

	# perform xy transformation
	for num in range(n):
		for i in range(X):
			for j in range(Y):
				val = 0
				for count in range(1,Z):
					val = X_3d_lattices[num][i][j][Z-count]
					if val != 0:
						break
				X_2d_xy_transform[num][i][j][0] = val

	# perform yz transformation
	for num in range(n):
		for i in range(Y):
			for j in range(Z):
				val = 0
				for count in range(1,X):
					val = X_3d_lattices[num][i][j][X-count]
					if val != 0:
						break
				X_2d_yz_transform[num][i][j][0] = val

	# perform xz transformation
	for num in range(n):
		for i in range(X):
			for j in range(Z):
				val = 0
				for count in range(1,Y):
					val = X_3d_lattices[num][i][j][Y-count]
					if val != 0:
						break
				X_2d_xz_transform[num][i][j][0] = val

	X_2d_lattices = np.concatenate((X_2d_xy_transform, X_2d_yz_transform, X_2d_xz_transform), axis=3)
	np.save('X_2d_lattices.npy', X_2d_lattices)

transform_2d()


def find_busiest_period(data):
    n = len(data)
    cnt = 0
    max_cnt = 0
    max_time = float('-inf')

    for i in range(n):
        timestamp, people, status = data[i]

        if status == 1:
            cnt += people
        else:
            cnt -= people

        if i + 1 < n and data[i][0] == data[i + 1][0]:
            continue

        if cnt > max_cnt:
            max_cnt = cnt
            max_time = timestamp

    return max_time


# uncompyle6 version 3.7.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /home/nb/publish/btw/tingyun/tingyun/armoury/external_urllib2.py
# Compiled at: 2016-07-03 22:35:45
"""

"""
import sys
from tingyun.packages import six
from tingyun.armoury.ammunition.tracker import current_tracker
from tingyun.armoury.ammunition.external_tracker import wrap_external_trace, parse_parameters
from tingyun.armoury.ammunition.external_tracker import MALFORMED_URL_ERROR_CODE
from tingyun.armoury.ammunition.external_tracker import OTHER_ERROR_CODE
from urllib2 import URLError, HTTPError

def wrap_exception(wrapped, url, parameters, *args, **kwargs):
    """
    """
    tracker = current_tracker()
    if tracker is None:
        return wrapped(*args, **kwargs)
    else:
        url = url if not callable(url) else url(*args, **kwargs)
        params = parameters if not callable(parameters) else parameters(*args, **kwargs)
        http_status = 500
        error_code = 0
        params = parse_parameters(url, params)
        try:
            rtv = wrapped(*args, **kwargs)
        except URLError:
            error_code = MALFORMED_URL_ERROR_CODE
            tracker.record_external_error(url, error_code, http_status, sys.exc_info(), params)
            raise
        except HTTPError as err:
            http_status = getattr(err, 'code')
            error_code = OTHER_ERROR_CODE
            tracker.record_external_error(url, error_code, http_status, sys.exc_info(), params)
            raise
        except Exception:
            error_code = OTHER_ERROR_CODE
            tracker.record_external_error(url, error_code, http_status, sys.exc_info(), params)
            raise

        http_status = rtv.getcode()
        if http_status is not None and int(http_status) != 200:
            tracker.record_external_error(url, error_code, int(http_status), sys.exc_info(), params)
        return rtv

def detect(module):

    def url_opener_open(instance, fullurl, *args, **kwargs):
        """
        :param instance:
        :param fullurl:
        :param args:
        :param kwargs:
        :return:
        """
        if isinstance(fullurl, six.string_types):
            return fullurl
        else:
            return fullurl.get_full_url()

    wrap_external_trace(module, 'OpenerDirector.open', 'urllib2', url_opener_open, exception_wrapper=wrap_exception)


import os, sys

def addpath(__file__, path):
    __file__ = os.path.normpath(os.path.abspath(__file__))
    __path__ = os.path.dirname(__file__)
    __added_path__ = os.path.join(__path__, path)

    if __path__ not in sys.path:
        sys.path.insert(0, __path__)
    if __added_path__ not in sys.path:
        sys.path.insert(0, __added_path__)


import os
import json
from urllib.request import urlopen

from jose import jwt
from werkzeug.exceptions import Unauthorized

PRODUCTION = os.getenv('PRODUCTION', False)
AUTH0_DOMAIN = 'eventzimmer.eu.auth0.com'
AUDIENCE = 'api.eventzimmer.de'
ALGORITHMS = ['RS256']

def info_from_aggregator(token):
    """
    Check and retrieve authentication information from custom bearer token.
    Returned value will be passed in 'token_info' parameter of your operation function, if there is one.
    'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one.

    :param token Token provided by Authorization header
    :type token: str
    :return: Decoded token information or None if token is invalid
    :rtype: dict | None
    """

    if not PRODUCTION:  # never check values in debug
        return {}

    # NOTE: Implements validation as suggested on the Auth0 site at
    # https://auth0.com/docs/quickstart/backend/python/01-authorization#validate-access-tokens
    json_url = urlopen('https://{}/.well-known/jwks.json'.format(AUTH0_DOMAIN))
    jwks = json.loads(json_url.read())
    unverified_header = jwt.get_unverified_header(token)
    rsa_key = {}

    for key in jwks['keys']:
        if key['kid'] == unverified_header['kid']:
            rsa_key = {
                'kty': key['kty'],
                'kid': key['kid'],
                'use': key['use'],
                'n': key['n'],
                'e': key['e']
            }

    if rsa_key:
        try:
            payload = jwt.decode(
                token,
                rsa_key,
                algorithms=ALGORITHMS,
                audience=AUDIENCE,
                issuer='https://{}/'.format(AUTH0_DOMAIN)
            )
        except jwt.ExpiredSignatureError:
            raise Unauthorized(
                {'code': 'token_expired', 'description': 'token is expired'})
        except jwt.JWTClaimsError:
            raise Unauthorized(
                {'code': 'invalid_claims', 'description': 'incorrect claims'})
        except jwt.JWTError as err:
            raise Unauthorized({'code': 'jwt_error', 'description': str(err)})
        except Exception:
            raise Unauthorized(
                {'code': 'invalid_header', 'description': 'Unable to parse authentication token'})

        return payload


from parselib import AV, Surfaces, Output, Matrix, Kill, Detail
import os
import numpy as np
import util

class DataModel(object):
    def __init__(self):
        self.term_vel = None
        self.burst_height = None
        self.attack_az = None
        self.aof = None
        self.blast_vol = None
        self.av_file = None
        self.srf_file = None
        self.mtx_extent_range, self.mtx_extent_defl = None, None
        self.cls_range, self.cls_defl = None, None
        self.offset_range, self.offset_defl = None, None
        self.gridlines_range, self.gridlines_defl = None, None
        self.gridlines_range_mid, self.gridlines_defl_mid = None, None
        self.cell_size_range, self.cell_size_defl = None, None
        self.pks = None
        self.surf_names = None
        self.surfaces = None
        self.srf_min_x, self.srf_max_x = None, None
        self.srf_min_y, self.srf_max_y = None, None
        self.srf_max_z = None
        self.comps = None
        self.x_avg_loc, self.y_avg_loc = None, None
        self.x_loc, self.y_loc, self.z_loc = None, None, None
        self.num_tables = None
        self.num_az, self.num_el, self.num_vl, self.num_ms = None, None, None, None
        self.az_idx = None
        self.el_idx = None
        self.azs = None
        self.els = None
        self.vls = None
        self.mss = None
        self.table_names = None
        self.avs = None
        self.pes = None
        self.av_averaging = None
        self.az_averaging = None
        self.num_kills = None
        self.kill_file = None
        self.kill_desc = None
        self.kill_id = None
        self.kill_lines = None
        self.last_node = None
        self.tgt_center = None
        self.volume_radius = None
        self.mtx_kill_id = None
        self.frag_ids = None
        self.blast_ids = None
        # noinspection SpellCheckingInspection
        self.invuln_ids = None
        self.dh_ids = None
        self.dtl_file = None
        self.comp_num = None
        self.sample_loc = None
        self.burst_loc = None

    def read_and_transform_all_files(self, out_file):
        av_file, srf_file, mtx_file, kill_file, dtl_file = Output(self).read(out_file)
        if av_file is None:
            raise IOError("Case didn't complete.")
        AV(self).read(av_file)
        Surfaces(self).read(srf_file)
        Kill(self).read(kill_file)
        if os.path.exists(mtx_file):
            Matrix(self).read(mtx_file)
            self.transform_matrix()
        if os.path.exists(dtl_file):
            detail = Detail(self)
            if detail.validate(dtl_file):
                detail.read(dtl_file)
                self.dtl_file = dtl_file
            else:
                raise IOError(".dtl file does not have the full level of detail.")
        # extract the component IDs that are part of the selected kill in the kill definition file.
        kill_comps = set(self.extract_components(self.mtx_kill_id))
        # translate the underlying geometric representation to the correct coordinates before display.
        self.transform_blast_volumes(kill_comps)
        self.transform_direct_hit_components(kill_comps)
        self.transform_frag_components(kill_comps)
        self.transform_surfaces()

    def transform_blast_volumes(self, kill_ids):
        """ Keep only the blast AVs that match with the frag components listed in the selected kill. """
        if kill_ids:
            self.blast_ids.intersection_update(kill_ids)
            self.blast_ids.difference_update(self.invuln_ids)

    def transform_direct_hit_components(self, kill_ids):
        """ Keep only the direct hit AVs that match with the frag components listed in the selected kill. """
        if kill_ids:
            self.dh_ids.intersection_update(kill_ids)
            self.dh_ids.difference_update(self.invuln_ids)

    def transform_frag_components(self, kill_ids):
        """ Keep only the fragment AVs that match with the frag components listed in the selected kill. """
        if kill_ids:
            self.frag_ids.intersection_update(kill_ids)
            self.frag_ids.difference_update(self.invuln_ids)

    def transform_surfaces(self):
        """ Calculate a volume radius and geometric center for the target surfaces. """
        self.surfaces = np.array(self.surfaces)
        self.volume_radius = max(self.srf_min_x, self.srf_max_x, self.srf_min_y, self.srf_max_y)
        for r1, r2, r3, z1, z2 in self.blast_vol.values():
            self.volume_radius = max(self.volume_radius, z1 + z2 + max(r3, r2, r1) + 10.0)

    def transform_matrix(self):
        # Store the matrix extents in range & deflection for later display in the 3D scene.
        self.mtx_extent_range = (self.gridlines_range[0], self.gridlines_range[-1])
        self.mtx_extent_defl = (self.gridlines_defl[0], self.gridlines_defl[-1])
        # Flip gridlines to do the 180 degree matrix rotation from munition-centered to target-centered.
        self.gridlines_range = [-i for i in self.gridlines_range]
        self.gridlines_defl = [-i for i in self.gridlines_defl]
        # Shift gridlines by applying matrix offset and target center extracted from .out file.
        # Otherwise, would have to apply the shift to the target/obstacle surfaces, AVs, blast volumes, etc.
        self.gridlines_range = util.apply_list_offset(self.gridlines_range, self.offset_range + self.tgt_center[0])
        self.gridlines_defl = util.apply_list_offset(self.gridlines_defl, self.offset_defl + self.tgt_center[1])
        # Calculate midpoint of gridlines and a list of cell sizes based on gridline measurements
        self.gridlines_range_mid = util.midpoints(self.gridlines_range)
        self.gridlines_defl_mid = util.midpoints(self.gridlines_defl)
        self.cell_size_range = util.measure_between(self.gridlines_range)
        self.cell_size_defl = util.measure_between(self.gridlines_defl)
        # Get rid of floating point noise that can cause Pk values > 1.0
        self.pks = np.clip(self.pks, 0.0, 1.0)

    def extract_components(self, kill_type, kill_node=None):
        """
        :param kill_type: string with k number (e.g., 'k1' or 'k5') matched against the same type in the kill
                          definition file.
        :param kill_node: node number in string format
        :return: list of components for that kill
        """
        if not kill_type:
            return []
        if kill_node is None:
            kill_node = self.last_node.get(kill_type, '')
        type_and_node = kill_type + ',' + kill_node
        if not self.kill_lines.get(type_and_node):
            return []
        components = []
        for item in self.kill_lines[type_and_node].items:
            if item.startswith('c'):
                components.append(int(item[1:]))
            elif item.startswith('n'):
                new_kill_type = kill_type.split(',')[0]
                components.extend(self.extract_components(new_kill_type, item[1:]))
            elif item.startswith('k'):
                new_kill_type, new_kill_node = item.split(',')
                components.extend(self.extract_components(new_kill_type, new_kill_node))
            else:
                raise ValueError("Unrecognized item %s in kill file for %s" % (item, kill_type))
        return components

    def get_sample_points(self):
        return self.sample_loc

    def get_burst_points(self):
        return self.burst_loc


#!/usr/bin/python3
# coding: utf-8
from ProjectBase import Project, PROJECT_ROOT
import os

# GoLang test class
class GoLangServant(Project):
    _app = 'Demo'
    _language = 'Golang'

    def publish(self):
        self._deploy_http()
        self._deploy_tars()

    def _deploy_http(self):
        prj_dir = os.path.join(PROJECT_ROOT, 'GoServer/GoHttp')
        try:
            self._upload_and_publish(
                app_name=self._app,
                module_name='GoHttp',
                pkg_dir=prj_dir,
                pkg_name_prefix='GoHttp',
                pkg_ext='.tgz'
            )
        except Exception as e:
            self.total_test_cnt += 1
            self.failed_tests.append('Deploy Http')
            self._print_err("{0}: Http deploy failed.".format(self._language))

    def _deploy_tars(self):
        prj_dir = os.path.join(PROJECT_ROOT, 'GoServer/GoTars')
        try:
            self._upload_and_publish(
                app_name=self._app,
                module_name='GoTars',
                pkg_dir=prj_dir,
                pkg_name_prefix='GoTars',
                pkg_ext='.tgz'
            )
        except Exception as e:
            self.total_test_cnt += 1
            self.failed_tests.append('Deploy Tars')
            self._print_err("{0}: Tars deploy failed.".format(self._language))

    def run_test(self):
        self._print_info("{0} Start testing...".format(self._language))
        self.ping_http()
        self.ping_tars()

    def ping_http(self):
        self._ping_http("{0}/test/ping")

    def ping_tars(self):
        self._ping_http("{0}/test/pingGo")


import cv2
import numpy as np

def hsv_filt(frame, lower_bounds, upper_bounds, wrap_bounds):
  hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

  if wrap_bounds:
    # Wrap the bounds around the 180 HSV discontinuity
    lowside = cv2.inRange(hsv,
                    np.array([0,lower_bounds[1],lower_bounds[2]]),
                    np.array([lower_bounds[0],upper_bounds[1],upper_bounds[2]]))
    highside = cv2.inRange(hsv,
                    np.array([upper_bounds[0],lower_bounds[1],lower_bounds[2]]),
                    np.array([180, upper_bounds[1], upper_bounds[2]]))
    binframe = cv2.bitwise_or(lowside, highside)
  else:
    binframe = cv2.inRange(hsv, lower_bounds, upper_bounds)
  return binframe

def hsv_denoise(binframe, kernel, iterations):
  temp = cv2.morphologyEx(binframe, cv2.MORPH_OPEN, kernel, iterations=iterations)
  return cv2.morphologyEx(temp, cv2.MORPH_CLOSE, kernel, iterations=iterations)

def hsv_filt_contours(binframe, imgframe, visualize):
  boats = []
  for cnt in cv2.findContours(binframe.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]:
    # Get the rotated rectangle surrounding the blob
    ((xcenter,ycenter), (width,height), ang) = cv2.minAreaRect(cnt)
    # Filter blobs by aspect ratio, area, and bottom 2/3 of image
    if max(width,height)>2*min(width,height) \
           and width*height > 4000 \
           and ycenter > 480*1/3:
      boats.append(((xcenter,ycenter),(width,height)))
      if visualize:
        box = cv2.cv.BoxPoints(((xcenter,ycenter),(width,height),ang))
        box = np.int0(box)
        cv2.drawContours(imgframe,[box],0,[0,0,255],2)
  return boats

def hsv_filt_buoy_contours(binframe, imgframe, visualize):
  buoys = []
  for cnt in cv2.findContours(binframe.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]:
    # Get the rotated rectangle surrounding the blob
    ((xcenter,ycenter), (width,height), ang) = cv2.minAreaRect(cnt)
    # Filter blobs by aspect ratio, area, and bottom 2/3 of image
    if max(width,height)<1.5*min(width,height):
      buoys.append((width*height, xcenter))
      if visualize:
        box = cv2.cv.BoxPoints(((xcenter,ycenter),(width,height),ang))
        box = np.int0(box)
        cv2.drawContours(imgframe,[box],0,[0,0,255],2)
  return buoys


# -*- coding: utf-8 -*-
#
# Copyright 2019-2021 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# 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.
"""Dispatcher tests."""
from pathlib import Path

import pytest

from renku.core import errors
from renku.core.management import LocalClient
from renku.core.management.command_builder.client_dispatcher import ClientDispatcher
from renku.core.management.command_builder.database_dispatcher import DatabaseDispatcher

def test_client_dispatcher(tmpdir):
    """Test getting correct current client."""
    test_dir = tmpdir.mkdir("test")
    other_test_dir = tmpdir.mkdir("other_test")

    dispatcher = ClientDispatcher()

    with pytest.raises(errors.ConfigurationError):
        dispatcher.current_client

    dispatcher.push_client_to_stack(Path(tmpdir))

    assert dispatcher.current_client.path == Path(tmpdir).resolve()

    dispatcher.push_client_to_stack(str(Path(test_dir)))

    assert dispatcher.current_client.path == Path(test_dir).resolve()

    dispatcher.push_created_client_to_stack(LocalClient(Path(other_test_dir)))

    assert dispatcher.current_client.path == Path(other_test_dir).resolve()

    dispatcher.pop_client()

    assert dispatcher.current_client.path == Path(test_dir).resolve()

    dispatcher.pop_client()

    assert dispatcher.current_client.path == Path(tmpdir).resolve()

    dispatcher.pop_client()

    with pytest.raises(errors.ConfigurationError):
        dispatcher.current_client

def test_database_dispatcher(tmpdir):
    """Test getting correct database."""

    test_dir = tmpdir.mkdir("test")
    other_test_dir = tmpdir.mkdir("other_test")

    dispatcher = DatabaseDispatcher()

    with pytest.raises(errors.ConfigurationError):
        dispatcher.current_database

    dispatcher.push_database_to_stack(Path(tmpdir))

    assert dispatcher.current_database._storage.path == Path(tmpdir).resolve()

    dispatcher.push_database_to_stack(str(Path(test_dir)))

    assert dispatcher.current_database._storage.path == Path(test_dir).resolve()

    dispatcher.push_database_to_stack(Path(other_test_dir), commit=True)

    assert dispatcher.current_database._storage.path == Path(other_test_dir).resolve()

    dispatcher.pop_database()

    # NOTE: Make sure the database was committed on pop
    assert (Path(other_test_dir) / "root").exists()

    assert dispatcher.current_database._storage.path == Path(test_dir).resolve()

    dispatcher.pop_database()

    # NOTE: Make sure the database was not committed on pop
    assert not (Path(test_dir) / "root").exists()

    assert dispatcher.current_database._storage.path == Path(tmpdir).resolve()

    dispatcher.pop_database()

    # NOTE: Make sure the database was not committed on pop
    assert not (Path(tmpdir) / "root").exists()

    with pytest.raises(errors.ConfigurationError):
        dispatcher.current_database


# 猫狗分类器
# Keras
# 准确率在90%左右

import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from tensorflow.keras.preprocessing.image import array_to_img, img_to_array, load_img, ImageDataGenerator
from tensorflow.keras import layers
from tensorflow.keras import Model
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.applications.inception_v3 import InceptionV3

local_weights_file = '../Model/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'
pre_trained_model = InceptionV3(
    input_shape=(150, 150, 3), include_top=False, weights=None)
pre_trained_model.load_weights(local_weights_file)

for layer in pre_trained_model.layers:
    layer.trainable = False

last_layer = pre_trained_model.get_layer('mixed7')
print('last layer output shape:', last_layer.output_shape)
last_output = last_layer.output

# Flatten the output layer to 1 dimension
x = layers.Flatten()(last_output)
# Add a fully connected layer with 1,024 hidden units and ReLU activation
x = layers.Dense(1024, activation='relu')(x)
# Add a dropout rate of 0.2
x = layers.Dropout(0.2)(x)
# Add a final sigmoid layer for classification
x = layers.Dense(1, activation='sigmoid')(x)

# Configure and compile the model
model = Model(pre_trained_model.input, x)
model.compile(loss='binary_crossentropy',
              optimizer=RMSprop(lr=0.0001),
              metrics=['acc'])

# 猫和狗训练数据和验证数据的目录
base_dir = '../Data'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')

# 猫的训练数据目录
train_cats_dir = os.path.join(train_dir, 'cats')

# 狗的训练数据目录
train_dogs_dir = os.path.join(train_dir, 'dogs')

# 猫的验证数据目录
validation_cats_dir = os.path.join(validation_dir, 'cats')

# 狗的验证数据目录
validation_dogs_dir = os.path.join(validation_dir, 'dogs')

# 猫的训练数据文件
train_cat_fnames = os.listdir(train_cats_dir)

# 狗的训练数据文件
train_dog_fnames = os.listdir(train_dogs_dir)

# 图像预处理
# All images will be rescaled by 1./255
train_datagen = ImageDataGenerator(
    rescale=1./255,
    rotation_range=40,
    width_shift_range=0.2,
    height_shift_range=0.2,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,)

test_datagen = ImageDataGenerator(rescale=1./255)

# Flow training images in batches of 20 using train_datagen generator
train_generator = train_datagen.flow_from_directory(
        train_dir,  # This is the source directory for training images
        target_size=(150, 150),  # All images will be resized to 150x150
        batch_size=20,
        # Since we use binary_crossentropy loss, we need binary labels
        class_mode='binary')

# Flow validation images in batches of 20 using test_datagen generator
validation_generator = test_datagen.flow_from_directory(
        validation_dir,
        target_size=(150, 150),
        batch_size=20,
        class_mode='binary')

history = model.fit_generator(
      train_generator,
      steps_per_epoch=100,
      epochs=2,
      validation_data=validation_generator,
      validation_steps=50,
      verbose=2)

from tensorflow.keras.optimizers import SGD

unfreeze = False

# Unfreeze all models after "mixed6"
for layer in pre_trained_model.layers:
  if unfreeze:
    layer.trainable = True
  if layer.name == 'mixed6':
    unfreeze = True

# As an optimizer, here we will use SGD
# with a very low learning rate (0.00001)
model.compile(loss='binary_crossentropy',
              optimizer=SGD(
                  lr=0.00001,
                  momentum=0.9),
              metrics=['acc'])

history = model.fit_generator(
      train_generator,
      steps_per_epoch=100,
      epochs=50,
      validation_data=validation_generator,
      validation_steps=50,
      verbose=2)

# Retrieve a list of accuracy results on training and test data
# sets for each training epoch
acc = history.history['acc']
val_acc = history.history['val_acc']

# Retrieve a list of list results on training and test data
# sets for each training epoch
loss = history.history['loss']
val_loss = history.history['val_loss']

# Get number of epochs
epochs = range(len(acc))

# Plot training and validation accuracy per epoch
acc_plot = plt.figure(figsize=(9, 6))
plt.plot(epochs, acc, label="Train accuracy")
plt.plot(epochs, val_acc, label="Validation accuracy")
plt.title('Training and validation accuracy')
plt.ylabel('Training Progress (Accuracy values)', fontsize=12)
plt.xlabel('Training Epoch', fontsize=12)
plt.legend(loc='best')
plt.show()

# Plot training and validation loss per epoch
loss_plot = plt.figure(figsize=(9, 6))
plt.plot(epochs, loss, label="Train loss")
plt.plot(epochs, val_loss, label="Validation loss")
plt.title('Training and validation loss')
plt.legend(loc='best')
plt.ylabel('Training Progress (Loss values)', fontsize=12)
plt.xlabel('Training Epoch', fontsize=12)
plt.show()


import flask
from flask import request
from predictor_api import make_prediction_ldamallet, make_prediction_bert, make_suggestion

# Initialize the app
app = flask.Flask(__name__)

# An example of routing:
# If they go to the page "/" (this means a GET request
# to the page http://127.0.0.1:5000/), return a simple
# page that says the site is up!
@app.route("/")
def hello():
    return "It's alive!!!"

@app.route("/predict", methods=["POST", "GET"])
def predict():
    # request.args contains all the arguments passed by our form
    # comes built in with flask. It is a dictionary of the form
    # "form name (as set in template)" (key): "string in the textbox" (value)
    review = request.form.get("review")
    pairs_ldamallet = make_prediction_ldamallet(review)
    pairs_bert = make_prediction_bert(review)
    if pairs_ldamallet is not None:
        suggestion_ldamallet = make_suggestion(pairs_ldamallet[0][0])
    else:
        suggestion_ldamallet = None
    if pairs_bert is not None:
        suggestion_bert = make_suggestion(pairs_bert[0][0])
    else:
        suggestion_bert = None
    return flask.render_template('predictor.html',
                                 review=review,
                                 prediction_ldamallet=pairs_ldamallet,
                                 prediction_bert=pairs_bert,
                                 suggestion_ldamallet=suggestion_ldamallet,
                                 suggestion_bert=suggestion_bert)

# Start the server, continuously listen to requests.
# We'll have a running web app!

# For local development:
if __name__ == '__main__':
    app.run(debug=True)

    # For public web serving:
    # app.run(host='0.0.0.0')


# -*- coding: utf-8 -*-
import os

from flask import Flask, request, jsonify
import requests

from grpc.beta import implementations
from tensorflow_serving.example import inception_inference_pb2

app = Flask(__name__)

@app.route('/')
def hello_world():
	return 'Hello, World!'

@app.route('/tag')
def tag():
	url = request.args.get('q')
	r  = requests.get(url)

	channel = implementations.insecure_channel('localhost', 9000)
	stub = inception_inference_pb2.beta_create_InceptionService_stub(channel)

	inception_request = inception_inference_pb2.InceptionRequest()
	inception_request.jpeg_encoded = r.content
	result = stub.Classify(inception_request, 10.0)  # 10 secs timeout

	return jsonify(result=str(result))


"""
27. Remove Element
Given an array nums and a value val, remove all instances of that value
in-place and return the new length.

The order of elements can be changed.

Result: 24 ms
"""

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        if nums.count(val) < 0:
            return 0

        for i in range(nums.count(val)):
            nums.remove(val)

        length = len(nums)

        return length


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.py
~~~

PURPOSE
Support calculations, namedtuples and constants used throughout the library and application.

REFERENCES

REQUIRES
numpy
numba

:author: R.K.Garcia <rayg@ssec.wisc.edu>
:copyright: 2015 by University of Wisconsin Regents, see AUTHORS for more details
:license: GPLv3, see LICENSE for more details
"""
from collections import namedtuple
import numpy as np
from enum import Enum

__author__ = 'rayg'
__docformat__ = 'reStructuredText'

import os, sys
import logging, unittest, argparse
from numba import jit, float64, int64, uint64, boolean, types as nb_types
from pyproj import Proj

LOG = logging.getLogger(__name__)

# if sys.platform.startswith("win"):
PREFERRED_SCREEN_TO_TEXTURE_RATIO = 1.0  # screenpx:texturepx that we want to keep, ideally, by striding
# else:
#     PREFERRED_SCREEN_TO_TEXTURE_RATIO = 0.5  # screenpx:texturepx that we want to keep, ideally, by striding

# http://home.online.no/~sigurdhu/WGS84_Eng.html

DEFAULT_TILE_HEIGHT = 512
DEFAULT_TILE_WIDTH = 512
DEFAULT_TEXTURE_HEIGHT=2
DEFAULT_TEXTURE_WIDTH=16
DEFAULT_ANIMATION_DELAY=100.0  # milliseconds
# The values below are taken from the test geotiffs that are projected to the `DEFAULT_PROJECTION` below.
# These units are in meters in mercator projection space
DEFAULT_X_PIXEL_SIZE = 4891.969810251281160
DEFAULT_Y_PIXEL_SIZE = -7566.684931505724307
DEFAULT_ORIGIN_X = -20037508.342789247632027
DEFAULT_ORIGIN_Y = 15496570.739723727107048

DEFAULT_PROJECTION = "+proj=merc +datum=WGS84 +ellps=WGS84 +over"
DEFAULT_PROJ_OBJ = p = Proj(DEFAULT_PROJECTION)
C_EQ = p(180, 0)[0] - p(-180, 0)[0]
C_POL = p(0, 89.9)[1] - p(0, -89.9)[1]
MAX_EXCURSION_Y = C_POL/2.0
MAX_EXCURSION_X = C_EQ/2.0
# how many 'tessellation' tiles in one texture tile? 2 = 2 rows x 2 cols
TESS_LEVEL = 20
IMAGE_MESH_SIZE = 10
# smallest difference between two image extents (in canvas units)
# before the image is considered "out of view"
CANVAS_EXTENTS_EPSILON = 1e-4

#R_EQ = 6378.1370  # km
#R_POL = 6356.7523142  # km
#C_EQ = 40075.0170  # linear km
#C_POL = 40007.8630  # linear km

# MAX_EXCURSION_Y = C_POL/4.0
# MAX_EXCURSION_X = C_EQ/2.0

box = namedtuple('box', ('b', 'l', 't', 'r'))  # bottom, left, top, right
rez = namedtuple('rez', ('dy', 'dx'))  # world km / pixel distance
pnt = namedtuple('pnt', ('y', 'x'))
geo = namedtuple('geo', ('n', 'e'))  # lat N, lon E
vue = namedtuple('vue', ('b', 'l', 't', 'r', 'dy', 'dx'))  # combination of box + rez

WORLD_EXTENT_BOX = box(b=-MAX_EXCURSION_Y, l=-MAX_EXCURSION_X, t=MAX_EXCURSION_Y, r=MAX_EXCURSION_X)

# presentation information for a layer; z_order comes from the layerset
prez = namedtuple('prez', [
    'uuid',      # UUID: dataset in the document/workspace
    'kind',      # what kind of layer it is
    'visible',   # bool: whether it's visible or not
    'a_order',   # int: None for non-animating, 0..n-1 what order to draw in during animation
    'colormap',  # name or uuid: color map to use; name for default, uuid for user-specified
    'climits',   # tuple: valid min and valid max used for color mapping normalization
    'gamma',     # float: valid (0 to 5) for gamma correction (default should be 1.0)
    'mixing'     # mixing mode constant
])

class TOOL(Enum):
    """Names for cursor tools.
    """
    PAN_ZOOM = "pan_zoom"
    POINT_PROBE = "point_probe"
    REGION_PROBE = "region_probe"

class KIND(Enum):
    """kind of entities we're working with
    """
    UNKNOWN = 0
    IMAGE = 1
    OUTLINE = 2
    SHAPE = 3
    RGB = 4
    COMPOSITE = 5

class COMPOSITE_TYPE(Enum):
    """Type of non-luminance image layers
    """
    RGB = 1
    ARITHMETIC = 2

class INSTRUMENT(Enum):
    UNKNOWN = '???'
    AHI = 'AHI'
    ABI = 'ABI'
    AMI = 'AMI'

class PLATFORM(Enum):
    UNKNOWN = '???'
    HIMAWARI_8 = 'Himawari-8'
    HIMAWARI_9 = 'Himawari-9'
    GOES_16 = 'G16'
    GOES_17 = 'G17'

class INFO(Enum):
    """
    Standard keys for info dictionaries
    Note: some fields correspond to database fields in workspace.metadatabase !
    """
    UNKNOWN = '???'
    PATHNAME = 'path'  # full path to the data file
    DATASET_NAME = 'dataset_name'  # logical name of the file (possibly human assigned)
    SHORT_NAME = 'short_name'  # CF short_name
    LONG_NAME = 'long_name'  # CF long_name
    STANDARD_NAME = 'standard_name'  # CF compliant standard_name (when possible)
    UNITS = 'units'  # CF compliant (udunits compliant) units string, original data units
    KIND = 'kind'  # KIND enumeration on what kind of layer this makes
    UUID = 'uuid'  # UUID assigned on import, which follows the layer around the system
    ORIGIN_X = 'origin_x'
    ORIGIN_Y = 'origin_y'
    CELL_WIDTH = 'cell_width'
    CELL_HEIGHT = 'cell_height'
    PROJ = 'proj4'
    CLIM = 'clim'  # (min,max) color map limits
    VALID_RANGE = 'valid_range'
    SHAPE = 'shape' # (rows, columns) or (rows, columns, levels) data shape
    COLORMAP = 'colormap'  # name or UUID of a color map
    DISPLAY_TIME = 'display_time'  # typically from guidebook, used for labeling animation frame
    # Previously in the GUIDE Enum:
    PLATFORM = 'platform' # full standard name of spacecraft
    SCHED_TIME = 'timeline'  # scheduled time for observation
    OBS_TIME = 'obstime'  # actual time for observation
    OBS_DURATION = 'obsduration'  # time from start of observation to end of observation
    BAND = 'band'  # band number (multispectral instruments)
    SCENE = 'scene'  # standard scene identifier string for instrument, e.g. FLDK
    INSTRUMENT = 'instrument'  # INSTRUMENT enumeration, or string with full standard name
    DISPLAY_NAME = 'display_name'  # preferred name in the layer list
    UNIT_CONVERSION = 'unit_conversion'  # (preferred CF units, convert_func, format_func)
    # unit numeric conversion func: lambda x, inverse=False: convert-to-units
    # unit string format func: lambda x, numeric=True, units=True: formatted string
    CENTRAL_WAVELENGTH = 'nominal_wavelength'

    def __lt__(self, other):
        """
        when using pickletype in sqlalchemy tables, a comparator is needed for enumerations
        :param other:
        :return:
        """
        if isinstance(other, str):
            return self.value < other
        elif isinstance(other, type(self)):
            return self.value < other.value
        raise ValueError("cannot compare {} < {}".format(repr(self), repr(other)))

    def __gt__(self, other):
        """
        when using pickletype in sqlalchemy tables, a comparator is needed for enumerations
        :param other:
        :return:
        """
        if isinstance(other, str):
            return self.value > other
        elif isinstance(other, type(self)):
            return self.value > other.value
        raise ValueError("cannot compare {} > {}".format(repr(self), repr(other)))

    def __hash__(self):
        return hash(self.value)

    def __eq__(self, other):
        """
        when using pickletype in sqlalchemy tables, a comparator is needed for enumerations
        :param other:
        :return:
        """
        if isinstance(other, str):
            return self.value == other
        elif isinstance(other, type(self)):
            return self.value == other.value
        raise ValueError("cannot compare {} == {}".format(repr(self), repr(other)))

@jit(nb_types.UniTuple(int64, 2)(float64[:, :], float64[:, :]))
def get_reference_points(img_cmesh, img_vbox):
    """Get two image reference point indexes.

    This function will return the two nearest reference points to the
    center of the viewed canvas. The first argument `img_cmesh` is all
    valid image mesh points that were successfully transformed to the
    view projection. The second argument `img_vbox` is these same mesh
    points, but in the original image projection units.

    :param img_cmesh: (N, 2) array of valid points across the image space
    :param img_vbox: (N, 2) array of valid points across the image space
    :return: (reference array index 1, reference array index 2)
    :raises: ValueError if not enough valid points to create
             two reference points
    """
    # Sort points by nearest to further from the 0,0 center of the canvas
    # Uses a cheap Pythagorean theorem by summing X + Y
    near_points = np.sum(np.abs(img_cmesh), axis=1).argsort()
    ref_idx_1 = near_points[0]
    # pick a second reference point that isn't in the same row or column as the first
    near_points_2 = near_points[~np.isclose(img_vbox[near_points][:, 0], img_vbox[ref_idx_1][0]) &
                                ~np.isclose(img_vbox[near_points][:, 1], img_vbox[ref_idx_1][1])]
    if near_points_2.shape[0] == 0:
        raise ValueError("Could not determine reference points")

    return ref_idx_1, near_points_2[0]

@jit(nb_types.UniTuple(int64, 2)(float64[:, :], boolean[:, :]))
def get_reference_points_image(img_dist, valid_mask):
    """Get two image reference point indexes close to image center.

    This function will return the two nearest reference points to the
    center of the image. The argument `img_vbox` is an array of points
    across the image that can be successfully projected to the viewed
    projection.

    :param img_dist: (N, 2) array of distances from the image center
                     in image space for points that can be projected
                     to the viewed projection
    :return: (reference array index 1, reference array index 2)
    :raises: ValueError if not enough valid points to create
             two reference points
    """
    # Sort points by nearest to further from the 0,0 center of the canvas
    # Uses a cheap Pythagorean theorem by summing X + Y
    near_points = np.sum(np.abs(img_dist), axis=1)
    near_points[~valid_mask] = np.inf
    near_points = near_points.argsort()
    ref_idx_1 = near_points[0]
    if np.isinf(near_points[ref_idx_1]):
        raise ValueError("Could not determine reference points")
    # pick a second reference point that isn't in the same row or column as the first
    near_points_2 = near_points[~np.isclose(img_dist[near_points][:, 0], img_dist[ref_idx_1][0]) &
                                ~np.isclose(img_dist[near_points][:, 1], img_dist[ref_idx_1][1])]
    if near_points_2.shape[0] == 0:
        raise ValueError("Could not determine reference points")

    return ref_idx_1, near_points_2[0]

@jit(nb_types.UniTuple(float64, 2)(float64, float64, int64, float64), nopython=True)
def _calc_extent_component(canvas_point, image_point, num_pixels, meters_per_pixel):
    """Calculate """
    # Find the distance in image space between the closest
    # reference point and the center of the canvas view (0, 0)
    # divide canvas_point coordinate by 2 to get the ratio of that distance to the entire canvas view (-1 to 1)
    viewed_img_center_shift_x = (canvas_point / 2. * num_pixels * meters_per_pixel)
    # Find the theoretical center of the canvas in image space (X/Y)
    viewed_img_center_x = image_point - viewed_img_center_shift_x
    # Find the theoretical number of image units (meters) that
    # would cover an entire canvas in a perfect world
    half_canvas_width = num_pixels * meters_per_pixel / 2.
    # Calculate the theoretical bounding box if the image was
    # perfectly centered on the closest reference point
    # Clip the bounding box to the extents of the image
    l = viewed_img_center_x - half_canvas_width
    r = viewed_img_center_x + half_canvas_width
    return l, r

@jit(nb_types.UniTuple(float64, 2)(float64[:, :], float64[:, :], nb_types.UniTuple(int64, 2)), nopython=True)
def calc_pixel_size(canvas_point, image_point, canvas_size):
    # Calculate the number of image meters per display pixel
    # That is, use the ratio of the distance in canvas space
    # between two points to the distance of the canvas
    # (1 - (-1) = 2). Use this ratio to calculate number of
    # screen pixels between the two reference points. Then
    # determine how many image units cover that number of pixels.
    dx = abs((image_point[1, 0] - image_point[0, 0]) /
             (canvas_size[0] * (canvas_point[1, 0] - canvas_point[0, 0]) / 2.))
    dy = abs((image_point[1, 1] - image_point[0, 1]) /
             (canvas_size[1] * (canvas_point[1, 1] - canvas_point[0, 1]) / 2.))
    return dx, dy

@jit(nopython=True)
def clip(v, n, x):
    return max(min(v, x), n)

@jit(nb_types.NamedUniTuple(float64, 4, box)(
        nb_types.NamedUniTuple(float64, 4, box),
        nb_types.Array(float64, 1, 'C'),
        nb_types.Array(float64, 1, 'C'),
        nb_types.UniTuple(int64, 2),
        float64,
        float64
    ),
    nopython=True)
def calc_view_extents(image_extents_box, canvas_point, image_point, canvas_size, dx, dy):
    l, r = _calc_extent_component(canvas_point[0], image_point[0], canvas_size[0], dx)
    l = clip(l, image_extents_box.l, image_extents_box.r)
    r = clip(r, image_extents_box.l, image_extents_box.r)

    b, t = _calc_extent_component(canvas_point[1], image_point[1], canvas_size[1], dy)
    b = clip(b, image_extents_box.b, image_extents_box.t)
    t = clip(t, image_extents_box.b, image_extents_box.t)

    if (r - l) < CANVAS_EXTENTS_EPSILON or (t - b) < CANVAS_EXTENTS_EPSILON:
        # they are viewing essentially nothing or the image isn't in view
        raise ValueError("Image can't be currently viewed")

    return box(l=l, r=r, b=b, t=t)

@jit(nb_types.UniTuple(float64, 2)(
        nb_types.NamedUniTuple(int64, 2, pnt),
        nb_types.NamedUniTuple(int64, 2, pnt),
        nb_types.NamedUniTuple(int64, 2, pnt)
    ),
     nopython=True)
def max_tiles_available(image_shape, tile_shape, stride):
    ath = (image_shape[0] / float(stride[0])) / tile_shape[0]
    atw = (image_shape[1] / float(stride[1])) / tile_shape[1]
    return ath, atw

# @jit(nb_types.NamedUniTuple(int64, 4, box)(
#         nb_types.NamedUniTuple(float64, 2, rez),
#         nb_types.NamedUniTuple(float64, 2, rez),
#         nb_types.NamedUniTuple(float64, 2, pnt),
#         nb_types.NamedUniTuple(int64, 2, pnt),
#         nb_types.NamedUniTuple(int64, 2, pnt),
#         nb_types.NamedUniTuple(float64, 6, vue),
#         nb_types.NamedUniTuple(int64, 2, pnt),
#         nb_types.NamedUniTuple(int64, 4, box)
#     ),
#      nopython=True)
@jit(nopython=True)
def visible_tiles(pixel_rez,
                  tile_size,
                  image_center,
                  image_shape,
                  tile_shape,
                  visible_geom, stride, extra_tiles_box):
    """
    given a visible world geometry and sampling, return (sampling-state, [box-of-tiles-to-draw])
    sampling state is WELLSAMPLED/OVERSAMPLED/UNDERSAMPLED
    returned box should be iterated per standard start:stop style
    tiles are specified as (iy,ix) integer pairs
    extra_box value says how many extra tiles to include around each edge
    """
    V = visible_geom
    X = extra_tiles_box  # FUTURE: extra_geom_box specifies in world coordinates instead of tile count
    Z = pixel_rez
    tile_size = rez(tile_size.dy * stride[0], tile_size.dx * stride[1])
    # should be the upper-left corner of the tile centered on the center of the image
    to = pnt(image_center[0] + tile_size.dy / 2.,
             image_center[1] - tile_size.dx / 2.)  # tile origin

    # number of data pixels between view edge and originpoint
    pv = box(
        b=(V.b - to.y) / -(Z.dy * stride[0]),
        t=(V.t - to.y) / -(Z.dy * stride[0]),
        l=(V.l - to.x) / (Z.dx * stride[1]),
        r=(V.r - to.x) / (Z.dx * stride[1])
    )

    th, tw = tile_shape
    # first tile we'll need is (tiy0, tix0)
    # floor to make sure we get the upper-left of the theoretical tile
    tiy0 = np.floor(pv.t / th)
    tix0 = np.floor(pv.l / tw)
    # number of tiles wide and high we'll absolutely need
    # add 0.5 and ceil to make sure we include all possible tiles
    # NOTE: output r and b values are exclusive, l and t are inclusive
    nth = np.ceil((pv.b - tiy0 * th) / th + 0.5)
    ntw = np.ceil((pv.r - tix0 * tw) / tw + 0.5)

    # now add the extras
    if X.b > 0:
        nth += int(X.b)
    if X.l > 0:
        tix0 -= int(X.l)
        ntw += int(X.l)
    if X.t > 0:
        tiy0 -= int(X.t)
        nth += int(X.t)
    if X.r > 0:
        ntw += int(X.r)

    # Total number of tiles in this image at this stride (could be fractional)
    ath, atw = max_tiles_available(image_shape, tile_shape, stride)
    # truncate to the available tiles
    hw = atw / 2.
    hh = ath / 2.
    # center tile is half pixel off because we want center of the center
    # tile to be at the center of the image
    if tix0 < -hw + 0.5:
        ntw += hw - 0.5 + tix0
        tix0 = -hw + 0.5
    if tiy0 < -hh + 0.5:
        nth += hh - 0.5 + tiy0
        tiy0 = -hh + 0.5
    # add 0.5 to include the "end of the tile" since the r and b are exclusive
    if tix0 + ntw > hw + 0.5:
        ntw = hw + 0.5 - tix0
    if tiy0 + nth > hh + 0.5:
        nth = hh + 0.5 - tiy0

    tilebox = box(
        b=np.int64(np.ceil(tiy0 + nth)),
        l=np.int64(np.floor(tix0)),
        t=np.int64(np.floor(tiy0)),
        r=np.int64(np.ceil(tix0 + ntw)),
    )
    return tilebox

class TileCalculator(object):
    """
    common calculations for mercator tile groups in an array or file
    tiles are identified by (iy,ix) zero-based indicators
    """
    OVERSAMPLED='oversampled'
    UNDERSAMPLED='undersampled'
    WELLSAMPLED='wellsampled'

    name = None
    image_shape = None
    pixel_rez = None
    zero_point = None
    tile_shape = None
    # derived
    image_extents_box = None  # word coordinates that this image and its tiles corresponds to
    tiles_avail = None  # (ny,nx) available tile count for this image

    def __init__(self, name, image_shape, ul_origin, pixel_rez,
                 tile_shape=(DEFAULT_TILE_HEIGHT, DEFAULT_TILE_WIDTH),
                 texture_shape=(DEFAULT_TEXTURE_HEIGHT, DEFAULT_TEXTURE_WIDTH),
                 projection=DEFAULT_PROJECTION,
                 wrap_lon=False):
        """
        name: the 'name' of the tile, typically the path of the file it represents
        image_shape: (h:int,w:int) in pixels
        ul_origin: (y:float,x:float) in world coords specifies upper-left coordinate of the image
        pixel_rez: (dy:float,dx:float) in world coords per pixel ascending from corner [0,0], as measured near zero_point
        tile_shape: the pixel dimensions (h:int, w:int) of the GPU tiling we want to use
        texture_shape: the size of the texture being used (h:int, w:int) in number of tiles

        Tiling is aligned to pixels, not world
        World coordinates are eqm such that 0,0 matches 0°N 0°E, going north/south +-90° and west/east +-180°
        Data coordinates are pixels with b l or b r corner being 0,0
        """
        super(TileCalculator, self).__init__()
        self.name = name
        self.image_shape = pnt(np.int64(image_shape[0]), np.int64(image_shape[1]))
        self.ul_origin = pnt(*ul_origin)
        self.pixel_rez = rez(np.float64(pixel_rez[0]), np.float64(pixel_rez[1]))
        self.tile_shape = pnt(np.int64(tile_shape[0]), np.int64(tile_shape[1]))
        # in units of tiles:
        self.texture_shape = texture_shape
        # in units of data elements (float32):
        self.texture_size = (self.texture_shape[0] * self.tile_shape[0], self.texture_shape[1] * self.tile_shape[1])
        self.image_tiles_avail = (self.image_shape[0] / self.tile_shape[0], self.image_shape[1] / self.tile_shape[1])
        self.wrap_lon = wrap_lon

        self.proj = Proj(projection)
        self.image_extents_box = e = box(
            b=np.float64(self.ul_origin[0] - self.image_shape[0] * self.pixel_rez.dy),
            t=np.float64(self.ul_origin[0]),
            l=np.float64(self.ul_origin[1]),
            r=np.float64(self.ul_origin[1] + self.image_shape[1] * self.pixel_rez.dx),
        )
        # Array of points across the image space to be used as an estimate of image coverage
        # Used when checking if the image is viewable on the current canvas's projection
        self.image_mesh = np.meshgrid(np.linspace(e.l, e.r, IMAGE_MESH_SIZE), np.linspace(e.b, e.t, IMAGE_MESH_SIZE))
        self.image_mesh = np.column_stack((self.image_mesh[0].ravel(), self.image_mesh[1].ravel(),))
        self.image_center = pnt(self.ul_origin.y - self.image_shape[0] / 2. * self.pixel_rez.dy,
                                self.ul_origin.x + self.image_shape[1] / 2. * self.pixel_rez.dx)
        # size of tile in image projection
        self.tile_size = rez(self.pixel_rez.dy * self.tile_shape[0], self.pixel_rez.dx * self.tile_shape[1])
        self.overview_stride = self.calc_overview_stride()

    def visible_tiles(self, visible_geom, stride=pnt(1, 1), extra_tiles_box=box(0, 0, 0, 0)):
        # return visible_tiles(self.pixel_rez,
        #                      self.tile_size,
        #                      self.image_center,
        #                      self.image_shape,
        #                      self.tile_shape,
        #                      visible_geom,
        #                      stride,
        #                      extra_tiles_box)
        v = visible_geom
        e = extra_tiles_box
        return visible_tiles(
            rez(np.float64(self.pixel_rez[0]), np.float64(self.pixel_rez[1])),
            rez(np.float64(self.tile_size[0]), np.float64(self.tile_size[1])),
            pnt(np.float64(self.image_center[0]), np.float64(self.image_center[1])),
            pnt(np.int64(self.image_shape[0]), np.int64(self.image_shape[1])),
            pnt(np.int64(self.tile_shape[0]), np.int64(self.tile_shape[1])),
            vue(
                np.float64(v[0]), np.float64(v[1]),
                np.float64(v[2]), np.float64(v[3]),
                np.float64(v[4]), np.float64(v[5]),
                ),
            pnt(np.int64(stride[0]), np.int64(stride[1])),
            box(
                np.int64(e[0]), np.int64(e[1]),
                np.int64(e[2]), np.int64(e[3])
            ))

    @jit
    def calc_tile_slice(self, tiy, tix, stride):
        """Calculate the slice needed to get data.

        The returned slice assumes the original image data has already
        been reduced by the provided stride.

        Args:
            tiy (int): Tile Y index (down is positive)
            tix (int): Tile X index (right is positive)
            stride (tuple): (Original data Y-stride, Original data X-stride)

        """
        y_offset = int(self.image_shape[0] / 2. / stride[0] - self.tile_shape[0] / 2.)
        y_start = int(tiy * self.tile_shape[0] + y_offset)
        if y_start < 0:
            row_slice = slice(0, max(0, y_start + self.tile_shape[0]), 1)
        else:
            row_slice = slice(y_start, y_start + self.tile_shape[0], 1)

        x_offset = int(self.image_shape[1] / 2. / stride[1] - self.tile_shape[1] / 2.)
        x_start = int(tix * self.tile_shape[1] + x_offset)
        if x_start < 0:
            col_slice = slice(0, max(0, x_start + self.tile_shape[1]), 1)
        else:
            col_slice = slice(x_start, x_start + self.tile_shape[1], 1)
        return row_slice, col_slice

    @jit
    def calc_tile_fraction(self, tiy, tix, stride):
        """Calculate the fractional components of the specified tile

        Returns:
            (factor, offset): Two `rez` objects stating the relative size
                              of the tile compared to a whole tile and the
                              offset from the origin of a whole tile.
        """
        mt = max_tiles_available(self.image_shape, self.tile_shape, stride)

        if tix < -mt[1] / 2. + 0.5:
            # left edge tile
            offset_x = -mt[1] / 2. + 0.5 - tix
            factor_x = 1 - offset_x
        elif mt[1] / 2. + 0.5 - tix < 1:
            # right edge tile
            offset_x = 0.
            factor_x = mt[1] / 2. + 0.5 - tix
        else:
            # full tile
            offset_x = 0.
            factor_x = 1.

        if tiy < -mt[0] / 2. + 0.5:
            # left edge tile
            offset_y = -mt[0] / 2. + 0.5 - tiy
            factor_y = 1 - offset_y
        elif mt[0] / 2. + 0.5 - tiy < 1:
            # right edge tile
            offset_y = 0.
            factor_y = mt[0] / 2. + 0.5 - tiy
        else:
            # full tile
            offset_y = 0.
            factor_y = 1.

        factor_rez = rez(dy=factor_y, dx=factor_x)
        offset_rez = rez(dy=offset_y, dx=offset_x)
        return factor_rez, offset_rez

    @jit
    def calc_stride(self, visible, texture=None):
        """
        given world geometry and sampling as a vue or rez tuple
        calculate a conservative stride value for rendering a set of tiles
        :param visible: vue or rez with world pixels per screen pixel
        :param texture: vue or rez with texture resolution as world pixels per screen pixel
        """
        # screen dy,dx in world distance per pixel
        # world distance per pixel for our data
        # compute texture pixels per screen pixels
        texture = texture or self.pixel_rez
        tsy = min(self.overview_stride[0].step, max(1, np.ceil(visible.dy * PREFERRED_SCREEN_TO_TEXTURE_RATIO / texture.dy)))
        tsx = min(self.overview_stride[1].step, max(1, np.ceil(visible.dx * PREFERRED_SCREEN_TO_TEXTURE_RATIO / texture.dx)))
        return pnt(np.int64(tsy), np.int64(tsx))

    @jit
    def calc_overview_stride(self, image_shape=None):
        image_shape = image_shape or self.image_shape
        # FUTURE: Come up with a fancier way of doing overviews like averaging each strided section, if needed
        tsy = max(1, int(np.floor(image_shape[0] / self.tile_shape[0])))
        tsx = max(1, int(np.floor(image_shape[1] / self.tile_shape[1])))
        y_slice = slice(0, image_shape[0], tsy)
        x_slice = slice(0, image_shape[1], tsx)
        return y_slice, x_slice

    @jit
    def calc_vertex_coordinates(self, tiy, tix, stridey, stridex,
                                factor_rez, offset_rez, tessellation_level=1):
        quad = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0],
                         [0, 0, 0], [1, 1, 0], [0, 1, 0]],
                        dtype=np.float32)
        quads = np.tile(quad, (tessellation_level * tessellation_level, 1))
        tile_w = self.pixel_rez.dx * self.tile_shape[1] * stridex
        tile_h = self.pixel_rez.dy * self.tile_shape[0] * stridey
        origin_x = self.image_center[1] - tile_w / 2.
        origin_y = self.image_center[0] + tile_h / 2.
        for x_idx in range(tessellation_level):
            for y_idx in range(tessellation_level):
                start_idx = x_idx * tessellation_level + y_idx
                quads[start_idx * 6:(start_idx + 1) * 6, 0] *= tile_w * factor_rez.dx / tessellation_level
                quads[start_idx * 6:(start_idx + 1) * 6, 0] += origin_x + tile_w * (tix + offset_rez.dx + factor_rez.dx * x_idx / tessellation_level)
                quads[start_idx * 6:(start_idx + 1) * 6, 1] *= -tile_h * factor_rez.dy / tessellation_level  # Origin is upper-left so image goes down
                quads[start_idx * 6:(start_idx + 1) * 6, 1] += origin_y - tile_h * (tiy + offset_rez.dy + factor_rez.dy * y_idx / tessellation_level)
        quads = quads.reshape(tessellation_level * tessellation_level * 6, 3)
        return quads[:, :2]

    @jit
    def calc_texture_coordinates(self, ttile_idx, factor_rez, offset_rez, tessellation_level=1):
        """Get texture coordinates for one tile as a quad.

        :param ttile_idx: int, texture 1D index that maps to some internal texture tile location
        """
        tiy = int(ttile_idx / self.texture_shape[1])
        tix = ttile_idx % self.texture_shape[1]
        # start with basic quad describing the entire texture
        quad = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0],
                         [0, 0, 0], [1, 1, 0], [0, 1, 0]],
                        dtype=np.float32)
        quads = np.tile(quad, (tessellation_level * tessellation_level, 1))
        # Now scale and translate the coordinates so they only apply to one tile in the texture
        one_tile_tex_width = 1.0 / self.texture_size[1] * self.tile_shape[1]
        one_tile_tex_height = 1.0 / self.texture_size[0] * self.tile_shape[0]
        for x_idx in range(tessellation_level):
            for y_idx in range(tessellation_level):
                start_idx = x_idx * tessellation_level + y_idx
                # offset for this tile isn't needed because the data should
                # have been inserted as close to the top-left of the texture
                # location as possible
                quads[start_idx * 6:(start_idx + 1) * 6, 0] *= one_tile_tex_width * factor_rez.dx / tessellation_level
                quads[start_idx * 6:(start_idx + 1) * 6, 0] += one_tile_tex_width * (tix + factor_rez.dx * x_idx / tessellation_level)
                quads[start_idx * 6:(start_idx + 1) * 6, 1] *= one_tile_tex_height * factor_rez.dy / tessellation_level
                quads[start_idx * 6:(start_idx + 1) * 6, 1] += one_tile_tex_height * (tiy + factor_rez.dy * y_idx / tessellation_level)
        quads = quads.reshape(6 * tessellation_level * tessellation_level, 3)
        quads = np.ascontiguousarray(quads[:, :2])
        return quads

    def calc_view_extents(self, canvas_point, image_point, canvas_size, dx, dy):
        return calc_view_extents(self.image_extents_box, canvas_point, image_point, canvas_size, dx, dy)

def main():
    parser = argparse.ArgumentParser(
        description="PURPOSE",
        epilog="",
        fromfile_prefix_chars='@')
    parser.add_argument('-v', '--verbose', dest='verbosity', action="count", default=0,
                        help='each occurrence increases verbosity 1 level through ERROR-WARNING-INFO-DEBUG')
    # http://docs.python.org/2.7/library/argparse.html#nargs
    # parser.add_argument('--stuff', nargs='5', dest='my_stuff',
    #                    help="one or more random things")
    parser.add_argument('pos_args', nargs='*',
                        help="positional arguments don't have the '-' prefix")
    args = parser.parse_args()

    levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
    logging.basicConfig(level=levels[min(3, args.verbosity)])

    if not args.pos_args:
        unittest.main()
        return 0

    for pn in args.pos_args:
        pass

    return 0

if __name__ == '__main__':
    sys.exit(main())


#!/usr/bin/env python
from web3 import Web3, IPCProvider
from web3.middleware import geth_poa_middleware

def init_web3():
    w3 = Web3(IPCProvider('~/mygethnode/geth.ipc'))
    w3.middleware_onion.inject(geth_poa_middleware, layer=0)
    w3.geth.personal.unlockAccount(w3.eth.coinbase,'123456',0)
    w3.eth.defaultAccount = w3.eth.coinbase
    key = w3.eth.coinbase
    enode = w3.geth.admin.nodeInfo().enode
    print('Welcome to the geth Python Console')
    print('Version:', w3.clientVersion)
    print('Your public address is:', key)
    print('Your enode is:', enode)

    return w3


#! /usr/local/bin/python3
#file for the links to I am not usre really. I assume its the symbols that you create.

import os
import glob

def split_stuff(thing):
	(folder, le_file) = thing.split('/')
	return le_file

def print_list():
	os.chdir('/Users/Zeroe/Documents/python_hw/csc344/')
	num_of_hw = 4 # I'm using this to make it easier to show if the number of HW's increases, changing this single number makes it easier to add another folder
	el_files = []
	count = 1
	while count <= 4:
		globber = 'a'+str(count)+'/*'
		el_files.extend(glob.glob(globber))
		count = count + 1

	return el_files

el_files = print_list()
html_string = ''
for each_file in el_files:
	html_string = html_string + '<input type=\"radio\" name=\"file\" value=\"'+each_file+'\" /> '+ split_stuff(each_file)+'
\n'

#************************WHATS PRINTED OUT***********************
print('Content-type: text/html\n')
print('')
print('<title>Homework 5</title>')
print('')
print("
Pick one to go to file (The \'Symbols\' files belong to any preceding code with extensions)
")
print('<form method=\"POST\" action=\"print_file.py\">')

print(html_string)
print('<input type=\"submit\" value=\"Choose this file\" />')

print('</form>')


# coding=utf-8
from __future__ import unicode_literals

from builtins import object

from snips_nlu_utils import (tokenize as _tokenize,
                             tokenize_light as _tokenize_light,
                             normalize)

class Token(object):
    """Token object which is output by the tokenization

    Attributes:
        value (str): Tokenized string
        normalized (str): Normalized value of the tokenized string
        stem (str, optional): Stemmed value, if defined, of the tokenized
            string
        start (int): Start position of the token within the sentence
        end (int): End position of the token within the sentence
    """

    def __init__(self, value, start, end, normalized=None, stem=None):
        self.value = value
        self.start = start
        self.end = end
        self._normalized_value = normalized
        self.stem = stem

    @property
    def normalized_value(self):
        if self._normalized_value is not None:
            return self._normalized_value
        self._normalized_value = normalize(self.value)
        return self._normalized_value

    def __eq__(self, other):
        if not isinstance(other, type(self)):
            return False
        return (self.value == other.value
                and self.start == other.start
                and self.end == other.end
                and self.stem == other.stem)

    def __ne__(self, other):
        return not self.__eq__(other)

def tokenize(string, language):
    """Tokenizes the input

    Args:
        string (str): Input to tokenize
        language (str): Language to use during tokenization

    Returns:
        list of :class:`.Token`: The list of tokenized values
    """
    tokens = [Token(value=token["value"],
                    start=token["char_range"]["start"],
                    end=token["char_range"]["end"])
              for token in _tokenize(string, language)]
    return tokens

def tokenize_light(string, language):
    """Same behavior as :func:`tokenize` but returns tokenized strings instead
        of :class:`Token` objects"""
    tokenized_string = _tokenize_light(string, language)
    return tokenized_string


import discord
# from transformers import pipeline
client = discord.Client()
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")

# summarizer = pipeline("summarization")
@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    # messages = ''
    # only remembers the last 6 messages in conversation
    max_iter = 6
    iter = 0
    for cached_message in reversed(client.cached_messages):
        if cached_message.channel == message.channel:
            # messages += cached_message.content + '\n'
            msg_tokens = tokenizer.encode(cached_message.content + tokenizer.eos_token, return_tensors='pt')
            chat_history_ids = torch.cat([chat_history_ids,msg_tokens], dim=-1) if iter > 0 else msg_tokens
            iter += 1
            if iter >  max_iter:
                break
    # print(messages)
    # chat_history_ids = tokenizer.encode(messages + tokenizer.eos_token, return_tensors='pt')

    # if message.content.startswith('$hello'):
    new_user_input_ids = tokenizer.encode(message.content + tokenizer.eos_token, return_tensors='pt')

    # append the new user input tokens to the chat history
    bot_input_ids = torch.cat([chat_history_ids, new_user_input_ids], dim=-1) #if step > 0 else new_user_input_ids

    # generated a response while limiting the total chat history to 1000 tokens,
    chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)

    generated = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)

    # pretty print last ouput tokens from bot
    print('user: ' + message.content)
    print('gene: ' + generated)
    await message.channel.send(generated)

client.run()


import abc
class A(metaclass=abc.ABCMeta):
    def __init__(self, name):
        self.name = name

    @abc.abstractmethod
    def printName(self):
        print(self.name)

if __name__ == '__main__':
    a = A("Hello") #The class instantiation does not happen.
    a.printName()


import numpy as np
import scipy.special
# from math import erf
from scipy.signal import find_peaks
from lmfit import Model
import TraceIO2 as tio
import matplotlib.pyplot as plt
from nptdms import TdmsFile
import os, re
import pandas as pd

# Hide warnings for non-matching keywords
import warnings

warnings.filterwarnings("ignore")

# specify constants
kT = 4.114  # Thermal energy [pN*nm]
nm_bp = 0.34  # length dsDNA [nm/bp]
nm_base = 0.55  # length ssDNA = [nm/base];
omega0 = 2 * np.pi / 3.6  # inverted pitch of dsDNA [nm-1]
Ebp_kT = 1.32  # average basepair melting energy [kT]

def dat_to_h5(filename):
    traces = pd.read_csv(filename, sep='\t')

    filename = filename.split('.')[0] + '.log'
    print(filename)

    with open(filename.split('.')[0] + '.log', "r") as logdata:
        log = logdata.read()
    print(log)

    items = re.findall("resol*", log, re.MULTILINE)
    for x in items:
        print(x)
    return

    with tio.Traces(filename) as data:
        for col_name in traces.columns:
            print(col_name)
        #     par_name = col_name.split()
        #     try:
        #         index = int(par_name[0][1:])
        #         data.write_par('selected', index, 1)
        #         col_names.append(f'{par_name[0][0]} {par_name[1]} > {index}')
        #         # preliminary data processing
        #         if par_name[0][0] == 'Z':
        #             data.write_par('Z0 (um)', index, traces[col_name].quantile(0.05))
        #             data.write_par('dZ (um)', index, traces[col_name].quantile(0.05) - traces[col_name].quantile(0.95))
        #         elif par_name[0][0] == 'X':
        #             data.write_par('X0 (um)', index, traces[col_name].median())
        #         elif par_name[0][0] == 'Y':
        #             data.write_par('Y0 (um)', index, traces[col_name].median())
        #     except:
        #         # data shared by all traces
        #         col_names.append(col_name)
        # print(f'FS>>> saving file: {filename}')
        # traces.columns = col_names
        # data.write_df('data/processed', traces)

    return

def TDMS_to_h5(filename):
    filename_base = os.path.splitext(filename)[0]
    print(f'FS>>> Processing file: {filename_base + ".tdms"}')
    tdms_file = TdmsFile(filename_base + '.tdms')
    traces = tdms_file.object('Processed data').as_dataframe()
    col_names = []

    with tio.Traces(filename) as data:
        for col_name in traces.columns:
            par_name = col_name.split()
            label = par_name[0][1:]
            if label.isdigit():
                data.write_par('selected', label, 1)
                col_names.append(f'{par_name[0][0]} {par_name[1]} > {label}')
                # preliminary data processing
                if par_name[0][0] == 'Z':
                    data.write_par('Z0 (um)', label, traces[col_name].quantile(0.05))
                    data.write_par('dZ (um)', label,
                                   traces[col_name].quantile(0.05) - traces[col_name].quantile(0.95))
                elif par_name[0][0] == 'X':
                    data.write_par('X0 (um)', label, traces[col_name].median())
                elif par_name[0][0] == 'Y':
                    data.write_par('Y0 (um)', label, traces[col_name].median())
            else:
                col_names.append(f'{col_name}')
        print(f'FS>>> saving file: {filename}')
        traces.columns = col_names
        data.write_df('data/processed', traces)
    return

def erf(x):
    # Approximation of the error function
    x = np.array(x)
    a = (8 * (np.pi - 3)) / (3 * np.pi * (4 - np.pi))
    b = -x ** 2 * (4 / np.pi + a * x ** 2) / (1 + a * x ** 2)
    return np.sign(x) * np.sqrt(1 - np.exp(b))

def diff(x, n=1):
    for i in np.arange(n):
        dx = np.diff(x)
        dx = np.insert(dx, 0, dx[0])
    return dx

def coth(x):
    return np.cosh(x) / np.sinh(x)

def Gauss(x, x0=0, w=1, a=1):
    return a * np.exp(-(x - x0) ** 2 / (2 * w ** 2))

def zHooke(f_pN, k_pN__nm=0.3, z0_nm=1.5, L_nm=5):
    z_nm = ((f_pN / k_pN__nm) + z0_nm)
    return z_nm

def gHooke(f_pN, k_pN__nm=0.3, z0_nm=1.5, L_nm=5):
    g_pNnm = ((f_pN ** 2) / (2 * k_pN__nm)) + (f_pN * z0_nm)
    z_nm = ((f_pN / k_pN__nm) + z0_nm)
    g_pNnm[z_nm > L_nm] *= 100
    return g_pNnm / kT

def zFJC(f_pN, k_pN__nm=0.3, z0_nm=0.0, L_nm=25.0, b_nm=None, sigma=None, L_bp=None):
    if b_nm is None:
        b_nm = 3 * kT / (L_nm * k_pN__nm)
    if L_bp is not None:
        L_nm = L_bp * nm_base
    z_nm = L_nm * (coth(b_nm * f_pN / kT) - (kT / (b_nm * f_pN))) + z0_nm
    if sigma is not None:
        z_nm = np.ones_like(sigma) * z_nm
    return z_nm

def gFJC(f_pN, k_pN__nm=0.3, L_nm=25.0, b_nm=None, sigma=None, C_nm=28, L_bp=None, p=16):
    if b_nm is None:
        b_nm = 3 * kT / (L_nm * k_pN__nm)
    if L_bp is not None:
        L_nm = L_bp * nm_base

    g_pNnm = -(kT * L_nm / b_nm) * (np.log(f_pN) - np.log(np.sinh((b_nm * f_pN) / (kT))))

    # Remove offset at f = 0
    f_pN = 1e-9
    g_pNnm -= -(kT * L_nm / b_nm) * (np.log(f_pN) - np.log(np.sinh((b_nm * f_pN) / (kT))))

    if sigma is not None:
        # See Meng et al. 2014 Biophysical Journal:
        # https://www.cell.com/cms/10.1016/j.bpj.2014.01.017/attachment/7b4445f3-d296-43b2-8dc2-d98e13f5f00f/mmc1.pdf

        c = kT * (omega0 ** -2) * C_nm
        if p != 0: g_pNnm += L_bp * 0.5 * c * ((sigma + 1)) ** p
        g_pNnm += L_bp * 0.5 * c * (sigma + 1) ** 2

    return g_pNnm / kT

def zWLC(f_pN, L_bp=1, A_nm=50, S_pN=1000, tw_turns=None):
    z_nm = nm_bp * L_bp * (1 - 0.5 * np.sqrt(kT / (f_pN * A_nm)) + f_pN / S_pN)
    if tw_turns is not None:
        z_nm = np.ones_like(tw_turns) * z_nm
    return z_nm

def gWLC(f_pN, L_bp=1, A_nm=50, S_pN=1000, sigma=None, C_nm=100):
    # definition: g = integral(z(f), df)
    g_pNnm = nm_bp * L_bp * (f_pN - np.sqrt(f_pN * kT / A_nm) + f_pN ** 2 / (2 * S_pN))
    if sigma is not None:
        # See Meng et al. 2014 Biophysical Journal:
        # https://www.cell.com/cms/10.1016/j.bpj.2014.01.017/attachment/7b4445f3-d296-43b2-8dc2-d98e13f5f00f/mmc1.pdf
        C_nm = C_nm * (1 - (C_nm / (4 * A_nm)) * (kT / (A_nm * f_pN)))  # force dependence of twist persistence length
        c = kT * (omega0 ** 2) * C_nm
        g_pNnm += L_bp * 0.5 * c * sigma ** 2
    return g_pNnm / kT

def gPlect(sigma, L_bp=1, C_nm=28):
    c = kT * (omega0 ** 2) * C_nm
    g_pNnm = L_bp * 0.5 * c * sigma ** 2
    return g_pNnm / kT

def zDNA(f_pN, L_bp=1, tw_turns=None):
    zds_bp = zWLC(f_pN, L_bp=1)
    zss_bp = zFJC(f_pN / 2, b_nm=1.5, L_bp=1)
    if tw_turns is None:
        # Torsionally relaxed
        gds = gWLC(f_pN, L_bp=1) - f_pN * zds_bp / kT
        gss = 2 * gFJC(f_pN / 2, b_nm=1.5, L_bp=1) - f_pN * zss_bp / kT + Ebp_kT

        c = np.min([1000, L_bp])  # tweak factor: limiting cooperativity, avoiding overflow
        Pds = np.exp(-gds * c) / (np.exp(-gds * c) + np.exp(-gss * c))
        Pss = 1 - Pds
        Z_nm = L_bp * (zds_bp * Pds + zss_bp * Pss)
    else:
        # Torsionally constraint
        if np.isscalar(tw_turns):
            tw_turns = np.ones_like(f_pN) * tw_turns

        # Range to compute
        Nds_range = np.linspace(0, L_bp, 100)
        TW_range = np.linspace(-3, 3, 50)  # change of twist in dsDNA to evaluate each force step

        # Matrices with all distributions of conformations and twist
        Nds = np.outer(Nds_range, np.ones_like(TW_range))
        Nss = L_bp - Nds
        deltaTWds = np.outer(np.ones_like(Nds_range), TW_range)
        TWds_last = tw_turns[0]  # start with all twist in dsDNA

        Z_nm = []
        for f, tw, zds, zss in zip(f_pN, tw_turns, zds_bp, zss_bp):
            TWds = TWds_last + deltaTWds
            TWss = tw - TWds - Nss / 10.4
            sigma_ds = TWds / (omega0 * Nds * nm_bp)
            Gds = gWLC(f, L_bp=Nds, sigma=sigma_ds) - f * zds * Nds / kT
            sigma_ss = (TWss / (omega0 * Nss * nm_bp))
            Gss = 2 * gFJC(f / 2, b_nm=1.5, L_bp=Nss, sigma=sigma_ss) - (f * zss * Nss / kT) + Ebp_kT * Nss
            G = Gds + Gss

            selected = np.isfinite(G)
            G -= np.min(G[selected])  # Avoid large numbers in exponents
            P = np.exp(-G[selected])
            P /= np.sum(P)  # Normalize P
            Z = P * (Nds[selected] * zds + Nss[selected] * zss)
            Z_nm.append(np.sum(Z))
            TWds_last = np.sum(P * TWds[selected])
    return Z_nm

def drift(time_s, dz_dt_nm__s=0, z0_nm=0):
    return (time_s * dz_dt_nm__s) + z0_nm

def get_fiber_states(Ntot=0, Ntetra=0, degeneracy=1):
    states = []
    fiber_degeneracy = []
    d = np.array([degeneracy, 1, 1, 1])
    for n3 in range(0, int(Ntot) + 1):
        for n2 in range(0, int(Ntot) + 1):
            for n1 in range(0, int(Ntot) + 1):
                n0 = Ntot - n1 - n2 - n3
                if (n2 + n3 >= Ntetra) and (n0 >= 0):
                    states.append(np.asarray([n0, n1, n2, n3]))
                    fiber_degeneracy.append(
                        scipy.special.factorial(np.sum(d * states[-1])) / np.prod(
                            scipy.special.factorial(d * states[-1])))
    return np.array(states), np.array(fiber_degeneracy)

def add_steps(force_pN, zfiber_nm, L_bp=3000, L2_bp=79, Ntot=0):
    # Unwrapping:
    pulling = diff(force_pN, 1) > 0
    funwrap_pN = force_pN[np.argmax(diff(zfiber_nm[pulling], 1))]
    unwrapevents = np.sort(np.random.normal(funwrap_pN, 6, Ntot))
    for i, f in enumerate(unwrapevents):
        selected = np.logical_and(force_pN > f, diff(force_pN) >= 0)
        z = zWLC(force_pN, L_bp - (Ntot - 1 - i) * L2_bp)
        zfiber_nm[selected] = z[selected]
    # wrapping:
    wrapevents = np.sort(np.random.normal(4, 2, Ntot))
    for i, f in enumerate(wrapevents):
        selected = np.logical_and(force_pN > f, diff(force_pN) <= 0)
        z = zWLC(force_pN, L_bp - (Ntot - 1 - i) * L2_bp)
        zfiber_nm[selected] = z[selected]
    return zfiber_nm

def get_steps(force_pN, zfiber_nm, L_bp, Ntot=0, k_pN__nm=0.3, NRL_bp=197, L2_bp=79, time_s=None):
    np.seterr(divide='ignore', invalid='ignore')
    var_track = 5 ** 2;
    df = diff(force_pN)
    length = np.arange(L_bp + 500, 0, -2)
    P = np.zeros_like(length)
    i = 0
    for i, l in enumerate(length):
        if l > L_bp - (Ntot * L2_bp):
            zwlc = zWLC(force_pN, l)
            sigma = np.sqrt(kT / (df / diff(zwlc)) + var_track)
            x = 1 - erf(abs((zwlc - zfiber_nm) / sigma))
            P[i] = np.nansum(x)
        else:
            zwlc = zWLC(force_pN, l)
            z_nuc, _ = zHooke(force_pN, k_pN__nm=k_pN__nm, z0_nm=0)
            n_nuc = (l - (Ntot * L2_bp)) / (NRL_bp - L2_bp)
            z_tot = zwlc + n_nuc * z_nuc
            sigma = np.sqrt(kT / (df / diff(z_tot)) + var_track)
            x = 1 - erf(abs((zwlc - zfiber_nm) / sigma))
            P[i] = np.nansum(x)

    peaks, _ = find_peaks(P, width=10)

    plt.plot(length, P)
    plt.show()

    return length[peaks]

def chromatin(force_pN, L_bp=3000, Ntot=0, Ntetra=0,
              L1_bp=90, L2_bp=79, NRL_bp=197,
              g1_kT=19, g2_kT=6.5, g3_kT=100,
              k_pN__nm=0.3, p_nm=50, S_pN=1000,
              degeneracy=1):
    # Create G(z) curves for each nucleosome conformation
    z_nuc = np.empty((4, len(force_pN)))
    g_nuc = np.empty_like(z_nuc)

    Lwrap_bp = [L1_bp, L2_bp, 0]
    Gunwrap_kT = [g1_kT, g1_kT + g2_kT, g1_kT + g2_kT + g3_kT]
    z_nuc[0] = zHooke(force_pN, k_pN__nm=k_pN__nm, z0_nm=0)
    g_nuc[0] = gHooke(force_pN, k_pN__nm=k_pN__nm, z0_nm=0)

    for i, (l, g) in enumerate(zip(Lwrap_bp, Gunwrap_kT)):
        z_nuc[i + 1] = zWLC(force_pN, NRL_bp - l, p_nm, S_pN)
        g_nuc[i + 1] = gWLC(force_pN, NRL_bp - l, p_nm, S_pN)
        g_nuc[i + 1] += g

    # Calculate extension of the DNA handles
    ztether_nm = zWLC(force_pN, L_bp - (Ntot * NRL_bp), p_nm, S_pN)

    # Get all possible distributions of nucleosome conformations, and their combinatoric degeneracy
    s_fiber, d_fiber = get_fiber_states(Ntot=Ntot, Ntetra=Ntetra, degeneracy=degeneracy)
    # For each force point, add the sum of the extensions of each nucleosome, weighted with its probability
    for i, (f, z) in enumerate(zip(force_pN, z_nuc.T)):
        gf_nuc = g_nuc - f * z_nuc / kT
        g = np.min(gf_nuc, axis=1)
        g_fiber = np.sum(s_fiber * g, axis=1)
        g_fiber -= np.min(g_fiber)
        p_fiber = np.exp(-g_fiber)
        z_fiber = np.sum(s_fiber * z, axis=1)
        ztether_nm[i] += np.sum(p_fiber * z_fiber * d_fiber) / np.sum(p_fiber * d_fiber)

    return ztether_nm

def calculate_force(shift_mm, L1_mm=1.4, L2_mm=0.8, f0_pN=0.01):
    # calculate the force from the magnet position.
    force_pN = (85 * (0.7 * np.exp(-shift_mm / L1_mm) + 0.3 * np.exp(-shift_mm / L2_mm)) + f0_pN)
    return force_pN

def bead_offset(force_pN, phi_rad=0, r_um=1.4, C_pNum_rad=100):
    # Calculate z-offset due to side attachment
    # by equating torsional energy to work.
    # For rotational stiffness bead see Klaue2009PRL.

    rho = np.linspace(0, np.pi / 2 - phi_rad, 1000)  # range of longitudes, given attachment point phi
    theta = []  # actual longitude at applied force
    try:
        for f in force_pN:
            err = -f * r_um * (1 - np.sin(rho)) + 0.5 * C_pNum_rad * (np.pi / 2 - (rho - phi_rad)) ** 2
            theta.append(rho[np.argmin(err ** 2)])
    except:
        # single force point
        err = f * r_um * (1 - np.sin(rho)) - 0.5 * C_pNum_rad * (np.pi / 2 - (rho - phi_rad)) ** 2
        theta = rho[np.argmin(err ** 2)]
    dz_um = -r_um * np.sin(theta)
    return dz_um * 1000

def fix(params):
    for p in params:
        params[p].set(vary=False)
    return

def test_simulate():
    #####################################################################
    # Simulate series of F-z curves
    shift_mm = np.arange(10, 0.9, -0.005)
    shift_mm = np.append(shift_mm, np.flip(shift_mm, axis=0))
    force_pN = calculate_force(shift_mm)

    duration_s = 30.0
    time_s = np.arange(0, duration_s, duration_s / len(force_pN))

    # selected = np.logical_and(force_pN < 10, force_pN > 1)
    selected = time_s < duration_s / 2
    selected *= force_pN < 7

    data.write_channel(data=force_pN, channel='Force (pN)', group='processed', label='')
    data.write_channel(data=time_s, channel='Time (s)', group='processed', label='')

    Ntot = 10
    Ntetra = 0
    L_bp = 3000

    for num, g2_kT in enumerate(np.linspace(0, 10, num=3)):
        zfiber_nm = chromatin(force_pN, L_bp=L_bp, Ntot=Ntot, Ntetra=Ntetra, g2_kT=g2_kT, degeneracy=1)

        # Make data more realistic by adding steps and noise
        zfiber_nm = add_steps(force_pN, zfiber_nm, L_bp, 80, Ntot)
        zfiber_nm += np.random.normal(0, 4, len(force_pN))

        if False:
            # fit force extension curve
            model = Model(chromatin) + Model(drift)
            params = model.make_params()
            fix(params)

            params['Ntot'].set(Ntot, vary=False, min=0)
            params['Ntetra'].set(Ntetra, vary=False, min=0)
            params['g1_kT'].set(10, vary=True, min=0, max=25)
            params['g2_kT'].set(g2_kT, vary=True, min=0, max=10)
            params['k_pN__nm'].set(1, vary=True, min=0.1, max=10)

            result = model.fit(zfiber_nm[selected], force_pN=force_pN[selected], time_s=time_s[selected], params=params)
            best_fit = model.eval(result.params, zfiber_nm=zfiber_nm, force_pN=force_pN, time_s=time_s)

            data.write_channel(data=selected, channel='Selected', group='processed', label=str(num))
            data.write_channel(data=zfiber_nm / 1000, channel='Z (um)', group='measured', label=str(num))
            data.write_fit('Fiber', 'Z (um)', best_fit / 1000, result.params, label=str(num))
            R2 = 1 - result.residual.var() / np.var(zfiber_nm[selected])
            data.write_par('R2_fiber', R2, label=str(num))

            g2_fit = data.read_par('g2_kT', label=str(num))
            print(f'{num}) G2 = {g2_kT:0.2} (kT) -> {g2_fit}')
        plt.plot(zfiber_nm / 1000, force_pN)
    tio.format_plot(r'z ($\mu$m)', 'F (pN)', data.plot_title(), aspect=2, scale_page=0.5, xrange=[0, 1.1])
    return

def test_plot():
    #####################################################################
    # Recover trace #2 and display fit parameters and F(z) plot
    label = '2'
    pars = data.parameters(label=label)

    # Add reference curves for single wrapped nucleosomes
    Ntot, _ = data.read_par('Ntot', label=label)
    L_bp, _ = data.read_par('L_bp', label=label)
    L2_bp, _ = data.read_par('L2_bp', label=label)
    force_pN = data.read_channel(channel='Force (pN)', group='processed', label='')
    selected = force_pN < 7
    selected[int(len(selected) / 2):] = 0

    curves = []
    for n in np.arange(0, Ntot + 1):
        curves.append(zWLC(force_pN, L_bp - (n * L2_bp)))

    zfit = data.read_channel(channel='Z (um)', group='fit_Fiber', label=label) * 1000.
    curves.append(zfit)

    z_nm = data.read_channel(channel='Z (um)', group='measured', label=label) * 1000

    ax = tio.format_plot('z (nm)', 'F (pN)', xrange=[0, L_bp / 2.5], title=data.plot_title(), pars=pars
                         , scale_page=1.0, aspect=5 / 8)

    ax.scatter(z_nm, force_pN, color='grey')
    ax.scatter(z_nm[selected], force_pN[selected], color='blue', marker='o')

    curves.reverse()
    linestyle = '-'
    color = 'black'
    for curve in curves:
        ax.plot(curve, force_pN, color=color, linestyle=linestyle, linewidth=1)
        linestyle = ':'
        color = 'grey'

    # plt.savefig(filename, pad_inches=0, transparent=True)
    plt.show()
    return

def plot_fz(data, index):
    t = data.read_df('data/processed', filter='Time')
    for name, z in data.read_df('data/processed', filter='Z').iteritems():
        offset, _ = data.read_par('Z0 (um)', int(name.split()[-1]))
        plt.plot(t, z - offset)
        tio.format_plot('t (s)', 'z (um)', data.plot_title(name))
    return

def _tmp_PlotFzDNA():
    m = np.linspace(10, 0, 1000)
    f = calculate_force(m)
    L_bp = 6000

    zDNA(f_pN=f, L_bp=L_bp, tw_turns=50)

    phi = 0  # degrees
    phi *= np.pi / 180  # rad

    dz = bead_offset(f, phi, C_pNum_rad=100)
    # i = np.argmin((f - 50) ** 2)
    # dz -= dz[i]

    legend = []
    # twist = np.linspace(0, -L_bp / 2, 6)
    # for t in twist:
    #     plt.plot(zDNA(f_pN=f, L_bp=L_bp, tw_turns=t) , f)
    #     legend.append(rf'$\sigma$ = {t / (omega0 * L_bp * nm_bp):.2f}')

    # dz -= np.min(dz)
    # dz -= 400

    plt.plot(zDNA(f_pN=f, L_bp=L_bp) + dz, f, color='blue')
    plt.plot(zWLC(f_pN=f, L_bp=L_bp) + dz, f, color='blue', linestyle='dashed')
    plt.plot(zFJC(f_pN=f / 2, b_nm=1.5, L_nm=L_bp * nm_base) + dz, f, color='blue', linestyle='dashed')
    dz = 0
    plt.plot(zDNA(f_pN=f, L_bp=L_bp) + dz, f, color='grey')
    plt.plot(zWLC(f_pN=f, L_bp=L_bp) + dz, f, color='grey', linestyle='dashed')
    plt.plot(zFJC(f_pN=f / 2, b_nm=1.5, L_nm=L_bp * nm_base) + dz, f, color='grey', linestyle='dashed')

    tio.format_plot('z (nm)', 'F (pN)', yrange=[0, 79], xrange=[0, L_bp / 1.5], ref='a)', legend=legend, aspect=2 / 3,
                    scale_page=1)
    print('done')

def _tmp_PlotGT():
    f = 100
    L_bp = 1000
    tw = np.linspace(-2 * L_bp, L_bp, 1000)
    sigma = tw / (omega0 * L_bp * nm_bp)

    Ztwisted = zWLC(f_pN=f, L_bp=L_bp, tw_turns=tw)
    Gtwisted = gWLC(f, L_bp=L_bp, sigma=sigma) - f * Ztwisted / kT

    Zmelted = zFJC(f / 2, b_nm=1.5, L_nm=L_bp * nm_base, sigma=sigma)
    Gmelted2 = 2 * gFJC(f / 2, b_nm=1.5, sigma=sigma, L_bp=L_bp, p=0) - f * Zmelted / kT + L_bp * Ebp_kT
    Gmelted = 2 * gFJC(f / 2, b_nm=1.5, sigma=sigma, L_bp=L_bp) - f * Zmelted / kT + L_bp * Ebp_kT

    Gplect = gPlect(sigma, L_bp=L_bp)

    plt.plot(sigma, Gtwisted / L_bp)
    plt.plot(sigma, Gplect / L_bp, color='Green')
    plt.plot(sigma, Gmelted / L_bp, color='Red')
    plt.plot(sigma, Gmelted2 / L_bp, color='Red', linestyle='dashed')
    plt.plot(sigma, Gplect * 0, color='Black', linewidth=1)
    legend = ['twisted', 'plectonemic', 'melted']
    tio.format_plot(r'$\sigma$ (-)', r'g ($k _B T$)', xrange=[-2.5, 1.5], aspect=2 / 6, yrange=[-1.5, 10.5],
                    scale_page=1,
                    ref='a)', legend=legend)

    return

if __name__ == "__main__":
    #   Intended as examples. Make your own script and import this module to your script.
    #   You can copy the code below as a start of your own script

    _tmp_PlotFzDNA()
    # _tmp_PlotGT()

    # test_simulate()

    filenames = [rf'C:\Users\noort\data\ForceTDMS\data_026.tdms']
    filenames = [r'C:\Users\noort\data\ForceTDMS\data_008.dat']
    filenames = [r'C:\Users\noort\LTS\werk\Software\Python\testdata\ForceTDMS\data_021.h5']

    # for filename in filenames:
    #     TDMS_to_h5(filename)
    # dat_to_h5(filename)

    # with tio.Traces(filename) as data:
    #     plot_fz(data, 4)


import time

from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.common.by import By

from utils import get_element, input_text

des_cap = {
"platformName" : "android" ,   #表示的是android  或者ios
"platformVersion" : "5.1.1",   #表示的是平台系统的版本号
"deviceName" : "****",    #表示的是设备的ID名称（如果只有一个设备可以用****来代替）
"appPackage" : "com.lufax.android",   #表示app的包名
"appActivity" :  ".activity.HomeActivity",      #表示的是app的界面名
"resetKeyboard": True,        # 重置设备的输入键盘
"unicodeKeyboard": True,        # 采用unicode编码输入
"noReset": True
####"".module_main.activity.MainActivity""
}  #定义字典参数

driver = webdriver.Remote("http://localhost:4723/wd/hub", des_cap)

me_btn = By.XPATH, "//*[@text='我的']"
get_element(driver, me_btn).click()

TouchAction(driver).press(x=260, y=720).wait(500).move_to(x=540, y=720)\
    .wait(500).move_to(x=820,y=720).wait(500).move_to(x=540, y=1000).wait(500).move_to(x=260, y=1270)\
    .wait(500).move_to(x=540, y=1270).wait(500).move_to(x=820, y=1270).release().perform()
driver.drag_and_drop()
time.sleep(5)
driver.quit()

09、UI自动化测试及黑马头条项目实战/day09/03代码/陆金所手势操作.py


from threading import Thread

from django.core.mail import EmailMessage
from django.template.loader import render_to_string

def send_template_mail(to, subject, template, context, fail_silently=True,
                       asynchronously=True, from_email=None):
    html = render_to_string(template, context)
    e_message = EmailMessage(
        subject=subject,
        body=html,
        from_email=from_email,
        to=to,
    )
    e_message.content_subtype = 'html'
    if not asynchronously:
        e_message.send(fail_silently=fail_silently)
    else:
        # we have toe use Celery here
        Thread(
            target=e_message.send,
            kwargs={'fail_silently': fail_silently}
        ).start()