import numpy as np
"""
Implements the Gillespie algorithm
Inspiration for implementation from course material
and exercises.
"""

def gillespie(S, M, h, c, t_max, max_reactions):

    N = S.shape[0]
    V = S.shape[1]

    T = np.zeros(max_reactions)
    X = np.zeros((max_reactions, N))

    current_state = M
    current_time = 0.0

    for idx in range(0, max_reactions):
        T[idx] = current_time
        X[idx, :] = current_state

        # Both species are extinct if sum of state is 0
        # if sum(current_state)==0:
        #   print("""
        #   Both species went extinct at time {0} and state was {1}
        #   """.format(current_time, current_state))

        # hazards for current state and hazard rates
        rates = h(current_state, c)

        # sample time
        lambd = sum(rates)
        t_next = np.random.exponential(scale=1/lambd)

        # updating current time
        current_time += t_next
        if current_time > t_max:
            break  # stop if timeis up

        reaction_index = np.random.choice(a=V, replace=True, p=rates / lambd)

        current_state = current_state + S[:, reaction_index].flatten()

    T = T[0:idx]
    X = X[0:idx, :]

    return T, X


from xai.brain.wordbase.nouns._heresy import _HERESY

#calss header
class _HERESIES(_HERESY, ):
	def __init__(self,):
		_HERESY.__init__(self)
		self.name = "HERESIES"
		self.specie = 'nouns'
		self.basic = "heresy"
		self.jsondata = {}


########################################################################################
#
# Common functions and classes
#
#    Copyright (C) 2009 Louis Caron
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
########################################################################################

class LegalException(Exception):
    "class representing an exception handled by the tool"
    def __init__(self, value, errornumber=0):
        # convert the value parameter into a string for print
        if isinstance(value, str):
            self.value = value
        else:
            self.value = repr(value)
        # record the errornumber to return to the OS
        self.errornumber = errornumber
    def __str__(self):
        "convert the exception into a string"
        return self.value


from django.shortcuts import render
import cv2
import numpy as np
from tensorflow.keras.models import load_model
from .models import Img
from .forms import ImageForm

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Create your views here.
def get_cropped_image_if_2_eyes(image_path):
    img = cv2.imread(image_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        roi_color = img[y:y+h, x:x+w]
        return roi_color

class_labels = ['Cristiano Ronaldo','Zlatan Ibrahimovic','Lionel Messi','Mbappe','Neymar']

path = r'C:\Users\flyas\Desktop\HarshitJain\21 Days\21_Days_Harshit_Jain\Project\my_model'

model = load_model(path)

def predicting(img_path):
    image = get_cropped_image_if_2_eyes(img_path)
    image = cv2.resize(image, (300,300))
    image = image / 255
    pre = np.argmax(model.predict(np.array([image])))
    return class_labels[pre]

def index(request):
    Img.objects.all().delete()
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            img_obj = form.instance
            try:
                result = 'You Look Like : ' + predicting('.'+str(img_obj.image.url))
                status = 'Match'
            except:
                result = "Input Image Can not be processed please change the image"
                status = "No Match"
            return render(request, 'predict/index.html', {'form': form, 'img_obj': img_obj, 'result': result, 'status':status})
    else:
        form = ImageForm()
    return render(request, 'predict/index.html',{'form': form})


import pygame
import random

green=(50,100,50)
black=(0,0,0)
red=(255,0,0)
white=(255,255,255)
blockSize=60
width=1200
height=900

def program():
    x = 600
    y = 600
    counts=1
    points=0
    xHoe=random.randrange(blockSize,width,blockSize)
    yHoe=random.randrange(blockSize,height,blockSize)
    lead_x=0
    lead_y=0
    h=0
    w=0
    fps=7
    snakeList=[]
    snakeLenght=1
    dtc="up"
    icon=pygame.image.load('images/iconn.png')
    macHead= pygame.image.load('images/macHead1.jpg')
    corpse=pygame.image.load('images/corpse.jpg')
    wallpaper=pygame.image.load('images/wallpaper.jpg')
    endwall=pygame.image.load('images/endgame.jpg')

    hoes=[]
    for i in range(15):
        hoes.append(pygame.image.load('images/hoe'+str(i)+'.jpg'))

    hoe = random.choice(hoes)

    def hoeAppear():
        screen.blit(hoe,[xHoe,yHoe,blockSize,blockSize] )

    def snake(snakeList):
        if dtc=="left":
            head=pygame.transform.rotate(macHead,90)
        if dtc=="right":
            head=pygame.transform.rotate(macHead,270)
        if dtc == "up":
            head = pygame.transform.rotate(macHead, 0)
        if dtc=="down":
            head=pygame.transform.rotate(macHead,180)

        screen.blit(head,(snakeList[-1][0],snakeList[-1][1]))
        for part in snakeList[:-1]:
            screen.blit(corpse,[part[0], part[1], blockSize, blockSize])

    screen = pygame.display.set_mode((width, height))

    pygame.font.init()
    font = pygame.font.SysFont("monotypecorsiva",70)
    font1=pygame.font.SysFont(None,30)
    def message(text, color,xcor,ycor):
        mtext = font.render(text,True,color)
        screen.blit(mtext, [xcor, ycor])
    def score(text, color,xcor,ycor):
        mtext = font1.render(text,True,color)
        screen.blit(mtext, [xcor,ycor])

    pygame.display.set_caption('Easy Hoes Catcher')
    pygame.display.set_icon(icon)
    clock = pygame.time.Clock()

    running=True
    notOver=True
    startingWin = True

    while running:
      for event in pygame.event.get():
        if event.type==pygame.QUIT:
          running=False
        if startingWin==True:
            # StartScreen
            screen.blit(wallpaper,[-100,-20])
            s = pygame.Surface((800, 300))
            s.set_alpha(128)
            s.fill(white)
            screen.blit(s, (200, 400))
            message("Easy Hoes Catcher", black, 400, 420)
            message("Catch as many hoes as possible!", black, 210, 520)
            message("Press 'w' to start", black, 400, 620)
            pygame.display.update()
            if event.type ==pygame.KEYDOWN:
                if event.key==pygame.K_w:
                    startingWin=False

        elif notOver==True:
            if event.type ==pygame.KEYDOWN:
                if event.key==pygame.K_a:
                    if h==0 or h==2:
                        dtc = "left"
                        lead_x=-blockSize
                        lead_y = 0
                        h=2
                        w=0
                elif event.key==pygame.K_d:
                    if h == 0 or h == 1:
                        dtc = "right"
                        lead_x=+blockSize
                        lead_y = 0
                        h=1
                        w=0
                elif event.key==pygame.K_w:
                    if w == 0 or w == 1:
                        dtc = "up"
                        lead_y=-blockSize
                        lead_x=0
                        w=1
                        h=0
                elif event.key==pygame.K_s:
                    if w == 0 or w == 2:
                        dtc = "down"
                        lead_y=+blockSize
                        lead_x=0
                        w=2
                        h=0

      x+=lead_x
      y+=lead_y

        #EXIT
      if x<=-15 or x>=width or y<=-15 or y>=height:
        screen.blit(endwall,[-40,0])
        s.fill(black)
        s.set_alpha(100)
        screen.blit(s, (180, 350))
        message("Game over noob", white,350,400)
        score("Hoes: "+str(points), black,20,20)
        message("Press 'w' to play again", white, 300, 500)
        pygame.display.update()
        notOver=False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                notOver=True
                x=600
                y=600
                snakeList = []
                snakeLenght = 1
                lead_x=0
                lead_y=0
                points=0

        #displaying
      if notOver==True and startingWin==False:
        screen.fill(black)
        snakeHead=[]
        snakeHead.append(x)
        snakeHead.append(y)
        snakeList.append(snakeHead)
        if len(snakeList)>snakeLenght:
            del snakeList[0]

        snake(snakeList)
        for part in snakeList[:-1]:
            if part==snakeHead:
                notOver = False

        hoeAppear()

        score("Hoes: " +str(points), red,20,20)
        pygame.display.update()
        if x==xHoe and y==yHoe:
            snakeLenght+=1
            #fps+=0.5
            points+=1
            counts+=1
            hoe=random.choice(hoes)
            xHoe=random.randrange(blockSize,width,blockSize)
            yHoe=random.randrange(blockSize,height,blockSize)
            for part in snakeList[:-1]:
                if part[0]==xHoe and part[1]==yHoe:
                    xHoe = random.randrange(blockSize, width, blockSize)
                    yHoe = random.randrange(blockSize, height, blockSize)

        clock.tick(fps)
    pygame.quit()

program()


import socket
import sys
import getopt

def getopts():
    try:
        (opts, args) = getopt.getopt(sys.argv[1:], 'p:m:t', [])
        return opts
    except getopt.GetoptError as err:
        print('Error: ' + str(err))
        exit()

(option, value) = getopt.getopt(sys.argv[1:], "a:p:c:h:")
for (opt, val) in option:
    if opt == "-a":
        host = val
    if opt == "-p":
        port = int(val)
    if opt == "-c":
        text = val
    if opt == "-h":
        hash_type = val

def main(port, host, text, hash_type):

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error:
        print('Failed to create socket')
        sys.exit()

    s.connect((host, port))

    to_hash = text + "|" + hash_type
    s.send(to_hash.encode())

    response = s.recv(1024)
    print(response.decode())

    s.close()

if __name__ == '__main__':
    main(port, host, text, hash_type)


# Use open to open file "foo.txt" for reading
f = open("foo.txt", "r")
# Print all the lines in the file
lines = f.read()
print(lines)
# Close the file
f.close()

# Use open to open file "bar.txt" for writing
file = open("bar.txt", "w")
# Use the write() method to write three lines to the file
with open("bar.txt", "w") as file:
    file.write("Line 1 is here.")
    file.write("line 2 is here.")
    file.write("Line 3 is here.")
# Close the file
file.close()


def build_profile(first, last, **user_info):
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_profile('lan', 'chunyuan',
                             location='beijing',
                             field='OPS',
                             age = 36)
print(user_profile)


from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
import os

UPLOAD_FOLDER = '/uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

wsgy_app = app.wsgi_app

@app.route('/', methods=['GET', 'POST'])
def hello():
    if request.method == 'POST':
        file = request.files['file']
        file.save(os.path.join('uploads', file.filename))
        return render_template('index.html', message='success')
    return render_template('index.html', message='error')

if __name__ == '__main__':
    import os
    HOST = os.environ.get('SERVER_HOST', 'localhost')
    try:
        PORT = int(os.environ.get('SERVER_PORT', 5555))
    except ValueError:
        PORT = 5555

    app.run()


"""
Provides functionality for reading and changing the tabbin files of Rigaku Crysalis (former Oxford)
"""

__author__ = "Konstantin Glazyrin"
__copyright__ = "Creative Commons"

__all__ = ["CrysalisTabbinController"]

try:
    from crysalis.imports import *
except ImportError:
    from ..imports import *

try:
    from crysalis.common.logger import *
except ImportError:
    from ..common.logger import *

try:
    from crysalis.common.config import *
except ImportError:
    from ..common.config import *

from .keys import *

class TabbinAbstract(Tester):
    """
    Class controlling abstract functionality, like data conversion
    """

    intlist = (np.int, np.int8, np.int16, np.int32, np.int64)
    uintlist = (np.uint, np.uint8, np.uint16, np.uint32, np.uint64)
    floatlist = (np.float, np.float32, np.double)

    def __init__(self, debug_mode=DEBUG, show_init=None):
        Tester.__init__(self, debug_mode=debug_mode, show_init=show_init)

    def _get_value_from_binary(self, nptype, value):
        """
        Returns a numpy type value from a binary string
        :param nptype:
        :param value:
        :return:
        """
        res = None
        try:
            if nptype in self.intlist:
                value = nptype(int.from_bytes(value, byteorder='little', signed=True))
            elif nptype in self.uintlist:
                value = nptype(int.from_bytes(value, byteorder='little', signed=False))
            elif nptype in self.floatlist:
                if len(value) == 8:
                    value = nptype(struct.unpack("d", value)[0])
                else:
                    value = nptype(struct.unpack("f", value)[0])
            res = value
        except ValueError:
            self.error("Cannot convert data ({}) to np.type ({})".format(value, nptype))
        return res

    def _get_pxdistance(self, x1, y1, x2, y2):
        """
        Returns the distance between the coordinates
        :param x1:
        :param y1:
        :param x2:
        :param y2:
        :return:
        """
        x1, x2, y1, y2 = float(x1), float(x2), float(y1), float(y2)
        return math.sqrt(math.pow(x2-x1, 2)+math.pow(y2-y1, 2))

    def _get_binary_from_value(self, nptype, value):
        """
        Returns a binary representation of the value
        :param ntype:
        :param value:
        :return:
        """
        res = None

        value_size = nptype(0.).itemsize

        if nptype in self.intlist or nptype in self.uintlist:
            res = int(value).to_bytes(length=value_size, byteorder="little")
        elif nptype in self.floatlist:
            if value_size == 8:
                res = bytearray(struct.pack("d", value))
            elif value_size == 4:
                res = bytearray(struct.pack("f", value))
            else:
                self.error("Could not pack the value ({}) of type ({})".format(value, nptype))
        return res

class TabbinPoint(TabbinAbstract):
    """
    Class controlling the information for the points of the tabbin file
    Reading and writing is conducted directly into the file data reference
    """
    GROUP_CHANGED = 0

    STRUCT_SIZE = 168

    # offsets going after the header in decimal, first number - start, numpy value - size
    OFFSETS_LOCAL = {
        OFFSET_DX: [0, np.float64],
        OFFSET_DY: [8, np.float64],
        OFFSET_DZ: [16, np.float64],
        OFFSET_DLENGTH: [24, np.float64],
        OFFSET_LINTENSITY: [32, np.uint32],
                                                    # OFFSET_IFILTER_OBSOLETE: [36, np.uint16],
                                                    # OFFSET_ISYMSETTING_OBSOLETE: [38, np.uint16],
                                                    # OFFSET_ISWSMODE_OBSOLETE: [40, np.uint16],
                                                    # OFFSET_IPHTSCANTYPE: [42, np.uint16],
        OFFSET_IXPIX: [44, np.uint16],
        OFFSET_IYPIX: [46, np.uint16],
        OFFSET_FCENTROIDX: [48, np.float32],
        OFFSET_FCENTROIDY: [52, np.float32],
                                                    # OFFSET_DAPHTSTARTANGLESRAD: [56, [np.float32, np.float32, np.float32, np.float32, np.float32, np.float32,]],
                                                    # OFFSET_DAPHTENDANGLESRAD: [104, [np.float32, np.float32, np.float32, np.float32, np.float32, np.float32,]]
                                                    # OFFSET_LCALCULATIONSTATUS: [152, np.uint32],
        OFFSET_UTWINGROUPFLAGS: [156, np.uint32],
        OFFSET_DWRUNFRAME1BASED: [160, np.int16],
                                                    #OFFSET_DWFRAMESTAMP_OR_LO_RINGNUMBER_HI_FRAMEID: [164, np.uint32],
        OFFSET_GROUPKEY: [None, np.int8]            # dummy, no real sence, but convinient
    }

    def __init__(self, npoint, file_contents, offset_start, offset_group, debug_mode=None, show_init=False):
        TabbinAbstract.__init__(self, debug_mode=debug_mode, show_init=show_init)

        self.init_variables(npoint, file_contents, offset_start, offset_group)

    def init_variables(self, npoint, file_contents, offset_start, offset_group):
        """
        Initializes the variables
        :return:
        """
        self.file_contents = file_contents

        self.offset_start = offset_start
        self.offset_group = offset_group

        # current point number
        self._number = npoint

        # initialize offsets
        self.fill_offsets()

    def fill_offsets(self):
        """
        Initializes the offsets for the given file and point
        :return:
        """

        self.offsets = {}

        for k in self.OFFSETS_LOCAL.keys():
            if k != OFFSET_GROUPKEY:
                offset = self.offset_start + self.OFFSETS_LOCAL[k][0]
                self.offsets.setdefault(k, offset)
            else:
                self.offsets.setdefault(k, self.offset_group)

        if self.is_debug_level() and self.number <2:
            self.debug(self.offsets)

    def _read_values(self, key):
        """
        Reads a value from the data and returns it in a given type
        :param key:
        :return:
        """
        res = None

        # get type of the value
        offset = self.offsets[key]
        value_type = self.OFFSETS_LOCAL[key][1]
        value_size = value_type(0).itemsize

        raw_value = self.file_contents[offset:offset + value_size]
        res = self._get_value_from_binary(value_type, raw_value)

        if self.is_debug_level():
            self.debug("Reading key ({}); type ({}); raw ({}) value ({})".format(key, value_type, raw_value, res))

        return res

    def _write_values(self, key, value):
        """
        Reads a value from the data and returns it in a given type
        :param key:
        :return:
        """
        res = None

        # get type of the value
        offset = self.offsets[key]
        value_type = self.OFFSETS_LOCAL[key][1]
        value_size = value_type(0).itemsize

        if self.is_debug_level():
            self.debug("Preparing a value key ({}) type ({}) value ({}) offset ({}) raw ({})".format(key, value_type, value, offset, self._get_binary_from_value(value_type, value)))

        raw_value = self._get_binary_from_value(value_type, value)

        self.debug(raw_value)
        self.file_contents[offset:offset+value_size] = raw_value
        res = raw_value

        if self.is_debug_level():
            self.debug("Writing key ({}); type ({}); raw ({}) value ({})".format(key, value_type, raw_value, value))
            tdata = [" {}".format(hex(int(raw_value[i])).upper()) for i in range(value_type(0).itemsize)]
            self.debug(tdata)

        return res

    @property
    def number(self):
        return self._number

    @number.setter
    def number(self, value):
        self._number = value

    @property
    def dx(self):
        key = OFFSET_DX
        v = self._read_values(key)
        if v is not None:
            v = v
        return v

    @property
    def dy(self):
        key = OFFSET_DY
        v = self._read_values(key)
        if v is not None:
            v = v
        return v

    @property
    def dz(self):
        key = OFFSET_DZ
        v = self._read_values(key)
        if v is not None:
            v = v
        return v

    @property
    def dlength(self):
        key = OFFSET_DLENGTH
        v = self._read_values(key)
        if v is not None:
            v = v
        return v

    @property
    def px(self):
        key = OFFSET_IXPIX
        v = self._read_values(key)
        if v is not None:
            v = v+1
        return v

    @property
    def py(self):
        key = OFFSET_IYPIX
        v = self._read_values(key)
        if v is not None:
            v = v + 1
        return v

    @property
    def intensity(self):
        key = OFFSET_LINTENSITY
        v = self._read_values(key)
        if v is not None:
            v = v + 1
        return v

    @property
    def frame(self):
        key = OFFSET_DWRUNFRAME1BASED
        v = self._read_values(key)
        if v is not None:
            v = v
        return v

    @property
    def group(self):
        key = OFFSET_GROUPKEY
        v = self._read_values(key)
        if v is not None:
            v = v + 1
        return v

    @group.setter
    def group(self, value):
        key = OFFSET_GROUPKEY
        try:
            # values start at 0
            value = value - 1

            if value < 1:
                value = 0
            elif value > 16:
                value = 15
            else:
                self._write_values(key, value)
                self.GROUP_CHANGED += 1
        except ValueError:
            self.error("Error on conversion the group value ({})".format(value))

    def setGroup(self, value):
        self.debug("Setting the {} {} {} ".format(self.number, self.px, self.py))
        self.group = value
        return value

    def resetGroupChanged(self):
        """
        Resets the class related counter
        :return:
        """
        self.GROUP_CHANGED = 0

    def getGroupChanged(self):
        """
        Returns the group change counter
        :return:
        """
        return self.GROUP_CHANGED

    def __str__(self):
        """
        Returns the text representation for the class
        :return:
        """
        return "{}(number={}, intensity={}, group={}, px={}, py={})".format(self.__class__.__name__, self.number, self.intensity, self.group, self.px, self.py)

class CrysalisTabbinController(TabbinAbstract):
    """
        Class controlling the tabbin file functionality of the Crysalis library
    """

    # global, known offsets
    OFFSETS = {
        OFFSET_POINT_NUM: [0, np.uint32],
        OFFSET_IVERSION_TABBIN_HEADER : [10, np.uint16],

        OFFSET_GROUP_LIST: None,   # variable

        # fixed offsets
        OFFSET_POINT_LIST: 312,  # 0x138 - fixed
        OFFSET_POINT_LISTNEXT: 168,
        OFFSET_GROUPSTART: 806,  # fixed with respect to the OFFSET_GROUP_LIST start of the group value for a point
        OFFSET_GROUPNEXT: 32,  # repetition of the group value for the point
    }

    # key to look for in order to find the groups
    OFFSET_GROUPSEARCHKEY = b'\x2B\x58\x47\x47'

    # VERSION test
    MIN_VERSION = 2
    MAX_VERSION = 16

    def __init__(self, debug_mode=None, show_init=None):
        Tester.__init__(self, debug_mode=debug_mode, show_init=show_init)

        # variables - globals
        self.num_points = 0
        self.version = None
        self.points = []
        self.file_contents = None

        # points xy
        self.points_xy = {}
        self.points_xy_ref = {}

        # points for the x and y direction
        self.points_framey = {}
        self.points_framey_ref = {}
        self.points_framex = {}
        self.points_framex_ref = {}

        # 2D representation of the detector
        self.nparray = None

        # array to use for testing neighboring points
        self.points_addskip = []

    def __str__(self):
        """
        Returns the text representation for the class
        :return:
        """
        return "{}(num_points={}, version={}, points={})".format(self.__class__.__name__,  self.num_points,self.version,  self.points)

    def read_file(self, path, binning=1.):
        """
        Reads the TABBIN
        :param path:
        :return:
        """
        test = self.test_existing_file(path)
        self.debug("Trying to read the file ({}). File exists ({})".format(path, test))

        # test for the file
        if not test:
            self.error("File ({}) does not exist".format(path))
            return

        # test the file format
        test_format = self.test_tabbin_format(path)
        if not test_format:
            return

        # read all the points
        self.read_points(binning=binning)

    def read_points(self, binning=1.):
        """
        Fill the data points with values
        :return:
        """
        # read the data - piece by piece
        maxx, maxy = 0, 0

        if self.num_points > 0:
            po = self.OFFSETS[OFFSET_POINT_LIST]
            pi = self.OFFSETS[OFFSET_POINT_LISTNEXT]
            of_group = self.OFFSETS[OFFSET_GROUP_LIST]
            of_group_pi = self.OFFSETS[OFFSET_GROUPNEXT]

            # get dimensions - this is fast
            for npoint in range(self.num_points):
                # get point data 168 byte - tabbin_header_tag
                offset_start = po + npoint * pi
                offset_stop = po + (npoint + 1) * pi
                offset_group = of_group + npoint * of_group_pi

                npoint_data = self.file_contents[offset_start:offset_stop]
                point = TabbinPoint(npoint, self.file_contents, offset_start, offset_group)

                # calculate statistics
                tpx = point.px
                tpy = point.py

                if tpx > maxx:
                    maxx = tpx
                if tpy > maxy:
                    maxy = tpy

            self.info("Max image dimensions are: ({}:{})".format(maxx, maxy))

            # represent the detector
            self.nparray = np.empty([maxx+1, maxy+1], dtype=list)

            # get real data
            for npoint in range(self.num_points):
                # get point data 168 byte - tabbin_header_tag
                offset_start = po + npoint * pi
                offset_stop = po + (npoint + 1) * pi
                offset_group = of_group + npoint * of_group_pi

                npoint_data = self.file_contents[offset_start:offset_stop]

                tdata = [" {}".format(hex(int(npoint_data[i])).upper()) for i in range(8)]

                # pass the reference to the full data, save the new object
                point = TabbinPoint(npoint, self.file_contents, offset_start, offset_group)

                # test - for the header + data
                if self.is_debug_level():
                    if npoint < 5:
                        self.debug("\t ({:02}) Data is ({})".format(npoint, npoint_data))
                        self.debug("\t ({:02}) First element is ({})".format(npoint, tdata))

                        tgroup = hex(int(self.file_contents[offset_group])).upper()
                        self.debug("\t ({:02}) Group number is ({}:{})".format(
                            npoint, offset_group, tgroup
                        ))

                        # read data from the tabbin class
                        self.debug(point)

                # append data
                self.points.append(point)
                self.debug("Offset stop is ({})".format(offset_stop))

                # calculate statistics
                tpx = point.px
                tpy = point.py
                tframe = point.frame

                # binning if needed
                tbpx = int(binning*round(float(tpx)/binning))
                tbpy = int(binning*round(float(tpy)/binning))

                if tbpx > self.nparray.shape[0] or tbpy > self.nparray.shape[1]:
                    self.error("Some size is wrong ( x: {}) or ( y: {})".format(tbpx, tbpy))
                    continue

                txy = "{} {}".format(tbpx, tbpy)
                if not txy in self.points_xy.keys():
                    self.points_xy.setdefault(txy, 1)
                else:
                    self.points_xy[txy] += 1

                # Y projection
                tframey = "{}+{}".format(tframe, tbpy)
                if not tframey in self.points_framey.keys():
                    self.points_framey.setdefault(tframey, 1)
                    self.points_framey_ref.setdefault(tframey, [])
                    self.points_framey_ref[tframey].append(point)
                else:
                    self.points_framey[tframey] += 1
                    self.points_framey_ref[tframey].append(point)

                # X projection
                tframex = "{}+{}".format(tframe, tbpx)
                if not tframex in self.points_framex.keys():
                    self.points_framex.setdefault(tframex, 1)
                    self.points_framex_ref.setdefault(tframex, [])
                    self.points_framex_ref[tframex].append(point)
                else:
                    self.points_framex[tframex] += 1
                    self.points_framex_ref[tframex].append(point)

                # creating a reference layout for the pixels
                if self.nparray[tbpx, tbpy] is None:
                    self.nparray[tbpx, tbpy] = list([point])
                    self.debug("Adding # {} {} {} ".format(point.number, tpx, tpy))
                else:
                    self.nparray[tbpx, tbpy].append(point)
                    self.debug("Adding multiple {} {} {} ".format(point.number, tpx, tpy))

                # add a reference for stats
                self.points_xy_ref.setdefault(point, [tpx, tpy, tbpx, tbpy])

    def mod_list_pixelmultiframe(self, path, group=None, radius=20., frame_threshold=7):
        """
        Returns a list of references where frames have pixels at the same spot
        :return:
        """
        # filter the list and flatten it
        tstart = time.time()
        radius = int(radius)

        # list of list with non zero values
        tlist_main = list(filter(lambda l: l is not None and len(l)> 1, list(self.nparray.flatten())))
        tlist_short = [sublist[0] for sublist in tlist_main]
        if len(tlist_short)>0:
            tlist_short[0].resetGroupChanged()

        tprep = time.time()
        self.info("Short list of the points with the same pixel coordinates withing binning ({})".format(len(tlist_short)))

        times = []
        tellist = []

        # filter diamonds appearing in different frames
        for el in tlist_short:
            tprep = time.time()
            elposx, elposy = self.points_xy_ref[el][0], self.points_xy_ref[el][1]
            el.setGroup(group)

            nxi, nxa = elposx-radius, elposx+radius
            nyi, nya = elposy-radius, elposy+radius

            if nxi < 0:
                nxi = 0

            if nyi < 0:
                nyi = 0

            self.debug("Origin X {} {} ({}:{}) Y {} ({}:{})".format(el.number, elposx, nxi, nxa, elposy, nyi, nya))

            tellist = list(filter(lambda l: l is not None, list(self.nparray[nxi:nxa, nyi:nya].flatten())))
            [item.setGroup(group) for sublist in tellist for item in sublist]

            times.append(time.time()-tprep)

        # filter diamonds creating stripes either in horizontal or vertical direction
        for vs in self.points_framey_ref.values():
            if( len(vs) > frame_threshold):
                for el in vs:
                    el.setGroup(group)

        for vs in self.points_framex_ref.values():
            if( len(vs) > frame_threshold):
                for el in vs:
                    el.setGroup(group)

        if len(tlist_short) > 0:
            self.info("Group was changed ({}) times".format(tlist_short[0].getGroupChanged()))

        self.debug("Converted {}".format(["--- {} {} {}".format(item.number, item.px, item.py) for sublist in tellist for item in sublist]))

        tstop = time.time()
        # write the file with the group
        with open(path, "wb") as fh:
            fh.write(self.file_contents)
        tfull = time.time()

        self.info("Times stop-start ({}) final-start ({}) write-stop ({})".format(tstop - tstart, tfull - tstart,
                                                                                tfull - tstop))

    def test_tabbin_format(self, path):
        """
        Tests the file for the format (first 4 bytes should provide the number of points, version header should have meaningful info)
        :param path:
        :return:
        """
        res = False

        self.debug("Testing the file ({}) format".format(path))

        with open(path, "rb") as fh:
            # get full file contents, find the mentioning of the group header, starting from the end of the file // typical file size is small
            file_contents = fh.read()

            # select the data piece by piece
            key = OFFSET_POINT_NUM
            offset = self.OFFSETS[key][0]
            num_files_type = self.OFFSETS[key][1]
            size = num_files_type(0).itemsize
            num_points = file_contents[offset:offset+size]

            # read version number
            key = OFFSET_IVERSION_TABBIN_HEADER
            offset = self.OFFSETS[key][0]
            version_type = self.OFFSETS[key][1]
            size = version_type(0).itemsize
            version = file_contents[offset:offset+size]

            try:
                if len(version) == 0 or len(num_points) == 0:
                    raise ValueError

                num_points = self._get_value_from_binary(num_files_type, num_points)
                version = self._get_value_from_binary(version_type, version)

                if version is None or num_points is None:
                    raise ValueError

                if not is_tabbin_version_allowed(version):
                    raise ValueError

                self.num_points = num_points
                self.version = version
                key = OFFSET_GROUP_LIST
                self.OFFSETS[key] = self.OFFSETS[OFFSET_POINT_LIST]+self.OFFSETS[OFFSET_POINT_LISTNEXT]*num_points+self.OFFSETS[OFFSET_GROUPSTART]

                self.info(
                    "The tabbin file ({}) has version ({}) and contains ({}) points. Group position reference is ({})".format(
                        path, version, num_points, self.OFFSETS[key]))

                # store a copy of the file contents - to modify and write
                self.file_contents = bytearray(file_contents)

                res = True
            except ValueError:
                self.error("The file format is wrong. Num. files ({}); Version ({}); Group position ({})".format(num_points, version, self.OFFSETS[OFFSET_GROUP_LIST]))

        return res

    def _get_value_from_binary(self, nptype, value):
        """
        Returns a numpy type value from a binary string
        :param nptype:
        :param value:
        :return:
        """
        res = None
        try:
            if nptype in self.intlist:
                value = nptype(int.from_bytes(value, byteorder='little', signed=True))
            elif nptype in self.uintlist:
                value = nptype(int.from_bytes(value, byteorder='little', signed=False))
            elif nptype in self.floatlist:
                value = nptype(float.fromhex(value))
            res = value
        except ValueError:
            self.error("Cannot convert data ({}) to np.type ({})".format(value, nptype))
        return res


class Solution(object):
    def findRestaurant(self, list1, list2):
        """
        :type list1: List[str]
        :type list2: List[str]
        :rtype: List[str]
        """
        m = {}

        for i in range(len(list1)):
            m[list1[i]] = (i, False)

        for i in range(len(list2)):
            if list2[i] in m:
                m[list2[i]] = (abs(m[list2[i]][0] + i), True)

        possible = [(k,v) for k,v in m.items() if v[1]]
        return [k for k,v in possible if v[0] == min(possible, key=lambda x: x[1][0])[1][0]]


#coding:utf-8

"""
���ݿ����ӹ���
"""

__author__ = "liangxiaokai@21cn.com"
__version__ = "1.0"
__date__ = "2011/04/14"
__copyright__ = "Copyright (c) 2011"
__license__ = "Python"

from connect import *

from sqlalchemy import Table,Column,func
from sqlalchemy.types import  *
from sqlalchemy.ext.declarative import declarative_base

tab_test = Table("test", metadata,
                 Column("id", Integer, primary_key=True,),
                 Column("name",String(255)),
                 Column("age",Integer),
                 Column("desc",TEXT),
                 )

class TTest(TableObject):
    def __init__(self):
        TableObject.__init__(self)

    #def __repr__(self):
    #    return "brithday=%s,id=%d,mobile=%s,nick=%s,state=%d,imei=%s,imsi=%s,password=%s,create_time=%d,nick=%s,sign=%s,address=%s, sex=%d,channel=%d" % \
    #            (self.brithday,self.id,self.mobile,self.nick,self.state,self.imei,self.imsi,self.password,self.create_time,self.nick,self.sign,self.address, self.sex,self.channel)

mapper_test = Mapper(TTest,tab_test)

if __name__=="__main__":
    pass


import count_mutant
from os import walk
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
from matplotlib.font_manager import FontProperties
import sys

def buildScatters(projects):
    indexState = 5

    colors_array = cm.rainbow(np.linspace(0, 1, len(projects)))
    markers = ['o', 's', '+', 'x', 'D', '>', '*', '^', '<', '1', ]

    prefix = "original/per_class/"

    z = 0
    scatters = []

    for project in projects:
        xaxis = []
        yaxis = []
        colors = []
        z += 1
        testClasses = []
        for (dirpath, dirnames, filenames) in walk(prefix + project):
            if filenames:
                for filename in filenames:
                    total , killed = count_mutant.countForTestClass(prefix + project + "/" + filename)
                    if total > 0:#skipping abstract test class that can not kill
                        xaxis.append(total)
                        yaxis.append(float(float(killed) / float(total) if total > 0 else 0) * 100)
                        colors.append(colors_array[projects.index(project)])
                        testClasses.append(filename)
        scatters.append((xaxis, yaxis, colors, project, markers[projects.index(project)], testClasses))
    return scatters

def run(projects=["javapoet", "mybatis", "traccar", "stream-lib", "mustache.java", "twilio-java", "jsoup", "protostuff",
                  "logback", "retrofit"]):
    scatters = buildScatters(projects)

    fig = plt.figure()
    ax = plt.gca()
    max_xaxis = -1
    for (xaxis, yaxis, colors, project, marker, testClasses) in scatters:
        ax.scatter(xaxis, yaxis, c=colors, s=60, label=project, marker=marker)
        if max(xaxis) > max_xaxis :
            max_xaxis  = max(xaxis)

    plt.xlabel('covered (absolute nb)')
    plt.ylabel('score (%)')
    plt.axis([-50, max_xaxis + 50, -10, 110])
    fontP = FontProperties()
    fontP.set_size('small')
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.1),
               ncol=5, fancybox=True, shadow=True, prop=fontP)
    plt.title("test suites\' power map")
    fig.savefig("original/power_map_all.pdf", bbox_inches='tight')
    fig.savefig("original/power_map_all.jpeg", bbox_inches='tight')

if __name__ == '__main__':
    if len(sys.argv) > 1:
        projects = sys.argv[1:]
        run(projects=projects)
    else:
        run()


'''CORREÇÃO DO EXERCÍCIO'''

salario = float(input('Digite o Sálario do Funcionario €: '))
if salario <= 1250:
    salario_novo = (salario * 15 / 100)
else:
    salario = (salario * 10 / 100)
print('Seu novo Sálario é : {}'.format(salario))


#! /usr/bin/env python
# coding: utf-8

'''
Author: xiezhw3@163.com
@contact: xiezhw3@163.com
@version: $Id$
Last modified: 2015-12-25
FileName: json_encoder.py
Description: 针对 mongodb 的 ObjectID 进行特殊处理
'''

import json
from bson import ObjectId

class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        return json.JSONEncoder.default(self, o)


from DiffTab import *

class RowDiffTab(DiffTab):
    def init_diff_table_header(self, sheet_name):
        self.diff_table.setHorizontalHeaderLabels((u"改动", u"行号"))

    def insert_data_into_diff_table(self, sheet_name):
        differ = self.forward_diffs[sheet_name]
        sheet_diff = differ.sheet_diff
        row_diff_count = 0
        if sheet_diff:
            for row, row_diff in enumerate(sheet_diff):
                if is_whole_row_deleted_and_inserted(differ, row):
                    row_diff_count += 2
                elif is_whole_row_only_deleted(differ, row):
                    row_diff_count += 1
                elif is_whole_row_only_inserted(differ, row):
                    row_diff_count += 1
            self.diff_table.setRowCount(row_diff_count)
            row_diff_count = 0
            for row, row_diff in enumerate(sheet_diff):
                if is_whole_row_deleted_and_inserted(differ, row):
                    self.diff_table.setItem(row_diff_count, 0, QTableWidgetItem(u"删除"))
                    self.diff_table.setItem(row_diff_count, 1,
                                            QTableWidgetItem(str(self.file1_diff_row_to_data_row[row] + 1)))
                    self.diff_table.setItem(row_diff_count + 1, 0, QTableWidgetItem(u"插入"))
                    self.diff_table.setItem(row_diff_count + 1, 1,
                                            QTableWidgetItem(str(self.file2_diff_row_to_data_row[row] + 1)))
                    row_diff_count += 2
                elif is_whole_row_only_inserted(differ, row):
                    self.diff_table.setItem(row_diff_count, 0, QTableWidgetItem(u"插入"))
                    self.diff_table.setItem(row_diff_count, 1,
                                            QTableWidgetItem(str(self.file2_diff_row_to_data_row[row] + 1)))
                    row_diff_count += 1
                elif is_whole_row_only_deleted(differ, row):
                    self.diff_table.setItem(row_diff_count, 0, QTableWidgetItem(u"删除"))
                    self.diff_table.setItem(row_diff_count, 1,
                                            QTableWidgetItem(str(self.file1_diff_row_to_data_row[row] + 1)))
                    row_diff_count += 1
        else:
            self.diff_table.setRowCount(0)

    def diff_cell_clicked(self, row, col):
        self.mw.colorize_data_table(self.sheet_combo.currentText())
        flag = self.diff_table.item(row, 0).text()
        row_label = self.diff_table.item(row, 1).text()
        file1_row = self.get_row_index_by_label(self.file1_data_table, row_label)
        file2_row = self.get_row_index_by_label(self.file2_data_table, row_label)
        col_count = self.file1_data_table.columnCount()
        gray = QColor(200, 200, 200)
        if flag == u"删除":
            for col in range(col_count):
                self.file1_data_table.item(file1_row, col).setBackground(gray)
                self.file2_data_table.item(file1_row, col).setBackground(gray)
            self.file1_data_table.setCurrentCell(file1_row, 0)
            self.file2_data_table.setCurrentCell(file1_row, 0)
        elif flag == u"插入":
            for col in range(col_count):
                self.file1_data_table.item(file2_row, col).setBackground(gray)
                self.file2_data_table.item(file2_row, col).setBackground(gray)
            self.file1_data_table.setCurrentCell(file2_row, 0)
            self.file2_data_table.setCurrentCell(file2_row, 0)

    def sheet_combo_change(self):
        sheet_name = self.sheet_combo.currentText()
        super().sheet_combo_change()
        self.insert_data_into_diff_table(sheet_name)


# https://www.hackerrank.com/challenges/sock-merchant/problem?h_r=next-challenge&h_v=zen

# !/bin/python3

import math
import os
import random
import re
import sys

# Complete the sockMerchant function below.
def sockMerchant(n, ar):
    freq = {}
    for e in ar:
        if e in freq.keys():
            freq[e] += 1
        else:
            freq[e] = 1

    pairs = 0
    for _, value in freq.items():
        pairs += value // 2

    return pairs

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    ar = list(map(int, input().rstrip().split()))

    result = sockMerchant(n, ar)

    fptr.write(str(result) + '\n')

    fptr.close()


import urllib.request
import json

mutantCount = 0
mutantNames = []

### User dictionary
ids = {
	"76561197986252179":"fender",
	"steam64id":"name1",
	"steam64id":"name2"
	}

### Calc how many users online and create list
def mutantCalc(steam_id):
	if isOnline(steam_id) == True:
		global mutantNames
		mutantNames.append(ids[steam_id])
		global mutantCount
		mutantCount = mutantCount + 1

### Check steam id for steam status (steamcheck.py - https://gist.github.com/mg393/3119259)
def isOnline(steam_id): #Steam ID is the 64bit one
    api_key = "YOUR_STEAM_API_KEY"
    req_headers = {'User-Agent': 'Python script'}
    url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=" + api_key + "&steamids=" + steam_id + "&format=json"
    req = urllib.request.Request(url, data=None, headers=req_headers, origin_req_host=None)
    response = urllib.request.urlopen(req)
    content = response.read()
    data = json.loads(content.decode('utf8'))
    if data["response"]["players"][0]["personastate"] == 0 or data["response"]["players"][0]["personastate"] == 2 or data["response"]["players"][0]["personastate"] == 3: #0 = offline, 2 = busy, 3 = away
        #print(steam_id,"  false")
        return False
    elif data["response"]["players"][0]["personastate"] == 1: #1 = online
        #print(steam_id,"  true")
        return True
    else:
        print("Error: Unknown persona state")
        input("Press enter to continue...")
        sys.exit()

### Check dictionary keys (steam ids) for steam status
for key in ids:
	mutantCalc(key)

### Convert list to string with JSON linebreaks
mutants = ""
for x in mutantNames:
	mutants = mutants + "   " + x + "\n"

### Json Post
if mutantCount >= 5:
	data = {"content":"You have " + str(mutantCount) + " mutants online.\n" + mutants}
	json_data = json.dumps(data).encode('utf8')
	headers = {'Content-type': 'application/json','User-Agent': 'Python script'}
	url = "PUT YOUR WEBHOOK URL HERE"
	req = urllib.request.Request(url, data=json_data, method='POST', headers=headers, origin_req_host=None)
	response = urllib.request.urlopen(req)


from discord.ext import commands
import datetime

class Authentication(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None
        self.is_protection_on = False

    @commands.command()
    @commands.dm_only()
    async def rule_acknowledged(self, ctx):
        if self.is_protection_on:
            ctx.send("Unfortunately, the moderators of 22/7 server has turned on the server protection protocol, "
                     "new members may not join at this time. Please wait until the restriction is lifted. ")
        else:
            user_id = ctx.author.id

            nananijiguild = self.bot.get_guild(336277820684763148)
            if nananijiguild.get_member(user_id) is None:
                await ctx.send("Unsupported operation.")
                return

            new_member_role = nananijiguild.get_role(663581221967757313)
            if new_member_role not in nananijiguild.get_member(user_id).roles:
                await ctx.send("You are already a member!")
                return

            await nananijiguild.get_member(user_id).remove_roles(new_member_role,
                                                                 reason="R.E.I.N.A. bot action. Executed at {} UTC".format(
                                                                     datetime.datetime.utcnow()))
            await ctx.send(
                "You now should have access to the rest of the server. If not, please DM one of the Moderators. ")

    @commands.command()
    @commands.has_any_role('Moderators')
    async def protect(self, ctx):
        """
        Do mysterious things.
        Note: this is an on/off switch command.
        """
        self.is_protection_on = not self.is_protection_on
        ctx.send("Protection is {}".format(self.is_protection_on))


import dolfin as _dolfin

def boundary_grid_from_fenics_mesh(fenics_mesh):
    """
    Return a boundary grid from a FEniCS Mesh.
    """
    from bempp.api import grid_from_element_data

    boundary_mesh = _dolfin.BoundaryMesh(fenics_mesh, "exterior", False)
    bm_coords = boundary_mesh.coordinates()
    bm_cells = boundary_mesh.cells()
    bempp_boundary_grid = grid_from_element_data(
        bm_coords.transpose(), bm_cells.transpose()
    )
    return bempp_boundary_grid

def fenics_to_bempp_trace_data(fenics_space):
    """
    Returns tuple (space,trace_matrix)
    """
    family, degree = fenics_space_info(fenics_space)

    if family == "Lagrange":
        if degree == 1:
            return p1_trace(fenics_space)
        else:
            raise NotImplementedError()
    else:
        raise NotImplementedError()

def fenics_space_info(fenics_space):
    """
    Returns tuple (family,degree) containing information about a FEniCS space
    """
    element = fenics_space.ufl_element()
    family = element.family()
    degree = element.degree()
    return (family, degree)

class FenicsOperator(object):
    """Wraps a FEniCS Operator into a BEM++ operator."""

    def __init__(self, fenics_weak_form):
        """Construct an operator from a weak form in FEniCS."""
        self._fenics_weak_form = fenics_weak_form
        self._sparse_mat = None

    def weak_form(self):
        """Return the weak form."""
        from bempp.api.assembly.discrete_boundary_operator import (
            SparseDiscreteBoundaryOperator,
        )
        from dolfin import as_backend_type, assemble, parameters
        from scipy.sparse import csr_matrix

        if self._sparse_mat is not None:
            return SparseDiscreteBoundaryOperator(self._sparse_mat)

        backend = parameters["linear_algebra_backend"]
        if backend != "PETSc":
            raise ValueError("Only the PETSc linear algebra backend is supported.")
        mat = as_backend_type(assemble(self._fenics_weak_form)).mat()
        (indptr, indices, data) = mat.getValuesCSR()
        self._sparse_mat = csr_matrix((data, indices, indptr), shape=mat.size)

        return SparseDiscreteBoundaryOperator(self._sparse_mat)

# pylint: disable=too-many-locals
def p1_trace(fenics_space):
    """
    Return the P1 trace operator.

    This function returns a pair (space, trace_matrix),
    where space is a Bempp space object and trace_matrix is the corresponding
    matrix that maps the coefficients of a FEniCS function to its boundary
    trace coefficients in the corresponding Bempp space.

    """

    import dolfin
    import bempp.api
    from scipy.sparse import coo_matrix
    import numpy as np

    family, degree = fenics_space_info(fenics_space)
    if not (family == "Lagrange" and degree == 1):
        raise ValueError("fenics_space must be a p1 Lagrange space")

    mesh = fenics_space.mesh()

    boundary_mesh = dolfin.BoundaryMesh(mesh, "exterior", False)
    bm_nodes = boundary_mesh.entity_map(0).array().astype(np.int64)
    bm_coords = boundary_mesh.coordinates()
    bm_cells = boundary_mesh.cells()
    bempp_boundary_grid = bempp.api.Grid(bm_coords.transpose(), bm_cells.transpose())

    # First get trace space
    space = bempp.api.function_space(bempp_boundary_grid, "P", 1)

    # Now FEniCS vertices to boundary dofs
    b_vertices_from_vertices = coo_matrix(
        (np.ones(len(bm_nodes)), (np.arange(len(bm_nodes)), bm_nodes)),
        shape=(len(bm_nodes), mesh.num_vertices()),
        dtype="float64",
    ).tocsc()

    # Finally FEniCS dofs to vertices.
    vertices_from_fenics_dofs = coo_matrix(
        (
            np.ones(mesh.num_vertices()),
            (dolfin.dof_to_vertex_map(fenics_space), np.arange(mesh.num_vertices())),
        ),
        shape=(mesh.num_vertices(), mesh.num_vertices()),
        dtype="float64",
    ).tocsc()

    # Get trace matrix by multiplication
    trace_matrix = b_vertices_from_vertices @ vertices_from_fenics_dofs

    # Now return everything
    return space, trace_matrix


#!/usr/bin/env python
from EPPs.common import StepEPP
from pyclarity_lims.entities import Protocol

class AssignNextStep(StepEPP):
    _use_load_config = False  # prevent the loading of the config file
    """
    This script checks the KAPA Next Step udf and assigns the input sample to the next step in the protocol or to remove from workflow
    """

    def _run(self):
        # obtain the actions of the step then creates a StepActions entity for the current step
        actions = self.process.step.actions

        # obtain the next actions in the step then creates a list of dict for next_actions for the step
        next_actions = actions.next_actions

        # prepare the step_object variable used for inputs that move to the next step
        current_step = self.process.step.configuration  # configuration gives the ProtocolStep entity.
        protocol = Protocol(self.process.lims, uri='/'.join(self.process.step.configuration.uri.split('/')[:-2]))
        steps = protocol.steps  # a list of all the ProtocolSteps in protocol
        next_step_object = steps[steps.index(current_step) + 1]

        for next_action in next_actions:

            # if KAPA Next Step is KAPA Make Normalised Libraries then assign to next step in the protocol (assumes next step is KAPA Make Normalised Libraries)

            if next_action['artifact'].udf.get('KAPA Next Step') == 'KAPA Make Normalised Libraries':
                # update the next action to "next step" with the step
                next_action['action'] = 'nextstep'
                next_action['step'] = next_step_object

            elif next_action['artifact'].udf.get('KAPA Next Step') == 'Make and Read qPCR Quant':
                #update the next action to re-work at Make and Read qPCR Quant
                next_action['action'] = 'rework'
                #find one instance of the qPCR step that the artifacts has been through
                qpcr_process = self.lims.get_processes(type='Make and Read qPCR Quant EG 1.0 ST',
                                                                     inputartifactlimsid=next_action['artifact'].id)[0]

                next_action['rework-step'] =qpcr_process.step

            # all other artifacts should be route to remove from workflow as the submitted sample will reassigned elsewhere
            else:
                next_action['action'] = 'remove'

        # put the next step actions into LIMS
        actions.put()

if __name__ == '__main__':
    AssignNextStep().run()


from comar.service import *

serviceType = "server"
serviceDesc = "Xinetd"
serviceDefault = "off"

def start():
    ret = run("/usr/sbin/xinetd -pidfile /var/run/xinetd.pid -stayalive -reuse")
    if ret == 0:
        notify("System.Service.changed", "started")
    else:
        fail("Unable to start service")

def stop():
    ret = run("/sbin/start-stop-daemon --stop --pidfile /var/run/xinetd.pid")
    if ret == 0:
        notify("System.Service.changed", "stopped")
    else:
        fail("Unable to stop service")

def reload():
    run("/usr/bin/killall -HUP xinetd")

def status():
    return checkDaemon("/var/run/xinetd.pid")


'''
给定N个元素，找到所需的最小交换数，以便最大元素在开头，
最小元素在最后，但仅允许相邻元素交换。
'''
def minSwaps(arr):
    n = len(arr)
    maxx, minn, l, r = -1, arr[0], 0, 0
    for i in range(n):
        if arr[i]>maxx:
            maxx = arr[i]
            l = i
        if arr[i]<=minn:
            minn = arr[i]
            r = i
    if r<l:
        print(l+(n-r-2))
    else:
        print(l+(n-r-1))


from diamond import *
import diamond.collector
import diamond.convertor

import disk

class DiskSpaceCollector(diamond.collector.Collector):
    """
    Uses /proc/mounts and os.statvfs() to get disk space usage
    """
    def collect(self):
        labels = disk.get_disk_labels()
        for key, info in disk.get_file_systems().iteritems():
            if labels.has_key(info.device):
                name = labels[info.device]
            else:
                name = info.mount_point.replace('/', '_')
                name = 'root' if name == '_' else name

            data = os.statvfs(info.mount_point)
            block_size = data.f_bsize

            blocks_total, blocks_free, blocks_avail = data.f_blocks, data.f_bfree, data.f_bavail
            inodes_total, inodes_free, inodes_avail = data.f_files, data.f_ffree, data.f_favail

            metric_name = '%s.%s_used' % (name, self.config['byte_unit'])
            metric_value = float(block_size) * float(blocks_total - blocks_free)
            metric_value = diamond.convertor.binary.convert(value = metric_value, oldUnit = 'byte', newUnit = self.config['byte_unit'])
            self.publish(metric_name, metric_value, 2)

            metric_name = '%s.%s_free' % (name, self.config['byte_unit'])
            metric_value = float(block_size) * float(blocks_free)
            metric_value = diamond.convertor.binary.convert(value = metric_value, oldUnit = 'byte', newUnit = self.config['byte_unit'])
            self.publish(metric_name, metric_value, 2)

            metric_name = '%s.%s_avail' % (name, self.config['byte_unit'])
            metric_value = float(block_size) * float(blocks_avail)
            metric_value = diamond.convertor.binary.convert(value = metric_value, oldUnit = 'byte', newUnit = self.config['byte_unit'])
            self.publish(metric_name, metric_value, 2)

            self.publish('%s.inodes_used'  % name, inodes_total - inodes_free)
            self.publish('%s.inodes_free'  % name, inodes_free)
            self.publish('%s.inodes_avail' % name, inodes_avail)


import logging
import websockets
import asyncio
import json
import sys
import traceback

from .gateway import get_gateway_url, Wetway
from .rest import InternetBenis
from .basics import OP, API_BASE
from .bares import User, Guild, Message, Channel, Member, DMChannel

logger = logging.getLogger(__name__)

class Dicker:
    '''
    Dicker - A dickord client

    It receives one keyword argument, `token`, self-explanatory.
    '''
    def __init__(self, **kwargs):
        self.token = kwargs.get('token')
        if self.token is None:
            self.user_pass = kwargs.get('user_pass')

        self.session_id = None
        self.http = InternetBenis(self.token)
        self.gateway = None

        self._hb_seq = None
        self._hb_task = None

        self.loop = None
        self.ws = None

        # cache objects
        self._guilds = {}
        self._channels = {}
        self._users = {}
        self._messages = {}
        self._dms = {}

        self._seq = 0
        self.fails = 0
        self.in_reconnection = False

        # Register events discord sends to me
        self.handlers = {
            'READY': [self.do_ready],
            'RESUMED': [self.resumed],
            'PRESENCE_UPDATE': [],
            'TYPING_START': [],

            'GUILD_CREATE': [self.guild_create],
            'GUILD_UPDATE': [self.guild_update],
            'GUILD_DELETE': [self.guild_delete],

            #'GUILD_MEMBER_ADD': [self.guild_member_add],
            #'GUILD_MEMBER_REMOVE': [self.guild_member_remove],
            #'GUILD_MEMBER_UPDATE': [self.guild_member_update],

            'MESSAGE_CREATE': [self.message_create],
            'MESSAGE_UPDATE': [self.message_update],
            'MESSAGE_DELETE': [self.message_delete],
            #'MESSAGE_DELETE_BULK': [self.message_delete_bulk],

            #'MESSAGE_REACTION_ADD': [self.m_reaction_add],
            #'MESSAGE_REACTION_REMOVE': [self.m_reaction_remove],

            #'CHANNEL_CREATE': [self.channel_create],
            #'CHANNEL_UPDATE': [self.channel_update],
            #'CHANNEL_DELETE': [self.channel_delete],

            #'GUILD_BAN_ADD': [self.guild_ban_add],
            #'GUILD_BAN_REMOVE': [self.guild_ban_remove],
            #'GUILD_INTEGRATIONS_UPDATE': [self.guild_integrations_update],

            #'VOICE_STATE_UPDATE': [self.voice.state_update],
        }

    def get_channel(self, channel_id):
        '''Get a channel from the client's cache'''
        _channel = self._channels.get(channel_id)
        if _channel is None:
            _channel = self._dms.get(channel_id)

        return _channel

    def get_guild(self, guild_id):
        '''Get a guild from the client's cache'''
        return self._guilds.get(guild_id)

    def get_message(self, message_id):
        '''Get a message from the client's cache'''
        return self._messages.get(message_id)

    def get_user(self, user_id):
        '''Get a user from the client's cache'''
        return self._users.get(user_id)

    def sensor(self, event):
        '''Add a event listener'''
        logger.debug(f'Add handler for {event}')

        def wrapped(function):
            if event not in self.handlers:
                self.handlers[event] = []
            self.handlers[event].append(function)

        return wrapped

    def get_identify(self):
        return {
            'op': OP['IDENTIFY'],
            'd': {
                "token": self.token,
                "properties": {
                    "$os": "linux",
                    "$browser": "dickord (Luna#4677)",
                    "$device": "dickord (Luna#4677)",
                    "$referrer": "",
                    "$referring_domain": ""
                },
                "compress": False,
                "large_threshold": 100,
                "shard": [0, 1]
            }
        }

    def get_resume(self):
        return {
            'op': OP["RESUME"],
            'd': {
                'token': self.token,
                'session_id': self.session_id,
                'seq': self._seq,
            }
        }

    async def resumed(self, payload):
        logger.info("Resumed with success")
        self.in_reconnection = False

    async def do_ready(self, payload):
        '''Populate the client's cache to have an initial state'''
        logger.info(f"Received {len(str(payload))} bytes from READY event, populating")

        self.session_id = payload['session_id']
        logger.debug(f"session_id: {self.session_id}")

        self.user = User(payload['user'])

        for _guild in payload['guilds']:
            if _guild['unavailable']:
                self._guilds[_guild['id']] = None

        for _dm in payload['private_channels']:
            self._dms[_dm['id']] = DMChannel(self, _dm)

    async def guild_create(self, payload):
        # payload is a guild object
        self._guilds[payload['id']] = Guild(self, payload, True)

        for channel in payload['channels']:
            self._channels[channel['id']] = Channel(self, channel)

    async def guild_delete(self, payload):
        removed = payload.get('unavailable', True)
        if removed:
            del self._guilds[payload['id']]
        else:
            self._guilds[payload['id']] = None

    async def guild_update(self, payload):
        try:
            g = self._guilds[payload['id']]
            g._update(payload)
        except KeyError:
            logger.info('Received a malformed GUILD_UPDATE, old_id didn\'t exist')
            return

    async def message_create(self, message):
        self._messages[message.id] = message

    async def message_update(self, payload):
        try:
            m = self._messages[payload['id']]
            m._update(payload)
        except KeyError:
            logger.info('Received a malformed MESSAGE_UPDATE, old_id didn\'t exist')
            return

    async def message_delete(self, payload):
        try:
            self._messages.pop(payload['id'])
        except KeyError:
            pass

    async def any_event(self, t, payload):
        logger.debug(f'Event: {t}')

    async def do_event(self, t, handler, payload):
        if t == 'MESSAGE_CREATE':
            msg = Message(self, payload)
            task = self.loop.create_task(handler(msg))
            return

        task = self.loop.create_task(handler(payload))

    async def select_ass(self, game_name):
        '''Sends a OP 3 Status Update over the websocket'''
        await self.ws.send(json.dumps({
            'op': OP['STATUS_UPDATE'],
            'd': {
                'idle_since': None,
                'game': {
                    'name': game_name,
                }
            }
        }))

    async def process_nut(self, _msg):
        '''Process a message sent by discord over the websocket'''
        msg = json.loads(str(_msg))
        op = msg['op']
        d = msg['d']
        evt_name = msg.get('t', None)
        s = msg.get('s', None)

        if op == OP['HELLO']:
            # create our heartbeat task
            self._hb_task = self.loop.create_task(self.gateway.heartbeat_handler(d))

            logger.debug(f'seq {self._seq} {self.in_reconnection}')

            if not self.in_reconnection:
                logger.info("Sending IDENTIFY")
                await self.ws.send(json.dumps(self.get_identify()))
            else:
                logger.info("Sending RESUME packet")
                await self.ws.send(json.dumps(self.get_resume()))

        elif op == OP['HEARTBEAT_ACK']:
            logger.debug('Received ACK')
            self._hb_expecting_ack = False

        elif op == OP['DISPATCH']:
            # a dispatched event from discord
            self._seq = s or self._seq

            if evt_name in self.handlers:
                await self.any_event(evt_name, d)
                for handler in self.handlers[evt_name]:
                    await self.do_event(evt_name, handler, d)
            else:
                logger.info(f"Unhandled event {evt_name}")

        elif op == OP['INVALID_SESSION']:
            logger.info("Session invalidated")
            if d:
                # wait a bit, then resume
                await asyncio.sleep(2)
                logger.info("Sending RESUME packet after an INVALID_SESSION")
                await self.ws.send(json.dumps(self.get_resume()))
            else:
                logger.info("Sending IDENTIFY after an INVALID_SESSION")
                # how 2 invalidate my session: part 1
                self.session_id = None
                await self.ws.send(json.dumps(self.get_identify()))

        elif op == OP['RECONNECT']:
            # Discord wants us to reconnect.... ok
            logger.info("Received RECONNECT, closing and reconnecting...")
            self.ws.close()
            self._hb_task.close()
            self.init(False, True)
        else:
            logger.info(f"Unhandled OP {op}")

    async def init(self, in_reconnection=False, ordered_reconnect=False):
        self.ws_url = get_gateway_url()

        if 'discordapp' in API_BASE and (self.token is None):
            logger.error('We can\'t automate /auth/login calls.')
            return False
        else:
            # we need to get our token
            if self.token is None:
                self.token = self.http.auth_token(self.user_pass)

        if self.fails > 9:
            logger.error("We tried 9 times, I give up.")
            return

        if self.fails > 3:
            logger.info("We tried more than 3 times to connect to the gateway, getting new URL")
            self.ws_url = get_gateway_url(True)

        if in_reconnection:
            logger.info("We are reconnecting to the gateway...")
            self.in_reconnection = True
            self.ws.close(4168)
        else:
            logger.info("We are connecting to the gateway...")

        if ordered_reconnect:
            logger.info("We are being forced to reconnect...")

        try:
            websocket = await websockets.connect(self.ws_url)
            self.ws = websocket
            self.gateway = Wetway(self)
        except Exception as err:
            logger.error('[init] Error while connecting to the gateway', exc_info=True)
            self.fails += 1
            await self.init(in_reconnection, ordered_reconnect)
            return

        while True:
            try:
                recv_message = await websocket.recv()
                await self.process_nut(recv_message)
            except websockets.exceptions.ConnectionClosed as err:
                logger.error(f"Websocket connection closed {err.code}, {err.reason!r}")
                if err.code in [4000, 4009]:
                    # reconnect
                    logger.info("Reconnecting...")
                    self._hb_task.cancel()
                    await self.init(True)
                elif err.code in [4001, 4002, 4005]:
                    logger.error('[ws] Discord didn\'t like what we did...')
                elif err.code == 4003:
                    logger.error('[ws] Sending a payload without identification')
                elif err.code == 4004:
                    logger.error('[ws] Authentication failed')
                elif err.code == 4007:
                    logger.error(f'[ws] Error resuming, sent invalid seq = {self._seq}, restarting')
                    self._hb_task.cancel()
                    self.init(False)

                elif err.code == 4008:
                    logger.error('[ws] Ratelimited.')
                elif err.code == 4010:
                    logger.error('[ws] Invalid shard')
                elif err.code == 4011:
                    logger.error('[ws] Sharding required')

                raise err
        logger.warning("[ws] Exited")

    def _cleanup(self):
        logger.debug("Cleaning up")
        self._hb_task.cancel()

    async def logout(self):
        logger.info('Logging out')
        self.ws.close()
        sys.exit(0)

    def infinite_insert(self, loop=None):
        '''Does the magic.'''
        if loop is None:
            loop = asyncio.get_event_loop()

        try:
            self.loop = loop
            loop.run_until_complete(self.init())
            return True, ""
        except KeyboardInterrupt:
            loop.run_until_complete(self.logout())
            return True, ""
        except Exception as err:
            print(traceback.format_exc())
            try:
                self.ws.close()
            except:
                pass
            return False, err


#
# Copyright (c) 2019 by:
# Kristoffer Paulsson <kristoffer.paulsson@talenten.se>
# This file is distributed under the terms of the MIT license.
#
"""Random dummy data generators."""
import os
import io
import random
import string
import datetime

from .lipsum import (
    SURNAMES,
    MALE_NAMES,
    FEMALE_NAMES,
    LIPSUM_LINES,
    LIPSUM_WORDS,
    CHURCHES,
)

from ..policy import PersonData, MinistryData, ChurchData

def filesize(file):
    """Real file filesize reader."""
    if isinstance(file, io.IOBase):
        return os.fstat(file.fileno()).st_size
    else:
        return os.stat(file).st_size

def random_person_entity_data(num=1):
    """Generate random entity data for number of person entities."""
    identities = []
    for i in range(num):
        sex = random.choices(
            ["man", "woman", "undefined"], [0.495, 0.495, 0.01], k=1
        )[0]
        if sex == "man":
            names = random.choices(MALE_NAMES, k=random.randrange(2, 5))
        elif sex == "woman":
            names = random.choices(FEMALE_NAMES, k=random.randrange(2, 5))
        else:
            names = random.choices(
                MALE_NAMES + FEMALE_NAMES, k=random.randrange(2, 5)
            )

        born = datetime.date.today() - datetime.timedelta(
            days=random.randrange(4748, 29220)
        )

        entity = PersonData()
        entity.given_name = names[0]
        entity.names = names
        entity.family_name = random.choices(SURNAMES, k=1)[0].capitalize()
        entity.sex = sex
        entity.born = born
        identities.append(entity)

    return identities

def random_ministry_entity_data(num=1):
    """Generate random entity data for number of ministry entities."""
    ministries = []
    for i in range(num):
        ministry = random.choices(LIPSUM_WORDS, k=random.randrange(3, 7))
        vision = random.choices(LIPSUM_WORDS, k=random.randrange(20, 25))
        founded = datetime.date.today() - datetime.timedelta(
            days=random.randrange(365, 29220)
        )

        entity = MinistryData()
        entity.ministry = " ".join(ministry).capitalize()
        entity.vision = " ".join(vision).capitalize()
        entity.founded = founded
        ministries.append(entity)

    return ministries

def random_church_entity_data(num=1):
    """Generate random entity data for number of church entities."""
    churches = []
    for i in range(num):
        church = random.choices(CHURCHES, k=1)[0]
        founded = datetime.date.today() - datetime.timedelta(
            days=random.randrange(730, 29220)
        )

        entity = ChurchData()
        entity.founded = founded
        entity.city = church[0]
        entity.region = church[1]
        entity.country = church[2]
        churches.append(entity)

    return churches

def generate_data():
    """Random lipsum data generator."""
    return (
        "\n".join(random.choices(LIPSUM_LINES, k=random.randrange(1, 10)))
    ).encode("utf-8")

def generate_filename(postfix=".txt"):
    """Random file name generator."""
    return (
        "".join(
            random.choices(
                string.ascii_lowercase + string.digits,
                k=random.randrange(5, 10),
            )
        )
        + postfix
    )