import os
import pickle
import random

import cv2
import numpy as np
from numpy import cos, pi, sin
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from util.fast_poisson import poisson_reconstruct

from scipy.interpolate import griddata
from util import helper

def dilate(img, ksize=5):
    kernel = np.ones((ksize, ksize), np.uint8)
    return cv2.dilate(img, kernel, iterations=1)

def erode(img, ksize=5):
    kernel = np.ones((ksize, ksize), np.uint8)
    return cv2.erode(img, kernel, iterations=1)

def interpolate_grad(img, mask):
    # mask = (soft_mask > 0.5).astype(np.uint8) * 255
    # cv2.imshow("mask_hard", mask)
    # pixel around markers
    mask_around = (dilate(mask, ksize=3) > 0) & (mask != 1)
    # mask_around = mask == 0
    mask_around = mask_around.astype(np.uint8)
    cv2.imshow("mask_around", mask_around * 255)

    x, y = np.arange(img.shape[0]), np.arange(img.shape[1])
    yy, xx = np.meshgrid(y, x)

    # mask_zero = mask == 0
    mask_zero = mask_around == 1
    mask_x = xx[mask_zero]
    mask_y = yy[mask_zero]
    points = np.vstack([mask_x, mask_y]).T
    values = img[mask_x, mask_y]
    markers_points = np.vstack([xx[mask != 0], yy[mask != 0]]).T
    method = "nearest"
    # method = "linear"
    # method = "cubic"
    x_interp = griddata(points, values, markers_points, method=method)
    x_interp[x_interp != x_interp] = 0.0
    ret = img.copy()
    ret[mask != 0] = x_interp
    return ret

def demark(diff, gx, gy):
    cv2.imshow("diff_before", diff / 255.0)

    mask = helper.find_marker(diff)
    cv2.imshow("mask", mask * 255.0)

    # gx[mask == 1] = 0
    # gy[mask == 1] = 0
    gx = interpolate_grad(gx, mask)
    gy = interpolate_grad(gy, mask)

    return gx, gy

class Class_3D:
    def __init__(self, model_fn="LUT.pkl", features_type="RGBXY"):
        self.features_type = features_type
        self.output_dir = "output/"
        self.load_lookup_table(model_fn)

    def load_lookup_table(self, model_fn):
        self.model = pickle.load(open(model_fn, "rb"))

    def infer(
        self,
        img,
        resolution=(0, 0),
        save_id=None,
        refine_gxgy=None,
        demark=None,
        display=True,
        reverse_RB=False,
    ):
        if reverse_RB:
            img = img[:, :, ::-1]
        if resolution != (0, 0):
            img = cv2.resize(img, resolution)

        if "G" not in self.features_type:
            img[:, :, 1] = 127.5
        if "R" not in self.features_type:
            img[:, :, 2] = 127.5
        if "B" not in self.features_type:
            img[:, :, 0] = 127.5

        W, H = img.shape[0], img.shape[1]

        X = np.reshape(img, [W * H, 3]) / 255 - 0.5

        x = np.arange(W)
        y = np.arange(H)
        yy, xx = np.meshgrid(y, x)
        xx, yy = np.reshape(xx, [W * H, 1]), np.reshape(yy, [W * H, 1])
        xx, yy = xx / W - 0.5, yy / H - 0.5

        X_features = [X, xx, yy]
        X = np.hstack(X_features)

        Y = self.model.predict(X)

        gx = np.reshape(Y[:, 0], [W, H])
        gy = np.reshape(Y[:, 1], [W, H])

        if demark is not None:
            gx, gy = demark(img, gx, gy)

        gx_raw, gy_raw = gx.copy(), gy.copy()

        if refine_gxgy is not None:
            print("before: gx.max() gy.max()", gx.max(), gy.max())
            gy_raw *= 0.0
            gx, gy = refine_gxgy(gx, gy)
            print("gx.max() gy.max()", gx.max(), gy.max())

        gx_img = (np.clip(gx / 2 + 0.5, 0, 1) * 255).astype(np.uint8)
        gy_img = (np.clip(gy / 2 + 0.5, 0, 1) * 255).astype(np.uint8)

        zeros = np.zeros_like(gx)
        depth = poisson_reconstruct(gx, gy, zeros)
        depth = cv2.resize(depth, (H, W))
        depth_single = poisson_reconstruct(gx_raw, gy_raw, zeros)
        depth_single = cv2.resize(depth_single, (H, W))
        print(depth.max())
        # depth_img = (np.clip(depth*255/15-80, 0, 255)).astype(np.uint8)
        scale = W / 200
        # depth_img = (np.clip(depth * 255 / 12 / scale - 50, 0, 255)).astype(np.uint8)
        # depth_single_img = (
        #     np.clip(depth_single * 255 / 12 / scale - 50, 0, 255)
        # ).astype(np.uint8)

        depth_img = (np.clip(depth * 255 / 24 / scale + 63, 0, 255)).astype(np.uint8)
        depth_single_img = (
            np.clip(depth_single * 255 / 24 / scale + 63, 0, 255)
        ).astype(np.uint8)

        depth_img_heat = cv2.applyColorMap(depth_img, cv2.COLORMAP_JET)

        if display:
            pass
            # cv2.imshow(
            #     "img", np.clip((img - 127.5) * 2 + 127.5, 0, 255).astype(np.uint8)
            # )

            cv2.imshow("gx", gx_img)
            cv2.imshow("gy", gy_img)

            # cv2.imshow("depth_calibrated_heat", depth_img_heat)
            # cv2.imshow("depth_single_img_gray", depth_single_img)
            # cv2.imshow("depth_calibrated_gray", depth_img)

        # depth = img2depth(img)
        # depth_img = (np.clip(depth*255*2.5, 0, 255)).astype(np.uint8)
        # # depth_img = cv2.applyColorMap(depth_img, cv2.COLORMAP_JET)

        # img[:, :, 1] = img[:, :, 0]
        # img[:, :, 2] = img[:, :, 0]

        # cv2.imshow('depth_est', depth_img)
        if save_id is not None:
            self.save_img(
                raw=img,
                gx_img=gx_img,
                gy_img=gy_img,
                z_gray=depth_img,
                z_heat=depth_img_heat,
                save_id=save_id,
            )
        return depth, gx, gy

    def save_img(
        self,
        raw=None,
        gx_img=None,
        gy_img=None,
        z_gray=None,
        z_heat=None,
        combine=True,
        save_id=None,
    ):
        if raw is not None:
            output_fn = os.path.join(self.output_dir, save_id + "_depth_calibrated.jpg")
            cv2.imwrite(output_fn, raw)

        if gx_img is not None:
            output_fn = os.path.join(self.output_dir, save_id + "_gx.jpg")
            cv2.imwrite(output_fn, gx_img)

        if gy_img is not None:
            output_fn = os.path.join(self.output_dir, save_id + "_gy.jpg")
            cv2.imwrite(output_fn, gy_img)

        if z_gray is not None:
            output_fn = os.path.join(self.output_dir, save_id + "_depth_gray.jpg")
            cv2.imwrite(output_fn, z_gray)

        if z_heat is not None:
            output_fn = os.path.join(self.output_dir, save_id + "_depth_heat.jpg")
            cv2.imwrite(output_fn, z_heat)

        if combine is True:
            # image sizes
            W, H = raw.shape[0], raw.shape[1]
            interval = 50

            # create canvas
            combine_img = (
                np.ones([W * 2 + interval * 2, H * 3 + interval * 2, 3], dtype=np.uint8)
                * 255
            )

            # image placement
            xy_list = [
                (0, 0),
                (W + interval, H + interval),
                (0, H + interval),
                (0, (H + interval) * 2),
                (W + interval, (H + interval) * 2),
            ]
            image_list = [raw, gx_img, gy_img, z_gray, z_heat]

            # draw to canvas
            for i in range(len(image_list)):
                image = image_list[i]
                x, y = xy_list[i]

                # gray to RGB
                if len(image.shape) == 2:
                    image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)

                print("image.shape", image.shape)
                combine_img[x : x + W, y : y + H] = image

            output_fn = os.path.join(self.output_dir, save_id + "_combine.jpg")
            cv2.imwrite(output_fn, combine_img)

if __name__ == "__main__":
    c3d = Class_3D()

    img = cv2.imread("cali_data/20200930_164410.jpg")
    c3d.infer(img)
    cv2.waitKey(0)


import webapp2
import MySQLdb
import json

from contextlib import closing

from lib.hitchcfg import CONFIG
from lib.util import connectdb, errorMessage, writeOut
from lib.util import checkCntType, checkJsonStruct, checkLogin, timeBorders
from lib.geo import *
from lib.sql import SQLqueries

class GetSpotsHandler(webapp2.RequestHandler):
	def get(self):
		writeOut(self, 405, "BAD_REQ")

	def post(self):
		if not checkCntType(self):
			return

		try:
			jsonData = json.loads(self.request.body)
		except ValueError:
			writeOut(self, 400, "BAD_JSON")
			return

		if not checkValues(self, jsonData):
			return

		if hasDestination(jsonData) and not isValidWithDestination(self, jsonData):
			return

		with closing(connectdb()) as db:
			if not checkLogin(self, db, jsonData['userid'], jsonData['hash']):
				return

			with closing(db.cursor()) as cursor:
				try:
					uid = jsonData['userid']
					lat = jsonData['pos']['lat']
					lng = jsonData['pos']['lng']
					radius = jsonData['radius']

					borders = geocalc(lat, lng, radius)
					data = []
					queryType = ""

					if hasDestination(jsonData) and isValidWithDestination(self, jsonData):

						dest_lat = jsonData['dest']['lat']
						dest_lng = jsonData['dest']['lng']
						hitchtime = jsonData['hitchtime']

						dist = geodistance(jsonData['pos'], jsonData['dest'])
						dest_radius = clamp(dist/5.0, 1, 50)
						dest_borders = geocalc(dest_lat, dest_lng, dest_radius)
						tb = timeBorders(hitchtime, CONFIG['time_interval'])
						vars = borders2tuple(dest_borders) + tb + tb + (hitchtime,) + borders2tuple(borders)

						cursor.execute(SQLqueries.select_spots_relevant_time, vars)

						for row in cursor.fetchall():
							data.append({
								'spotid': row[0],
								'pos': {
									'lat': round(row[1], 6),
									'lng': round(row[2], 6)
								},
								'nrides': row[3],
								'nmatching': row[4],
								'best_time': round(float(row[5]), 2),
								'timefactor': round(float(row[6]), 3),
								'score': round(float(row[7]), 3)
							})

						queryType = "complex"
					else:
						cursor.execute(SQLqueries.select_spots_all,
							borders2tuple(borders))

						for row in cursor.fetchall():
							data.append({
								'spotid': row[0],
								'pos': {
									'lat': round(row[1], 6),
									'lng': round(row[2], 6)
								},
								'nrides': row[3],
								'nmatching': 0,
								'best_time': 0,
								'timefactor': 0,
								'score': 0
							})

						queryType = "simple"

					returnJson = errorMessage(200, "OK")
					returnJson['spots'] = data
					returnJson['query'] = queryType
					self.response.write(json.dumps(returnJson))

				except MySQLdb.Error as e:
					writeOut(self, 501, "MYSQL_ERROR")

def clamp(value, min, max):
	if value < min:
		return min
	elif value > max:
		return max
	else:
		return value

def checkValues(self, jsonData):
	expected = {
		'userid': 'int',
		'hash': 'string',
		'pos': {
			'lat': 'float',
			'lng': 'float'
		},
		'radius': 'float'
	}

	if not checkJsonStruct(expected, jsonData):
		writeOut(self, 400, "INVAL_STRUCT")
		return False

	if jsonData['userid'] < 1:
		writeOut(self, 400, "INVAL_UID")
		return False

	if not len(jsonData['hash'])==32:
		writeOut(self, 400, "INVAL_HASH")
		return False

	if jsonData['pos']['lat'] < -90 or jsonData['pos']['lat'] > 90:
		writeOut(self, 400, "INVAL_LAT:pos")
		return False

	if jsonData['pos']['lng'] < -180 or jsonData['pos']['lng'] > 180:
		writeOut(self, 400, "INVAL_LNG:pos")
		return False

	if jsonData['radius'] <= 0 or jsonData['radius'] > 25:
		writeOut(self, 400, "INVAL_RAD")
		return False

	return True

def hasDestination(jsonData):
	expected = {
		'dest': {
			'lat': 'float',
			'lng': 'float'
		},
		'hitchtime': 'int'
	}

	return checkJsonStruct(expected, jsonData)

def isValidWithDestination(self, jsonData):
	if jsonData['dest']['lat'] < -90 or jsonData['dest']['lat'] > 90:
		writeOut(self, 400, "INVAL_LAT:dest")
		return False

	if jsonData['dest']['lng'] < -180 or jsonData['dest']['lng'] > 180:
		writeOut(self, 400, "INVAL_LNG:dest")
		return False

	if jsonData['hitchtime'] < 0 or jsonData['hitchtime'] >= CONFIG['max_time']:
		writeOut(self, 400, "INVAL_TIME")
		return False

	return True


from eelbrain import *

class WordExperiment(MneExperiment):

    path_version = 1  # path scheme for starting a new experiment

    variables = {'stimulus': {10: 'fixation', (1, 2, 3, 4): 'word'},
                 'word_type': {(1, 2): 'noun', (3, 4): 'verb', 10: 'none'},
                 'frequency': {(1, 3): 'low', (2, 4): 'high', 10: 'none'}}

    defaults = {'experiment': 'words'}


# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /Users/philewels/GitHub/MultiQC/multiqc/modules/homer/homer.py
# Compiled at: 2019-11-13 05:22:42
# Size of source mod 2**32: 2235 bytes
""" MultiQC module to parse output from HOMER """
from __future__ import print_function
from collections import OrderedDict
import logging
from multiqc.modules.base_module import BaseMultiqcModule
from .findpeaks import FindPeaksReportMixin
from .tagdirectory import TagDirReportMixin
log = logging.getLogger(__name__)

class MultiqcModule(BaseMultiqcModule, FindPeaksReportMixin, TagDirReportMixin):
    __doc__ = ' HOMER has a number of different commands and outputs.\n    This MultiQC module supports some but not all. The code for\n    each script is split into its own file and adds a section to\n    the module output if logs are found. '

    def __init__(self):
        super(MultiqcModule, self).__init__(name='HOMER', anchor='homer', href='http://homer.ucsd.edu/homer/',
          info='is a suite of tools for Motif Discovery and next-gen sequencing analysis.')
        self.general_stats_headers = OrderedDict()
        self.general_stats_data = dict()
        n = dict()
        self.tagdir_data = {'GCcontent':{},  'restriction':{},  'restriction_norm':{},  'length':{},  'taginfo_total':{},  'taginfo_total_norm':{},  'taginfo_uniq':{},  'taginfo_uniq_norm':{},  'FreqDistribution':{},  'header':{},  'interChr':{}}
        n['findpeaks'] = self.parse_homer_findpeaks()
        if n['findpeaks'] > 0:
            log.info('Found {} findPeaks reports'.format(n['findpeaks']))
        n['Homer_tagDir'] = self.homer_tagdirectory()
        if n['Homer_tagDir'] > 0:
            log.info('Found {} reports'.format(n['Homer_tagDir']))
        if sum(n.values()) == 0:
            raise UserWarning
        self.general_stats_addcols(self.general_stats_data, self.general_stats_headers)


""".. Ignore pydocstyle D400.

================
Elastic Viewsets
================

.. autoclass:: resolwe.elastic.viewsets.ElasticSearchMixin
    :members:

"""
from __future__ import absolute_import, division, print_function, unicode_literals

from elasticsearch_dsl.query import Q

from django.conf import settings
from django.contrib.auth import get_user_model
from django.db.models import Case, IntegerField, Value, When

from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from .pagination import LimitOffsetPostPagination

__all__ = (
    'ElasticSearchMixin',
    'PaginationMixin',
    'ElasticSearchBaseViewSet',
)

ELASTICSEARCH_SIZE = 10000  # maximum number of results returned by ElasticSearch

class TooManyResults(APIException):
    """Exception when elastic query returns more than ``ELASTICSEARCH_SIZE`` results."""

    status_code = 400
    default_detail = 'Query returned too many results. Please, add more filters or use pagination.'
    default_code = 'bad_request'

class ElasticSearchMixin(object):
    """Mixin to use Django REST Framework with ElasticSearch based querysets.

    This mixin adds following methods:
      * :func:`~ElasticSearchMixin.order_search`
      * :func:`~ElasticSearchMixin.filter_search`
      * :func:`~ElasticSearchMixin.filter_permissions`

    """

    filtering_fields = []
    ordering_fields = []
    ordering_map = {}
    ordering = None

    def get_query_param(self, key, default=None):
        """Get query parameter uniformly for GET and POST requests."""
        value = self.request.query_params.get(key, None)
        if value is None:
            value = self.request.data.get(key, None)
        if value is None:
            value = default
        return value

    def order_search(self, search):
        """Order given search by the ordering parameter given in request.

        :param search: ElasticSearch query object

        """
        ordering = self.get_query_param('ordering', self.ordering)
        if not ordering:
            return search

        ordering_field = ordering.lstrip('-')
        if ordering_field not in self.ordering_fields:
            raise KeyError('Ordering by `{}` is not supported.'.format(ordering_field))

        ordering_field = self.ordering_map.get(ordering_field, ordering_field)
        direction = '-' if ordering[0] == '-' else ''

        return search.sort('{}{}'.format(direction, ordering_field))

    def filter_search(self, search):
        """Filter given search by the filter parameter given in request.

        :param search: ElasticSearch query object

        """
        for field in self.filtering_fields:
            value = self.get_query_param(field, None)
            if value:
                custom_filter = getattr(self, 'custom_filter_{}'.format(field), None)
                if custom_filter is not None:
                    search = custom_filter(value, search)
                elif isinstance(value, list):
                    # Default is 'should' between matches. If you need anything else,
                    # a custom filter for this field should be implemented.
                    filters = [Q('match', **{field: item}) for item in value]
                    search = search.query('bool', should=filters)
                else:
                    search = search.query('match', **{field: value})

        return search

    def filter_permissions(self, search):
        """Filter given query based on permissions of the user in the request.

        :param search: ElasticSearch query object

        """
        user = self.request.user
        if user.is_superuser:
            return search
        if user.is_anonymous:
            user_model = get_user_model()
            user = user_model.objects.get(**{user_model.USERNAME_FIELD: settings.ANONYMOUS_USER_NAME})

        filters = [Q('match', users_with_permissions=user.pk)]
        filters.extend([
            Q('match', groups_with_permissions=group.pk) for group in user.groups.all()
        ])
        filters.append(Q('match', public_permission=True))

        # `minimum_should_match` is set to 1 by default
        return search.query('bool', should=filters)

class PaginationMixin(object):
    """Mixin for making paginated response in case pagination parameters are provided."""

    def paginate_response(self, queryset, serializers_kwargs={}):
        """Optionally return paginated response.

        If pagination parameters are provided in the request, then paginated response
        is returned, otherwise response is not paginated.

        """
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True, **serializers_kwargs)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True, **serializers_kwargs)
        return Response(serializer.data)

class ElasticSearchBaseViewSet(PaginationMixin, ElasticSearchMixin, GenericViewSet):
    """Base ViewSet for ElasticSearch based views.

    This ViewSet creates search based on ``document_class`` parameter, specified
    in subclass and:

      * filter it by query parameters
      * apply ordering
      * filter permissions
      * apply pagination

    .. IMPORTANT::

        Both ``POST`` and ``GET`` requests are supported.
    """

    document_class = None

    pagination_class = LimitOffsetPostPagination

    def custom_filter(self, search):
        """Perform custom search filtering.

        This method is intended to be overriden in subclasses.
        """
        return search

    def search(self):
        """Handle the search request."""
        search = self.document_class().search()  # pylint: disable=not-callable

        search = self.custom_filter(search)

        search = self.filter_search(search)
        search = self.order_search(search)
        search = self.filter_permissions(search)

        if search.count() > ELASTICSEARCH_SIZE:
            limit = self.paginator.get_limit(self.request)

            if not limit or limit > ELASTICSEARCH_SIZE:
                raise TooManyResults()

        search = search.extra(size=ELASTICSEARCH_SIZE)
        return search

    def list_with_post(self, request):
        """Endpoint handler."""
        search = self.search()
        return self.paginate_response(search)

    def list(self, request):
        """Endpoint handler."""
        return self.list_with_post(request)

class ElasticSearchCombinedViewSet(ElasticSearchBaseViewSet):
    """ViewSet, which combines database and ES queries.

    To use this viewset, you should mixin the viewset that handles
    the database part, for example:

    .. code:: python

        class MyCombinedViewSet(ElasticSearchCombinedViewSet, MyViewSet):
            # ...

    Whenever any of the filters declared in ``filtering_fields`` are
    used, the search part is used. Otherwise, only the database part is
    used. In both cases, search results are only used to get the primary
    keys to filter the database query.

    In order for this to work, your index must store the primary key
    in a field (by default it should be called ``id``). You can change
    this by setting ``primary_key_field``.
    """

    primary_key_field = 'id'

    def is_search_request(self):
        """Check if current request is a search request."""
        return any([
            self.get_query_param(field, None) is not None
            for field in self.filtering_fields
        ])

    def list_with_post(self, request):
        """Endpoint handler."""
        if self.is_search_request():
            search = self.search()

            page = self.paginate_queryset(search)
            if page is None:
                items = search
            else:
                items = page

            try:
                primary_keys = []
                order_map_cases = []
                for order, item in enumerate(items):
                    pk = item[self.primary_key_field]
                    primary_keys.append(pk)
                    order_map_cases.append(When(pk=pk, then=Value(order)))

                queryset = self.get_queryset().filter(
                    pk__in=primary_keys
                ).order_by(
                    Case(*order_map_cases, output_field=IntegerField()).asc()
                )
            except KeyError:
                raise KeyError("Combined viewset requires that your index contains a field with "
                               "the primary key. By default this field is called 'id', but you "
                               "can change it by setting primary_key_field.")

            # Pagination must be handled differently.
            serializer = self.get_serializer(queryset, many=True)
            if page is not None:
                return self.get_paginated_response(serializer.data)

            return Response(serializer.data)
        else:
            queryset = self.filter_queryset(self.get_queryset())
            return self.paginate_response(queryset)

    def list(self, request):
        """Endpoint handler."""
        return self.list_with_post(request)


# Author: Xinshuo Weng
# email: xinshuo.weng@gmail.com

# this file is for the adding the path for python library
import os, sys

def add_path(path):
    if path not in sys.path:
        sys.path.insert(0, path)

this_dir = os.path.dirname(os.path.abspath(__file__))

test_path = os.path.join(this_dir, '../')
add_path(test_path)


#!/usr/bin/env python
from pathlib import Path

from gin.errors import ManifestNotFound, ParseError
from gin.parser import Parser
from gin.project import Project

class Gin:
    _manifest: Path
    _project: Project

    def __init__(self):
        pass

    def _parse(self):
        try:
            parser = Parser(self._manifest)
            self._project = parser.get_project()
        except ParseError:
            print("Failed to parse the manifest")

    def manifest(self, manifest):
        path = Path(manifest)
        if not path.exists():
            raise ManifestNotFound(f"Manifest {manifest} not found")
        self._manifest = Path(manifest)
        self._parse()


from fms.models.project import SkillTag, MilestoneProgress, ProjectCategory, ProjectType, ProjectRole, Project, WorkspaceUserLog, Message
from fms.models.core import MenuItem
from django.utils import timezone
from datetime import datetime, date
from fms.service import projects_service
from django.contrib.auth.models import User

def init(company):
	if SkillTag.objects.filter(company=company).count() == 0:
		skilltag = SkillTag.objects.create(company=company, tagcode='DEFAULT', tagdesc='Default skill tag')
		skilltag.save()

	if MilestoneProgress.objects.all().count() == 0:
		progress = MilestoneProgress.objects.create(code='NS', description='Not started')
		progress.save()
		progress = MilestoneProgress.objects.create(code='IP', description='In progress')
		progress.save()
		progress = MilestoneProgress.objects.create(code='CP', description='Completed')
		progress.save()
		progress = MilestoneProgress.objects.create(code='RJ', description='Rejected')
		progress.save()

	if MenuItem.objects.all().count() == 0:
		MenuItem.objects.all().delete()
		menu = MenuItem.objects.create(menuItem='Dashboard', menuCss='fa-dashboard', menuLink='/fms/', menuOrder=0)
		menu.save()
		menu = MenuItem.objects.create(menuItem='Workspace', menuCss='fa-object-group', menuLink='/fms/workspaces/', menuOrder=3)
		menu.save()
		menu = MenuItem.objects.create(menuItem='Project Category', menuCss='fa-wrench', menuLink='/fms/category/', menuOrder=4)
		menu.save()
		menu = MenuItem.objects.create(menuItem='Project Type', menuCss='fa-wrench', menuLink='/fms/projecttype/', menuOrder=6)
		menu.save()
		menu = MenuItem.objects.create(menuItem='Skill Tags', menuCss='fa-wrench', menuLink='/fms/skilltag/', menuOrder=8)
		menu.save()
		menu = MenuItem.objects.create(menuItem='Maven Prophet', menuCss='fa-bar-chart-o', menuLink='/fms/prophet/', menuOrder=9)
		menu.save()

	if ProjectCategory.objects.filter(company=company).count() == 0:
		category = ProjectCategory.objects.create(company=company, category_code='DEFAULT', category_desc='Default project category')
		category.save()

	if ProjectType.objects.filter(company=company).count() == 0:
		project_type = ProjectType.objects.create(company=company, typecode='DEFAULT', typedesc='Default project type', category=category)
		project_type.save()

	if ProjectRole.objects.all().count() == 0:
		ProjectRole.objects.all().delete()
		role = ProjectRole.objects.create(code='PM', desc='Project Manager')
		role.save()
		role = ProjectRole.objects.create(code='CO', desc='Collaborator')
		role.save()
		role = ProjectRole.objects.create(code='OB', desc='Observer')
		role.save()

def get_menu():
	items = []
	links = []
	css = []

	itemlist = MenuItem.objects.filter(is_visible=True).order_by('menuOrder')
	for item in itemlist:
		items.append(item.menuItem)
		links.append(item.menuLink)
		css.append(item.menuCss)

	return zip(items, links, css)

def get_meta_data(request):
	projects = projects_service.get_involved_project_list(user=request.user)
	notifications = []

	for project in projects:
		count = 0
		last_seen = None
		messages = Message.objects.filter(project=project)
		workspaceuserlog = WorkspaceUserLog.objects.filter(project=project, user=request.user)

		if workspaceuserlog is not None and len(workspaceuserlog) == 1:
			last_seen = workspaceuserlog[0].last_seen

		if messages is not None and len(messages) > 0:
			for message in messages:
				if last_seen is None:
					last_seen = timezone.make_aware(datetime.combine(date(2000, 1, 1), datetime.min.time()))

				if last_seen < message.created_date:
					count += 1

			if count > 0:
				notification = {
					'project_name' : project.title,
					'count' : count,
					'project_id' : project.id
				}

				notifications.append(notification)

	is_disabled = False
	try:
		is_disabled = MenuItem.objects.get(menuLink=request.get_full_path()).is_disabled
	except Exception as e:
		print('MenuItem for ', request.get_full_path(), ' does not exist')
		print(str(e))

	context = {
		'menus' : get_menu(),
		'current_user' : request.user.username,
		'notifications' : notifications,
		'notifications_count' : len(notifications),
		'is_disabled' : is_disabled
	}

	return context

def is_fms_user(username):
	users = User.objects.filter(username=username).count()
	return (users > 0)


#!/usr/bin/env python

"""
Installs the flowstats module for Kaluza data analysis
"""

# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

# Get the long description from the README file
with open(path.join(here, 'README.txt'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='sample',
    version='0.0.1',
    description='Flowstats: a module to analyze Kaluza flow cytometry data.',
    long_description=long_description,
    url='https://github.com/pypa/sampleproject',
    author='katdev',
    author_email='katdev@users.noreply.github.com',
    license='Apache',

    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: End users/Desktop',
        'Topic :: Software Development :: Build Tools',
        'License :: OSI Approved :: Apache',
        'Programming Language :: Python :: 3.5',
    ],
    scripts=['bin/create_database.py', 'bin/flowstats_gui.py'],
    keywords=['Kaluza', 'flow cytometry'],
    packages=find_packages(exclude=['contrib', 'docs', 'tests']),
    install_requires=['sqlalchemy'],
)


from collections import deque

def print_orders(tasks, prerequisites):
    sorted_order = []

    if tasks <= 0:
        return False

    in_degree = {i: 0 for i in range(tasks)}
    graph = {i: [] for i in range(tasks)}

    for prerequisite in prerequisites:
        parent, child = prerequisite[0], prerequisite[1]
        graph[parent].append(child)
        in_degree[child] += 1

    sources = deque()
    for key in in_degree:
        if in_degree[key] == 0:
            sources.append(key)

    print_all_top_sorts(graph, in_degree, sources, sorted_order)

def print_all_top_sorts(graph, in_degree, sources, sorted_order):
    if sources:
        for vertex in sources:
            sorted_order.append(vertex)
            sources_for_next_call = deque(sources)

            sources_for_next_call.remove(vertex)

            for child in graph[vertex]:
                in_degree[child] -= 1
                if in_degree[child] == 0:
                    sources_for_next_call.append(child)

            print_all_top_sorts(graph, in_degree, sources_for_next_call, sorted_order)

            sorted_order.remove(vertex)
            for child in graph[vertex]:
                in_degree[child] += 1

    if len(sorted_order) == len(in_degree):
        print(sorted_order)

print("Task Orders: ")
print_orders(3, [[0, 1], [1, 2]])

print("Task Orders: ")
print_orders(4, [[3, 2], [3, 0], [2, 0], [2, 1]])

print("Task Orders: ")
print_orders(6, [[2, 5], [0, 5], [0, 4], [1, 4], [3, 2], [1, 3]])


import confvar
import argparser

# Needs to be above local imports
# If the stealth flag is set then overwrite conf
args = argparser.parse()
if args.l:
    confvar.locale(args.l)
if args.t:
    confvar.theme(args.t)
if args.s:
    confvar.stealth()
else:
    confvar.stealth(False)
confvar.confb()

import adblock
import extension
import bookmark
from browser import *
import threading
import sys
import os

if args.URL:
    open_url_arg(args.URL)

def runbrowser():
    app = QApplication(sys.argv)
    app.setApplicationName(confvar.BROWSER_WINDOW_TITLE)

    translator = QTranslator()
    if not confvar.BROWSER_LOCALE:
        confvar.BROWSER_LOCALE = QLocale.system().name()
    print('Localization loaded:', translator.load(confvar.BROWSER_LOCALE + '.qm', '../localization'), confvar.BROWSER_LOCALE)
    app.installTranslator(translator)

    window = MainWindow()
    window.setWindowTitle(confvar.BROWSER_WINDOW_TITLE)

    if os.path.isfile("./img/icons/" + confvar.BROWSER_STYLESHEET + "-lynx_logo.ico"):
        app.setWindowIcon(QIcon(os.path.abspath("./img/icons/" + confvar.BROWSER_STYLESHEET + "-lynx_logo.ico")))
    else:
        app.setWindowIcon(QIcon(os.path.abspath('./img/icons/lynx_logo.ico')))

    app.setStyleSheet(open(BASE_PATH + "themes/" + confvar.BROWSER_STYLESHEET + ".qss").read())
    app.exec_()

if __name__ == "__main__":
    adblock.readBlocker()
    extension.readExtensions()
    bookmark.readBookmarks()
    runbrowser()


from __future__ import division
from __future__ import print_function

import sys
import argparse
import cv2
import editdistance
from DataLoader import DataLoader, Batch
from Model import Model, DecoderType
from SamplePreprocessor import preprocess
import os

class FilePaths:
	"filenames and paths to data"
	fnCharList = '../model/charList.txt'
	fnAccuracy = '../model/accuracy.txt'
	fnTrain = '../data/'
	#fnTrain = '/content/' # for colab, copy the data from drive.
	fnInfer = '../data/test.png'
	fnCorpus = '../data/corpus.txt'

def train(model, loader, datablock_size):
	"train NN"
	model.trainBatch(loader, FilePaths.fnAccuracy, datablock_size)

def infer(model, batch):
	"recognize text in image provided by file path"
	if DecoderType == DecoderType.WordBeamSearch:
		recognized = model.inferBatch(batch)
		print('result is ')
		print(recognized)
		return recognized
	else:
		(recognized, probability) = model.inferBatch(batch)
		print(recognized)
		print('Probability:', probability)
		return recognized

def main():
	"main function"
	# optional command line args
	parser = argparse.ArgumentParser()
	parser.add_argument('--train', help='train the NN', action='store_true')
	parser.add_argument('--beamsearch', help='use beam search instead of best path decoding', action='store_true')
	parser.add_argument('--wordbeamsearch', help='use word beam search instead of best path decoding', action='store_true')
	parser.add_argument('--batch_size', help='batch size? default is 100', type=int, default=100)
	parser.add_argument('--block_size', help='datablock size? default is 10,000. decrease if RAM is lower than 16gigs', \
		type=int, default=10000)

	args = parser.parse_args()

	decoderType = DecoderType.BestPath
	if args.beamsearch:
		decoderType = DecoderType.BeamSearch
	elif args.wordbeamsearch:
		decoderType = DecoderType.WordBeamSearch

	batch_size = args.batch_size
	datablock_size = args.block_size

	# train on IAM dataset
	if args.train:
		# load training data, create TF model
		print('Setting up loader')
		loader = DataLoader(FilePaths.fnTrain, Model.imgSize, Model.maxTextLen)

		# save characters of model for inference mode
		print('Writing charlist')
		open(FilePaths.fnCharList, 'w').write(str().join(loader.charList))

		# save words contained in dataset into file
		print('Writing words')
		open(FilePaths.fnCorpus, 'w').write(str(' ').join(loader.words))

		# execute training
		if args.train:
			print('Setting up model')
			model = Model(loader.charList, decoderType, batch_size)
			# train(model, loader)
			train(model, loader, datablock_size)

	# infer text on test image
	else:
		file = open(FilePaths.fnInfer + 'preds.txt', 'w')
		model = Model(open(FilePaths.fnCharList).read(), decoderType, batch_size=100)
		imgs = []
		for filename in os.listdir(FilePaths.fnInfer):
			img = FilePaths.fnInfer + filename
			imgs.append(preprocess(cv2.imread(img, cv2.IMREAD_GRAYSCALE), Model.imgSize))
		size = len(imgs)
		dummy_txts = [None for i in range(size)]
		batch = Batch(dummy_txts, imgs)
		preds = infer(model, batch)
		for word in preds:
			file.write(word+' ')
		file.close()

if __name__ == '__main__':
	main()


from boardfarm.lib.installers import apt_install

class SipCenter(object):
    '''
    asterisk  server
    '''

    model = ('asterisk')
    profile = {}

    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

        self.numbers = self.kwargs.get('numbers', ["1000", "2000", "3000"])
        # local installation without internet will be added soon
        self.ast_local_url = kwargs.get("local_site", None)
        self.profile[self.name] = self.profile.get(self.name, {})
        sipcenter_profile = self.profile[self.name] = {}
        sipcenter_profile["on_boot"] = self.start_asterisk

    def __str__(self):
        return "asterisk"

    def install_essentials(self):
        '''
        install asterisk essentials
        '''
        apt_install(self, 'build-essential')
        apt_install(self, 'libncurses5-dev')
        apt_install(self, 'libjansson-dev')
        apt_install(self, 'uuid-dev')
        apt_install(self, 'libxml2-dev')
        apt_install(self, 'libsqlite3-dev')
        apt_install(self, 'tshark')

    def install_asterisk(self):
        '''
        install asterisk from internet
        '''
        self.install_essentials()
        apt_install(self, 'asterisk', timeout=300)

    def setup_asterisk_config(self):
        '''
        Generates sip.conf and extensions.conf file.

        '''
        gen_conf = '''cat > /etc/asterisk/sip.conf << EOF
[general]
context=default
bindport=5060
allowguest=yes
qualify=yes
registertimeout=900
allow=all
allow=alaw
allow=gsm
allow=g723
allow=g729
EOF'''
        gen_mod = '''cat > /etc/asterisk/extensions.conf << EOF
[default]
EOF'''
        self.sendline(gen_conf)
        self.expect(self.prompt)
        self.sendline(gen_mod)
        self.expect(self.prompt)
        for i in self.numbers:
            num_conf = '''cat >> /etc/asterisk/sip.conf << EOF
[''' + i + ''']
type=friend
regexten=''' + i + '''
secret=1234
qualify=no
nat=force_rport
host=dynamic
canreinvite=no
context=default
dial=SIP/''' + i + '''
EOF'''
            self.sendline(num_conf)
            self.expect(self.prompt)
            num_mod = '''cat >> /etc/asterisk/extensions.conf << EOF
exten => ''' + i + ''',1,Dial(SIP/''' + i + ''',20,r)
same =>n,Wait(20)
EOF'''
            self.sendline(num_mod)
            self.expect(self.prompt)

    def start_asterisk(self):
        '''
        Start the asterisk server if executable is present
        '''
        self.install_asterisk()
        self.setup_asterisk_config()
        self.sendline('nohup asterisk -vvvvvvvd &> ./log.ast &')
        self.expect(self.prompt)

    def kill_asterisk(self):
        '''
        Kill  the asterisk server
        '''
        self.sendline('killall -9 asterisk')
        self.expect(self.prompt)


from queue import Queue
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    """
    TC: O(total number of nodes in the tree) = O(n)
    SC: O(max. breadth of the tree)
    """

    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:

        if root == None:
            return None

        output = []
        queue = Queue()
        queue.put(root)

        while not queue.empty():
            size = queue.qsize()

            for i in range(size):
                front = queue.get()

                if i == size - 1:
                    output.append(front.val)

                if front.left != None:
                    queue.put(front.left)

                if front.right != None:
                    queue.put(front.right)

        return output


from tkinter import *
from tkinter import filedialog #tuodaan tiedostodialogi toiminnallisuus
from tkinter import messagebox #tuodaan messagebox-toiminnallisuus
from tkinter.font import Font #tuodaan fonttikirjasto

def tallennaTxt(): #Luodaan funktio, jolla tallennetaan kirjoitettu teksti.

    file = filedialog.asksaveasfilename() #file-muuttujaan tallennetaan tiedostolle annettava nimi. avaus ja tallentaminen
                                         #tapahtuu windows-käyttöjärjestelmän vakio-dialogeissa, joka on toteutettu
                                         #filedialog kirjastolla.

    tiedosto = open(file,'w')#Avataan tiedosto, jonka nimi on file-muuttujan syötetty tiedostonimi. w-kirjaimella
                             #kerrotaan, että tallennus tehdään tekstimuodossa ja korvataan mahdollinen vanha sisältö.
    teksti = tekstikentta.get('1.0','end-1c') #tallennetaan muuttujaan tekstikentän teksti ensimmäisestä kirjaimesta viimeiseen.
    tiedosto.write(teksti)                    #Kirjoitetaan teksti tiedostoon.

    messagebox.showinfo('Tallennus','Tiedosto on tallennettu!') #näytetään ilmoitus erillisessä ikkunassa
    #kun tiedosto on tallennettu onnistuneesti.
    tiedosto.close #suljetaan tiedosto.

def avaaTxt(): #Luodaan funktio, jolla voidaan avata olemassaoleva tekstitiedosto.
    haettava = filedialog.askopenfilename(initialdir = 'C:\\',) #haettava muuttujaan tallennetaan avattavan tiedoston nimi,
    #initialdir komennolla asetetaan oletussijainniksi c-levy.

    tiedosto = open(haettava, encoding = 'utf-8')#avataan tiedosto ja käytetään siinä encoding komennolla utf-8 merkistökoodausta.
    tekstikentta.insert('1.0', tiedosto.read())#näytetään tiedoston teksti sisältö tekstikenttä laatikossa.
    tiedosto.close

#luodaan funktiot, joiden avulla voi vaihtaa fonttia. font komennolla määritellään, mitä fonttia käytetään.
def courier():
    tekstikentta.config(font = 'Courier')

def arial():
    tekstikentta.config(font = 'Arial')

def georgia():
    tekstikentta.config(font = 'Georgia')

def system():
    tekstikentta.config(font = 'System')

def clear():
    tekstikentta.delete('1.0',END)

ikkuna = Tk()
ikkuna.geometry('250x250') #määritellään käyttöliittymäikkunan kooksi 250 * 250 pikseliä.
ikkuna.configure(background = 'slate gray') #määritellään ikkuna-komponentin taustaväri.
ikkuna.title('TXT-editor') #annetaan ikkunassa näkyvä otsikko.

tallenna = PhotoImage(file = 'NotepadSave.png') #tuodaan png-kuvat ohjelmaan, joita käytetään kuvakkeina ohjelman pudotus
#valikossa.
tallennus = tallenna.subsample(4,4)

avaa = PhotoImage(file = 'NotepadOpen.png')
avaatiedosto = avaa.subsample(4,4)

#luodaan alasvetovalikot toiminnoille ja fonteille.
valikko = Menu(ikkuna)
ikkuna.config(menu=valikko)
toiminnot = Menu(valikko)
fontit = Menu(valikko)

#Lisätään alasvetovalikkoihin toimintoja. command komennolla lisätään funktiot, jotka suoritetaan jos toiminto valitaan.
#image komennolla tuodaan kuvatiedosto tekstin yhteyteen, joka asetetaan compound komennolla tekstin oikealle puolelle.

valikko.add_cascade(label = 'Functions', menu = toiminnot)
toiminnot.add_command(label = 'Save', command = tallennaTxt, image = tallennus, compound = RIGHT)

toiminnot.add_command(label = 'Load', command = avaaTxt, image = avaatiedosto, compound = RIGHT)
toiminnot.add_command(label = 'Clear textbox', command = clear)
valikko.add_cascade(label = 'Fonts', menu = fontit)

fontit.add_command(label = 'Courier', command = courier)
fontit.add_command(label = 'Arial', command = arial)
fontit.add_command(label = 'Georgia', command = georgia)
fontit.add_command(label = 'System', command = system)

#tallennetaan muuttujaan georgia fontti koossa 11, jota käytetään ohjelman otsikossa.
otsikkofontti = Font(family = 'Georgia', size = 11)

rullauspalkki = Scrollbar(ikkuna) #luodaan rullauspalkki ohjelmaan.
rullauspalkki.pack(side = RIGHT, fill = Y) #asemoidaan rullauspalkki oikealle, fill komennolla kerrotaan rullaussuunta.

#luodaan label-komennolla tekstikomponentti. text-komennolla annetaan komponentissa näkyvä teksti, background
#komennolla komponentin taustaväri ja font komennolla käytettävä fontti.
ohjnimi = Label(ikkuna, text = 'Txt-editor', background = 'white smoke', font = otsikkofontti, relief = 'solid')

#luodaan tekstikentta niminen tekstilaatikko, width ja height komennoilla määritellään sen koko.
tekstikentta = Text(ikkuna, width = 40, height = 10, borderwidth = 2, relief = 'sunken', yscrollcommand = rullauspalkki.set)
rullauspalkki.config (command = tekstikentta.yview)

alaosa = Label(ikkuna, background = 'slate gray')

ohjnimi.pack(pady=2) #pakataan luodut komponentit, jolloin ne näkyvät ohjelmassa.
tekstikentta.pack()
alaosa.pack()
mainloop()


import xml.etree.ElementTree as et
import time
from debug import printMsg

def getGraphFromFile(file, showMessage = True):
    printMsg("=================== START FILE CONVERSION ===================", showMessage)
    startTime = time.time()
    graph = createGraph(file)
    printMsg(("Took : " + str(time.time() - startTime) + " seconds to make a graph from the file."), showMessage)
    printMsg("=============================================================", showMessage)
    return graph

def createGraph(file):
    graph = {}
    nodes = {}
    links = []
    tree = None
    root = None

    with open(file, encoding='utf-8') as data:
        tree = et.parse(data)
        root = tree.getroot()

    for rawNode in root.findall("node"):
        nodes[int(rawNode.get("id"))] = (float(rawNode.get("lat")), float(rawNode.get("lon")))
        graph[nodes[int(rawNode.get("id"))]] = []

    for rawLink in root.findall("way"):
        neighbors = []
        i = 0
        for neighbor in rawLink.iter("nd"):
            neighbors.append(nodes[int(neighbor.attrib["ref"])])
        links.append(neighbors)

    for link in links:
        length = len(link)

        for i in range(length):
            l = graph.get(link[i], [])

            if length > 1 and i == 0:
                if link[1] not in l:
                    graph[link[0]].append(link[1])

            elif i == (length - 1):
                if link[length - 2] not in l:
                    graph[link[length - 1]].append(link[length - 2])

            else:
                if link[i - 1] not in l:
                    graph[link[i]].append(link[i - 1])
                if link[i + 1] not in l:
                    graph[link[i]].append(link[i + 1])

    return graph


# -*- coding:UTF-8 -*-

'''
找出整型数组里除了两个数字以外，其它都出现了两次。要求时间复杂度是O(n) 空间复杂度是 O(1)
'''

class Solution(object):
    def printContiSeq(self, small, big):
        for i in range(small, big + 1):
            print(i)
        print()

    def findContiSeq(self, target):
        if target < 3:
            return;
        small = 1
        big = 2
        tmp = small + big
        mid = (1 + target) / 2

        while small < mid:
            if tmp == target:
                print(" ".join([str(x) for x in range(small, big + 1)]))
                # self.printContiSeq(small, big)

            while tmp > target and small < mid:
                tmp = tmp - small
                small = small + 1
                if (tmp == target):
                    print(" ".join([str(x) for x in range(small, big + 1)]))
                    # self.printContiSeq(small, big)
            big = big + 1
            tmp = tmp + big

if __name__ == '__main__':
    nums = [1, 2, 4, 7, 11, 15]
    # nums = []
    target = 15
    print(Solution().findContiSeq(target))


# from json import JSONEncoder
import json
from fractions import Fraction
from JrpgBattle.Character import CharacterTemplate, Multiplier
from JrpgBattle.Attack import Attack, VanillaAttack
from typing import Dict, Callable

class JrpgDataManager:
    """
    The JrpgDataManager is used to load up attack and character data from JSON files.
    It also maintains functionality for looking up CharacterTemplates and Attacks by their names.
    """

    def __init__(self):
        self.character_cache: Dict[str, CharacterTemplate] = {}
        self.attack_cache: Dict[str, Attack] = {}

    def get_jrpg_decoder_func(self) -> Callable:
        def decoder_func(data: Dict):
            if '__class__' not in data:
                return data
            elif data['__class__'] == VanillaAttack.__name__:
                attack = VanillaAttack(name=data['template_name'],
                                       attack_type=data['type'],
                                       target_range=data['target_range'],
                                       stamina_point_cost=data['sp_cost'],
                                       mana_point_cost=data['mp_cost'],
                                       damage=data['damage'])
                assert attack.name not in self.attack_cache
                self.attack_cache[attack.name] = attack
                return attack
            elif data['__class__'] == CharacterTemplate.__name__:
                # print(str(data['attack_list']))
                character = CharacterTemplate(name=data['template_name'],
                                              max_hp=data['max_hp'],
                                              offensive_type_affinities=data['offensive_type_affinities'],
                                              defensive_type_affinities=data['defensive_type_affinities'],
                                              attack_list={self.attack_cache[atk_name] for atk_name in data['attack_list']},
                                              parry_effectiveness=Fraction(data['parry_effectiveness']))
                assert character.template_name not in self.character_cache
                self.character_cache[character.template_name] = character
                return character
        return decoder_func

def encode_jrpg_data(obj):
    # print('in function')
    # print(obj)
    if isinstance(obj, Fraction):
        # print('got there')
        return obj.numerator, obj.denominator
    elif isinstance(obj, CharacterTemplate):
        return {'__class__': CharacterTemplate.__name__,
                'template_name': obj.template_name,
                'max_hp': obj.max_hp,
                'offensive_type_affinities': list(obj.get_offensive_type_affinities()),
                'defensive_type_affinities': list(obj.get_defensive_type_affinities()),
                'attack_list': list(obj.get_attack_list()),
                'parry_effectiveness': str(obj.get_parry_effectiveness())
                }
    elif isinstance(obj, VanillaAttack):
        return {'__class__': VanillaAttack.__name__,
                'template_name': obj.get_name(),
                'event_type': obj.get_attack_type(),
                'target_range': obj.get_target_range(),
                'sp_cost': obj.get_sp_cost(),
                'mp_cost': obj.get_mp_cost(),
                'damage': obj.damage
                }
    raise TypeError(repr(obj) + " is not JSON serializable")

def decode_jrpg_data(dictionary: Dict):
    if '__class__' not in dictionary:
        return dictionary
    elif dictionary['__class__'] == VanillaAttack.__name__:
        return VanillaAttack(name=dictionary['template_name'],
                             attack_type=dictionary['event_type'],
                             target_range=dictionary['target_range'],
                             stamina_point_cost=dictionary['sp_cost'],
                             mana_point_cost=dictionary['mp_cost'],
                             damage=dictionary['damage'])
    elif dictionary['__class__'] == CharacterTemplate.__name__:
        return CharacterTemplate(name=dictionary['template_name'],
                                 max_hp=dictionary['max_hp'],
                                 offensive_type_affinities=dictionary['offensive_type_affinities'],
                                 defensive_type_affinities=dictionary['defensive_type_affinities'],
                                 attack_list=dictionary['attack_list'],
                                 parry_effectiveness=dictionary['parry_effectiveness'])


"""
Module for receiving LOGs via API.
"""
from datetime import datetime
from os import path
from typing import Dict, List, Optional, Union

import requests

from log_processing_demo.log_item import LogItem
from log_processing_demo.sort import sort

LOG_LIST_NAME = "logs"
ERROR_NAME = "error"

class RequestError(Exception):
    """Exception for wrapping all possible exceptions of 'requests' module."""

    pass

class LogReceiver:
    """Class for receiving LOGs via API.
    See methods docstrings.
    """

    def __init__(self, base_url: str):
        """Constructor remembers a base API URL.

        Parameters
        ----------
        base_url : str
            Base API URL.
        """
        self.base_url: str = base_url

    def __call__(
        self, date_string: str, sort_by_time: Optional[bool] = False
    ) -> List[Dict[str, Union[datetime, str]]]:
        """Call an instance of class to retreive a list of LOG messages for desired date.

        Parameters
        ----------
        date_string : str
            Date to get LOG messages for. Format: YYMMDD
        sort_by_time : Optional[bool]
            Whether or not the result should be sorted by record creation time.

        Returns
        -------
        List[Dict[str, Union[datetime, str]]]
            Either sorted or unsorted list of LOG records.

        Raises
        ------
        RequestError
            Re-rised for any 'requests' module exception.
        ValueError
            Rised when API returns an error message.

        """
        try:
            response = requests.get(path.join(self.base_url, date_string))
            response.raise_for_status()
        except Exception as error:
            raise RequestError(str(error))

        data = response.json()
        if data[ERROR_NAME]:
            raise ValueError(data[ERROR_NAME])

        log_list = list(map(LogItem.parse_obj, data[LOG_LIST_NAME]))

        if sort_by_time:
            sort(log_list, key=lambda x: x.created_at)

        return log_list


# -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 16:55:48 2018

Convert geojson to simple json dict

@author: Edward
"""

import json
# %% plot map
def plot_state_map(states, P_AK=[-77, 5, -0.22, 0.25, 0.35], P_HI=[-38, 17, 0, 0.4, 0.4], exclude_states=['','PR', 'VI', 'DC', 'GU', 'MP', 'AS']):
    xs, ys = states['AK']['lons'],states['AK']['lats']
    #  transoformation
    X = np.array([xs, ys, list(np.ones(len(xs)))])
    A = spm_matrix_2d(P=P_AK)
    Y = A @ X
    states['AK']['lons'] = list(Y[0,:])
    states['AK']['lats'] = list(Y[1,:])

    xs, ys = states['HI']['lons'],states['HI']['lats']
    X = np.array([xs, ys, list(np.ones(len(xs)))])
    A = spm_matrix_2d(P=P_HI)
    Y = A @ X
    states['HI']['lons'] = list(Y[0,:])
    states['HI']['lats'] = list(Y[1,:])

    #  plot transformation
    fig, ax = plt.subplots(1,1)
    fig.set_size_inches(7, 4.5)
    for s in states.keys():
        if s in exclude_states: continue
        xs, ys = states[s]['lons'],states[s]['lats']
        ax.plot(xs, ys)
    return states

# %% states
#fs = '5m'
#file_dir = 'D:/Edward/Documents/Assignments/Scripts/Python/Plots/resource/cb_2017_us_state_%s.geojson'%fs
#with open(file_dir, 'r') as data_file:
#    state_map = json.load(data_file)
#
#state_map = state_map['features']
#states = {}
#for sm in state_map:
#    name = sm['properties']['NAME']
#    key = sm['properties']['STUSPS']
#    state_id = sm['properties']['STATEFP']
#    coords = sm['geometry']['coordinates']
#    lons_lats = np.empty((0, 2))
#    # Gather the lons and lats
#    for n, c in enumerate(coords):
#        current_coords = np.array(c).squeeze()
#        if key == 'AK' and any(current_coords[:, 0]>0):
#            current_coords[:, 0] = -current_coords[:, 0]
#        lons_lats = np.concatenate((lons_lats, current_coords), axis=0)
#        if n < len(coords)-1:
#            lons_lats = np.concatenate((lons_lats, np.array([[np.nan, np.nan]])), axis=0)
#
#    lons = list(lons_lats[:, 0])
#    lats = list(lons_lats[:, 1])
#    states[key] = {'name':name, 'id':state_id, 'lons':lons, 'lats':lats}
#
##plot_state_map(states, P_AK)
#if fs == '500k':
#    states_shifted = plot_state_map(states, P_AK=[-70, 9, 0, 0.30, 0.30], P_HI=[-4, 12, 0,0.6, 0.6]) # for 500k resolution only
#else:
#    states_shifted = plot_state_map(states, P_AK=[-70, 9, 0, 0.30, 0.30], P_HI=[51, 7, 0,])
## write file
#file_dir = 'D:/Edward/Documents/Assignments/Scripts/Python/Plots/resource/CBUS_states_scaled_%s.json'%fs
#with open(file_dir,'w') as outfile:
#    json.dump(states_shifted, outfile)

# %%
def plot_county_map(counties, P_AK=[-77, 5, -0.22, 0.25, 0.35], P_HI=[-38, 17, 0, 0.4, 0.4], exclude_states=['', 'PR', 'VI', 'DC', 'GU', 'MP', 'AS']):
    for key in counties.keys():
        if key[0] == 2 or key[0] == 15: # Alaska or Hawaii
            xs = counties[key]['lons']
            ys = counties[key]['lats']
            X = np.array([xs, ys, list(np.ones(len(xs)))])
            A = spm_matrix_2d(P=P_HI if key[0]==15 else P_AK)
            Y = A @ X
            counties[key]['lons'] = list(Y[0,:])
            counties[key]['lats'] = list(Y[1,:])
        else:
            pass

    #  plot transformation
    fig, ax = plt.subplots(1,1)
    fig.set_size_inches(7, 4.5)
    for c in counties.keys():
        #print(counties[c]['state_key'])
        if counties[c]['state_key'] in exclude_states: continue
        xs, ys = counties[c]['lons'],counties[c]['lats']
        ax.plot(xs, ys)
    return counties

# %% Counties
fs = '20m'
state_dir = 'D:/Edward/Documents/Assignments/Scripts/Python/Plots/resource/CBUS_states_scaled_20m.json'
county_dir = 'D:/Edward/Documents/Assignments/Scripts/Python/Plots/resource/cb_2017_us_county_%s.geojson'%fs
with open(state_dir, 'r') as data_file:
    states = json.load(data_file)

with open(county_dir, 'r') as data_file:
    county_map = json.load(data_file)

counties = {}
counties_ids = []
county_map = county_map['features']
for cm in county_map:
    name = cm['properties']['NAME']
    county_id = cm['properties']['COUNTYFP']
    state_id = cm['properties']['STATEFP']
    state_name, state_key = '', ''
    for kk in states:
        if states[kk]['id'] == state_id:
            state_name = states[kk]['name']
            state_key = kk
            break

    coords = cm['geometry']['coordinates']
    lons_lats = np.empty((0, 2))
    # Gather the lons and lats
    for n, c in enumerate(coords):
        current_coords = np.array(c).squeeze()
        if current_coords.ndim<2:
            current_coords = np.empty((0,2))
            for m, cc in enumerate(c):
                current_coords = np.concatenate((current_coords, cc), axis=0)
                if  m < len(c)-1:
                    current_coords = np.concatenate((current_coords, np.array([[np.nan, np.nan]])), axis=0)
        if state_key == 'AK' and any(current_coords[:, 0]>0):
            current_coords[:, 0] = -current_coords[:, 0]
        lons_lats = np.concatenate((lons_lats, current_coords), axis=0)
        if n < len(coords)-1:
            lons_lats = np.concatenate((lons_lats, np.array([[np.nan, np.nan]])), axis=0)

    lons = list(lons_lats[:, 0])
    lats = list(lons_lats[:, 1])
    counties[(int(state_id), int(county_id))] = {'name':name, 'id': county_id, 'state': state_name,
                'state_key': state_key, 'lons':lons, 'lats':lats}
if fs == '500k':
    counties_scaled = plot_county_map(counties, P_AK=[-70, 9, 0, 0.30, 0.30], P_HI=[-4, 12, 0,0.6, 0.6]) # for 500k resolution only
else:
    counties_scaled = plot_county_map(counties, P_AK=[-70, 9, 0, 0.30, 0.30], P_HI=[51, 7, 0,])

# write file
file_dir = 'D:/Edward/Documents/Assignments/Scripts/Python/Plots/resource/CBUS_counties_scaled_%s.json'%fs
def remap_keys(mapping, func=str): #json can't take tuple keys, only string keys
    return {func(k):v for k,v in mapping.items()}

with open(file_dir,'w') as outfile:
    json.dump(remap_keys(counties_scaled), outfile)

# %%
with open(file_dir, 'r') as outfile:
    counties_loaded = remap_keys(json.load(outfile), func=lambda x: tuple(str2num(x)))


# -*- coding: utf-8 -*-

from odoo import models, api, fields, _
from odoo.exceptions import UserError

class SupplierInfo(models.Model):
    _inherit = 'product.supplierinfo'

    duty = fields.Float(string='Duty/Brokerage %', digits=(12, 2))
    freight = fields.Float(string='Freight %', digits=(12, 2))
    estimated_landed_cost = fields.Float(string='Estimated Landed Cost', compute='_compute_estimated_landed_cost')
    currency_rate = fields.Float(string='Currency Rate', related='currency_id.rate')

    @api.depends('price', 'duty', 'freight', 'currency_rate')
    def _compute_estimated_landed_cost(self):
        for record in self:
            try:
                record.estimated_landed_cost = record.price / record.currency_rate * record.duty * record.freight
            except:
                record.estimated_landed_cost = record.estimated_landed_cost or 0.0

    def _overwrite_product_cost(self):
        if self.env.user.has_group('purchase.group_purchase_manager'):
            if len(set([record.name for record in self])) == 1:
                for record in self:
                    if record.product_id:
                        record.product_id.standard_price = record.estimated_landed_cost
                    else:
                        record.product_tmpl_id.standard_price = record.estimated_landed_cost
            else:
                raise UserError(_("Cannot overwrite costs for multiple vendors at the same time."))
        else:
            raise UserError(_("Only managers can overwrite product costs."))


from IPython.display import Markdown as md

def mdd(text: str, h: int = None, bold=False):
    """
    Shortucut function for displaying markdown
    :param text: text to display as MD
    :param h: optional header level
    """
    display(
        md(
            f'{"#" * h + " " if h is not None else ""}{"__" if bold else ""}{text}{"__" if bold else ""}'
        )
    )


# -*- coding: utf-8 -*-

"""
calculate-integrative-complexity.py

This version shows conditional entropy using different dimensions of source information.
"""

import sys, re, os, math, nltk
from classes_prosFirst import *

def usage():
	print (
#########################################################
# USAGE INSTRUCTIONS: calculate-integrative-complexity.py
#########################################################
)

def main():

	vcFreqs = {
		"ICØ": 235,
		"ICL": 379,
		"ICN1": 2,
		"ICN2": 243,
		"ICNG": 213
	}
	sumLexes = 0
	for vc in ["ICØ", "ICL", "ICN1", "ICN2", "ICNG"]:
		sumLexes += vcFreqs[vc]
	'''for vc in ["ICØ", "ICL", "ICN1", "ICN2", "ICNG"]:
		prop = vcFreqs[vc] / sumLexes
		print(vc)
		print(str(prop))'''

	mpsFreqs = {
		"IMP.PFV": 298,
		"PST.PFV": 1950,
		"PRS": 1529,
		"IMP.IPFV": 285,
		"PST.IPFV": 836,
		"FUT": 135,
		"CHAR": 1006,
		"NMLZ": 837,
		"MV": 2823
	}
	sumTokens = 0
	for mps in ["IMP.PFV", "PST.PFV", "PRS", "IMP.IPFV", "PST.IPFV", "FUT", "CHAR", "NMLZ", "MV"]:
		sumTokens += mpsFreqs[mps]
	'''for mps in ["IMP.PFV", "PST.PFV", "PRS", "IMP.IPFV", "PST.IPFV", "FUT", "CHAR", "NMLZ", "MV"]:
		prop = mpsFreqs[mps] / sumTokens
		print(mps)
		print(str(prop))'''

	input = open('pitjantjatjara-verb-infl.txt', 'r')
	output = open('integrative-complexity_prosFirst.txt', 'w')
	output.write("NOTE: ALL AVERAGES ARE WEIGHTED BY IC FREQUENCY ACROSS LEXICAL TYPES, AND MPS FREQUENCY ACROSS CORPUS TOKENS.\nWEIGHTED AVERAGES APPEAR AT THE BOTTOM OF THIS OUTPUT.\n\n")

	inputLines = input.readlines()

	# These are unordered sets for collecting all the cell objects
	cells = []
	cellDict = {} # the lookup keys for these are "vc.mps"

	for line in inputLines:
		line = re.sub('[\n\r]*', '', line) #chomp
		line = re.sub('\s*$', '', line) #chomp trailing space too
		#print line

		# only process the lines that start with VC numbers
		if not re.search('^IC', line):
			continue

		fields = line.split('\t')
		vc = fields.pop(0)

		for mps in ["IMP.PFV", "PST.PFV", "PRS", "IMP.IPFV", "PST.IPFV", "FUT", "CHAR", "NMLZ", "MV"]:

			#print fields
			form = fields.pop(0)
			form = form.replace('\"', '') # get rid of any quote marks added by Excel

			(pros, aug, suff) = form.split('-')

			cell = Cell(mps, vc, form, pros, aug, suff)
			cells.append(cell)
			cellDict['.'.join([vc, mps])] = cell

	# For each cell , find out how predictive other MPS values are given this cell
	for sourceCell in cells:
		#output.write("###############\nTarget cell:")
		#output.write(str(targetCell))
		#output.write("\n")

		#sourceCellAggrEnt
		weightedAvSourceCellEnt = {
			'cueless': 0,
			'pros': 0,
			'prosAug': 0,
			'prosAugSuff': 0
		}

		# get the set of cells from the same VC as the target (but not including self). these will be used as "sources" for testing conditional predictability
		targetCells = [cell for cell in cells if ((cell.vc == sourceCell.vc) and not (cell is sourceCell))]

		# this will be used for probability weighting of entropy below
		sumTargetFreqs = 0
		for t in targetCells:
			sumTargetFreqs += mpsFreqs[t.mps]

		# for each source cell, calculate how well it predicts the target
		for targetCell in targetCells:

			#probWeighting = 1 / len(targetCells) # use this if you want to treat all MPS as equiprobable
			probWeighting = mpsFreqs[targetCell.mps] / sumTargetFreqs

			# get the equivalent cells from all the vc's that have the same (available) cues as the sourceCell for the source MPS
			for cue in ('cueless', 'pros', 'prosAug', 'prosAugSuff'):

				# a little hack to deal with the NG-class, where stems can be either monomoraic, or polymoraic/extrametrical. So they need to match against both N1-class and N2-class, which however don't match each other.
				if (sourceCell.vc=='ICNG' and cue=='pros'):
					sourceAnalogues = [cell for cell in cells if ( (cell.mps == sourceCell.mps) and ( (cell.vc=='ICN2') or (cell.vc=='ICNG')) )]
				elif (sourceCell.vc=='ICN1' and cue=='pros'):
					sourceAnalogues = [cell for cell in cells if ( (cell.mps == sourceCell.mps) and ( (cell.vc=='ICN1') or (cell.vc=='ICNG')) )]
				elif (sourceCell.vc=='ICN2' and cue=='pros'):
					sourceAnalogues = [cell for cell in cells if ( (cell.mps == sourceCell.mps) and ( (cell.vc=='ICN2') or (cell.vc=='ICNG')) )]
				else:
					sourceAnalogues = [cell for cell in cells if (cell.cues[cue] == sourceCell.cues[cue] and cell.mps == sourceCell.mps)]

				# then get all the forms implied by these analogues

				# if there is only one VC where this MPS takes this form, then we know that the entropy will be 0, because there is only one possibility
				if len(sourceAnalogues)==1:
					entropy = 0
					# for more detailed output
					#output.write('\t'.join([str(sourceCell), str(targetCell), cue, str(entropy), '\n']))
				else:
					impliedExponences = [] #this list is where we will store all the target cells from the analogous sources
					for analog in sourceAnalogues:
						# *even more* detailed output
						#output.write("Cand: "+analog.vc+"\t"+str(vcFreqs[analog.vc])+"\n")
						#print "VC that matches this source:" + str(analogousCell)
						lookupString = '.'.join([analog.vc, targetCell.mps])
						impliedCell = cellDict[lookupString] #look up the implied cell
						#print "\tand its implied cell:" + str(impliedCell)
						# this version added each IC's exponence once
						#impliedExponences.append(impliedCell.cues['augSuff'])
						# this for-loop means that the exponences set is a frequency distribution based on dictionary frequencies of inflection classes
						impliedExponences.extend([impliedCell.cues['augSuff'] for n in range(vcFreqs[analog.vc])])

					# calculate entropy of impliedExponences set
					entropy = getEntropy(impliedExponences)
					# for more detailed output
					#output.write('\t'.join([str(sourceCell), str(targetCell.mps), cue, str(entropy), '\n']))
					weightedAvSourceCellEnt[cue] += (entropy * probWeighting)

		#avSourceCellEnt = {}
		for cue in ('cueless', 'pros', 'prosAug', 'prosAugSuff'):
			#avSourceCellEnt[cue] = sourceCellAggrEnt[cue] / len(targetCells)
			sourceCell.avgEnt[cue] = weightedAvSourceCellEnt[cue]

	systemWeightedAvEnt = {
		'cueless': 0,
		'pros': 0,
		'prosAug': 0,
		'prosAugSuff': 0
	}
	prevCue = 'cueless'
	avEntropies = {} # entropies[cue][mps] = 0
	for cue in ('cueless', 'pros', 'prosAug', 'prosAugSuff'):
		output.write("============\nCue: "+cue+"\n\n")
		avEntropies[cue] = {}
		for mps in ["IMP.PFV", "PST.PFV", "PRS", "IMP.IPFV", "PST.IPFV", "FUT", "CHAR", "NMLZ", "MV"]:
			mpsWeighting = mpsFreqs[mps] / sumTokens
			# mpsWeighting = 1 / 9 # if you want to treat MPSs as equiprobable
			mpsWeightedAvEnt = {
				'cueless': 0,
				'pros': 0,
				'prosAug': 0,
				'prosAugSuff': 0
				}
			for vc in ["ICØ", "ICL", "ICN1", "ICN2", "ICNG"]:
				vcWeighting = vcFreqs[vc] / sumLexes
				# vcWeighting = 1 / 5 # if you treat VCs as equiprobable
				output.write(vc+"\t"+mps+"\t")
				cell = cellDict[".".join([vc, mps])]
				output.write(cell.form+"\t")
				output.write(str(cell.avgEnt[cue])+"\n")
				mpsWeightedAvEnt[cue] += cell.avgEnt[cue] * vcWeighting
				avEntropies[cue][mps] = mpsWeightedAvEnt[cue] # store in dictionary for comparison after next cue is added
			contr = avEntropies[prevCue][mps] - mpsWeightedAvEnt[cue]
			output.write("Av entropy with "+cue+" ")
			output.write('\t'.join([str(mps), str(mpsWeightedAvEnt[cue]), "\n"]))
			output.write("Av info contributed ")
			output.write('\t'.join([str(mps), str(contr), "\n"]))
			output.write("\n")
			systemWeightedAvEnt[cue] += mpsWeightedAvEnt[cue] * mpsWeighting
		output.write("System average entropy with "+cue+": "+str(systemWeightedAvEnt[cue])+"\n")
		output.write("\n\n")
		prevCue = cue

# looks through a set of items, and calculates their entropy
def getEntropy(items):
	#print items
	freqdist = nltk.FreqDist(items)
	probs = [freqdist.freq(l) for l in nltk.FreqDist(items)]
	return -sum([p * math.log(p,2) for p in probs])

if __name__ == "__main__":
	main()


# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
import sys
import time
from PyQt4.QtGui  import *
from PyQt4.QtCore import *

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class CheckBoxDelegate(QItemDelegate):

    def __init__(self, parent=None):
        QItemDelegate.__init__(self, parent)
        self.chkboxSize = 19 #?!

    def createEditor(self, parent, option, index):
        chkbox = QCheckBox(parent)
        chkbox.setText('')
        chkbox.setTristate(False) #只用两个状态
        left = option.rect.x() + (option.rect.width() - self.chkboxSize) / 2
        top  = option.rect.y() + (option.rect.height() - self.chkboxSize) / 2
        chkbox.setGeometry(left, top, self.chkboxSize, self.chkboxSize)
        return chkbox

    def paint(self, painter, option, index):
        value = index.data().toBool()
        opt = QStyleOptionButton()
        opt.state |= QStyle.State_Enabled | (QStyle.State_On if value else QStyle.State_Off)
        opt.text = ''
        left = option.rect.x() + (option.rect.width() - self.chkboxSize) / 2
        top  = option.rect.y() + (option.rect.height() - self.chkboxSize) / 2
        opt.rect = QRect(left, top, self.chkboxSize, self.chkboxSize)
        QApplication.style().drawControl(QStyle.CE_CheckBox, opt, painter)

    def updateEditorGeometry(self, editor, option, index):
        pass

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(696, 518)
        self.tableView = QtGui.QTableView(Dialog)
        self.tableView.setGeometry(QtCore.QRect(7, 0, 351, 441))
        self.tableView.setObjectName(_fromUtf8("tableView"))
        self.groupBox = QtGui.QGroupBox(Dialog)
        self.groupBox.setGeometry(QtCore.QRect(370, 10, 321, 121))
        self.groupBox.setObjectName(_fromUtf8("groupBox"))
        self.textEdit = QtGui.QTextEdit(self.groupBox)
        self.textEdit.setGeometry(QtCore.QRect(10, 20, 301, 91))
        self.textEdit.setObjectName(_fromUtf8("textEdit"))
        self.pushButton = QtGui.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(10, 480, 75, 31))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.pushButton_2 = QtGui.QPushButton(Dialog)
        self.pushButton_2.setGeometry(QtCore.QRect(90, 480, 75, 31))
        self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
        self.label_2 = QtGui.QLabel(Dialog)
        self.label_2.setGeometry(QtCore.QRect(20, 450, 141, 30))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.label_3 = QtGui.QLabel(Dialog)
        self.label_3.setGeometry(QtCore.QRect(180, 450, 171, 61))
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.groupBox_2 = QtGui.QGroupBox(Dialog)
        self.groupBox_2.setGeometry(QtCore.QRect(370, 140, 321, 371))
        self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
        self.textEdit_2 = QtGui.QTextEdit(self.groupBox_2)
        self.textEdit_2.setGeometry(QtCore.QRect(10, 20, 301, 341))
        self.textEdit_2.setObjectName(_fromUtf8("textEdit_2"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "FTP黑链挂载器    谢谢 灰帽程序员论坛 hmhacker.org  技术帮助", None, QtGui.QApplication.UnicodeUTF8))
        self.groupBox.setTitle(QtGui.QApplication.translate("Dialog", "挂马地址：", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton.setText(QtGui.QApplication.translate("Dialog", "全选", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton_2.setText(QtGui.QApplication.translate("Dialog", "反选", None, QtGui.QApplication.UnicodeUTF8))
        self.label_2.setText(QtGui.QApplication.translate("Dialog", "选择了0个要上传的FTP", None, QtGui.QApplication.UnicodeUTF8))
        self.label_3.setText(QtGui.QApplication.translate("Dialog", "处理了0个页面\n"
"更新成功0个页面\n"
"页面已有现在的连接0个", None, QtGui.QApplication.UnicodeUTF8))
        self.groupBox_2.setTitle(QtGui.QApplication.translate("Dialog", "MsessageBox消息提示：", None, QtGui.QApplication.UnicodeUTF8))

    def ini_Dialog(self):
        #########################
#        self.tableView.setRowCount(10)  #创建行
#        self.tableView.setColumnCount(6)  #创建列
        model = QStandardItemModel(300, 7, self.tableView)   #行 列
        model.setHorizontalHeaderLabels([u'选择',u'IP',u'用户名',u'密码',u'root权限',u'title网页标题',u'time时间'])
        self.tableView.setModel(model)
        self.tableView.setItemDelegateForColumn(0, CheckBoxDelegate(self.tableView))

        #########################
        self.textEdit_2.setEnabled(0)  #给改成禁用
        self.textEdit_2.append(u"欢迎使用FTP黑链挂在器---"+time.strftime('%Y.%m.%d-%H.%M.%S'))
        self.textEdit_2.append(u"root 列表解释")
        self.textEdit_2.append(u"0  连接不上FTP")
        self.textEdit_2.append(u"1  连接成功什么权限都没给")
        self.textEdit_2.append(u"2  仅有上传权限")
        self.textEdit_2.append(u"3  有上传和删除权限")
        #########################

class Start(QtGui.QMainWindow):
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui=Ui_Dialog()#这儿跟上面那个class一样
        self.ui.setupUi(self)
        self.ui.ini_Dialog()

if __name__=="__main__":
    app=QtGui.QApplication(sys.argv)
    myapp=Start()
    myapp.show()
    sys.exit(app.exec_())


import time
import win32clipboard
import requests

EmojiName = [line.rstrip('\n') for line in open("EmojiName.txt")]
EmojiURL = [line.rstrip('\n') for line in open("EmojiImageURL.txt")]
print(EmojiURL)

for i in range(0,(len(EmojiName))):
    response = requests.get(EmojiURL[i])
    file = open((EmojiName[i]+".png"), "wb")
    file.write(response.content)
    file.close()


import os
from invoke import Collection, task, Exit

@task
def test(c):
    """ Run tests, linters, and coverage. """
    c.run('flake8')

    migrations = c.run(
        'python manage.py makemigrations --dry-run | grep -v "No changes"',
        env=os.environ, warn=True)
    if len(migrations.stdout) > 0:
        print(migrations.stdout)
        raise Exit('makemigrations is showing that migration is missing!')

    c.run('python manage.py test --keepdb', env=os.environ)

# when running fab commands, echo the command before running:
ns = Collection(test)
ns.configure({'run': {'echo': True}})


#!/usr/bin/env python

import rospy
import traceback
import numpy as np
# IMPORT the custom messages:
from armrob_util.msg import ME439WaypointXYZ
from sensor_msgs.msg import JointState

# global variable to hold the waypoint currently being tracked
waypoint = ME439WaypointXYZ()
waypoint.xyz = np.array([0.,0.,0.])

# Load parameters from rosparam to keep handy for the functions below:
# Sign of 'positive' rotations w.r.t. the y axis
y_rotation_sign = np.sign(rospy.get_param('/y_rotation_sign'))
# Vectors from each frame origin to the next frame origin, in the proximal
r_01 = np.matrix(rospy.get_param('/frame_offset_01')).transpose()
r_12 = np.matrix(rospy.get_param('/frame_offset_12')).transpose()
r_23 = np.matrix(rospy.get_param('/frame_offset_23')).transpose()
r_34 = np.matrix(rospy.get_param('/frame_offset_34')).transpose()
r_45 = np.matrix(rospy.get_param('/frame_offset_45')).transpose()
r_56 = np.matrix(rospy.get_param('/frame_offset_56')).transpose()
r_6end = np.matrix(rospy.get_param('/endpoint_offset_in_frame_6')).transpose()

# limits for each of the joints
rotlim_01 = np.radians(np.array(rospy.get_param('/rotational_limits_joint_01')))
rotlim_12 = np.radians(np.array(rospy.get_param('/rotational_limits_joint_12')))
rotlim_23 = np.radians(np.array(rospy.get_param('/rotational_limits_joint_23')))
rotlim_34 = np.radians(np.array(rospy.get_param('/rotational_limits_joint_34')))
rotlim_45 = np.radians(np.array(rospy.get_param('/rotational_limits_joint_45')))
rotlim_56 = np.radians(np.array(rospy.get_param('/rotational_limits_joint_56')))

# Create the publisher. Name the topic "joint_angles_desired", with message type "JointState"
pub_joint_angles_desired = rospy.Publisher('/joint_angles_desired', JointState, queue_size=1)

# Create the message
joint_angles_desired_msg = JointState()
joint_angles_desired_msg.name = ['base_joint', 'shoulder_joint', 'elbow_joint', 'forearm_joint', 'wrist_joint', 'fingers_joint'];
joint_angles_desired_msg.position = [0., -np.pi/2., np.pi/2., 0., 0., 0.]      # upright neutral position

def main():
    # Actually launch a node called "inverse_kinematics"
    rospy.init_node('inverse_kinematics', anonymous=False)

    # Subscriber to the "target_xyz" topic
    sub_waypoint = rospy.Subscriber('/target_xyz', ME439WaypointXYZ, compute_joint_angles)

    # Spin() to keep the node from exiting
    rospy.spin()

# =============================================================================
# # Function to update the path to the waypoint based on the robot's current position
# =============================================================================
def compute_joint_angles(endpoint_msg_in):
#    print(endpoint_msg_in.xyz)
    # First compute the inverse kinematics for perfect endpoint positioning
    joint_angles_IK = compute_IK(endpoint_msg_in)
#    print(joint_angles_IK)

    # Then Limit the angle at each joint to its achievable range
    angles_limited = limit_joint_angles(joint_angles_IK)

    # Pack the joint angles and publish the message
    joint_angles_desired_msg.position = angles_limited
    joint_angles_desired_msg.header.stamp = rospy.Time.now()
    pub_joint_angles_desired.publish(joint_angles_desired_msg)

#    rospy.loginfo(joint_angles_desired_msg)

def compute_IK(endpoint_msg_in):
    xyz = endpoint_msg_in.xyz

    # Compute base rotation plus 2-link IK...
    # Assuming that the "forearm" and "fingers" do not rotate
    gamma3 = 0
    gamma5 = 0
    # ... and assume the wrist is controlled so the "fingers" point directly in the radial direction
    # (in order to hold the "marker" directly vertical)
    # THIS WOULD ALL CHANGE if the wrist is controlled in some other way.

    # ... and assume the wrist is controlled so the "fingers" point directly in the radial direction
    # (in order to hold the "marker" directly vertical)
    # THIS WOULD ALL CHANGE if the wrist is controlled in some other way.

    # First the out-of-plane rotation
    alpha0 = np.arctan2(xyz[1], xyz[0])

    # Now compute the radial and vertical distances spanned by the two links of the arm
    R = np.linalg.norm(xyz[0:2])   # Remember that this means "start at 0, stop BEFORE 2"
    dR = R - (r_12[0] + r_6end[0])        # subtract off the x of all the links that are not part of the 2-link kinematic solution. NOTE this only works because the X offsets are known to be positioned in the R direction.
    dz = xyz[2] - (r_01[2] + r_12[2] + r_6end[2])   # subtract off the Z of all the links that are not part of the 2-link kinematic solution

    # Now compute the "overall elevation" angle from the "shoulder" to the "wrist"
    # NOTE this assumes rotations about the +y axis (positive rotations push the wrist down)
    psi = -np.arctan2(dz, dR)  # use negative because of the positive-rotations-down convention.
    # Now the difference between the actual shoulder angle and the overall elevation angle
    # ... being aware that there are two solutions and we want the "elbow up" configuration.
    L1 = np.linalg.norm(r_23)  # vector magnitude of the link that spans from shoulder to elbow ("upper arm")
    L2 = np.linalg.norm(r_34)  # vector magnitude of the link that spans from elbow to wrist ("lower arm")
    H = np.linalg.norm(np.array((dz,dR))) # vector magnitude of the vector from shoulder to wrist. (H = hypotenuse)
    phi = np.arccos( (L2**2 - L1**2 - H**2)/(-2*L1*H) )  # arccos will always return a positive value.

    # Compute the "elbow up" solution for beta1
    beta1 = psi - phi   #  phi is always positive (from arccos function) so "-phi" is the elbow pose in a more negative position (elbow up for the +y axis rotations)

    # Compute the corresponding solution for beta2VL (VL = "virtual link" direct from joint 2 to joint 3 (elbow to wrist)
    # Use the ArcTangent (two quadrant)
    beta2VL = np.arctan2(H*np.sin(phi), H*np.cos(phi)-L1)
#    print(beta2VL)

    # Compute the offset in angle between  the VL (virtual link straight from joint 3 to joint 4) and the true link axis.
    # True link should be more positive by this amount.
    beta2_offset_from_VL = np.arctan2(r_34[2], r_34[0])

    # Real-world beta2, assuming +y axis rotations
    beta2 = beta2VL + beta2_offset_from_VL

    # Depending on the sign of positive rotations, give back the rotations.
    beta1 = beta1 * y_rotation_sign
    beta2 = beta2 * y_rotation_sign

    # Compute beta4 to cancel out beta1 and beta2 (works regardless of the sign)
    beta4 = -(beta1+beta2)

    return np.array([alpha0, beta1, beta2, gamma3, beta4, gamma5])

def limit_joint_angles(angles):
    angles_limited = angles

    # Clip (saturate) the angles at the achievable limits.
    angles_limited[0] = np.clip(angles_limited[0], np.min(rotlim_01), np.max(rotlim_01))
    angles_limited[1] = np.clip(angles_limited[1], np.min(rotlim_12), np.max(rotlim_12))
# special case for angle 2 below, skip it here:
# Reinstated 2019 with modified arms
    angles_limited[2] = np.clip(angles_limited[2], np.min(rotlim_23), np.max(rotlim_23))
    angles_limited[3] = np.clip(angles_limited[3], np.min(rotlim_34), np.max(rotlim_34))
    angles_limited[4] = np.clip(angles_limited[4], np.min(rotlim_45), np.max(rotlim_45))
    angles_limited[5] = np.clip(angles_limited[5], np.min(rotlim_56), np.max(rotlim_56))

## Removed 2019    -  No longer a palletizing robot.
#    # Also a version of beta2 called beta2WORLD that accounts for the fact that Link 2 is
#    # controlled by a parallelogram structure. This means beta2WORLD = beta2 + beta1.
#    # beta2WORLD is the one that should be sent to the Joint.
#    beta1 = angles_limited[1]
#    beta2 = angles_limited[2]
#    beta2WORLD = beta1 + beta2
#    # beta2WORLD has special limits that depend on beta1
#    # nuanced negative limit for beta2World are a mess. Use a reasonable limit instead:
#    beta2WORLD_min = np.min( rotlim_23 )
#    # Nuanced max limit is not as bad.
#    beta2WORLD_max = np.min( [np.max(rotlim_23) + (beta1-np.max(rotlim_12)), np.max(rotlim_23)] )
#    beta2WORLD_limited = np.clip(beta2WORLD, beta2WORLD_min, beta2WORLD_max)
#
#    beta2_limited = beta2WORLD - beta1
#    angles_limited[2] = beta2_limited
#
##    # Alternative: return a version that has "beta2WORLD" (limited version) in the [2] element
##    angles_limited[2] = beta2WORLD_limited

    return angles_limited

if __name__ == '__main__':
    try:
        main()
    except rospy.ROSInterruptException:
        traceback.print_exc()
        pass


from datetime import datetime
from ftw.builder import Builder
from ftw.builder import create
from ftw.bumblebee.interfaces import IBumblebeeDocument
from ftw.bumblebee.tests.helpers import asset as bumblebee_asset
from ftw.bumblebee.tests.helpers import DOCX_CHECKSUM
from ftw.bumblebee.tests.helpers import download_token_for
from ftw.testbrowser import browsing
from opengever.core.testing import OPENGEVER_FUNCTIONAL_BUMBLEBEE_LAYER
from opengever.testing import FunctionalTestCase
from plone.namedfile.file import NamedBlobFile
from plone.uuid.interfaces import IUUID
from Products.Archetypes.event import ObjectEditedEvent
from zope.event import notify
from zope.lifecycleevent import ObjectModifiedEvent
import transaction

class TestBumblebeeDownloadView(FunctionalTestCase):
    """Test the bumblebee_download view.

    Duplicates (and uses docuemnt builder in) methods from ftw.bumblebee tests
    since we still want the original behaviour as long as the document is not
    checked out.

    """
    layer = OPENGEVER_FUNCTIONAL_BUMBLEBEE_LAYER

    def setUp(self):
        super(TestBumblebeeDownloadView, self).setUp()

        self.repo, self.repo_folder = create(Builder('repository_tree'))
        self.dossier = create(Builder('dossier').within(self.repo_folder))

    @browsing
    def test_download_last_version_for_checked_out_docs(self, browser):
        content = bumblebee_asset('example.docx').bytes()
        document = create(Builder('document')
                          .attach_file_containing(
                              content,
                              u'example.docx')
                          .checked_out())

        document.update_file('foo',
                             content_type='text/plain',
                             filename=u'foo.txt')
        notify(ObjectModifiedEvent(document))
        transaction.commit()

        # checksum has not been updated
        self.assertEqual(
            DOCX_CHECKSUM, IBumblebeeDocument(document).get_checksum())

        # download first history version
        browser.open(view='bumblebee_download',
                     data={'token': download_token_for(document),
                           'uuid': IUUID(document),
                           'checksum': DOCX_CHECKSUM})
        self.assertEqual(content, browser.contents)
        self.assertEqual(
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            browser.headers.get('Content-Type'))

    @browsing
    def test_download_newest_version(self, browser):
        doc = create(Builder('document')
                     .attach_file_containing(u'The Content', name=u'file.pdf')
                     .within(self.dossier))

        browser.open(view='bumblebee_download',
                     data={'token': download_token_for(doc),
                           'uuid': IUUID(doc),
                           'checksum': IBumblebeeDocument(doc).get_checksum()})
        self.assertEqual('The Content', browser.contents)
        self.assertEqual('application/pdf',
                         browser.headers.get('Content-Type'))

    @browsing
    def test_parameters_required(self, browser):
        with browser.expect_http_error(reason='Bad Request'):
            browser.open(view='bumblebee_download')

    @browsing
    def test_download_version_after_a_change(self, browser):
        doc = create(Builder('document')
                     .attach_file_containing(u'text', name=u'file.pdf')
                     .within(self.dossier))
        initial_checksum = IBumblebeeDocument(doc).get_checksum()

        # We store these parameters as they were sent to bumblebee with /store
        params = {'token': download_token_for(doc),
                  'uuid': IUUID(doc),
                  'checksum': initial_checksum}

        # then the file changes, a new version is created.
        doc.file = NamedBlobFile(data='some other text', filename=u'foo.pdf')
        doc.setModificationDate(datetime.now())
        notify(ObjectEditedEvent(doc))
        transaction.commit()

        self.assertNotEqual(
            initial_checksum, IBumblebeeDocument(doc).get_checksum(),
            'Expected the checksum to have changed when object was updated.')

        # when accessing the previous version, the LRU may trigger a refresh
        # and may want to download the file again.
        browser.open(view='bumblebee_download', data=params)
        self.assertEqual('text', browser.contents)
        self.assertEqual('application/pdf',
                         browser.headers.get('Content-Type'))

    @browsing
    def test_notfound_when_we_have_no_version_with_this_checksum(self, browser):
        doc = create(Builder('document')
                     .attach_file_containing(u'The Content', name=u'file.pdf')
                     .within(self.dossier))

        with browser.expect_http_error(reason='Not Found'):
            browser.open(view='bumblebee_download',
                         data={'token': download_token_for(doc),
                               'uuid': IUUID(doc),
                               'checksum': 'wrong-checksum'})


import allure
import requests
import time
from allure_commons.types import AttachmentType
from selenium import webdriver
import pytest
from datetime import datetime
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
from model.urls import default_urls
from model.urls import urls_events

def test_presence_of_main_image(app):
    driver = app.driver
    default_urls_ = default_urls()
    urls = urls_events(default_urls_)
    errors = []

    for url in urls:
        driver.get(url)
        driver.implicitly_wait(4)
        articles = driver.find_elements_by_xpath('//a[@class = "item item-event js-masonryElement"]')
        urls_articles = []
        for href in articles:
            url_article = href.get_attribute('href')
            urls_articles.append(url_article)
        for one_article in urls_articles:
            driver.get(one_article)
            try:
                href_image = driver.find_element_by_xpath('//img[@class = "pageHeroImage"]').get_attribute('src')
                status = requests.get(href_image)
                assert status.status_code == 200
            except Exception as e:
                errors.append(one_article + ' without main image')
                continue
    assert not errors, "errors occured:\n{}".format("\n".join(errors))

def test_check_all_links_on_the_page_of_article(app):
    default_urls_ = default_urls()
    urls = urls_events(default_urls_)
    errors = []
    for url in urls:

        re = requests.get(url)
        soupe = BeautifulSoup(re.text, 'lxml')

        all_articles = soupe.find_all(class_='item item-event')
        for one_article in all_articles:
            req = requests.get(one_article.get('href'))
            soup = BeautifulSoup(req.text, 'lxml')
            to = soup.find(class_='content')
            try:
                for link in to.findAll('a'):
                    href_link = link.get('href')
                    try:
                        if href_link == '#':
                            continue
                        elif 'upload' in href_link:
                            continue
                        elif href_link == "":
                            continue
                        else:
                            r = requests.get(href_link)
                            assert r.status_code == 200
                    except Exception as e:
                        errors.append('Incorrect link --- ' + href_link + ' from page ' + one_article.get('href'))
            except:
                continue
    assert not errors, "errors occured:\n{}".format("\n".join(errors))


'''
Created on Apr 7, 2015

@author: Helena Zecevic
'''

from Evaluator import tokenizer
from Evaluator.util import check_validity
from Evaluator.postfix import to_postfix
from Evaluator.evaluate import evaluate
from Evaluator.expression_validity import check_expression

if __name__ == '__main__':
    expression = input('Enter expression for evaluation (x - Exit): ')
    while expression != 'x':
        if not check_validity(expression):
            print('Expression must consist only of numbers and operands.')
        else:
            expression = tokenizer.tokenize(expression)
            if not check_expression(expression):
                print('Expression is incorrect.')
            else:
                postfix_expr = to_postfix(expression)
                print('Result: ' + str(evaluate(postfix_expr)))
        expression = input('Enter expression for evaluation (x - Exit): ')