from transformers import pipeline
import torch
from typing import Union

def get_device(ignore_mps: bool = False, cuda_as_int: bool = False) -> Union[str, int]:
    """
    Determines and returns a PyTorch device name.

    :param ignore_mps: Manual deactivate MPS
    :param cuda_as_int: Return cuda as device number
    :return: device name as str
    """
    # Define device (either GPU, M1/2, or CPU)
    if torch.cuda.is_available():
        #print('Device: using CUDA')
        return "cuda" if not cuda_as_int else 0
    elif torch.backends.mps.is_available() and not ignore_mps:
        print('Device: using MPS')
        return "mps"
    else:
        print('Device: using CPU :(')
        return "cpu"

def mclass(text_prompt, top_k=3, topics = ['Mask creation', 'Object  detection', 'Inpainting', 'Segmentation', 'Upscaling', 'Creating an image from another one', 'Generating:q an image from text'], model='MoritzLaurer/mDeBERTa-v3-base-xnli-multilingual-nli-2mil7'):
    # Get the device (CPU, GPU, Apple M1/2 aka MPS)
    # Ignoring MPS because this particular model contains some int64 ops that are not supported by the MPS backend yet :(
    # see https://github.com/pytorch/pytorch/issues/80784
    device = get_device(ignore_mps=True, cuda_as_int=True)

    # Define a german hypothesis template and the potential candidates for entailment/contradiction
    template_de = 'The topic is {}'

    # Pipeline abstraction from hugging face
    pipe = pipeline(task='zero-shot-classification', model=model, tokenizer=model, device=device)

    # Run pipeline with a test case
    prediction = pipe(text_prompt, topics, hypothesis_template=template_de)

    # Top 3 topics as predicted in zero-shot regime
    #print(f'Zero-shot prediction for: \n {prediction["sequence"]}')
    top_3 = zip(prediction['labels'][0:top_k], prediction['scores'][0:top_k])
    return top_3


from .models import CourseRequest
from ..utils import Session_Maker

from falcon import HTTPBadRequest

class db:

    def __init__(self, Api_Session):
        self.Api_Session = Api_Session

    # Creates course request
    def create_course_request(self, title, account_id):
        sm = Session_Maker(self.Api_Session)
        with sm as session:
            try:
                cr = CourseRequest(title=title, account_id=account_id)
                session.add(cr)
                session.commit()
            except Exception:
                msg = "Could not insert into database."
                raise HTTPBadRequest("DB Exception", msg)

    # Return set of requested course titles
    def get_requested_courses(self):
        sm = Session_Maker(self.Api_Session)
        with sm as session:
            rows = session.query(CourseRequest).all()
            requested_courses = list({row.title for row in rows})

            return requested_courses


import cv2
import time
import HandTrackingModule as htm
import math
import numpy as np
# import volume packages Pycaw, ctypes,comtypes
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume

# setup webcam

# detect hands
detector = htm.handDetector()
cap = cv2.VideoCapture(0)
x4, y4 = 0,0
x8, y8 = 0,0
distance = 0
# colors constants   rgb   bgr
red = (0,0,255)
green  = (0,255,0)
blue = (255,0,0)
def findDistance(A,B):
    AB =math.sqrt((A[0]-B[0])**2 + (A[1]-B[1])**2)
    return AB

# initialize the volume
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
    IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
vol = volume.GetVolumeRange()

print(vol)
while True:
    success, img = cap.read()
    img = detector.findHands(img)
    lm = detector.findPosition(img, draw =False)
    if len(lm) != 0:
        x4 = int(lm[4][1])
        y4 = int(lm[4][2])
        x8 = int(lm[8][1])
        y8 = int(lm[8][2])
    A=(x4,y4)
    B = (x8,y8)
    cx, cy = (x4+x8) //2, (y4+y8) //2
    C = (cx, cy)
    cv2.line(img,A,B,(0,0,255), 4, )
    # Draw a circle on A and B
    cv2.circle(img, A, 15, red, cv2.FILLED)
    cv2.circle(img, B, 15, red, cv2.FILLED)

    # draw circle on the center
    cv2.circle(img, C, 15, red, cv2.FILLED )
    cv2.imshow("HAND GESTURE VOLUME CONTROL", img)
    # Distance
    distance = findDistance(A,B)
    # convert the distance to the volume range | hand range 20 - 290 | volume range -63,5  0
    handRange =[20, 290]
    volRange = [vol[0],vol[1]]
    volu = np.interp(distance,handRange,volRange )
    # Change the volume level
    print(findDistance(A, B), volu)
    volume.SetMasterVolumeLevel(volu, None)
    cv2.waitKey(1)

Gesture Volume Hand Controle/VolumeControl.py


# -*- coding: utf-8 -*-
"""
Tests for vector_tile/decoder.py
"""

import unittest

import mapbox_vector_tile

class BaseTestCase(unittest.TestCase):
	def test_decoder(self):
		vector_tile = '\x1aI\n\x05water\x12\x1a\x08\x01\x12\x06\x00\x00\x01\x01\x02\x02\x18\x03"\x0c\t\x00\x80@\x1a\x00\x01\x02\x00\x00\x02\x0f\x1a\x03foo\x1a\x03baz\x1a\x03uid"\x05\n\x03bar"\x05\n\x03foo"\x02 {(\x80 x\x02'
		self.assertEqual(mapbox_vector_tile.decode(vector_tile),
				{
					'water': [{
						'geometry': [[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]],
						'properties': {
							'foo': 'bar',
							'baz': 'foo',
							'uid': 123
						},
						'id': 1
					}]
				}
			)


import random

#pretty prints the matrix
def pretty_print(mat1, r):
	for i in range(r):
		for j in range(r):

			print(str(round(mat1[i][j],2))+"\t", end ='')
		print()

#swaps the matrices by rows given the matrix and the 2 rows
def swap(mat1, i, j):
	for k in range(r):
		mat1[i][k], mat1[j][k] = mat1[j][k], mat1[i][k]

#to check if any of the diagonal elements is 0 and to swap it
def check(mat1, mat2):
	flag = 1
	for i in range(r):
		if(mat1[i][i] == 0):
			flag = -1
			for j in range(r):
				if(j == i):
					continue
				if(mat1[j][i] != 0 and mat1[i][j] != 0):
					swap(mat1, i, j)
					swap(mat2, i, j)
					flag = 1
	if(flag == -1):
		print("issue cannot be resolved: singular matrix or zero matrix")
		exit()

#converts the diagonal element to one and divides all the respective row ele with the same that is used to divide the diagonal ele
def ones(mat1, mat2, i, r):
	ele = mat1[i][i]
	for j in range(r):
		mat1[i][j] = mat1[i][j] / ele
		mat2[i][j] = mat2[i][j] / ele

#convert all the ele on the current column to 0 along with their connected column elements
def zeros(mat1, mat2, i, r):
	for j in range(r):
		if(j == i):
			continue
		ele = mat1[j][i]
		for k in range(r):
			mat1[j][k] = mat1[j][k] - ele * mat1[i][k]
			mat2[j][k] = mat2[j][k] - ele * mat2[i][k]

#finds the inverse of 2 matrix
def inverse(mat3, mat2):
	for i in range(r):
		check(mat3, mat2)
		ones(mat3, mat2, i, r)
		zeros(mat3, mat2, i, r)

#finds the product of 2 matrices
def product_mat(mat1, mat2):
	product = []
	for i in range(r):
		temp = []
		for j in range(r):
			s = 0
			for k in range(r):
				s += mat1[i][k] * mat2[k][j]
			if(s <= 0.0001):
				s = 0
			temp.append(s)
		product.append(temp)
	return product

#creates the identity matrix of specified r
def id_mat(r):
	mat2 = []
	for i in range(r):
		col = []
		for j in range(r):
			if(i == j):
				col.append(1)
			else:
				col.append(0)
		mat2.append(col)
	return mat2

#creates  square matrix of specified length and returns it along with a hard copy of it
def create_mat(r):
	mat1 = []
	mat3 = []
	for i in range(r):
		col = []
		for j in range(r):
			temp = random.randint(0, 10)
			print(temp)
			#temp = float(input())    #uncomment this for user input matrix
			col.append(temp)
		mat1.append(col)
		mat3.append(col[:])
	return mat1, mat3

r = int(input())
c = int(input())
if(r != c):
	print("the matrix is not a square matrix\nthe inverse cannot be found")
	exit()

mat1, mat3 = create_mat(r)
mat2 = id_mat(r)
inverse(mat3, mat2)
product = product_mat(mat1, mat2)
print("inputed matrix is :\n")
pretty_print(mat1, r)
print("inverse matrix is:\n")
pretty_print(mat2, r)
print("product matrix is:\n")
pretty_print(product, r)


# process7.py to show synchronization and locking
from functools import partial
from multiprocessing import Pool, Manager

def printme (lock, msg):
    lock.acquire()
    try:
        print(msg)
    finally:
        lock.release()

def main():
    with Pool(3) as proc:
        lock = Manager().Lock()
        func = partial(printme,lock)
        proc.map(func, ["Orange", "Apple", "Banana",
                                 "Grapes","Pears"])

    print("Exiting the main process")

if __name__ == '__main__':
    main()


"""
Can you guess the output of
the following Python 🐍 Snippet?

Options
=========

1. 1
2. 1.0
3. 2
4. 2.0
"""

a = 10 and 1
b = 0 or 1
print(a + b ** 2)

"""
Solution
=========

3. 2

Explanation:
    >>> (10 and 1) + (0 or 1) ** 2

    * Here, when we use "and", the second value will return if
    * first one is true, else the first one is returned

    * when we use "or", the first value will return if it is true,
    * else the second value

    >>> 1 + (1 ** 2) # Operator Precedence

    >>> 1 + 1

    >>> 2

For more Pythonic 🐍 Content, find me on Twitter @GaganGulyani
"""


import torch.utils.data as data
import os
from PIL import Image
import numpy as np
from albumentations.pytorch import ToTensorV2
import random
import albumentations as A
import glob
from omegaconf import OmegaConf

config = OmegaConf.load(os.path.join(os.path.dirname(
    os.path.abspath(__file__)), 'config/test_ours.yaml'))

class P3M10KBlurred(data.Dataset):
    def __init__(self, config=config['datasets']):
        super(P3M10KBlurred, self).__init__()
        dataset_path = config['p3m10k']['path']

        self.bg_files = sorted(glob.glob(config['bg']+'/*.jpg'))
        self.original_files = sorted(
            glob.glob(dataset_path+'/train/blurred_image/*.jpg'))
        self.mask_path = sorted(glob.glob(dataset_path+'/train/mask/*.png'))
        if config['p3m10k']['transform'] == 'hard':
            self.transform = A.Compose([
                A.LongestMaxSize(max_size=1080, interpolation=1,
                                 always_apply=True, p=1),
                A.HorizontalFlip(p=0.5),
                A.RandomBrightnessContrast(p=0.2),
                A.ShiftScaleRotate(
                    rotate_limit=5, scale_limit=0.05, shift_limit=0.02, p=.5),
                A.Blur(blur_limit=3),
                A.PadIfNeeded(config.image_crop, config.image_crop),
                A.RandomCrop(width=config.image_crop,
                             height=config.image_crop),
                A.HueSaturationValue(),
                A.Normalize(),
                ToTensorV2()])
        else:
            self.transform = A.Compose([A.PadIfNeeded(min_height=None, min_width=None, pad_height_divisor=8, pad_width_divisor=8),
                                        A.Normalize(),
                                        ToTensorV2()
                                        ])

    def __getitem__(self, idx):
        image_file = self.original_files[idx]

        image = np.array(Image.open(image_file).convert('RGB'))

        mask_file = image_file.replace('foregrounds', 'mask')[:-3]+'png'
        mask = np.array(Image.open(mask_file).convert('L'))
        transformed = self.transform(image=image, mask=mask)

        return transformed['image'], transformed['mask'] / 255.

    def __len__(self):
        return len(self.original_files)

class AM2K(data.Dataset):
    def __init__(self, config=config, is_train=True, fake_bg=True):
        super(AM2K, self).__init__()

        if is_train:
            self.original_files = sorted(
                glob.glob(config['am2k']['train_original']+'/*.jpg'))
            self.mask_path = config['am2k']['train_mask']
            masks_path = glob.glob(config['am2k']['train_mask']+'/*.png')
            masks_names = set(
                [path.split('/')[-1][:-3]+'jpg' for path in masks_path])

            # there is semgentations in fg folder for them in original dataset
            self.original_files_no_masks = []
            for files in self.original_files:
                if files.split('/')[-1] not in masks_names:
                    self.original_files_no_masks.append(files)
            self.original_files = sorted(
                list(set(self.original_files)-set(self.original_files_no_masks)))

        else:
            self.original_files = sorted(
                glob.glob(config['am2k']['validation_original']+'/*.jpg'))
            self.mask_path = config['am2k']['validation_mask']

        self.transform = A.Compose([
            A.LongestMaxSize(max_size=1080, interpolation=1,
                             always_apply=True, p=1),
            A.CLAHE(),
            A.HorizontalFlip(p=0.5),
            A.ShiftScaleRotate(
                rotate_limit=5, scale_limit=0.05, shift_limit=0.02, p=.5),
            A.Blur(blur_limit=3),
            A.PadIfNeeded(config.image_crop, config.image_crop),
            A.RandomCrop(width=config.image_crop, height=config.image_crop),

        ])

        if fake_bg:
            self.bg_list = sorted(
                glob.glob(config['am2k']['background']+'/*.jpg'))
            self.bg_transform = A.Compose([
                A.LongestMaxSize(max_size=1080, interpolation=1,
                                 always_apply=True, p=1),
                A.CLAHE(),
                A.HorizontalFlip(p=0.5),
                A.RandomBrightnessContrast(p=0.2),
                A.ShiftScaleRotate(
                    rotate_limit=5, scale_limit=0.05, shift_limit=0.02, p=.5),
                A.Blur(blur_limit=5),
                A.PadIfNeeded(config.image_crop, config.image_crop),
                A.RandomCrop(width=config.image_crop,
                             height=config.image_crop),
            ])
        else:
            self.bg_list = None

        self.final_transform = A.Compose([
            A.RandomBrightnessContrast(p=0.2),
            A.HueSaturationValue(),
            A.Normalize(),
            ToTensorV2()
        ])

    def __getitem__(self, idx):
        image_file = self.original_files[idx]
        file_name = image_file.split('/')[-1]

        image = np.array(Image.open(image_file).convert('RGB'))
        mask_file = self.mask_path + '/' + file_name.replace('jpg', 'png')
        mask = np.array(Image.open(mask_file).convert('L'))
        transformed = self.transform(image=image, mask=mask)
        if self.bg_list is not None:
            background_img = np.array(Image.open(
                random.choice(self.bg_list)).convert('RGB'))
            background = self.bg_transform(image=background_img)['image']
            mask = (transformed['mask'] / 255.)[:, :, None]
            composite = np.uint8(
                (transformed['image']*mask+background*(1-mask)))
            final_transformed = self.final_transform(
                image=composite, mask=transformed['mask'])

            return final_transformed['image'], final_transformed['mask'] / 255.
        else:
            final_transformed = self.final_transform(
                image=transformed['image'], mask=transformed['mask'])

            return final_transformed['image'], final_transformed['mask'] / 255.

    def __len__(self):
        return len(self.original_files)

if __name__ == '__main__':
    ds = AM2K(config=config['datasets'])
    print(f'Dataset length: {len(ds)}')


from django_elasticsearch_dsl import Document
from django_elasticsearch_dsl.registries import registry
from .models import Titre

from article_wiki.models import Article

@registry.register_document
class TitreDocument(Document):
    class Index:
        # Name of the Elasticsearch index
        name = 'titres'
        # See Elasticsearch Indices API reference for available settings
        settings = {'number_of_shards': 1,
                    'number_of_replicas': 0}

    class Django:
        model = Titre # The model associated with this Document

        # The fields of the model you want to be indexed in Elasticsearch
        fields = [
            'header',
        ]
        # queryset_pagination = 5000


# This is a demo of running face recognition on a Raspberry Pi.
# This program will print out the names of anyone it recognizes to the console.

# To run this, you need a Raspberry Pi 2 (or greater) with face_recognition and
# the picamera[array] module installed.
# You can follow this installation instructions to get your RPi set up:
# https://gist.github.com/ageitgey/1ac8dbe8572f3f533df6269dab35df65

import face_recognition
import numpy as np
import cv2
from encoding import loadEncoding

font = cv2.FONT_HERSHEY_DUPLEX

print("Initialize camera (use OpenCV)")
camera = cv2.VideoCapture(0)
camera.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
camera.set(cv2.CAP_PROP_FPS, 24)

# Load a sample picture and learn how to recognize it.
print("Loading known face encodings")
known_face_encodings, known_names = loadEncoding()

# Initialize some variables
face_locations = []
face_encodings = []

while True:
    rval, frame = camera.read()
    frame = cv2.flip(frame, -1) # Flip vertically
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # covert frame from BGR(opencv use) to RGB(face_recognition use)
    # rgb_small_frame = small_frame[:, :, ::-1]

    # Find all the faces and face encodings in the current frame of video
    face_locations = face_recognition.face_locations(small_frame)
    face_encodings = face_recognition.face_encodings(small_frame, face_locations)

    predice_name = []
    # Loop over each face found in the frame to see if it's someone we know.
    for face_encoding in face_encodings:
        # See if the face is a match for the known face(s)
        matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
        for idx in range(len(matches)):
            if matches[idx]:
                predice_name.append(known_names[idx])
            else:
                predice_name.append("Unknown")

    # draw the result
    i = 0
    for (top, right, bottom, left) in face_locations:
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4
        if(predice_name[i] == "Unknown"):
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
        else:
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
        cv2.putText(frame, predice_name[i], (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
        i += 1

    cv2.imshow('Video', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

camera.release()
cv2.destroyAllWindows()


from common.text_manipulations import TextParser

class StateMachine:
    def __init__(self, data, binary=False):
        if binary:
            self.data = data
        else:
            self.data = ''.join(bin(int(c, 16))[2:].zfill(4) for c in data)
        self.state = self.ini_state
        self.c = 0
        self.result = 0
        self.ver = self.id = None
        self.vsum = 0

    def run(self):
        while self.state != self.end_state:
            self.state()
        return self.result

    def end_state(self):
        pass

    def ini_state(self):
        self.ver = int(self.data[self.c:self.c+3],2)
        self.id = int(self.data[self.c+3:self.c+6],2)
        self.c += 6
        self.vsum += self.ver

        if self.id == 4:
            self.state = self.literal_state
        else:
            self.state = self.operation_state

    def literal_state(self):
        num = []
        while True:
            num.append(self.data[self.c+1:self.c+5])
            if self.data[self.c] == '0':
                self.c += 5
                break
            self.c += 5
        self.result = int(''.join(num),2)
        self.state = self.end_state

    def operation_state(self):
        t = self.data[self.c]
        self.c += 1

        chunks = []

        if t == '0':
            end = self.c + 15 + int(self.data[self.c:self.c+15], 2)
            self.c += 15
            while self.c < end:
                new = self.new_state_machine(self.data[self.c:], binary=True)
                new.run()
                chunks.append(new.result)
                self.vsum += new.vsum
                self.c += new.c
        else:
            n_packets = int(self.data[self.c:self.c+11], 2)
            self.c += 11
            for _ in range(n_packets):
                new = self.new_state_machine(self.data[self.c:], binary=True)
                new.run()
                chunks.append(new.result)
                self.vsum += new.vsum
                self.c += new.c

        if self.id == 0:
            self.result = sum(chunks)
        elif self.id == 1:
            res = 1
            for p in chunks:
                res *= p
            self.result = res
        elif self.id == 2:
            self.result = min(chunks)
        elif self.id == 3:
            self.result = max(chunks)
        elif self.id == 5:
            self.result = 1 if chunks[0] > chunks[1] else 0
        elif self.id == 6:
            self.result = 1 if chunks[0] < chunks[1] else 0
        elif self.id == 7:
            self.result = 1 if chunks[0] == chunks[1] else 0
        else:
            raise ValueError

        self.state = self.end_state

    @classmethod
    def new_state_machine(cls, data, binary=False):
        return cls(data, binary=binary)

def run():

    source = TextParser("day16.txt").load_file_as_raw_string()
    sm = StateMachine(source)
    sm.run()

    # Part 1
    print(f"Part 1 result: {sm.vsum}")

    #Part 2
    print(f"Part 2 result: {sm.result}")

if __name__ == "__main__":

    run()


#12-Calcular la suma de los cuadrados de los primeros 100 enteros y escribir el resultado.
def suma2():
    suma=0
    i=1
    for i in 100:
        suma = suma+i*i
    print(suma)
suma2()


from __future__ import unicode_literals, division, absolute_import, print_function

__license__   = 'GPL v3'
__copyright__ = '2011, Grant Drake'

# calibre Python 3 compatibility.
from six import text_type as unicode

try:
    from qt.core import QDialog, QAbstractItemView, QDialogButtonBox, QListWidgetItem, \
                     QListWidget, QVBoxLayout
except ImportError:
    from PyQt5.Qt import QDialog, QAbstractItemView, QDialogButtonBox, QListWidgetItem, \
                     QListWidget, QVBoxLayout

from calibre_plugins.user_category.common_icons import get_icon

class ChooseMultipleDialog(QDialog):

    def __init__(self, parent=None, values=[], action='', label='', icon=''):
        QDialog.__init__(self, parent)
        self.setWindowTitle('Select values to ' + action)
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        self.values_list = QListWidget(self)
        self.values_list.setSelectionMode(QAbstractItemView.MultiSelection)
        layout.addWidget(self.values_list)

        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
        self.resize(self.sizeHint())

        for value in values:
            self.values_list.addItem(QListWidgetItem(get_icon(icon), value))
        self.values_list.selectAll()

    @property
    def selected_values(self):
        values = []
        for item in self.values_list.selectedItems():
            values.append(unicode(item.text()))
        return values


import requests
from bs4 import BeautifulSoup as bs
import json
from datetime import datetime
import sys
sys.path.append("../../")
sys.path.append("functionalities/moodle/")
from usersapi.views import Users

class Announcements:
    def show_course_announcements(self, course_id, sender_whatsapp_no, n = None):
        '''
        Show course announcements of a particular course
        Input:
            course_id (int)
            n (int)
        '''
        token, userid = Users(sender_whatsapp_no).getMoodle()
        if token == -1:
            return "Please register moodle credentials"

        print("userid:", token, userid)
        if token is None:
            return "Please update Moodle Credentials"

        payload = {'wstoken': token,'wsfunction':'mod_forum_get_forums_by_courses','courseids[0]': course_id}

        res = requests.post('https://moodle.iitb.ac.in/webservice/rest/server.php?moodlewsrestformat=json',data=payload)

        id = None
        for x in json.loads(res.text):
            if 'announce' in x['name'].lower():
                id = x['id']
                break

        if id is None:
            return ("Course does not exist")
        else:
            payload = {'wstoken': token,'wsfunction':'mod_forum_get_forum_discussions', 'forumid': id}

            res = requests.post('https://moodle.iitb.ac.in/webservice/rest/server.php?moodlewsrestformat=json', data=payload)
            ret = 'Announcements:\n'
            i = 1
            for x in json.loads(res.text)['discussions']:
                if n is not None and int(n) < i:
                    break

                ret += "\t" f"{i}. [" + str(datetime.fromtimestamp(x['created'])) + "] " + x['name'] + '\n'
                ret +=  bs(x['message'],'html.parser').get_text() + '\n\n'
                i += 1

        return ret


from redbot.core import commands, checks, Config, VersionInfo, version_info
import discord
import traceback
from typing import Optional
from .process_message import MessageProcessor, ConversionResult
from .convert_units.converter import loadConversionsData
from .error import Error
from .reply import Reply

class UnitCog(commands.Cog):
  """Searches for units in a message and tries to convert them from metric to imperial and vice versa"""

  def __init__(self, bot):
    # load data
    loadConversionsData()
    _ = MessageProcessor()
    self.bot = bot
    self.config = Config.get_conf(self, 0xdd227e37d7df40f780bcb9981ac91e26, force_registration=True)
    default_guild = { 'emoji' : "⚙" }
    self.config.register_guild(**default_guild)
    self.cache = { 'emoji' : None }

  @commands.group(name="units")
  @commands.guild_only()
  @checks.mod_or_permissions(manage_messages=True)
  async def units(self, ctx: commands.Context) -> None:
    """
        Settings for unit conversions
    """
    pass

  @units.command()
  @checks.mod_or_permissions(manage_messages=True)
  async def emoji(self, ctx, emoji: Optional[str] = None,):
    """
        Gets or sets the emoji used for reaction-triggered conversion
    """
    if not emoji:
      val = await self._getConfig(ctx.guild, "emoji")
      repl = Reply.CreateEmbed(f"Emoji used for reaction-triggered conversion: {val}", "Config")
      await ctx.send(embed = repl.embed)
    else:
      val = str(emoji)
      await self.config.guild(ctx.guild).emoji.set(val)
      self.cache['emoji'] = None
      repl = Reply.CreateEmbed(f"Emoji used for reaction-triggered conversion set", "Config")
      await ctx.send(embed = repl.embed)

  @commands.command()
  async def convert(self, ctx, *, txt):
    """Do the conversion"""
    msg = await self._convert(txt, None)
    if msg:
      await ctx.send(embed = msg.embed)

  @commands.Cog.listener()
  async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent) -> None:
    """Request a conversion by reaction"""
    if version_info >= VersionInfo.from_str("3.2.0"):
      await self.bot.wait_until_red_ready()
    else:
      await self.bot.wait_until_ready()
    channel = self.bot.get_channel(id=payload.channel_id)
    if not channel:
      return
    try:
      guild = channel.guild
    except AttributeError:
      return
    if guild is None:
      return
    reacted_user = guild.get_member(payload.user_id)
    if reacted_user.bot:
        return
    try:
      message: discord.Message = await channel.fetch_message(id=payload.message_id)
    except (discord.errors.NotFound, discord.Forbidden):
      return

    if str(payload.emoji) != await self._getConfig(guild, 'emoji'):
      return

    msg = await self._convert(message.content, reacted_user)
    if msg:
      await channel.send(embed = msg.embed)

  async def _convert(self, txt: str, user: discord.Member = None):
    mp: MessageProcessor = MessageProcessor()
    try:
      result = mp.processMessage(txt)
      if isinstance(result, str):
        return Reply.CreateEmbed(result, "Value conversion")
      elif len(result) > 0:
        tmp = []
        for t in result:
          cr: ConversionResult = t
          tmp.append("%s = %s" % (cr.orig, cr.conv))
        answer = "%s" % "\n".join(tmp)
        repl = Reply.CreateEmbed(answer, "Value conversion")
        if user:
          repl.embed.set_footer(text = f"Requested by {user.display_name}")
        return repl
      else:
        print("No convertable units found in %s" % txt)
    except Error as e:
      return Reply.CreateError(e)
    except Exception as e:
      print("Exception was thrown while trying to process the message: %s" % e)
      traceback.print_exc()
    return None

  async def _getConfig(self, guild, key: str):
    if not self.cache[key]:
      self.cache[key] = await getattr(self.config.guild(guild), key)()
    return self.cache[key]


#!/bin/env python2.7

#import netCDF4 as nc
import numpy as np
#import matplotlib.pyplot as plt
#import sys,os
import ipdb

from imogen import delQ
from maths_tools import SmoothTools as STs

start_year,end_year=1850,2100
n_yrs=end_year-start_year

SCENARIO='1p5deg'
#SCENARIO_DIR='/users/eow/edwcom/CLIFFTOP/IMOGEN/scenarios/'
SCENARIO_DIR='/prj/CLIFFTOP/COMMON_DATA/SCENARIOS/'

HadCRUT_fname=SCENARIO_DIR+'HadCRUT.4.5.0.0.annual_ns_avg_smooth.rtf'

RCP_in_CO2file=SCENARIO_DIR+'rcp2.6_concs_co2_vn1p1.txt'
RCP_in_CH4N2Ofile=SCENARIO_DIR+'rcp2.6_concs_ch4_n2o_vn1p1.txt'
RCP_in_Aerosolfile=SCENARIO_DIR+'rcp2.6_dq_aerosol.txt'
RCP_in_NonCO2file=SCENARIO_DIR+'rcp2.6_qnonco2_vn1p1.txt'
RCP_in_Qco2ch4n2ofile=SCENARIO_DIR+'rcp2.6_q_co2_ch4_n2o_vn1p0.txt'
RCP_in_QstratoOzonefile=SCENARIO_DIR+'rcp2.6_qOzone_qstratoWV.txt'

SSP_in_Tfile=SCENARIO_DIR+'SSP2-2.6_IMAGE_temp_anomaly_raw.dat'
SSP_in_CO2file=SCENARIO_DIR+'SSP2-2.6_IMAGE_concs_co2_raw.txt'
SSP_in_CH4N2Ofile=SCENARIO_DIR+'SSP2-2.6_IMAGE_concs_ch4_n2o_raw.txt'
SSP_in_Aerosolfile=SCENARIO_DIR+'SSP2-2.6_IMAGE_qaerosol_raw.txt'
SSP_in_NonCO2file=SCENARIO_DIR+'SSP2-2.6_IMAGE_qnonco2_raw.txt'
SSP_in_Qco2ch4n2ofile=SCENARIO_DIR+'SSP2-2.6_IMAGE_q_co2_ch4_n2o_vn1p0.txt'

SSP_out_Tfile=SCENARIO_DIR+'SSP2-2.6_IMAGE_temp_anomaly' #.dat'
SSP_out_CO2file=SCENARIO_DIR+'SSP2-2.6_IMAGE_concs_co2'# .txt'
SSP_out_CH4N2Ofile=SCENARIO_DIR+'SSP2-2.6_IMAGE_concs_ch4_n2o'#.txt'
SSP_out_Aerosolfile=SCENARIO_DIR+'SSP2-2.6_IMAGE_qaerosol'#.txt'
SSP_out_NonCO2file=SCENARIO_DIR+'SSP2-2.6_IMAGE_qnonco2'#.txt'

#Read in Hadcrut data
HadCRUT_lines=open(HadCRUT_fname,'r').readlines()
HadCRUT_T=np.array([float(line.split()[1]) for line in HadCRUT_lines])
HadCRUT_years=np.array([float(line.split()[0]) for line in HadCRUT_lines])
# Normalise T to median of first 51 years
median_51 = np.median(HadCRUT_T[:51])
HadCRUT_T-=median_51

#Read RCP data in:
rcp_start,rcp_end=1850,2100
rcp_nyr=rcp_end-rcp_start+1
RCP_co2lines=open(RCP_in_CO2file,'r').readlines()
RCP_ch4n2olines=open(RCP_in_CH4N2Ofile,'r').readlines()
RCP_aerosollines=open(RCP_in_Aerosolfile,'r').readlines()
RCP_nonco2lines=open(RCP_in_NonCO2file,'r').readlines()
RCP_qco2ch4n2olines=open(RCP_in_Qco2ch4n2ofile,'r').readlines()
#RCP_qOzoneWVlines=open(RCP_in_QstratoOzonefile,'r').readlines()
RCP_co2=np.zeros(rcp_nyr)
RCP_ch4=np.zeros(rcp_nyr)
RCP_n2o=np.zeros(rcp_nyr)
RCP_aerosol=np.zeros(rcp_nyr)
RCP_nonco2=np.zeros(rcp_nyr)
RCP_qco2=np.zeros(rcp_nyr)
RCP_qch4=np.zeros(rcp_nyr)
RCP_qn2o=np.zeros(rcp_nyr)
#RCP_qozone=np.zeros(rcp_nyr)
#RCP_qstratoWV=np.zeros(rcp_nyr)
RCP_years=np.arange(rcp_start,rcp_end+1)
#ipdb.set_trace()
for i_yr in range(rcp_nyr):
   print(i_yr)
   RCP_co2[i_yr]=float(RCP_co2lines[i_yr].split()[1])
   RCP_ch4[i_yr]=float(RCP_ch4n2olines[i_yr].split()[1])
   RCP_n2o[i_yr]=float(RCP_ch4n2olines[i_yr].split()[2])
   RCP_aerosol[i_yr]=float(RCP_aerosollines[i_yr].split()[1])
   RCP_nonco2[i_yr]=float(RCP_nonco2lines[i_yr].split()[1])
   RCP_qco2[i_yr]=float(RCP_qco2ch4n2olines[i_yr].split()[1])
   RCP_qch4[i_yr]=float(RCP_qco2ch4n2olines[i_yr].split()[2])
   RCP_qn2o[i_yr]=float(RCP_qco2ch4n2olines[i_yr].split()[3])
   #RCP_qozone[i_yr]=float(RCP_qOzoneWVlines[i_yr].split()[1])
   #RCP_qstratoWV[i_yr]=float(RCP_qOzoneWVlines[i_yr].split()[2])

# Substitute the etminan ch4 and n2o
RCP_qn2o_etminan=delQ.etminan_N2O(RCP_n2o,RCP_co2,RCP_ch4) #,
#                        ch4_ppb_0=RCP_ch4[0],n2o_ppb_0=RCP_n2o[0],co2_ppm_0=RCP_co2[0])
RCP_qch4_etminan=delQ.etminan_CH4(RCP_ch4,RCP_n2o)#,ch4_ppb_0=RCP_ch4[0],n2o_ppb_0=RCP_n2o[0])
#RCP_qSozone_collins=delQ.collins_CH4StratoOzone(RCP_ch4)

RCP_nonco2_etminan = RCP_nonco2-RCP_qch4        -RCP_qn2o        \
                                +RCP_qch4_etminan+RCP_qn2o_etminan

#RCP_qnonco2_etminan = RCP_nonco2-RCP_qch4        -RCP_qn2o        -RCP_qozone-RCP_qstratoWV   \
#                                +RCP_qch4_etminan+RCP_qn2o_etminan+RCP_qSozone_collins

#Read SSP data in:
SSP_Tlines=open(SSP_in_Tfile,'r').readlines()
SSP_co2lines=open(SSP_in_CO2file,'r').readlines()
SSP_ch4n2olines=open(SSP_in_CH4N2Ofile,'r').readlines()
SSP_aerosollines=open(SSP_in_Aerosolfile,'r').readlines()
SSP_nonco2lines=open(SSP_in_NonCO2file,'r').readlines()
SSP_qco2ch4n2olines=open(SSP_in_Qco2ch4n2ofile,'r').readlines()
ssp_nyr=len(SSP_co2lines)
SSP_years_in=np.zeros(ssp_nyr)
SSP_T_in=np.zeros(ssp_nyr)
SSP_co2_in=np.zeros(ssp_nyr)
SSP_ch4_in=np.zeros(ssp_nyr)
SSP_n2o_in=np.zeros(ssp_nyr)
SSP_aerosol_in=np.zeros(ssp_nyr)
SSP_nonco2_in=np.zeros(ssp_nyr)
SSP_qco2_in=np.zeros(ssp_nyr)
SSP_qch4_in=np.zeros(ssp_nyr)
SSP_qn2o_in=np.zeros(ssp_nyr)
for i_yr in range(ssp_nyr):
   SSP_years_in[i_yr]=float(SSP_co2lines[i_yr].split()[0])
   SSP_T_in[i_yr]=float(SSP_Tlines[i_yr].split()[1])
   SSP_co2_in[i_yr]=float(SSP_co2lines[i_yr].split()[1])
   SSP_ch4_in[i_yr]=float(SSP_ch4n2olines[i_yr].split()[1])
   SSP_n2o_in[i_yr]=float(SSP_ch4n2olines[i_yr].split()[2])
   SSP_aerosol_in[i_yr]=float(SSP_aerosollines[i_yr].split()[1])
   SSP_nonco2_in[i_yr]=float(SSP_nonco2lines[i_yr].split()[1])
   SSP_qco2_in[i_yr]=float(SSP_qco2ch4n2olines[i_yr].split()[1])
   SSP_qch4_in[i_yr]=float(SSP_qco2ch4n2olines[i_yr].split()[2])
   SSP_qn2o_in[i_yr]=float(SSP_qco2ch4n2olines[i_yr].split()[3])

# Substitute the etminan ch4 and n2o and Collin WV and Ozone
SSP_qn2o_etminan=delQ.etminan_N2O(SSP_n2o_in,SSP_co2_in,SSP_ch4_in)
SSP_qch4_etminan=delQ.etminan_CH4(SSP_ch4_in,SSP_n2o_in) #,ch4_ppb_0=722.,n2o_ppb_0=270.)

SSP_T_in[-2:]=SSP_T_in[-3]

# Interpolate SSP data to yearly
SSP_years_interp=np.arange(SSP_years_in[0],SSP_years_in[-1]+1)
SSP_T_interp=np.interp(SSP_years_interp,SSP_years_in,SSP_T_in)
SSP_co2_interp=np.interp(SSP_years_interp,SSP_years_in,SSP_co2_in)
SSP_ch4_interp=np.interp(SSP_years_interp,SSP_years_in,SSP_ch4_in)
SSP_n2o_interp=np.interp(SSP_years_interp,SSP_years_in,SSP_n2o_in)
SSP_aerosol_interp=np.interp(SSP_years_interp,SSP_years_in,SSP_aerosol_in)
SSP_nonco2_interp=np.interp(SSP_years_interp,SSP_years_in,SSP_nonco2_in)
SSP_qco2_interp=np.interp(SSP_years_interp,SSP_years_in,SSP_qco2_in)
SSP_qch4_interp=np.interp(SSP_years_interp,SSP_years_in,SSP_qch4_in)
SSP_qn2o_interp=np.interp(SSP_years_interp,SSP_years_in,SSP_qn2o_in)

# Smooth data
SSP_T_smooth=STs.meanbox_iterate(SSP_T_interp,iterations=10)
SSP_co2_smooth=STs.meanbox_iterate(SSP_co2_interp,iterations=10)
SSP_ch4_smooth=STs.meanbox_iterate(SSP_ch4_interp,iterations=10)
SSP_n2o_smooth=STs.meanbox_iterate(SSP_n2o_interp,iterations=10)
SSP_aerosol_smooth=STs.meanbox_iterate(SSP_aerosol_interp,iterations=10)
SSP_nonco2_smooth=STs.meanbox_iterate(SSP_nonco2_interp,iterations=10)
SSP_qco2_smooth=STs.meanbox_iterate(SSP_qco2_interp,iterations=10)
SSP_qch4_smooth=STs.meanbox_iterate(SSP_qch4_interp,iterations=10)
SSP_qn2o_smooth=STs.meanbox_iterate(SSP_qn2o_interp,iterations=10)

# Substitute the etminan ch4 and n2o and Collin WV and Ozone
SSP_qn2o_etminan_smooth=delQ.etminan_N2O(SSP_n2o_smooth,SSP_co2_smooth,SSP_ch4_smooth)
SSP_qch4_etminan_smooth=delQ.etminan_CH4(SSP_ch4_smooth,SSP_n2o_smooth)

#SSP_ozoneWV = delQ.SSP_CH4StratoOzone(SSP_ch4_interp)
#SSP_ozoneWV_collins = delQ.collins_CH4StratoOzone(SSP_ch4_interp)

SSP_nonco2_etminan_smooth = SSP_nonco2_smooth-SSP_qch4_smooth-SSP_qn2o_smooth \
                                +SSP_qch4_etminan_smooth+SSP_qn2o_etminan_smooth

splice_year=2005
SSP_start_index = np.where(SSP_years_interp==splice_year)[0][0]
RCP_start_index = np.where(RCP_years==splice_year)[0][0]

HadCRUT_T_trans=HadCRUT_T[RCP_start_index]
delT_1p5 = 1.5-HadCRUT_T_trans
delT_2   = 2.-HadCRUT_T_trans

SSP_T_a=SSP_T_smooth-SSP_T_smooth[SSP_start_index]
SSP_co2_a=SSP_co2_smooth-SSP_co2_smooth[SSP_start_index]
SSP_aerosol_a=SSP_aerosol_smooth-SSP_aerosol_smooth[SSP_start_index]
SSP_nonco2_a=SSP_nonco2_etminan_smooth-SSP_nonco2_etminan_smooth[SSP_start_index]

ratio_1p5 = delT_1p5/SSP_T_a[-1]
ratio_2   = delT_2/SSP_T_a[-1]

SSP_T_raw=np.zeros_like(RCP_co2)
SSP_T_raw[:RCP_start_index]=HadCRUT_T[:RCP_start_index]
SSP_T_raw[RCP_start_index:]=HadCRUT_T_trans+(SSP_T_a[SSP_start_index:])
SSP_T_raw[RCP_start_index-10:]=STs.meanbox_iterate(SSP_T_raw[RCP_start_index-10:],iterations=10)
outf=open(SSP_out_Tfile+'.dat','w')
for i_yr in range(len(SSP_T_raw)):
    outf.write('%4i %8.4f\n'%(RCP_years[i_yr],SSP_T_raw[i_yr]))
outf.close()
quit()

SSP_T_1p5=np.zeros_like(RCP_co2)
SSP_T_1p5[:RCP_start_index]=HadCRUT_T[:RCP_start_index]
SSP_T_1p5[RCP_start_index:]=HadCRUT_T_trans+(SSP_T_a[SSP_start_index:]*ratio_1p5)
SSP_T_1p5[RCP_start_index-10:]=STs.meanbox_iterate(SSP_T_1p5[RCP_start_index-10:],iterations=10)
outf=open(SSP_out_Tfile+'_1p5deg.dat','w')
for i_yr in range(len(SSP_T_1p5)):
    outf.write('%4i %8.4f\n'%(RCP_years[i_yr],SSP_T_1p5[i_yr]))
outf.close()

SSP_aero_1p5=np.zeros_like(RCP_co2)
SSP_aero_1p5[:RCP_start_index]=RCP_aerosol[:RCP_start_index]
SSP_aero_1p5[RCP_start_index:]=RCP_aerosol[RCP_start_index]+\
                                (SSP_aerosol_a[SSP_start_index:]*ratio_1p5)
SSP_aero_1p5[RCP_start_index-5:]=STs.meanbox_iterate(SSP_aero_1p5[RCP_start_index-5:],
                                                       iterations=10)
outf=open(SSP_out_Aerosolfile+'_1p5deg.dat','w')
for i_yr in range(len(SSP_aero_1p5)):
    outf.write('%4i %8.4f\n'%(RCP_years[i_yr],SSP_aero_1p5[i_yr]))
outf.close()

SSP_nonco2_1p5=np.zeros_like(RCP_co2)
SSP_nonco2_1p5[:RCP_start_index]=RCP_nonco2_etminan[:RCP_start_index]
SSP_nonco2_1p5[RCP_start_index:]=RCP_nonco2_etminan[RCP_start_index]+\
                                (SSP_nonco2_a[SSP_start_index:]*ratio_1p5)
SSP_nonco2_1p5[RCP_start_index-5:]=STs.meanbox_iterate(SSP_nonco2_1p5[RCP_start_index-5:],
                                                       iterations=10)
outf=open(SSP_out_NonCO2file+'_1p5deg.dat','w')
for i_yr in range(len(SSP_nonco2_1p5)):
    outf.write('%4i %8.4f\n'%(RCP_years[i_yr],SSP_nonco2_1p5[i_yr]))
outf.close()

quit()

SSP_T_2=np.zeros_like(RCP_co2)
SSP_T_2[:RCP_start_index]=HadCRUT_T[:RCP_start_index]
SSP_T_2[RCP_start_index:]=HadCRUT_T_trans+(SSP_T_a[SSP_start_index:]*ratio_2)
SSP_T_2[RCP_start_index-10:]=STs.meanbox_iterate(SSP_T_2[RCP_start_index-10:],iterations=10)

outf=open(SSP_out_Tfile+'_2deg.dat','w')
for i_yr in range(len(SSP_T_2)):
    outf.write('%4i %8.4f\n'%(RCP_years[i_yr],SSP_T_2[i_yr]))
outf.close()

quit()

SSP_co2_1p5=np.zeros_like(RCP_co2)
SSP_co2_1p5[:SSP_start_index]=RCP_co2[:SSP_start_index]
SSP_co2_1p5[SSP_start_index:]=RCP_co2[SSP_start_index]+(SSP_co2_a*ratio_1p5)

SSP_ch4_1p5=np.zeros_like(RCP_co2)
SSP_n2o_1p5=np.zeros_like(RCP_co2)
SSP_nonco2_1p5=np.zeros_like(RCP_co2)
SSP_aerosol_1p5=np.zeros_like(RCP_co2)

SSP_T_2=np.zeros_like(RCP_co2)
SSP_co2_2=np.zeros_like(RCP_co2)
SSP_ch4_2=np.zeros_like(RCP_co2)
SSP_n2o_2=np.zeros_like(RCP_co2)
SSP_nonco2_2=np.zeros_like(RCP_co2)
SSP_aerosol_2=np.zeros_like(RCP_co2)


txt = open("calorias.txt", "r")

calorias = txt.read()

lista_calorias = calorias.split("\n\n")

lista = []
maior_cal = 0
i = 0

txt.close()

for numbers in lista_calorias:
    lista.append(numbers.split("\n"))

lista_int = [[int(x) for x in y] for y in lista]

for item in lista_int:
    if maior_cal < sum(item):
        maior_cal = sum(item)

for item in lista_int:
    if maior_cal == sum(item):
        i = lista_int.index(item)

print(f"o indice do elfo com o maior numero de calorias é {i}")
print(f"o maior número de calorias foi {maior_cal}")

#PART 2

lista_sum = []
top_calorias = []

for item in lista_int:
    lista_sum.append(sum(item))

lista_sum.sort()
top_calorias = lista_sum[-3:]

top_calorias_sum = sum(top_calorias)

print(f"O total carregado pelos elfos com maior numero de calorias é {top_calorias_sum}")


#!/usr/bin/env python
# -*- coding: utf8 -*

S = "나는 가끔 여행을 떠나고 싶을 때가 있어"

word_list = S.split()   # word_list = ['나는', '가끔', '여행을', '떠나고', '싶을', '때가', '있어']
word_list.reverse()     # word_list = ['있어', '때가', '싶을', '떠나고', '여행을', '가끔', '나는']

# l = []
# for x in range(1,10):
#     l.append(x**2)
#
# print(l)
#
# l1 = [x**2 for x in range(1,10)] # list comprehension
#
# print(l1)

S = ' '.join([x[::-1] for x in word_list])
#['어있','가때','을싶','고나떠','을행여','끔가','는나']
print(S)


def value_toothless():
    return 0
def value_sick(i):
    if i == 0:
        return 0
    return 4 + .9 * (3/4 * value_sick(i-1) + 1/4 * value_healthy(i-1))
def value_healthy(i):
    if i == 0:
        return 0
    return 10 + .9 * (3/4 * value_sick(i-1) + 1/4 * value_healthy(i-1))

# print('healthy', value_healthy(30))
# print('sick', value_sick(30))

candy = 7/8 * (10 + .9 * 51.1685) + 1/8 * (10 +.9*0)
vegetable = 3/4 * (4 + .9 * 51.1685) + 1/4 * (4 + .9 * 57.1685)

print("candy" , candy)
print("veg", vegetable)

candy = 3/4 * (10 + .9 * 51.1685) + 1/4 * (10 + .9 * 57.1685)
vegetable = 1 * (4 + .9 * 57.1685)

print("candy" , candy)
print("veg", vegetable)


import requests
import telebot
from telebot import types
from auth_data import token

# Инициализация словаря для хранения значений фильтров
filters = {
    'region': '',
    'name': '',
    'min_salary': ''
}

def telegram_bot(token):
    bot = telebot.TeleBot(token)

    @bot.message_handler(commands=["start"])
    def start_message(message):
        bot.send_message(message.chat.id, "Привет! Рассказать тебе о новых вакансиях на портале Работа России?")
        info_message(message)

    @bot.message_handler(commands=["help"])
    def info_message(message):
        info = """Руководство по использованию telegram-бота
        Бот предназначен для упрощенного просмотра информации о вакансиях онлайн портала

    Список команд:
    - /start - Создание чата
    - /help - Получение справки о командах

    - /filter - Просмотр фильтра вакансий (регион, название вакансии, минимальная зарплата)
    - /region - Установить регион РФ для поиска вакансий (введите число, /region 59)
    - /name - Установить название вакансии (/name менеджер)
    - /min_salary - Установить минимальную З/П (/min_salary 60000)

    - /search - Поиск вакансий по фильтру
    """
        bot.send_message(message.chat.id, info)

    @bot.message_handler(commands=["filter"])
    def filter_get(message):
        bot.send_message(message.chat.id, f"""Текущие параметры фильтра:
Регион: {filters['region'] if filters['region'] else "-"}
Название: {filters['name'] if filters['name'] else "-"}
Минимальная зарплата: {filters['min_salary'] if filters['min_salary'] else "-"}""")

    @bot.message_handler(commands=['region'])
    def region_set(message):
        filters['region'] = message.text.split()[1]
        bot.reply_to(message, f"Регион: {filters['region']}")

    @bot.message_handler(commands=['name'])
    def name_set(message):
        filters['name'] = "/s".join(message.text.split()[1:])
        bot.reply_to(message, f"Название: {filters['name']}")

    @bot.message_handler(commands=['min_salary'])
    def min_salary_set(message):
        filters['min_salary'] = message.text.split()[1]
        bot.reply_to(message, f"Минимальная З/П: {filters['min_salary']}")

    @bot.message_handler(commands=["search"])
    def search(message):
        # Используйте значения из словаря filters
        region = filters['region']
        name = filters['name']
        min_salary = filters['min_salary']

        request_str = f"http://opendata.trudvsem.ru/api/v1/vacancies" \
                      f"{f'/region/{region}' if region else ''}" \
                      f"?text={name}" \
                      f"&salary_min={min_salary}" \
                      f"&limit=10"

        try:
            # запрос
            req = requests.get(request_str)
            response = req.json()

            vacs = response["results"]['vacancies']
            t = "Вакансии по запросу:\n\n"
            for v in vacs:
                i = v['vacancy']
                t += f"{i['job-name']}\n"          # должность - гиперссылка
                t += f"Специализация: {i['category']['specialisation']}\n"      # специализация
                t += f"Компания: {i['company']['name']}\n"               # работадатель
                t += f"Зарплата: {i['salary_min']}-{i['salary_max']} {i['currency'][1:-2]}\n"    # зарплата
                t += f"Контакты: {i['contact_list'][0]['contact_value']}\n\n"                  # контактные данные

            bot.send_message(message.chat.id, t, parse_mode='html')

        except Exception as ex:
            print(ex)
            bot.send_message(
                message.chat.id,
                "Ничего не найдено"
            )

    bot.polling()

if __name__ == '__main__':
    telegram_bot(token)


#!/usr/bin/env python3
'''

This is Linux/macOS MAC (random) address changer.
by n0a https://n0a.pw

=====================================================================
Run without args will show available network interfaces with MAC only
=====================================================================
[-] Error: specify interface
[!] Available interfaces:
en0: e4:d7:f4:ee:42:4d
en3: d0:37:35:18:48:79

===========================================================
ex. MAC random generation (-v vendor for vendor mac prefix)
===========================================================
sudo ./mac_changer.py -i en0 -v apple
[+] Interface seems good: en0
[+] Random MAC address for this case: [apple] D4:61:9D:dc:70:5d
[+] Backup: en0: 02:00:00:8a:09:ca -> D4:61:9D:dc:70:5d write in backup.txt
[+] Changing MAC from 02:00:00:8a:09:ca -> D4:61:9D:dc:70:5d successful.

===================
ex. with custom MAC
===================
sudo ./mac_changer.py -i en0 -m e4:d7:f4:ee:42:4d
[+] Interface seems good: en0
[+] MAC address seems good: e4:d7:f4:ee:42:4d
[+] Backup: en0: 76:bf:25:3a:b1:bd -> e4:d7:f4:ee:42:4d write in backup.txt
[+] Changing MAC from 76:bf:25:3a:b1:bd -> e4:d7:f4:ee:42:4d is OK.

======================
cat backup.txt example
======================
en0: e0:3f:49:86:51:0d -> cb:48:34:6f:a6:80
en0: cb:48:34:6f:a6:80 -> e0:3f:49:86:51:0d
en0: e0:3f:49:86:51:0d -> 76:bf:25:3a:b1:bd
en0: 76:bf:25:3a:b1:bd -> e4:d7:f4:ee:42:4d
'''

import os
import re
import sys
import random
import argparse
import subprocess
from platform import system

# default_vendor object can be: xen, huawei, cisco, samsung, google, juniper, dell,
# broadcom, tplink, hp, indel, dlink, zte, nokia, netgear, microsoft, xiaomi, apple

default_vendor	= "xen"
backup_file 	= "backup.txt"
backup_enable	= True

def is_tool(name):
	# Check whether `name` is on PATH and marked as executable.
	from shutil import which
	return which(name) is not None

def get_avialible_ifaces():
	current_os = system()
	# Because macOS ipconfig output has't splin network interface with \n\n
	if current_os == 'Linux':
		if is_tool("ifconfig"):
			out = os.popen("ifconfig").read().split('\n\n')
		else:
			sys.exit("[-] Can't find Linux ifconfig tool.")
	elif current_os == 'Darwin':
		if is_tool("netstat"):
			out = os.popen("netstat -i").read().split('\n')
		else:
			sys.exit("[-] Can't find macOS netstat tool.")
	else:
		sys.exit('MAC address change on this OS not supported :(')

	result = []
	for paragraph in out:
		d = {}
		iface = re.search('^([A-z]*\d)', paragraph)
		mac = re.search('([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})', paragraph)
		if mac and iface:
			d['iface'] = iface[0]
			d['mac'] = mac[0]
			result.append(d)
	return result

def avialible_ifaces_format():
	ifaces = get_avialible_ifaces()
	print("[!] Available interfaces:")
	for i in ifaces:
		iface = i['iface']
		mac = i['mac']
		print(f"{iface}: {mac}")

def mac_check(mac):
	if re.match(r"([0-9a-fA-F]{2}[-:]){5}[0-9a-fA-F]{2}$", mac):
		return 1
	else:
		return 0

def mac_random(m_type):
	'''
	More vendors: http://standards-oui.ieee.org/oui.txt
	Check MAC vendor: https://www.ipchecktool.com/tool/macfinder
	'''

	d = {'vendor': 'apple', 'mac': 'D4:61:9D'}, {'vendor': 'xen', 'mac': '02:00:00'}, {'vendor': 'huawei', 'mac': 'CC:05:77'}, {'vendor': 'cisco', 'mac': '30:8B:B2'}, {'vendor': 'samsung', 'mac': '8C:B8:4A'}, {'vendor': 'google', 'mac': '30:FD:38'}, {'vendor': 'juniper', 'mac': '20:D8:0B'}, {'vendor': 'dell', 'mac': 'E0:D8:48'}, {'vendor': 'broadcom', 'mac': 'BC:97:E1'}, {'vendor': 'tplink', 'mac': '54:A7:03'}, {'vendor': 'hp', 'mac': '40:B0:34'}, {'vendor': 'indel', 'mac': '00:E1:8C'}, {'vendor': 'dlink', 'mac': '10:62:EB'}, {'vendor': 'zte', 'mac': 'D0:71:C4'}, {'vendor': 'nokia', 'mac': '40:7C:7D'}, {'vendor': 'netgear', 'mac': '08:BD:43'}, {'vendor': 'microsoft', 'mac': '6C:5D:3A'}, {'vendor': 'xiaomi', 'mac': '2C:D0:66'}

	for i in d:
		if i["vendor"] == m_type:
			mac_part = i["mac"]

	try:
		mac_part
	except NameError:
		print(f"[-] Incorrect vendor: {m_type}")
		print(f"[!] Possible vendors: xen, huawei, cisco, samsung, google, juniper, dell, broadcom, tplink, hp, indel, dlink, zte, nokia, netgear, microsoft, xiaomi")
		sys.exit(0)
	else:
		random_mac = mac_part + ":%02x:%02x:%02x" % (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
		return random_mac

def do_backup(interface, old_mac, new_mac):
	# without checking permission because ifconfig needs root in all ways
	print(f"[+] Backup: {interface}: {old_mac} -> {new_mac} write in {backup_file}")
	file_to_write = open(backup_file, "a")
	file_to_write.write(interface + ": " + old_mac + " -> " + new_mac)
	file_to_write.write("\n")
	file_to_write.close()

def change_mac(interface, old_mac, new_mac):
	current_os = system()

	if is_tool("ifconfig"):
		if current_os == 'Linux':
			subprocess.call(["ifconfig", interface, "down"])
			subprocess.call(["ifconfig", interface, "hw", "ether", new_mac])
			subprocess.call(["ifconfig", interface, "up"])

		if current_os == 'Darwin': # a little bit different way on macOS
			subprocess.call(["ifconfig", interface, "ether", new_mac])
	else:
		print("[-] Error: ifconfig isn't installed. Try apt/yum install -y net-tools first.")
		sys.exit(0)

	ifaces = get_avialible_ifaces()

	for i in ifaces:
		if i["iface"] == interface:
			current_mac = i["mac"]

	if old_mac != current_mac:
		return 1
	else:
		return 0

def main():
	parser = argparse.ArgumentParser("Linux/macOS MAC address changer by n0a")
	parser.add_argument("-i", "--interface", help="set network interface")
	parser.add_argument("-m", "--mac", help="set new MAC. If not set MAC will be randomly generated.")
	parser.add_argument("-v", "--vendor", help="Set vendor for MAC: xen (default), huawei, cisco, samsung, google, juniper, dell, broadcom, tplink, hp, indel, dlink, zte, nokia, netgear, microsoft, xiaomi")

	options = parser.parse_args()

	iface_is_good	= False
	mac_is_good		= False
	random_enable	= False

	if options.interface is not None:
		interface 	= options.interface
		newmac 		= options.mac

		ifaces = get_avialible_ifaces()
		for i in ifaces:
			if i["iface"] == interface:
				old_mac = i["mac"]
				iface_is_good = True

		if iface_is_good:
			print(f"[+] Interface seems good: {interface}")
		else:
			print(f"[-] Interface {interface} can't do this shit.")
			avialible_ifaces_format()
			sys.exit(0)

		if options.mac is not None:
			if mac_check(newmac):
				mac_is_good = True
				print(f"[+] MAC address seems good: {newmac}")
			else:
				print(f"[+] But yours MAC address looks like shit: {newmac}")
				sys.exit(0)
		else:
			random_enable = True
			if options.vendor is not None:
				vendor = options.vendor
				random_mac = mac_random(options.vendor)
			else:
				vendor = default_vendor
				random_mac = mac_random(default_vendor)

			print(f"[+] Random MAC address for this case: [{vendor}] {random_mac}")

		if iface_is_good and mac_is_good:
			working_mac = newmac

		if iface_is_good and random_enable:
			working_mac = random_mac

		run = change_mac(interface, old_mac, working_mac)

		if run:
			if backup_enable:
				do_backup(interface, old_mac, working_mac)
			print(f"[+] Changing MAC from {old_mac} -> {working_mac} successful.")
		else:
			print(f"[-] Something wrong. Try run with sudo.")

	else:
		print("[-] Error: what about set network interface?")
		avialible_ifaces_format()
		print("")
		parser.print_help()
		sys.exit(0)

if __name__== "__main__":
	main()


"""
116. Populating Next Right Pointers in Each Node

"""
class Node:
    def __init__(self, val: int = 0, left = None, right= None, next= None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next

from collections import deque
class Solution:
    def connect(self, root):
        # level order traversal
        if not root:
            return root
        queue =deque()
        queue.append(root)
        while queue:
            newqueue = []
            prev = None
            while queue:
                cur = queue.pop()
                cur.next = prev
                # add next level
                if cur.right:
                    newqueue.append(cur.right)
                if cur.left:
                    newqueue.append(cur.left)
                prev = cur
            """ add right + left ==> reverse newqueue"""
            queue = newqueue[::-1]
            print(queue)
        return root

"""
sol 2
useing next pointer

 leftmost = root
 while (leftmost.left != null)
 {
     head = leftmost
     while (head.next != null)
     {
         1) Establish Connection 1
         2) Establish Connection 2 using next pointers
         head = head.next
     }
     leftmost = leftmost.left
 }
"""


import asyncio
import logging
import subprocess
from os import environ, system
from tastyworks.models.session import TastyAPISession
from tastyworks.streamer import DataStreamer
from tastyworks.tastyworks_api import tasty_session

LOGGER = logging.getLogger(__name__)

async def main_loop(session: TastyAPISession, streamer: DataStreamer):
    # Call TMT-CLI for active symbols (dxfeed style)
    symbols = subprocess.getoutput('tmt tasty_dxfeed')
    sub_values = {
        "Quote": symbols.split(',')
    }

    # Subscribe
    LOGGER.info(f'Adding subscription(s): {sub_values}')
    await streamer.add_data_sub(sub_values)

    # Update the bid/ask via TMT-CLI
    streamer_symbols = symbols.split(',')
    async for item in streamer.listen():
        for data in item.data:
            try:
                if not streamer_symbols:
                    break
                streamer_symbols.remove(data['eventSymbol'])
                # LOGGER.info('{} data: {}'.format(data['eventSymbol'], data))
                system('tmt tasty_stream {} --bid={} --ask={}'.format(data['eventSymbol'], data['bidPrice'], data['askPrice']))
                if not streamer_symbols:
                    break
            except:
                print('.', end='')
                continue
        if not streamer_symbols:
            break
    system('tmt tasty_refresh')
    LOGGER.info(f'================================ End')

def main():
    tasty_client = tasty_session.create_new_session(environ.get('TW_USER', ""), environ.get('TW_PASSWORD', ""))

    streamer = DataStreamer(tasty_client)
    loop = asyncio.get_event_loop()

    try:
        loop.run_until_complete(main_loop(tasty_client, streamer))
    except Exception:
        LOGGER.exception('Exception in streamer')
    except (KeyboardInterrupt, RuntimeError) as e:
        system('tmt tasty_refresh')
    finally:
        if loop.is_running():
            pending_tasks = [
                task for task in asyncio.all_tasks() if not task.done()
            ]
            if pending_tasks.size:
                loop.run_until_complete(asyncio.gather(*pending_tasks))

if __name__ == '__main__':
    main()


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

u"""
Модуль утилит для домашнего задания №4
"""

__author__ = "Mihail Zhelyaskov aka m_zhelyaskoff"
__copyright__ = "Copyright 2014, The Homework Project"
__version__ = "0.0.1"
__maintainer__ = "Mihail Zhelyaskov"
__email__ = "mzhelyaskov@yandex.ru"
__status__ = "Production"

import math

def calc_percent(rate, x=1, ndigits=0):
    u"""Вычисляет процентное значение x от rate

    Описание аргументов:
    rate -- значение которое соответствует 100 процентам
    x -- значение для которого вычисляется процент (default 1)
    ndigits -- округлить результат с заданной точностью в десятичных цифрах (default 0)
    """
    res = round(100.0 * x / rate, ndigits)
    return res


from tkinter import *

# from tkinter import filedialog

class Container:
    @staticmethod
    def create_menu(root, tearoff):
        menu = Menu(root)
        menu["tearoff"] = tearoff
        return menu

    @staticmethod
    def create_label(root, text, font, size):
        label = Label(root, text=text)
        label["font"] = (font, size)
        return label

    @staticmethod
    def create_button(root, text, font, width):
        btn = Button(root, text=text)
        btn["font"] = font
        btn["width"] = width
        return btn

    @staticmethod
    def create_radiobutton(root, text, var, value):
        return Radiobutton(root, text=text, variable=var, value=value)

    @staticmethod
    def var_radiobutton(typevar, setvalue):
        if typevar == "str":
            var = StringVar()
            var.set(setvalue)
        if typevar == "int":
            var = IntVar()
            var.set(setvalue)

    @staticmethod
    def container_pack(container, side):
        container.pack(side=side)

    @staticmethod
    def container_pack_forget(container):
        container.pack_forget()


names = ['femi', 'kamal', 'eniola', 'dinho']
print(names[0])

names[0] = 'seun'  # changing item in index 0

print(names)

# exercise 2 find largest no in a list

numbers = [3, 6, 20, 2, 8, 4, 2, 2, 2, 2, 2, 9]
highest = numbers[0]
for n in numbers:
    if n > highest:
        highest = n
print(f'MAx = {highest}')

# 2D LIST:

''' list methods: .insert(index, oject)

    .pop .remove. replace .clear(clears entires content of a list)

    .sort(you orint list after say: number.sort(), print(number)
    .reverse(does opposite of
     .COPY() '''

# duplicates

numbers = [2, 2, 4, 5, 6, 33, 8, 5, 6, 33]
uniques = []

for n in numbers:
    if n not in uniques:
        uniques.append(n)
print(uniques)


import cv2
import numpy as np
import tensorflow as tf
from color_correction import adain
from color_correction import color_hist_match

class FaceTransformer(object):
    """
    Attributes:
        path_func: string, direction for the transformation: either AtoB or BtoA.
        model: the generator of the faceswap-GAN model
    """
    def __init__(self, image_shape=(64, 64, 3)):
        self.path_func = None
        self.swap_sess_A = None
        self.swap_x_A = None
        self.swap_y_A = None
        self.swap_sess_B = None
        self.swap_x_B = None
        self.swap_y_B = None
        self.image_shape = image_shape

        self.inp_img = None
        self.input_size = None
        self.roi = None
        self.roi_size = None
        self.ae_input = None
        self.ae_output = None
        self.ae_output_masked = None
        self.ae_output_rgb = None
        self.ae_output_a = None
        self.result = None
        self.result_rawRGB = None
        self.result_alpha = None

    def set_model(self, model_path):
        # face swap model A
        swap_graph_def = tf.GraphDef()
        swap_graph_def.ParseFromString(open(model_path + "/pico_FaceSwapA_model.pb", "rb").read())
        tf.import_graph_def(swap_graph_def, name="")
        self.swap_sess_A = tf.Session()
        self.swap_sess_A.graph.get_operations()
        self.swap_x_A = self.swap_sess_A.graph.get_tensor_by_name("swap_inputA:0")
        self.swap_y_A = self.swap_sess_A.graph.get_tensor_by_name("model_2/concatenate_1/concat:0")

        # face swap model B
        swap_graph_def = tf.GraphDef()
        swap_graph_def.ParseFromString(open(model_path + "/pico_FaceSwapB_model.pb", "rb").read())
        tf.import_graph_def(swap_graph_def, name="")
        self.swap_sess_B = tf.Session()
        self.swap_sess_B.graph.get_operations()
        self.swap_x_B = self.swap_sess_B.graph.get_tensor_by_name("swap_inputB:0")
        self.swap_y_B = self.swap_sess_B.graph.get_tensor_by_name("model_4/concatenate_2/concat:0")

    def _preprocess_inp_img(self, input_img, roi_coverage, IMAGE_SHAPE):
        input_size = input_img.shape
        roi_x, roi_y = int(input_size[0]*(1-roi_coverage)), int(input_size[1]*(1-roi_coverage))
        roi = input_img[roi_x:-roi_x, roi_y:-roi_y,:] # RGB, [0, 255]
        roi_size = roi.shape
        ae_input = cv2.resize(roi, IMAGE_SHAPE[:2]) / 255. * 2 - 1 # BGR, [-1, 1]
        self.input_img = input_img
        self.input_size = input_size
        self.roi = roi
        self.roi_size = roi_size
        self.ae_input = ae_input

    def _ae_forward_pass(self, ae_input):
        ae_out = self.swap_sess_A
        self.ae_output = np.squeeze(np.array([ae_out]))

    def _postprocess_roi_img(self, ae_output, roi, roi_size, color_correction):
        ae_output_a = ae_output[:,:,0] * 255.0
        ae_output_a = cv2.resize(ae_output_a, (roi_size[1],roi_size[0]))[...,np.newaxis]
        ae_output_rgb = np.clip( (ae_output[:,:,1:] + 1) * 255.0 / 2, 0, 255)
        ae_output_rgb = cv2.resize(ae_output_rgb, (roi_size[1],roi_size[0]))
        ae_output_masked = (ae_output_a/255.0 * ae_output_rgb + (1 - ae_output_a/255.0) * roi).astype('uint8')
        self.ae_output_a = ae_output_a
        if color_correction == "adain":
            self.ae_output_masked = adain(ae_output_masked, roi)
            self.ae_output_rgb = adain(ae_output_rgb, roi)
        elif color_correction == "hist_match":
            self.ae_output_masked = color_hist_match(ae_output_masked, roi)
            self.ae_output_rgb = color_hist_match(ae_output_rgb, roi)
        else:
            self.ae_output_masked = ae_output_masked
            self.ae_output_rgb = ae_output_rgb

    def _merge_img_and_mask(self, ae_output_rgb, ae_output_masked, input_size, roi, roi_coverage):
        blend_mask = self.get_feather_edges_mask(roi, roi_coverage)
        blended_img = blend_mask/255.0 * ae_output_masked + (1-blend_mask/255.0) * roi
        result = self.inp_img.copy()
        roi_x, roi_y = int(input_size[0]*(1-roi_coverage)), int(input_size[1]*(1-roi_coverage))
        result[roi_x:-roi_x, roi_y:-roi_y,:] = blended_img.astype('uint8')
        result_rawRGB = self.inp_img.copy()
        result_rawRGB[roi_x:-roi_x, roi_y:-roi_y,:] = ae_output_rgb
        result_alpha = np.zeros_like(self.inp_img)
        result_alpha[roi_x:-roi_x, roi_y:-roi_y,:] = (blend_mask/255.0) * self.ae_output_a
        self.result = result
        self.result_rawRGB = result_rawRGB
        self.result_alpha = result_alpha

    @staticmethod
    def get_feather_edges_mask(img, roi_coverage):
        img_size = img.shape
        mask = np.zeros_like(img)
        roi_x, roi_y = int(img_size[0]*(1-roi_coverage)), int(img_size[1]*(1-roi_coverage))
        mask[roi_x:-roi_x, roi_y:-roi_y,:]  = 255
        mask = cv2.GaussianBlur(mask,(15,15),10)
        return mask

    def transform(self, inp_img, direction, roi_coverage, color_correction):

        self.check_roi_coverage(inp_img, roi_coverage)

        self.inp_img = inp_img

        # pre-process input image
        # Set 5 members: self.inp_img, self.input_size, self.roi, self.roi_size, self.ae_input
        self._preprocess_inp_img(self.inp_img, roi_coverage, self.image_shape)

        # model inference
        # Set 1 member: self.ae_output
        if direction == "AtoB":
            ae_out = self.swap_sess_B.run(self.swap_y_B, feed_dict={self.swap_x_B: [self.ae_input]})
            self.ae_output = np.squeeze(np.array([ae_out]))
        elif direction == "BtoA":
            ae_out = self.swap_sess_A.run(self.swap_y_A, feed_dict={self.swap_x_A: [self.ae_input]})
            self.ae_output = np.squeeze(np.array([ae_out]))
        else:
            raise ValueError("direction should be either AtoB or BtoA, recieved {direction}.")

        # post-process transformed roi image
        # Set 3 members: self.ae_output_a, self.ae_output_masked, self.ae_output_bgr
        self._postprocess_roi_img(self.ae_output, self.roi, self.roi_size, color_correction)

        # merge transformed output back to input image
        # Set 3 members: self.result, self.result_rawRGB, self.result_alpha
        self._merge_img_and_mask(self.ae_output_rgb, self.ae_output_masked,
                                 self.input_size, self.roi, roi_coverage)

        return self.result, self.result_rawRGB, self.result_alpha

    @staticmethod
    def check_roi_coverage(inp_img, roi_coverage):
        input_size = inp_img.shape
        roi_x, roi_y = int(input_size[0]*(1-roi_coverage)), int(input_size[1]*(1-roi_coverage))
        if roi_x == 0 or roi_y == 0:
            raise ValueError("Error occurs when cropping roi image. \
            Consider increasing min_face_area or decreasing roi_coverage.")


from flask import render_template,request,redirect,url_for
from . import main
from ..request import get_sources,get_articles
from ..models import Sources,Articles

#Views
@main.route('/')
def source():

    '''
    View root page function that returns the source page and its data
    '''
    #Getting general news
    general_news = get_sources('general')
    print(general_news)
    #getting technology news
    technology_news = get_sources('technology')
    #getting sport_news
    sport_news = get_sources('sports')
    #getting business news
    business_news = get_sources('business')
    #getting science news
    science_news = get_sources('science')

    title = 'Home -Let us get to the briefs'
    return render_template('source.html', title = title,general=general_news,technology=technology_news,sports=sport_news,business=business_news,science=science_news)

@main.route('/')
def article():
    '''
    Returns the article page and its data
    '''
    article=get_articles
    title ='Articles'
    return render_template('article.html',title=title,article = get_articles)


import numpy as np
from numba import jit
from collections import deque
import itertools
import os
import os.path as osp
import time
import torch
import cv2
import torch.nn.functional as F
from pt_soft_nms import soft_nms

from src.lib.models.model import create_model, load_model
from src.lib.models.decode import mot_decode
from src.lib.tracking_utils.utils import *
from src.lib.tracking_utils.log import logger
from src.lib.tracking_utils.kalman_filter import KalmanFilter
from src.lib.models import *
from src.lib.tracker import matching
from .basetrack import BaseTrack, TrackState
from src.lib.utils.post_process import ctdet_post_process
from src.lib.utils.image import get_affine_transform, transform_preds
from src.lib.models.utils import _tranpose_and_gather_feat, _gather_feat
from ..models.ada_decode import adamot_decode
from ..models.ada_model import AdaptiveNet

class STrack(BaseTrack):
    shared_kalman = KalmanFilter()
    def __init__(self, tlwh, score, temp_feat, buffer_size=30):

        # wait activate
        self._tlwh = np.asarray(tlwh, dtype=np.float)
        self.kalman_filter = None
        self.mean, self.covariance = None, None
        self.is_activated = False

        self.score = score
        self.tracklet_len = 0

        self.smooth_feat = None
        self.update_features(temp_feat)
        self.features = deque([], maxlen=buffer_size)
        self.alpha = 0.9

    def update_features(self, feat):
        feat /= np.linalg.norm(feat)
        self.curr_feat = feat
        if self.smooth_feat is None:
            self.smooth_feat = feat
        else:
            self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat
        self.features.append(feat)
        self.smooth_feat /= np.linalg.norm(self.smooth_feat)

    def predict(self):
        mean_state = self.mean.copy()
        if self.state != TrackState.Tracked:
            mean_state[7] = 0
        self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)

    @staticmethod
    def multi_predict(stracks):
        if len(stracks) > 0:
            multi_mean = np.asarray([st.mean.copy() for st in stracks])
            multi_covariance = np.asarray([st.covariance for st in stracks])
            for i, st in enumerate(stracks):
                if st.state != TrackState.Tracked:
                    multi_mean[i][7] = 0
            multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)
            for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
                stracks[i].mean = mean
                stracks[i].covariance = cov

    def activate(self, kalman_filter, frame_id):
        """Start a new tracklet"""
        self.kalman_filter = kalman_filter
        self.track_id = self.next_id()
        self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xyah(self._tlwh))

        self.tracklet_len = 0
        self.state = TrackState.Tracked
        if frame_id == 1:
            self.is_activated = True
        #self.is_activated = True
        self.frame_id = frame_id
        self.start_frame = frame_id

    def re_activate(self, new_track, frame_id, new_id=False):
        self.mean, self.covariance = self.kalman_filter.update(
            self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh)
        )

        self.update_features(new_track.curr_feat)
        self.tracklet_len = 0
        self.state = TrackState.Tracked
        self.is_activated = True
        self.frame_id = frame_id
        if new_id:
            self.track_id = self.next_id()

    def update(self, new_track, frame_id, update_feature=True):
        """
        Update a matched track
        :type new_track: STrack
        :type frame_id: int
        :type update_feature: bool
        :return:
        """
        self.frame_id = frame_id
        self.tracklet_len += 1

        new_tlwh = new_track.tlwh
        self.mean, self.covariance = self.kalman_filter.update(
            self.mean, self.covariance, self.tlwh_to_xyah(new_tlwh))
        self.state = TrackState.Tracked
        self.is_activated = True

        self.score = new_track.score
        if update_feature:
            self.update_features(new_track.curr_feat)

    @property
    # @jit(nopython=True)
    def tlwh(self):
        """Get current position in bounding box format `(top left x, top left y,
                width, height)`.
        """
        if self.mean is None:
            return self._tlwh.copy()
        ret = self.mean[:4].copy()
        ret[2] *= ret[3]
        ret[:2] -= ret[2:] / 2
        return ret

    @property
    # @jit(nopython=True)
    def tlbr(self):
        """Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
        `(top left, bottom right)`.
        """
        ret = self.tlwh.copy()
        ret[2:] += ret[:2]
        return ret

    @staticmethod
    # @jit(nopython=True)
    def tlwh_to_xyah(tlwh):
        """Convert bounding box to format `(center x, center y, aspect ratio,
        height)`, where the aspect ratio is `width / height`.
        """
        ret = np.asarray(tlwh).copy()
        ret[:2] += ret[2:] / 2
        ret[2] /= ret[3]
        return ret

    def to_xyah(self):
        return self.tlwh_to_xyah(self.tlwh)

    @staticmethod
    # @jit(nopython=True)
    def tlbr_to_tlwh(tlbr):
        ret = np.asarray(tlbr).copy()
        ret[2:] -= ret[:2]
        return ret

    @staticmethod
    # @jit(nopython=True)
    def tlwh_to_tlbr(tlwh):
        ret = np.asarray(tlwh).copy()
        ret[2:] += ret[:2]
        return ret

    def __repr__(self):
        return 'OT_{}_({}-{})'.format(self.track_id, self.start_frame, self.end_frame)

class AdaTracker(object):
    def __init__(self, opt, frame_rate=30):
        self.opt = opt
        if opt.gpus[0] >= 0:
            opt.device = torch.device('cuda')
        else:
            opt.device = torch.device('cpu')
        print('Creating model...')
        # self.model = create_model(opt.arch, opt.heads, opt.head_conv)
        self.model = AdaptiveNet(backbone_name='dla', num_class=1, layers=34, gn=False, head_conv=256, reid_dim=opt.reid_dim, is_train=False)
        self.model = _load_model(self.model, opt.load_model)
        self.model = self.model.to(opt.device)
        self.model.eval()

        self.tracked_stracks = []  # type: list[STrack]
        self.lost_stracks = []  # type: list[STrack]
        self.removed_stracks = []  # type: list[STrack]

        self.frame_id = 0
        self.det_thresh = opt.conf_thres
        self.buffer_size = int(frame_rate / 30.0 * opt.track_buffer)
        self.max_time_lost = self.buffer_size
        self.max_per_image = opt.K
        self.mean = np.array(opt.mean, dtype=np.float32).reshape(1, 1, 3)
        self.std = np.array(opt.std, dtype=np.float32).reshape(1, 1, 3)

        self.kalman_filter = KalmanFilter()

        self.no_nms = opt.no_nms
        print('===> using Soft-NMS ?:', not self.no_nms)

    def post_process(self, dets, meta):
        dets = dets.detach().cpu().numpy()
        dets = dets.reshape(1, -1, dets.shape[2])
        dets = ctdet_post_process(
            dets.copy(), [meta['c']], [meta['s']],
            meta['out_height'], meta['out_width'], self.opt.num_classes)
        for j in range(1, self.opt.num_classes + 1):
            dets[0][j] = np.array(dets[0][j], dtype=np.float32).reshape(-1, 5)
        return dets[0]

    def merge_outputs(self, detections):
        results = {}
        for j in range(1, self.opt.num_classes + 1):
            results[j] = np.concatenate(
                [detection[j] for detection in detections], axis=0).astype(np.float32)

        scores = np.hstack(
            [results[j][:, 4] for j in range(1, self.opt.num_classes + 1)])
        if len(scores) > self.max_per_image:
            kth = len(scores) - self.max_per_image
            thresh = np.partition(scores, kth)[kth]
            for j in range(1, self.opt.num_classes + 1):
                keep_inds = (results[j][:, 4] >= thresh)
                results[j] = results[j][keep_inds]
        return results

    def update(self, im_blob, img0):
        self.frame_id += 1
        activated_starcks = []
        refind_stracks = []
        lost_stracks = []
        removed_stracks = []

        width = img0.shape[1]
        height = img0.shape[0]
        inp_height = im_blob.shape[2]
        inp_width = im_blob.shape[3]
        c = np.array([width / 2., height / 2.], dtype=np.float32)
        s = max(float(inp_width) / float(inp_height) * height, width) * 1.0
        # meta = {'c': c, 's': s,
        #         'out_height': inp_height // self.opt.down_ratio,
        #         'out_width': inp_width // self.opt.down_ratio}
        meta = {'c': c, 's': s,
                'out_height': inp_height,
                'out_width': inp_width}

        ''' Step 1: Network forward, get detections & embeddings'''
        with torch.no_grad():
            output = self.model(im_blob)[-1]
            cls_logits = output['cls_pred_logits']
            bbox = output['bbox_preds']
            id_feature = output['id_emb_logits']
            id_feature = F.normalize(id_feature, dim=1)
            dets, inds = adamot_decode(cls_logits, bbox, K=self.opt.K, nms=False)
            # dets, inds = adamot_decode(cls_logits, bbox, K=100, nms=False)
            id_feature = _gather_feat(id_feature.flatten(1, 2), inds)
            '''
                def _tranpose_and_gather_feat(feat, ind):
                    feat = feat.permute(0, 2, 3, 1).contiguous()
                    feat = feat.view(feat.size(0), -1, feat.size(3))
                    feat = _gather_feat(feat, ind)
                    return feat
            '''
            id_feature = id_feature.squeeze(0)
            id_feature = id_feature.cpu().numpy()

            grids = gen_grids(cls_logits)
            grids = grids.permute(1, 2, 0).view(-1, 2)
            pt_xy = grids[inds]
            pt_xy = pt_xy.cpu().numpy()

        dets = self.post_process(dets, meta)
        dets = self.merge_outputs([dets])[1]

        # default: 0.4
        remain_inds = dets[:, 4] > self.opt.conf_thres
        dets = dets[remain_inds]

        id_feature = id_feature[remain_inds]
        # pt_xy = pt_xy[0, remain_inds]

        if not self.no_nms:
            _, keep = soft_nms(torch.from_numpy(dets[:, :4]), torch.from_numpy(dets[:, 4]), 0.5, 0.2)
            dets = dets[keep]
            id_feature = id_feature[keep]

            # pt_xy = pt_xy[keep]
            # pt_xy[:, :] = transform_preds(
            #     pt_xy[:, :], meta['c'], meta['s'],  (meta['out_width'], meta['out_height']))

        # vis
        # for i in range(0, dets.shape[0]):
        #     bbox = dets[i][0:4]
        #     cv2.rectangle(img0, (bbox[0], bbox[1]),
        #                   (bbox[2], bbox[3]),
        #                   (0, 255, 0), 2)
        #     xy = pt_xy[i]
        #     cv2.circle(img0, (int(xy[0]), int(xy[1])), 1, (0, 255, 0), 5)
        # cv2.imshow('dets', img0)
        # cv2.waitKey(0)
        # id0 = id0-1

        # for i in range(0, pt_xy.shape[0]):
        #     xy = pt_xy[i]
        #     cv2.circle(img0, (int(xy[0]), int(xy[1])), 1, (0, 255, 0), 2)
        # cv2.imshow('dets', img0)
        # cv2.waitKey(0)

        if len(dets) > 0:
            '''Detections'''
            if len(dets.shape) == 1:
                dets = dets.reshape(1, -1)
                id_feature = id_feature.reshape(1, -1)
            detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
                          (tlbrs, f) in zip(dets[:, :5], id_feature)]
        else:
            detections = []

        ''' Add newly detected tracklets to tracked_stracks'''
        unconfirmed = []
        tracked_stracks = []  # type: list[STrack]
        for track in self.tracked_stracks:
            if not track.is_activated:
                unconfirmed.append(track)
            else:
                tracked_stracks.append(track)

        ''' Step 2: First association, with embedding'''
        strack_pool = joint_stracks(tracked_stracks, self.lost_stracks)
        # Predict the current location with KF
        #for strack in strack_pool:
            #strack.predict()
        STrack.multi_predict(strack_pool)
        dists = matching.embedding_distance(strack_pool, detections)
        #dists = matching.iou_distance(strack_pool, detections)
        dists = matching.fuse_motion(self.kalman_filter, dists, strack_pool, detections)
        matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.4)

        for itracked, idet in matches:
            track = strack_pool[itracked]
            det = detections[idet]
            if track.state == TrackState.Tracked:
                track.update(detections[idet], self.frame_id)
                activated_starcks.append(track)
            else:
                track.re_activate(det, self.frame_id, new_id=False)
                refind_stracks.append(track)

        ''' Step 3: Second association, with IOU'''
        detections = [detections[i] for i in u_detection]
        r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
        dists = matching.iou_distance(r_tracked_stracks, detections)
        matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)

        for itracked, idet in matches:
            track = r_tracked_stracks[itracked]
            det = detections[idet]
            if track.state == TrackState.Tracked:
                track.update(det, self.frame_id)
                activated_starcks.append(track)
            else:
                track.re_activate(det, self.frame_id, new_id=False)
                refind_stracks.append(track)

        for it in u_track:
            track = r_tracked_stracks[it]
            if not track.state == TrackState.Lost:
                track.mark_lost()
                lost_stracks.append(track)

        '''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
        detections = [detections[i] for i in u_detection]
        dists = matching.iou_distance(unconfirmed, detections)
        matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
        for itracked, idet in matches:
            unconfirmed[itracked].update(detections[idet], self.frame_id)
            activated_starcks.append(unconfirmed[itracked])
        for it in u_unconfirmed:
            track = unconfirmed[it]
            track.mark_removed()
            removed_stracks.append(track)

        """ Step 4: Init new stracks"""
        for inew in u_detection:
            track = detections[inew]
            if track.score < self.det_thresh:
                continue
            track.activate(self.kalman_filter, self.frame_id)
            activated_starcks.append(track)
        """ Step 5: Update state"""
        for track in self.lost_stracks:
            if self.frame_id - track.end_frame > self.max_time_lost:
                track.mark_removed()
                removed_stracks.append(track)

        # print('Ramained match {} s'.format(t4-t3))

        self.tracked_stracks = [t for t in self.tracked_stracks if t.state == TrackState.Tracked]
        self.tracked_stracks = joint_stracks(self.tracked_stracks, activated_starcks)
        self.tracked_stracks = joint_stracks(self.tracked_stracks, refind_stracks)
        self.lost_stracks = sub_stracks(self.lost_stracks, self.tracked_stracks)
        self.lost_stracks.extend(lost_stracks)
        self.lost_stracks = sub_stracks(self.lost_stracks, self.removed_stracks)
        self.removed_stracks.extend(removed_stracks)
        self.tracked_stracks, self.lost_stracks = remove_duplicate_stracks(self.tracked_stracks, self.lost_stracks)
        # get scores of lost tracks
        output_stracks = [track for track in self.tracked_stracks if track.is_activated]

        logger.debug('===========Frame {}=========='.format(self.frame_id))
        logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks]))
        logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks]))
        logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks]))
        logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks]))

        return output_stracks

def joint_stracks(tlista, tlistb):
    exists = {}
    res = []
    for t in tlista:
        exists[t.track_id] = 1
        res.append(t)
    for t in tlistb:
        tid = t.track_id
        if not exists.get(tid, 0):
            exists[tid] = 1
            res.append(t)
    return res

def sub_stracks(tlista, tlistb):
    stracks = {}
    for t in tlista:
        stracks[t.track_id] = t
    for t in tlistb:
        tid = t.track_id
        if stracks.get(tid, 0):
            del stracks[tid]
    return list(stracks.values())

def remove_duplicate_stracks(stracksa, stracksb):
    pdist = matching.iou_distance(stracksa, stracksb)
    pairs = np.where(pdist < 0.15)
    dupa, dupb = list(), list()
    for p, q in zip(*pairs):
        timep = stracksa[p].frame_id - stracksa[p].start_frame
        timeq = stracksb[q].frame_id - stracksb[q].start_frame
        if timep > timeq:
            dupb.append(q)
        else:
            dupa.append(p)
    resa = [t for i, t in enumerate(stracksa) if not i in dupa]
    resb = [t for i, t in enumerate(stracksb) if not i in dupb]
    return resa, resb

def _load_model(model, model_path, optimizer=None, resume=False,
               lr=None, lr_step=None):

    start_epoch = 0
    checkpoint = torch.load(model_path, map_location=lambda storage, loc: storage)
    print('loaded {}, epoch {}'.format(model_path, checkpoint['epoch']))
    # state_dict_ = checkpoint['state_dict']
    # print(checkpoint.keys())
    state_dict_ = checkpoint['state_dict']

    state_dict = {}

    # convert data_parallal to model
    for k in state_dict_:
        if k.startswith('module') and not k.startswith('module_list'):
            state_dict[k[7:]] = state_dict_[k]
        else:
            state_dict[k] = state_dict_[k]
    model_state_dict = model.state_dict()

    # check loaded parameters and created model parameters
    msg = 'If you see this, your model does not fully load the ' + \
          'pre-trained weight. Please make sure ' + \
          'you have correctly specified --arch xxx ' + \
          'or set the correct --num_classes for your own dataset.'
    for k in state_dict:
        if k in model_state_dict:
            if state_dict[k].shape != model_state_dict[k].shape:
                print('Skip loading parameter {}, required shape{}, ' \
                      'loaded shape{}. {}'.format(
                    k, model_state_dict[k].shape, state_dict[k].shape, msg))
                state_dict[k] = model_state_dict[k]
        else:
            print('Drop parameter {}.'.format(k) + msg)
    for k in model_state_dict:
        if not (k in state_dict):
            print('No param {}.'.format(k) + msg)
            state_dict[k] = model_state_dict[k]
    model.load_state_dict(state_dict, strict=False)

    # resume optimizer parameters
    if optimizer is not None and resume:
        if 'optimizer' in checkpoint:
            optimizer.load_state_dict(checkpoint['optimizer'])
            start_epoch = checkpoint['epoch']
            start_lr = lr
            for step in lr_step:
                if start_epoch >= step:
                    start_lr *= 0.1
            for param_group in optimizer.param_groups:
                param_group['lr'] = start_lr
            print('Resumed optimizer with start lr', start_lr)
        else:
            print('No optimizer parameters in checkpoint.')
    if optimizer is not None:
        return model, optimizer, start_epoch
    else:
        return model

def gen_grids(heatmap):
    bs, hs, ws, _ = heatmap.shape
    device = heatmap.device

    shifts_x = torch.arange(
        0, ws * 4, step=4,
        dtype=torch.float32, device=device)

    shifts_y = torch.arange(
        0, hs * 4, step=4,
        dtype=torch.float32, device=device)

    shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)
    shift_x = shift_x.reshape(-1)
    shift_y = shift_y.reshape(-1)
    grids = torch.stack((shift_x, shift_y), dim=1) + 4 // 2

    # [2, H, W]
    grids = grids.reshape(hs, ws, 2).permute(2, 0, 1)

    return grids


'''
- 1<=n<=10억
- 1<=time<=10억
- 1<=심사관<=10만
- 모든 사람이 심사를 받는데 걸리는 시간을 최소로
>>> 각 심사관이 처리한 사람을 m1,m2,m3 ... 라 할때,
    m1 + m2 + m3 + ... = n이 되도록 한다
    이때 time*m의 최댓값이 최소가 되도록 해야한다

>>> 매개변수로 풀어야 할 것 같은데?
    - 최댓값이 x일때 m1+m2+...=n을 만족하는가?
    - times를 정렬할 수 있음

>>> greedy적으로 풀어보는건?
    - 최소 시간에 먼저 집어넣고, 이후 초과되면 다른 시간도 올려주는 방법

>>>>>>> 매개변수로 풀어보자
'''
def solution(n, times):
    # 각 심사관이 몇명을 통과시켰는지 확인하는 함수
    def check(target, takeTime, times):
        cur = 0
        # 각 심사관이 통과시킨 사람을 cur에 더해줌
        for examiner in times:
            cur += takeTime//examiner
        # 전체 통과 인원이 target과 같다면 true를 리턴
        return True if cur >= target else False

    # 심사 시간의 최솟값을 찾는 이분탐색 : 심사시간을 매개변수로 잡음
    def binary_search(target, times):
        l = 1
        r = times[-1] * target
        minTime = 1e9
        while l<=r:
            mid = (l+r)//2
            # check를 통과했다면, 시간이 충분하다는 뜻이므로 더 줄여봄
            if check(target, mid, times):
                minTime = mid
                r = mid-1
            else:
                l = mid+1
        return minTime

    # 이분탐색을 하기 위해 times를 정렬하여 사용
    times.sort()
    answer = binary_search(n,times)
    return answer

프로그래머스/lv3/43238. 입국심사/입국심사.py


a=eval(input())
for i in range(a):
    b=[int(x) for x in input().split()]
    c=[int(x) for x in input().split()]
    j=0;d=[]

    if(b[j]<c[j] and c[j]<b[j+2]) or(b[j]<c[j+2] and c[j+2]<b[j+2]):
        d.append(True)
    else:
        d.append(False)
    j=1
    if (b[j+2] < c[j] and c[j] < b[j]) or (b[j+2] < c[j + 2] and c[j + 2] < b[j]):
        d.append(True)
    else:
        d.append(False)
    if(d[0] and d[1]):
        print(1)
    else:
        print(0)


"""Ensemble backend that combines results from multiple projects"""
from __future__ import annotations

from typing import TYPE_CHECKING, Any

import annif.eval
import annif.parallel
import annif.util
from annif.exception import NotSupportedException
from annif.suggestion import SuggestionBatch

from . import backend, hyperopt

if TYPE_CHECKING:
    from datetime import datetime

    from optuna.study.study import Study
    from optuna.trial import Trial

    from annif.backend.hyperopt import HPRecommendation
    from annif.corpus.document import DocumentCorpus

class BaseEnsembleBackend(backend.AnnifBackend):
    """Base class for ensemble backends"""

    def _get_sources_attribute(self, attr: str) -> list[bool | None]:
        params = self._get_backend_params(None)
        sources = annif.util.parse_sources(params["sources"])
        return [
            getattr(self.project.registry.get_project(project_id), attr)
            for project_id, _ in sources
        ]

    def initialize(self, parallel: bool = False) -> None:
        # initialize all the source projects
        params = self._get_backend_params(None)
        for project_id, _ in annif.util.parse_sources(params["sources"]):
            project = self.project.registry.get_project(project_id)
            project.initialize(parallel)

    def _suggest_with_sources(
        self, texts: list[str], sources: list[tuple[str, float]]
    ) -> dict[str, SuggestionBatch]:
        return {
            project_id: self.project.registry.get_project(project_id).suggest(texts)
            for project_id, _ in sources
        }

    def _merge_source_batches(
        self,
        batch_by_source: dict[str, SuggestionBatch],
        sources: list[tuple[str, float]],
        params: dict[str, Any],
    ) -> SuggestionBatch:
        """Merge the given SuggestionBatches from each source into a single
        SuggestionBatch. The default implementation computes a weighted
        average based on the weights given in the sources tuple. Intended
        to be overridden in subclasses."""

        batches = [batch_by_source[project_id] for project_id, _ in sources]
        weights = [weight for _, weight in sources]
        return SuggestionBatch.from_averaged(batches, weights).filter(
            limit=int(params["limit"])
        )

    def _suggest_batch(
        self, texts: list[str], params: dict[str, Any]
    ) -> SuggestionBatch:
        sources = annif.util.parse_sources(params["sources"])
        batch_by_source = self._suggest_with_sources(texts, sources)
        return self._merge_source_batches(batch_by_source, sources, params)

class EnsembleOptimizer(hyperopt.HyperparameterOptimizer):
    """Hyperparameter optimizer for the ensemble backend"""

    def __init__(
        self, backend: EnsembleBackend, corpus: DocumentCorpus, metric: str
    ) -> None:
        super().__init__(backend, corpus, metric)
        self._sources = [
            project_id
            for project_id, _ in annif.util.parse_sources(
                backend.config_params["sources"]
            )
        ]

    def _prepare(self, n_jobs: int = 1) -> None:
        self._gold_batches = []
        self._source_batches = []

        for project_id in self._sources:
            project = self._backend.project.registry.get_project(project_id)
            project.initialize()

        psmap = annif.parallel.ProjectSuggestMap(
            self._backend.project.registry,
            self._sources,
            backend_params=None,
            limit=int(self._backend.params["limit"]),
            threshold=0.0,
        )

        jobs, pool_class = annif.parallel.get_pool(n_jobs)

        with pool_class(jobs) as pool:
            for suggestions, gold_batch in pool.imap_unordered(
                psmap.suggest_batch, self._corpus.doc_batches
            ):
                self._source_batches.append(suggestions)
                self._gold_batches.append(gold_batch)

    def _normalize(self, hps: dict[str, float]) -> dict[str, float]:
        total = sum(hps.values())
        return {source: hps[source] / total for source in hps}

    def _format_cfg_line(self, hps: dict[str, float]) -> str:
        return "sources=" + ",".join(
            [f"{src}:{weight:.4f}" for src, weight in hps.items()]
        )

    def _objective(self, trial: Trial) -> float:
        eval_batch = annif.eval.EvaluationBatch(self._backend.project.subjects)
        proj_weights = {
            project_id: trial.suggest_float(project_id, 0.0, 1.0)
            for project_id in self._sources
        }
        for gold_batch, src_batches in zip(self._gold_batches, self._source_batches):
            batches = [src_batches[project_id] for project_id in self._sources]
            weights = [proj_weights[project_id] for project_id in self._sources]
            avg_batch = SuggestionBatch.from_averaged(batches, weights).filter(
                limit=int(self._backend.params["limit"])
            )
            eval_batch.evaluate_many(avg_batch, gold_batch)
        results = eval_batch.results(metrics=[self._metric])
        return results[self._metric]

    def _postprocess(self, study: Study) -> HPRecommendation:
        line = self._format_cfg_line(self._normalize(study.best_params))
        return hyperopt.HPRecommendation(lines=[line], score=study.best_value)

class EnsembleBackend(BaseEnsembleBackend, hyperopt.AnnifHyperoptBackend):
    """Ensemble backend that combines results from multiple projects"""

    name = "ensemble"

    @property
    def is_trained(self) -> bool:
        sources_trained = self._get_sources_attribute("is_trained")
        return all(sources_trained)

    @property
    def modification_time(self) -> datetime | None:
        mtimes = self._get_sources_attribute("modification_time")
        return max(filter(None, mtimes), default=None)

    def get_hp_optimizer(
        self, corpus: DocumentCorpus, metric: str
    ) -> EnsembleOptimizer:
        return EnsembleOptimizer(self, corpus, metric)

    def _train(self, corpus: DocumentCorpus, params: dict[str, Any], jobs: int = 0):
        raise NotSupportedException("Training ensemble backend is not possible.")


'''7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence:    0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.
You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.'''
#solution
file = open(input('enter file name: '))
#string to be found
identifier = 'X-DSPAM-Confidence: '
#place to store all found numbers
all_nos = ''
#serching through file for line with identifier
for i in file:
    if i.startswith(identifier):
        all_nos += i[identifier.index(identifier[-1]):-1]
#I know there is sum() & len() function, but I wanna do it with loops, so add for sum and count for no
count = 0
add = 0
for p in all_nos.split():
    add = add + float(p)
    count += 1
print(add / count)


class Solution:
    def numWays(self, steps: int, arrLen: int) -> int:

        mod = 1e9 + 7
        @lru_cache(maxsize=None)
        def dp(balance, s):
            if s == steps:
                if balance == 0: return 1
                else: return 0

            cnt =  dp(balance, s+1)
            if balance > 0: cnt += dp(balance-1, s+1)
            if balance < arrLen-1: cnt += dp(balance+1, s+1)
            return int(cnt % mod)

        return dp(0, 0)


from db import db

def add_rating(rating, course_id):
    sql="""INSERT INTO reviews (rating, course_id) VALUES (:rating, :course_id)"""
    db.session.execute(sql, {"rating":rating, "course_id":course_id})
    db.session.commit()

def rev(id):
    sql= """SELECT rating FROM reviews WHERE course_id=:id"""
    result_list = db.session.execute(sql, {"id":id}).fetchall()
    if len(result_list) == 0:
        return None
    return result_list

def fit(id):
    sql= """SELECT fit FROM shape WHERE course_id=:id"""
    fit_list = db.session.execute(sql, {"id":id}).fetchall()
    if len(fit_list) == 0:
        return None
    return fit_list

def add_shape(fit, course_id):
    sql="""INSERT INTO shape (fit, course_id) VALUES (:fit, :course_id)"""
    db.session.execute(sql, {"fit":fit, "course_id":course_id})
    db.session.commit()


#!/usr/bin/python3
"""prints the State object with name passed as argument from hbtn_0e_6_usa"""
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sys import argv
from model_state import Base, State

if __name__ == "__main__":
    connector = 'mysql+mysqldb://{}:{}@localhost/{}'
    engine = create_engine(connector.format(
        argv[1], argv[2], argv[3]), pool_pre_ping=True)
    Base.metadata.create_all(engine)
    Base.metadata.bind = engine
    Session = sessionmaker()
    Session.bind = engine
    session = Session()

    state = session.query(State).filter(State.name == argv[4]).first()
    print("Not found" if not state else state.id)
    session.close()