import json

from json.decoder import JSONDecodeError

from collections import defaultdict

from django.http import (
    HttpResponse,
    HttpResponseBadRequest,
    HttpResponseForbidden,
    HttpResponseNotFound
)
from django.shortcuts import render, redirect

from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required

from django.views.decorators.csrf import csrf_exempt

from bbq_organizer.models import Event
from bbq_organizer.models import MeatType
from bbq_organizer.models import MeatOption
from bbq_organizer.models import MeatChoice
from bbq_organizer.models import SignUp

from bbq_organizer.forms import EventForm

@login_required
def home(request):
    return render(request, "home.html")

@login_required
def create_event(request):
    meats = MeatType.objects.all().order_by("name")

    if request.method == "POST":
        form = EventForm(request.POST)

        if form.is_valid():
            meats_string = request.POST.get("meats")
            meats = {}
            if meats_string:
                try:
                    meats = json.loads(meats_string)
                except JSONDecodeError:
                    messages.add_message(
                        request, messages.ERROR, "Malformed meats json"
                    )
                    return redirect("/error/")

            intermediate_form = form.save(commit=False)
            intermediate_form.author = request.user
            event = intermediate_form.save()

            for key, value in meats.items():
                if value:
                    option = MeatOption(event=event, meat_id=key)
                    option.save()

            return redirect("/events/admin/{}".format(event.slug))
    else:
        form = EventForm()

    # Return meats selected so far in case the form is not valid
    meats_chosen = {}
    meats_chosen_string = request.POST.get("meats")
    if meats_chosen_string:
        try:
            meats_chosen = json.loads(meats_chosen_string)
        except JSONDecodeError:
            messages.add_message(
                request, messages.ERROR, "Malformed meats json"
            )
            return redirect("/error/")

    # Remove meats that were chosen and unselected
    keys = list(meats_chosen.keys())
    for key in keys:
        if meats_chosen[key] is False:
            del meats_chosen[key]

    return render(
        request,
        "create_event.html",
        {"form": form, "meats": meats, "meats_chosen": meats_chosen},
    )

@login_required
def admin_event(request, slug):
    event = Event.objects.filter(slug=slug).first()
    if event is None:
        messages.add_message(
            request, messages.ERROR, "Event does not exist"
        )
        return redirect("/error/")

    host = request.get_host()
    url = "{}/events/invite/{}".format(host, event.slug)

    signups = SignUp.objects.filter(event__pk=event.id)
    meatchoices = []

    total = 0
    for signup in signups:
        meatchoices.extend(MeatChoice.objects.filter(signup__pk=signup.id))
        total += signup.extras + 1

    meat_count = defaultdict(int)
    for meatchoice in meatchoices:
        meat_count[meatchoice.meat.name] += 1

    return render(
        request,
        "admin_event.html",
        {
            "event": event,
            "url": url,
            "meats": dict(meat_count),
            "signups": signups,
            "total": total,
        },
    )

def invite_event(request, slug):
    value = request.COOKIES.get("registered")
    if value != slug:
        event = Event.objects.filter(slug=slug).first()
        if event:
            meats = MeatOption.objects.filter(event__pk=event.id)
            return render(
                request, "invite_event.html", {"event": event, "meats": meats}
            )
        else:
            return render(request, "does_not_exist.html")
    return render(request, "already_registered.html")

@csrf_exempt
@login_required
def register_event(request, slug):
    if request.method == "POST":
        value = request.COOKIES.get("registered")
        if value != slug:
            data = json.loads(request.body)

            extras = data.get("extras", 0)
            name = data.get("name", "")
            meats = data.get("meats", [])
            event = Event.objects.filter(slug=slug).first()

            if event is None:
                return HttpResponseNotFound()

            try:
                extras = int(extras)
            except ValueError:
                return HttpResponseBadRequest("invalid numeric value")
            if extras < 0:
                return HttpResponseBadRequest("extras cannot be less than 0")

            if name == "":
                return HttpResponseBadRequest("name cannot be blank")

            signup = SignUp(event=event, extras=extras, name=name)
            signup = signup.save()

            for meat in meats:
                try:
                    meat_id = int(meat)
                    meat = MeatType.objects.filter(pk=meat_id).first()
                    if meat is not None:
                        meat_choice = MeatChoice(signup=signup, meat_id=meat_id)
                        meat_choice.save()
                    else:
                        messages.add_message(
                            request, messages.ERROR, "Invalid meat value"
                        )
                        return redirect("/error/")
                except ValueError:
                    messages.add_message(
                        request, messages.ERROR, "Invalid meat value"
                    )
                    return redirect("/error/")

            response = HttpResponse()
            response.set_cookie("registered", slug)
            return response
        else:
            return HttpResponseForbidden()
    else:
        return render(request, "already_registered.html")

@login_required
def events_list(request):
    events = Event.objects.filter(author__pk=request.user.id)
    return render(request, "events_list.html", {"events": events})

def signup(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data["username"]
            messages.add_message(
                request, messages.INFO, "{} signed up successfully".format(username)
            )
            return redirect("login")
    else:
        form = UserCreationForm()
    return render(request, "signup.html", {"form": form})

@login_required
@csrf_exempt
def delete_event(request):
    if request.method == "POST":
        data = json.loads(request.body)
        try:
            Event.objects.get(slug=data["slug"]).delete()
        except Event.DoesNotExist:
            messages.add_message(
                request, messages.ERROR, "Event does not exist"
            )
            return redirect("/error/")

        return HttpResponse("")

def view_404(request, exception):
    return redirect("/")


'''Exercício Python 114: Crie um código em Python que teste se o site pudim está acessível pelo computador usado.'''

import urllib
import urllib.request
import webbrowser
url=input("Insira uma url pra saber se está acessível : ")
try:
    site=urllib.request.urlopen(url)
except:
    print(f"O site {url} não está acessível no momento")
else:
    print(f"O site {url} está acessível no momento")
    webbrowser.open(url)


# 汇入 excel 并新增字段
import pandas as pd

# 请注意路径随环境更改，且路径符号是用"斜线"!
# sheet_name 可以指定要 excel 中的哪个工作表
data1 = pd.read_excel("C:/Users/Administrator/Desktop/python/2330_211202.xlsx")

# # value 型态可以混用，但各个 key 包含的参数量一定要一致
# data2 = pd.DataFrame({
#     '券商分点': 1,
#     '绩效': [2],
#     '总损益(仟)': [3],
#     '买卖超': [4],
#     '均价': [5]
# })
# # 将两笔数据合并
# # ignore_index:忽略合并时旧的 index 字段，改采用自动产生的 index
# dataAppend = data1.append(data2, ignore_index=True)

# mean() 取字段平均
# 指定一列取平均，若没有指定列，会自动确定哪些列适合应用 mean() 功能
performance_average = data1['绩效'].mean()
dataAppend = data1.append(data1.mean(), ignore_index=True)


import os
import csv
election_data = os.path.join('election_data.csv')
with open(election_data, newline='') as csvfile:
    csvreader = csv.reader (csvfile, delimiter=',')
    print (csvreader)
    csv_header = next (csvreader)

    candidatelist =[]
    unique_candidate =[]
    candidates = []
    votes = []
    percent = []
    individual_vote_count = []
    max_votes_count = []
    winner = []
    for row in csvreader:
        votes.append(row[0])
        candidatelist.append(row[2])
        votes_count = len(votes)
    for x in set(candidatelist):
        unique_candidate.append(x)
        percent.append(round(int(candidatelist.count(x))/int (votes_count),2)*100)
        individual_vote_count.append(candidatelist.count(x))
        max_votes_count = max(individual_vote_count)
        winner = unique_candidate[individual_vote_count.index(max_votes_count)]
    print("Election Result")
    print("-----------------------------")
    print ("Total Votes: " + str(votes_count))
    print("-----------------------------")
    print("Candidates: " + str(unique_candidate))
    print("-----------------------------")
    for i in range(len(unique_candidate)):
        print(unique_candidate[i] + ":" +str(percent[i])+"% (" + str(individual_vote_count[i])+")" )
    print ("winner is: " + str(winner))


import unittest
from configparser import ConfigParser
from pathlib import Path
from src.detectors.sift import SiftDuplicateDetector
from src.image import Image

class TestSift(unittest.TestCase):
    def test_SiftDuplicateDetector(self):
        config = ConfigParser()
        config.read('./config.ini')

        images = {
            'new': load_images(config['unittests']['fixtures_dir'] + "/new"),
            'existing': load_images(config['unittests']['fixtures_dir'] + "/store")
        }

        expected = {
            'tests/fixtures/new/bmw3.jpg',
            'tests/fixtures/new/bmw2_scaled_down.jpg',
        }

        options = {'config': config}
        sut = SiftDuplicateDetector(images=images, options=options)
        sut.detect()

        result = sut.get_duplicates()

        self.assertSetEqual(set(result), expected)

def load_images(path: str) -> list:
    images = []

    for file in Path(path).iterdir():
        if not file.is_file():
            continue

        images.append(Image(file.as_posix()))

    return images


from fastapi import APIRouter, Request, Depends, Form
from fastapi.exceptions import HTTPException
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from typing import List
from datetime import datetime
from starlette.responses import RedirectResponse
from database.database import SessionLocal
from database import schema, crud
import urllib

templates = Jinja2Templates(directory="templates")
router=APIRouter(prefix="/message")

###########################################message table##############################################
#####message#####

def get_database_session():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

@router.get("/message" ,response_model=List[schema.MessageReturn])
async def read_msgs(request: Request, db: Session = Depends(get_database_session)):
    records = crud.get_msgs(db=db)
    return records

@router.get("/message/{mid}",response_model=schema.MessageReturn)
def read_msg(request:Request, mid:int, db: Session = Depends(get_database_session)):

    item = crud.get_msg(db=db,msg_id = mid)
    if item is None:
        raise HTTPException(status_code=404, detail="msg not found")

    return item

@router.get("/message/keyword/{keyword}",response_model=List[schema.MessageReturn])
async def read_msg_keyword(request:Request, keyword:str, db: Session = Depends(get_database_session)):
    item = crud.get_msg_by_keyword(db=db, keyword = keyword)
    if item is None:
        raise HTTPException(status_code=404, detail="msg not found")

    return item

@router.get("/message/user_keyword/{user}",response_model=List[schema.MessageReturn])
def read_msg_user_keyword(request:Request, uid:str, db: Session = Depends(get_database_session)):

    item = crud.get_msg_by_user_keyword(db=db, uid = uid)
    if not item:
        raise HTTPException(status_code=404, detail="msg not found")

    return item

#####read#####

#####create#####
@router.post('/message_keyword')
async def create_msg( db:Session = Depends(get_database_session),title:str=Form(...), contents:str=Form(...), keyword1:str = Form(...),keyword2:str = Form(...),keyword3:str = Form(...)):

    msg = schema.Message(title=title, contents = contents, datetime = datetime.now())
    keywords = list(set([keyword1, keyword2, keyword3]))
    if 'none' in keywords:
        keywords.remove('none')
    print(keywords)
    response = crud.create_msg(db = db, msg=msg, keywords = keywords)
    if response == None:
        raise HTTPException(status_code=412, detail="User ID already exists")
    response = RedirectResponse('/page/admin',status_code=303)
    return response
#####create#####
###########################################message


from PyQt5.QtWidgets import QWidget, QHBoxLayout, QComboBox

class LabelFilterComboBox(QWidget):
    def __init__(self, parent=None, items=[]):
        super(LabelFilterComboBox, self).__init__(parent)
        self.items = items
        self.combo_box = QComboBox()
        self.combo_box.addItems(self.items)
        self.combo_box.currentIndexChanged.connect(
            parent.combo_selection_changed
        )

        layout = QHBoxLayout()
        layout.addWidget(self.combo_box)
        self.setLayout(layout)

    def update_items(self, items):
        self.items = items
        self.combo_box.clear()
        self.combo_box.addItems(self.items)


from typing import Optional

class ListNode:
    def __init__(self, val=0, _next=None):
        self.val = val
        self.next = _next

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        # Check if either l1 or l2 is None. If one of them is None, return the other linked list.
        if l1 is None:
            return l2
        if l2 is None:
            return l1

        # Create a new linked list to store the result
        ans = ListNode()
        node = ans  # Initialize a pointer to the head of the result linked list
        value, extra = 0, 0  # Initialize variables to store the sum and carry (extra)

        # Loop until both l1 and l2 are None and there is no carry (extra) left
        while l1 is not None or l2 is not None or extra:
            # Calculate the sum of the current nodes' values and the carry (extra)
            value = extra
            if l1 is not None:
                value += l1.val
                l1 = l1.next
            if l2 is not None:
                value += l2.val
                l2 = l2.next

            # Calculate the new carry (extra) for the next iteration
            extra = value // 10

            # Create a new node with the value (sum % 10) and append it to the result linked list
            node.next = ListNode(value % 10)
            node = node.next  # Move the pointer to the newly created node

        return ans.next  # Return the head of the result linked list (skip the dummy first node)


# NOT WORKING?
import numpy as np
# READ FILE
with open('test.txt') as f:
    input = f.read().splitlines()

# GET DRAW NUMBERS
randomNumbers = map(int, input[0].split(","))
drawnNumbers = []

# CLEAN DATA
del input[0:2]
rawBoards = list(filter(None, input))

# CREATE BOARDS
boardMaxRows = 5
currentBoard = 0
currentBoardRows = 1

amountBoards = len(rawBoards) / boardMaxRows
boards = [[] for _ in range(amountBoards)]

for idx, row in enumerate(rawBoards, start=1):
    row = map(int, list(filter(None, row.split(" "))))

    if currentBoardRows < boardMaxRows:
        boards[currentBoard].append(row)
        currentBoardRows = currentBoardRows + 1

    elif currentBoardRows == boardMaxRows:
        boards[currentBoard].append(row)
        # RESET
        if currentBoard < amountBoards - 1:
            currentBoard = currentBoard + 1
        currentBoardRows = 1

def calculateScore(board, drawnNumbers):
    print("CALC DRAWNNUMBERS {}".format(drawnNumbers))
    notDrawnNumbers = []
    for row in board:
        notDrawnNumbers = notDrawnNumbers + \
            [number for number in row if number not in drawnNumbers]
    return sum(notDrawnNumbers)

def checkHorizonalWin(boards, drawnNumbers):
    print("chekH DRAWNNUMBERS {}".format(drawnNumbers))
    isWin = False
    score = 0
    winningBoard = 0
    for boardNumber, board in enumerate(boards):
        for rowNumber in range(boardMaxRows):
            if set(board[rowNumber]).issubset(drawnNumbers):
                isWin = True
                winningBoard = boardNumber
                score = calculateScore(board, drawnNumbers)
    return isWin, score, winningBoard

def checkVerticalWin(boards, drawnNumbers):
    print("chekV DRAWNNUMBERS {}".format(drawnNumbers))
    isWin = False
    score = 0
    winningBoard = 0
    for boardNumber, board in enumerate(boards):
        board = np.array(board).transpose()
        for rowNumber in range(boardMaxRows):
            if set(board[rowNumber]).issubset(drawnNumbers):
                isWin = True
                winningBoard = boardNumber
                score = calculateScore(board, drawnNumbers)
    return isWin, score, winningBoard

# THE LOOP
alreadyWonBoards = []
for theNumberThatWasJustCalled in randomNumbers:
    drawnNumbers.append(theNumberThatWasJustCalled)
    print("DRAWNNUMBERS {}".format(drawnNumbers))

    hWin, hScore, hWinningBoard = checkHorizonalWin(boards, drawnNumbers)
    if hWin and hWinningBoard not in alreadyWonBoards:
        print("We have a winner with Number {} and the Score {} with Board {}".format(
            theNumberThatWasJustCalled, hScore*theNumberThatWasJustCalled, hWinningBoard))
        alreadyWonBoards.append(hWinningBoard)

    vWin, vScore, vWinningBoard = checkVerticalWin(boards, drawnNumbers)
    if vWin and vWinningBoard not in alreadyWonBoards:
        print("We have a winner with Number {} and the Score {} with Board {}".format(
            theNumberThatWasJustCalled, vScore*theNumberThatWasJustCalled, vWinningBoard))
        alreadyWonBoards.append(vWinningBoard)


#
# project: project 2
# file: mnist.py
# author: MING Yao
#

import tensorflow as tf
import numpy as np
from convnet.convnet import ConvNet
import gzip
import os
import sys
from six.moves import urllib

SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
WORK_DIRECTORY = 'data'
IMAGE_SIZE = 28
NUM_CHANNELS = 1
PIXEL_DEPTH = 255
NUM_LABELS = 10
# VALIDATION_SIZE = 5000  # Size of the validation set.
SEED = 66478  # Set to None for random seed.
BATCH_SIZE = 100
NUM_EPOCHS = 20
EVAL_BATCH_SIZE = 100
EVAL_FREQUENCY = 600  # Number of steps between evaluations.

def maybe_download(filename):
    """Download the data from Yann's website, unless it's already here."""
    if not tf.gfile.Exists(WORK_DIRECTORY):
        tf.gfile.MakeDirs(WORK_DIRECTORY)
    filepath = os.path.join(WORK_DIRECTORY, filename)
    if not tf.gfile.Exists(filepath):
        filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)
        with tf.gfile.GFile(filepath) as f:
            size = f.size()
        print('Successfully downloaded', filename, size, 'bytes.')
    return filepath

def extract_data(filename, num_images):
    """Extract the images into a 4D tensor [image index, y, x, channels].

     Values are rescaled from [0, 255] down to [-0.5, 0.5].
     """
    print('Extracting', filename)
    with gzip.open(filename) as bytestream:
        bytestream.read(16)
        buf = bytestream.read(IMAGE_SIZE * IMAGE_SIZE * num_images * NUM_CHANNELS)
        data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
        data = (data - (PIXEL_DEPTH / 2.0)) / PIXEL_DEPTH
        data = data.reshape(num_images, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS)
        return data

def extract_labels(filename, num_images):
    """Extract the labels into a vector of int64 label IDs."""
    print('Extracting', filename)
    with gzip.open(filename) as bytestream:
        bytestream.read(8)
        buf = bytestream.read(1 * num_images)
        labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64)
    return labels

def main(argv=None):  # pylint: disable=unused-argument

    # Get the data.
    train_data_filename = maybe_download('train-images-idx3-ubyte.gz')
    train_labels_filename = maybe_download('train-labels-idx1-ubyte.gz')
    test_data_filename = maybe_download('t10k-images-idx3-ubyte.gz')
    test_labels_filename = maybe_download('t10k-labels-idx1-ubyte.gz')

    # Extract it into numpy arrays.
    train_data = extract_data(train_data_filename, 60000)
    train_labels = extract_labels(train_labels_filename, 60000)
    test_data = extract_data(test_data_filename, 10000)
    test_labels = extract_labels(test_labels_filename, 10000)

    num_epochs = NUM_EPOCHS

    # LeNet-5 like Model
    model = ConvNet('mnist')
    model.push_input_layer(dshape=[None, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS])
    model.push_conv_layer(filter_size=[5, 5], out_channels=32, strides=[1, 1], activation='relu')
    model.push_pool_layer('max', kernel_size=[1, 2, 2, 1], strides=[2, 2])
    model.push_conv_layer(filter_size=[5, 5], out_channels=64, strides=[1, 1], activation='relu')
    model.push_pool_layer('max', kernel_size=[1, 2, 2, 1], strides=[2, 2])
    model.push_flatten_layer()
    model.push_fully_connected_layer(out_channels=512, activation='relu')
    model.push_dropout_layer(0.5)
    model.push_fully_connected_layer(out_channels=NUM_LABELS, activation='linear')

    model.set_loss('sparse_softmax')
    model.set_regularizer('l2', 5e-4)
    model.set_learning_rate(0.001)
    model.set_optimizer('Adam')
    model.set_data(train_data[:10000, ...], train_labels[:10000,...], test_data, test_labels)
    model.compile()
    model.train(BATCH_SIZE, 50, EVAL_FREQUENCY)

if __name__ == '__main__':
    tf.app.run()


from logging import error, exception
from flask import Flask, render_template, request, redirect, send_file
from so import get_so_jobs
from exporter import save_to_file

app = Flask("SuperScrapper")

db = {}

@app.route("/")
def	home():
	return render_template("index.html")

@app.route("/report")
def report():
	word = request.args.get("word")
	if word:
		word = word.lower()
		existing_jobs = db.get(word)
		if existing_jobs:
			jobs = existing_jobs
		else:
			jobs = get_so_jobs(word)
			db[word] = jobs
	else:
		return render_template("/")
	return render_template(
		"report.html",
		SearchingBy = word,
		resultsNumber = len(jobs),
		jobs = jobs,
	)

@app.route("/export")
def	export():
	try:
		word = request.args.get('word')
		if not word:
			raise exception()
		word = word.lower()
		jobs = db.get(word)
		if not jobs:
			raise exception()
		save_to_file(word, jobs)
		return send_file(f"{word}-jobs.csv")
	except:
		return redirect("/")

app.run()


import boto3

# Get All Regions
regions = boto3.session.Session().get_available_regions('ec2')

# List instances
def list_instances(i):
    "List EC2 instances"
    ec2 = boto3.session.Session(region_name= i ).resource('ec2')
    for i in ec2.instances.all():
        print(', '.join((
            i.id,
            i.instance_type,
            i.placement['AvailabilityZone'],
            i.state['Name'],
            i.public_dns_name)))

# Stop instances
def stop_instances(i):
    "Stop EC2 instances"
    ec2 = boto3.session.Session(region_name= i ).resource('ec2')
    instances = ec2.instances.filter(Filters=[{'Values': ['running']}])
    for i in ec2.instances.all():
        ec2.instances.stop()

for i in regions:
    print('List of all EC2 instances')
    list_instances(i)

    print('*****************************')

    print('Stopping all running EC2 instances')
    # TO STOP INSTANCES REMOVE COMMENT
    # stop_instances(i)

    print('*****************************')
    print('List of all EC2 instances')
    list_instances(i)   # list all Instancess again


# There are n servers numbered from 0 to n-1 connected by undirected server-to-server connections forming a
# network where connections[i] = [a, b] represents a connection between servers a and b.
# Any server can reach any other server directly or indirectly through the network.
# A critical connection is a connection that, if removed, will make some server unable to reach some other
# server.
# Return all critical connections in the network in any order.

# Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
# Output: [[1,3]]
# Explanation: [[3,1]] is also accepted.

# IDEA: check removing each connection and
# run dfs from the first connection, if the number of reached nodes is different than n then we return

import collections

class Solution:

    def parseConnections(self, connections, graph):

        for i in range(len(connections)):
            if connections[i][0] not in graph:
                graph[connections[i][0]] = [connections[i][1]]

            if connections[i][1] not in graph:
                graph[connections[i][1]] = [connections[i][0]]

            if connections[i][0] not in graph[connections[i][1]]:
                graph[connections[i][1]].append(connections[i][0])

            if connections[i][1] not in graph[connections[i][0]]:
                graph[connections[i][0]].append(connections[i][1])

    def bfs(self, graph, root, mc):  # missingConnection = [x,y]
        queue = collections.deque()
        queue.append(root)
        seen = {}
        while len(queue) > 0:
            curr = queue.pop()
            seen[curr] = True  # visited node
            # add all neighbors to queue
            for i in range(len(graph[curr])):
                if graph[curr][i] in mc and curr in mc:
                    pass

                elif graph[curr][i] not in seen:
                    # ADD NODE
                    queue.append(graph[curr][i])
                    seen[graph[curr][i]] = False

        return len(seen)

    def criticalConnections(self, n, connections):
        graph = {}
        self.parseConnections(connections, graph)

        expectedNodes = self.bfs(graph, connections[0][0], [-1, -1])

        criticalConnections = []
        for i in range(len(connections)):
            receivedNodes = self.bfs(graph, connections[0][0], connections[i])
            if receivedNodes != expectedNodes:
                criticalConnections.append(connections[i])
        return criticalConnections
        # graph= {
        #
        # "4" : [1,2,5,7,8]
        # "5" : [4]
        # }

s = Solution()
n = 4,
connections = [[0, 1], [1, 2], [2, 0], [1, 3]]

print(s.criticalConnections(4, connections))

leetcode/1192. Critical connections in a network/main.py


import pygame
import numpy as np
from random import randint

from configs.game.weapon_config import weapon_data
from configs.game.spell_config import magic_data

from .components.stats import StatsHandler
from .components._input import InputHandler
from .components.animaton import AnimationHandler

from effects.particle_effects import AnimationPlayer

from agents.ppo.agent import Agent

class Player(pygame.sprite.Sprite):
    def __init__(self,
                 player_id,
                 role,
                 position,
                 map_edge,
                 groups,
                 obstacle_sprites,
                 visible_sprites,
                 attack_sprites,
                 attackable_sprites
                 ):
        super().__init__(groups)

        self.initial_position = position
        self.map_edge = map_edge
        self.player_id = player_id
        self.distance_direction_from_enemy = None

        # Sprite Setup
        self.sprite_type = "player"
        self.obstacle_sprites = obstacle_sprites
        self.visible_sprites = visible_sprites
        self.attack_sprites = attack_sprites
        self.attackable_sprites = attackable_sprites

        # Graphics Setup
        self.animation_player = AnimationPlayer()
        self.animation = AnimationHandler(self.sprite_type)
        self.animation.import_assets(position)
        # Input Setup
        self._input = InputHandler(
            self.sprite_type, self.animation_player)

        # Setup Stats
        self.role = role
        self.stats = StatsHandler(self.sprite_type, self.role)

    def setup_agent(self,
                    gamma,
                    alpha,
                    policy_clip,
                    batch_size,
                    n_epochs,
                    gae_lambda,
                    chkpt_dir,
                    entropy_coef,
                    no_load=False):

        self.max_num_enemies = len(self.distance_direction_from_enemy)
        self.get_current_state()
        self.num_features = len(self.state_features)

        self.agent = Agent(
            input_dims=self.num_features,
            n_actions=len(self._input.possible_actions),
            gamma=gamma,
            alpha=alpha,
            policy_clip=policy_clip,
            batch_size=batch_size,
            n_epochs=n_epochs,
            gae_lambda=gae_lambda,
            entropy_coef=entropy_coef,
            chkpt_dir=chkpt_dir
        )
        print(
            f"\nAgent initialized on player {self.player_id} using {self.agent.actor.device}.")

        if not no_load:
            print("Attempting to load models ...")
            try:
                self.agent.load_models(
                    actr_chkpt=f"A{self.player_id}",
                    crtc_chkpt=f"C{self.player_id}"
                )
                print("Models loaded ...\n")

            except FileNotFoundError:
                print(
                    f"FileNotFound for player {self.player_id}.\
                    \nSkipping loading ...\n")

    def get_status(self):
        if self._input.movement.direction.x == 0\
                and self._input.movement.direction.y == 0:

            if 'idle' not in self._input.status and 'attack' not in self._input.status:
                self._input.status += '_idle'

        if self._input.attacking:
            self._input.movement.direction.x = 0
            self._input.movement.direction.y = 0
            if 'attack' not in self._input.status:
                if 'idle' in self._input.status:
                    self._input.status = self._input.status.replace(
                        'idle', 'attack')
                else:
                    self._input.status += '_attack'
        else:
            if 'attack' in self._input.status:
                self._input.status = self._input.status.replace('_attack', '')

    def attack_logic(self):
        if self.attack_sprites:
            for attack_sprite in self.attack_sprites:
                collision_sprites = pygame.sprite.spritecollide(
                    attack_sprite, self.attackable_sprites, False)
                if collision_sprites:
                    for target_sprite in collision_sprites:
                        if target_sprite.sprite_type == 'grass':
                            pos = target_sprite.rect.center
                            offset = pygame.math.Vector2(0, 75)
                            for leaf in range(randint(3, 6)):
                                self.animation_player.create_grass_particles(
                                    position=pos - offset,
                                    groups=[self.visible_sprites])

                            target_sprite.kill()
                        else:
                            target_sprite.get_damaged(
                                self, attack_sprite.sprite_type)

    def get_full_weapon_damage(self):
        base_damage = self.stats.attack
        weapon_damage = weapon_data[self._input.combat.weapon]['damage']
        return (base_damage + weapon_damage)

    def get_full_magic_damage(self):
        base_damage = self.stats.magic
        spell_damage = magic_data[self._input.combat.magic]['strength']
        return (base_damage + spell_damage)

    def get_current_state(self):

        if self.distance_direction_from_enemy != []:
            sorted_distances = sorted(
                self.distance_direction_from_enemy, key=lambda x: x[0])
        else:
            sorted_distances = np.zeros(self.num_features)

        nearest_dist, _, nearest_enemy = sorted_distances[0]

        self.action_features = [self._input.action]

        self.reward = self.stats.exp\
            + self.stats.health/self.stats.stats['health'] - 1\
            - nearest_dist/np.sqrt(np.sum(self.map_edge))\
            - nearest_enemy.stats.health/nearest_enemy.stats.monster_info['health']\
            - 2*len(self.distance_direction_from_enemy)/self.max_num_enemies

        self.state_features = [
            self.animation.rect.center[0]/self.map_edge[0],
            self.animation.rect.center[1]/self.map_edge[1],
            self._input.movement.direction.x,
            self._input.movement.direction.y,
            self.stats.health/self.stats.stats['health'],
            self.stats.energy/self.stats.stats['energy'],
            1 if 'attack' in self._input.status else 0,

        ]

        for distance, direction, enemy in self.distance_direction_from_enemy:
            self.state_features.extend([

                distance/np.sqrt(np.sum(self.map_edge)),

                direction[0],

                direction[1],

                enemy.stats.health /
                enemy.stats.monster_info['health'],

                enemy.stats.exp,
            ])

        if hasattr(self, 'num_features'):
            while len(self.state_features) < self.num_features:
                self.state_features.append(0)

        self.state_features = np.array(self.state_features)

    def is_dead(self):
        if self.stats.health <= 0:
            self.stats.health = 0
            self.animation.import_assets((3264, 448))
            return True
        else:
            return False

    def agent_update(self):

        # Get the current state
        self.get_current_state()

        # Choose action based on current state
        action, probs, value\
            = self.agent.choose_action(self.state_features)

        # Apply chosen action
        self._input.check_input(action,
                                self.stats.speed,
                                self.animation.hitbox,
                                self.obstacle_sprites,
                                self.animation.rect,
                                self)

        self.agent.remember(self.state_features, action,
                            probs, value, self.reward, self.is_dead())

        self.get_current_state()

    def update(self):

        self.agent_update()

        # Cooldowns and Regen
        self.stats.health_recovery()
        self.stats.energy_recovery()

        # Refresh player based on input and animate
        self.get_status()
        self.animation.animate(
            self._input.status, self._input.combat.vulnerable)
        self._input.cooldowns(self._input.combat.vulnerable)


"""
Знайти суму елементів масиву дійсних чисел, що мають непарні номери.
Розмірність масиву 20. Заповнення масиву здійснити випадковими числами від 100
до 200.
Mikhalina Myroslav 122D
"""

import random
mass = [random.uniform(100, 200) for x in range(1, 21)]
summ = 0
for i in range(len(mass)):
    if i % 2 == 0:
        summ += mass[i]
print(mass)
print(summ)


listgood = []
listmid = []
listbad = []
N = int(input("Cik ir skolenu: "))
for x in range(N):
 x = int(input("Īevadi visu prieksmetu videjo atzimi: "))
 if x > 8:
   listgood.append(x)
 if 3 < x < 9:
   listmid.append(x)
 if x < 4:
   listbad.append(x)
print("Teicamnieks ir: ")
print(len(listgood))
print("Viduveji macas: ")
print(len(listmid))
print("Neseksmigais skolens ir: ")
print(len(listbad))


import click
from ddt_probe.probe import main
from ddt_probe.utils import PodInfo
import os

@click.command()
@click.argument('app_id')
@click.argument('pod_id')
@click.argument('pod_ip')
@click.argument('domain_id')
@click.argument('server_ip')
@click.argument('server_port')
def cli(server_ip, server_port, app_id, pod_id, pod_ip, domain_id):
    podinfo = PodInfo(app_id=app_id,
                        pod_id = pod_id,
                        pod_ip = pod_ip,
                        domain_id = domain_id,
                        debug = os.getenv('ZENOH_DEBUG', None),
                        dst_port = os.getenv('DST_PORT', 7447),
                        listen_port = os.getenv('LISTEN_PORT', 8000),
                        listen_server = os.getenv('LISTEN_SERVER', "0.0.0.0"))
    main(server_ip, server_port, podinfo)


from tkinter import *
from modu import top_canvas, left_semester, result_format
import sqlite3
from tkinter import messagebox
import json

class Semester:
    def clear(self):
        self.var_sub1.set("")
        self.var_sub2.set("")
        self.var_sub3.set("")
        self.var_sub4.set("")
        self.var_sub5.set("")
        self.var_sub6.set("")

    def submit_marks(self, args):
        db = sqlite3.connect(database="srms.db")
        cur = db.cursor()
        try:
            cur.execute("select marks from result where email = (select email from users where tu_registered_id=?)",
                        (self.var_tu_id.get(),))
            record = cur.fetchone()
            if record is None:
                if args == 1:
                    json_dict = {'Computer Fundamentals and Applications': self.var_sub1.get(),
                                 'Society and Technology': self.var_sub2.get(),
                                 'English I': self.var_sub3.get(),
                                 'Mathematics I': self.var_sub4.get(),
                                 'Digital Logic': self.var_sub5.get()
                                 }
                    self.json_marks = json.dumps(json_dict)

                if args == 2:
                    json_dict = {'C programming': self.var_sub1.get(),
                                 'Financial Accounting': self.var_sub2.get(),
                                 'English II': self.var_sub3.get(),
                                 'Mathematics II': self.var_sub4.get(),
                                 'Microprocessor and Comp. Architecture': self.var_sub5.get()
                                 }
                    self.json_marks = json.dumps(json_dict)

                if args == 3:
                    json_dict = {'Data Structure and Algorithms': self.var_sub1.get(),
                                 'Probability and Statistics': self.var_sub2.get(),
                                 'System Analysis and Design': self.var_sub3.get(),
                                 'OOP in Java': self.var_sub4.get(),
                                 'Web Technology': self.var_sub5.get()
                                 }
                    self.json_marks = json.dumps(json_dict)

                if args == 4:
                    json_dict = {'Operating System': self.var_sub1.get(),
                                 'Numerical Methods': self.var_sub2.get(),
                                 'Software Engineering': self.var_sub3.get(),
                                 'Scripting Language': self.var_sub4.get(),
                                 'Database Management System': self.var_sub5.get(),
                                 'Project I': self.var_sub6.get()
                                 }
                    self.json_marks = json.dumps(json_dict)

                if args == 5:
                    json_dict = {'MIS and e-Business': self.var_sub1.get(),
                                 'DotNet Technology': self.var_sub2.get(),
                                 'Computer Networking': self.var_sub3.get(),
                                 'Introduction to Management': self.var_sub4.get(),
                                 'Computer Graphics and Animation': self.var_sub5.get()
                                 }
                    self.json_marks = json.dumps(json_dict)

                if args == 6:
                    json_dict = {'Mobile Programming': self.var_sub1.get(),
                                 'Distributed System': self.var_sub2.get(),
                                 'Applied Economics': self.var_sub3.get(),
                                 'Advanced Java Programming': self.var_sub4.get(),
                                 'Network Programming': self.var_sub5.get(),
                                 'Project II': self.var_sub6.get()
                                 }
                    self.json_marks = json.dumps(json_dict)

                if args == 7:
                    json_dict = {'Cyber Law and Professional Ethics': self.var_sub1.get(),
                                 'Cloud Computing': self.var_sub2.get(),
                                 'Internship': self.var_sub3.get(),
                                 'Elective Course I': self.var_sub4.get()
                                 }
                    self.json_marks = json.dumps(json_dict)

                if args == 8:
                    json_dict = {'Operations Research': self.var_sub1.get(),
                                 'Project III': self.var_sub2.get(),
                                 'Elective Course II': self.var_sub3.get()
                                 }
                    self.json_marks = json.dumps(json_dict)

                cur.execute("insert into result (email,marks) values((select email from users where tu_registered_id=?),"
                            "'" + self.json_marks + "')", (self.var_tu_id.get(),))
                db.commit()
                db.close()
                messagebox.showinfo('Info', 'Marks entered successfully', parent=self.root2)
            else:
                messagebox.showinfo('Info', 'Marks for selected student have already been provided', parent=self.root2)

        except Exception as e:
            messagebox.showerror('Error', f'Error due to {str(e)}', parent=self.root2)
        self.clear()

    def search_tu_id(self, args):
        db = sqlite3.connect(database="srms.db")
        cur = db.cursor()
        try:
            if self.var_tu_id.get() == "":
                messagebox.showinfo('Info', 'Please enter the TU registration number first!', parent=self.root2)
            else:
                if args == 1:
                    cur.execute("select name,roll from users where tu_registered_id=? and faculty='BCA' and "
                                "semester='First' and profession=2 and permission=1", (self.var_tu_id.get(),))
                if args == 2:
                    cur.execute("select name,roll from users where tu_registered_id=? and faculty='BCA' and "
                                "semester='Second' and profession=2 and permission=1", (self.var_tu_id.get(),))
                if args == 3:
                    cur.execute("select name,roll from users where tu_registered_id=? and faculty='BCA' and "
                                "semester='Third' and profession=2 and permission=1", (self.var_tu_id.get(),))
                if args == 4:
                    cur.execute("select name,roll from users where tu_registered_id=? and faculty='BCA' and "
                                "semester='Fourth' and profession=2 and permission=1", (self.var_tu_id.get(),))
                if args == 5:
                    cur.execute("select name,roll from users where tu_registered_id=? and faculty='BCA' and "
                                "semester='Fifth' and profession=2 and permission=1", (self.var_tu_id.get(),))
                if args == 6:
                    cur.execute("select name,roll from users where tu_registered_id=? and faculty='BCA' and "
                                "semester='Sixth' and profession=2 and permission=1", (self.var_tu_id.get(),))
                if args == 7:
                    cur.execute("select name,roll from users where tu_registered_id=? and faculty='BCA' and "
                                "semester='Seventh' and profession=2 and permission=1", (self.var_tu_id.get(),))
                if args == 8:
                    cur.execute("select name,roll from users where tu_registered_id=? and faculty='BCA' and "
                                "semester='Eighth' and profession=2 and permission=1", (self.var_tu_id.get(),))
                info = cur.fetchone()
                if info is None:
                    messagebox.showerror("Error", "Please select valid TU registration id of student for selected"
                                                  " semester.", parent=self.root2)
                else:
                    self.var_name.set(info[0])
                    self.var_roll.set(info[1])
        except Exception as e:
            messagebox.showerror('Error', f'Error due to {str(e)}', parent=self.root2)
        self.clear()

    def courses(self, args):
        global json_subs
        self.root2 = Toplevel()
        result_format(self)

        # ==== BCA first semester ====
        if args == 1:
            json_subs = {'Computer Fundamentals and Applications': self.var_sub1,
                         'Society and Technology': self.var_sub2,
                         'English I': self.var_sub3,
                         'Mathematics I': self.var_sub4,
                         'Digital Logic': self.var_sub5
                         }

        # ==== BCA second semester ====
        if args == 2:
            json_subs = {'C programming': self.var_sub1,
                         'Financial Accounting': self.var_sub2,
                         'English II': self.var_sub3,
                         'Mathematics II': self.var_sub4,
                         'Microprocessor and Comp. Architecture': self.var_sub5
                         }

        # ==== BCA third semester ====
        if args == 3:
            json_subs = {'Data Structure and Algorithms': self.var_sub1,
                         'Probability and Statistics': self.var_sub2,
                         'System Analysis and Design': self.var_sub3,
                         'OOP in Java': self.var_sub4,
                         'Web Technology': self.var_sub5
                         }

        # ==== BCA fourth semester ====
        if args == 4:
            json_subs = {'Operating System': self.var_sub1,
                         'Numerical Methods': self.var_sub2,
                         'Software Engineering': self.var_sub3,
                         'Scripting Language': self.var_sub4,
                         'Database Management System': self.var_sub5,
                         'Project I': self.var_sub6
                         }

        # ==== BCA fifth semester ====
        if args == 5:
            json_subs = {'MIS and e-Business': self.var_sub1,
                         'DotNet Technology': self.var_sub2,
                         'Computer Networking': self.var_sub3,
                         'Introduction to Management': self.var_sub4,
                         'Computer Graphics and Animation': self.var_sub5
                         }
        # ==== BCA sixth semester ====
        if args == 6:
            json_subs = {'Mobile Programming': self.var_sub1,
                         'Distributed System': self.var_sub2,
                         'Applied Economics': self.var_sub3,
                         'Advanced Java Programming': self.var_sub4,
                         'Network Programming': self.var_sub5,
                         'Project II': self.var_sub6
                         }

        # ==== BCA seventh semester ====
        if args == 7:
            json_subs = {'Cyber Law and Professional Ethics': self.var_sub1,
                         'Cloud Computing': self.var_sub2,
                         'Internship': self.var_sub3,
                         'Elective Course I': self.var_sub4
                         }

        # ==== BCA eighth semester ====
        if args == 8:
            json_subs = {'Operations Research': self.var_sub1,
                         'Project III': self.var_sub2,
                         'Elective Course II': self.var_sub3
                         }
        a = 290
        for i, j in json_subs.items():
            lbl = Label(self.root2, text=i, font=("times", 15,))
            lbl.place(x=90, y=a)
            sub = Entry(self.root2, textvariable=j, font=("times", 15,))
            sub.place(x=650, y=a, width=50)
            a = a + 50

        btn = Button(self.root2, text='search', command=lambda: self.search_tu_id(args), font=('times', 12, 'bold'),
                     cursor='hand2', bg='light gray', relief=RIDGE, activebackground='gray').place(x=1110, y=57, width=80)

        btn1 = Button(self.root2, text='submit', command=lambda: self.submit_marks(args), font=('times', 12, 'bold'),
                      cursor='hand2', bg='green', relief=RIDGE, activebackground='green').place(x=350, y=610, width=100)

    def __init__(self, root1):
        self.root = root1
        # self.root.title("Semester selection")
        # self.root.geometry("1520x775+1+5")

        self.var_tu_id = StringVar()
        self.var_name = StringVar()
        self.var_roll = StringVar()

        self.var_sub1 = StringVar()
        self.var_sub2 = StringVar()
        self.var_sub3 = StringVar()
        self.var_sub4 = StringVar()
        self.var_sub5 = StringVar()
        self.var_sub6 = StringVar()

        top_canvas(self)
        left_semester(self)

if __name__ == "__main__":
    root = Tk()
    obj = Semester(root)
    root.mainloop()


# -*- coding: utf-8 -*-
# © 2016 Danimar Ribeiro, Trustcode
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from odoo.exceptions import UserError
from odoo.addons.br_boleto.tests.test_common import TestBoleto

class TestBoletoSicoob(TestBoleto):

    def _return_payment_mode(self):
        super(TestBoletoSicoob, self)._return_payment_mode()
        sequencia = self.env['ir.sequence'].create({
            'name': u"Nosso Número"
        })
        sicoob = self.env['res.bank'].search([('bic', '=', '756')])
        conta = self.env['res.partner.bank'].create({
            'acc_number': '12345',  # 5 digitos
            'acc_number_dig': '0',  # 1 digito
            'bra_number': '1234',  # 4 digitos
            'bra_number_dig': '0',
            'codigo_convenio': '123456-7',  # 7 digitos
            'bank_id': sicoob.id,
            'partner_id': self.main_company.partner_id.id,
        })
        journal = self.env['account.journal'].create({
            'name': 'Banco Sicoob',
            'code': 'SIC',
            'type': 'bank',
            'bank_account_id': conta.id,
            'company_id': self.main_company.id,
        })
        mode = self.env['l10n_br.payment.mode'].create({
            'name': 'Sicoob',
            'boleto': True,
            'boleto_type': '9',
            'boleto_carteira': '1',
            'boleto_modalidade': '01',
            'nosso_numero_sequence': sequencia.id,
            'journal_id': journal.id,
        })
        return mode.id

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

    # Não precisa fazer essa validação em outras classes
    def test_basic_validation(self):
        with self.assertRaises(UserError):
            self.invoices.action_invoice_open()

    def _update_main_company(self):
        self.main_company.write({
            'name': 'Trustcode',
            'legal_name': 'Trustcode Tecnologia da Informação',
            'cnpj_cpf': '92.743.275/0001-33',
            'inscr_est': '219.882.606',
            'zip': '88037-240',
            'street': 'Vinicius de Moraes',
            'number': '42',
            'district': 'Córrego Grande',
            'country_id': self.env.ref('base.br').id,
            'state_id': self.env.ref('base.state_br_sc').id,
            'city_id': self.env.ref('br_base.city_4205407').id,
            'phone': '(48) 9801-6226',
        })

    def _update_partner_fisica(self):
        self.partner_fisica.write({
            'cnpj_cpf': '075.932.961-30',
            'district': 'Centro',
            'zip': '88032-050',
            'country_id': self.env.ref('base.br').id,
            'state_id': self.env.ref('base.state_br_sc').id,
            'city_id': self.env.ref('br_base.city_4205407').id,
        })

    def test_raise_error_if_not_payment(self):
        self._update_main_company()
        self._update_partner_fisica()
        self.invoices.action_invoice_open()

        self.assertEquals(len(self.invoices.receivable_move_line_ids), 1)

        move = self.invoices.receivable_move_line_ids[0]
        vals = move.action_print_boleto()

        self.assertEquals(vals['report_name'], 'br_boleto.report.print')
        self.assertEquals(vals['report_type'], 'qweb-pdf')

        vals = self.invoices.action_print_boleto()

        self.assertEquals(vals['report_name'], 'br_boleto.report.print')
        self.assertEquals(vals['report_type'], 'qweb-pdf')

        line_ids = self.env['payment.order.line'].action_register_boleto(
            self.invoices.receivable_move_line_ids)

        boleto_list = line_ids.generate_boleto_list()
        boleto = boleto_list[0]
        self.assertEquals(len(boleto_list), 1)
        self.assertEquals(boleto.valor_documento, '1000.00')
        self.assertEquals(boleto.valor, '1000.00')

        self.assertEquals(boleto.cedente_documento, self.main_company.cnpj_cpf)
        self.assertEquals(
            boleto.sacado_documento, self.partner_fisica.cnpj_cpf)


import random

class TicTacToe():
    # class variables

    # The game board for playing Tic-Tac-Toe (size 3 x 3 cells).
    # A list of 10 strings representing the board (ignore index 0)
    board = list()

    # A list with the user's letter as the first item
    # and the bot's letter as the second.
    game_letters = list()

    # Player who performs the current move ('user' or 'bot')
    turn = ''

    # Player who performs the next move ('user' or 'bot')
    next_player = ''

    # class methods

    def init_board(self):

        self.board = ['  '] * 10

    def get_board(self):

        return self.board

    def get_drawn_board(self, board):

        row_0 = '✎\n'
        row_1 = self.board[7] + '|' + self.board[8] + '|' + \
                self.board[9] + '\n'
        row_2 = '--+--+--\n'
        row_3 = self.board[4] + '|' + self.board[5] + '|' + \
                self.board[6] + '\n'
        row_4 = '--+--+--\n'
        row_5 = self.board[1] + '|' + self.board[2] + '|' + \
                self.board[3] + '\n'

        drawn_board = row_0 + row_1 + row_2 + row_3 + row_4 + row_5

        return drawn_board

    def set_game_letters(self, user_game_letter):

        if user_game_letter == 'X':
            self.game_letters = ['X', 'O']
        else:
            self.game_letters = ['O', 'X']

    def get_user_game_letter(self):

        return self.game_letters[0]

    def get_bot_game_letter(self):

        return self.game_letters[1]

    def set_turn(self):

        if random.randint(0, 1) == 0:
            self.turn = 'bot'
        else:
            self.turn = 'user'

    def get_turn(self):

        return self.turn

    def set_next_turn(self, current_turn):

        if current_turn == 'bot':
            self.turn = 'user'
        else:
            self.turn = 'bot'

    def make_move(self, board, game_letter, move):

        board[move] = game_letter

    def is_winner(self, board, game_letter):

        # -1- check the top row
        top_row_check = board[7] == game_letter and \
                        board[8] == game_letter and board[9] == game_letter

        # -2- check the middle row
        middle_row_check = board[4] == game_letter and \
                           board[5] == game_letter and board[6] == game_letter

        # -3- check the bottom row
        bottom_row_check = board[1] == game_letter and \
                           board[2] == game_letter and board[3] == game_letter

        # -4- check the left column
        left_column_check = board[7] == game_letter and \
                            board[4] == game_letter and board[1] == game_letter

        # -5- check the middle column
        middle_column_check = board[8] == game_letter and \
                              board[5] == game_letter and board[2] == game_letter

        # -6- check the right column
        right_column_check = board[9] == game_letter and \
                             board[6] == game_letter and board[3] == game_letter

        # -7- check the main diagonal
        main_diagonal_check = board[7] == game_letter and \
                              board[5] == game_letter and board[3] == game_letter

        # -8- check the secondary diagonal
        secondary_diagonal_check = board[9] == game_letter and \
                                   board[5] == game_letter and board[1] == game_letter

        # check all winner combinations
        is_winner_check = top_row_check or middle_row_check or \
                          bottom_row_check or left_column_check or \
                          middle_column_check or right_column_check or \
                          main_diagonal_check or secondary_diagonal_check

        return is_winner_check

    def get_board_copy(self, board):

        board_copy = []

        for i in board:
            board_copy.append(i)

        return board_copy

    def is_space_free(self, board, move):

        return board[move] == '  '

    def choose_random_move_from_list(self, board, moves_list):

        possible_moves = []

        for i in moves_list:
            if self.is_space_free(board, i):
                possible_moves.append(i)

        if len(possible_moves) != 0:
            return random.choice(possible_moves)
        else:
            return None

    def get_bot_move(self, board, bot_game_letter):

        if bot_game_letter == 'X':
            player_game_letter = 'O'
        else:
            player_game_letter = 'X'

        # Here is our algorithms for our Tic Tac Toe AI:
        # First, check if we can win in the next move
        for i in range(1, 10):
            board_copy = self.get_board_copy(board)
            if self.is_space_free(board_copy, i):
                self.make_move(board_copy, bot_game_letter, i)
                if self.is_winner(board_copy, bot_game_letter):
                    return i

        # Check if the player could win on his next move and block them
        for i in range(1, 10):
            board_copy = self.get_board_copy(board)
            if self.is_space_free(board_copy, i):
                self.make_move(board_copy, player_game_letter, i)
                if self.is_winner(board_copy, player_game_letter):
                    return i

        # Try to take one of the corners, if they are free.
        move = self.choose_random_move_from_list(board, [1, 3, 7, 9])
        if move is not None:
            return move

        # Try to take the center, if it is free.
        if self.is_space_free(board, 5):
            return 5

        # Move on one of the sides.
        return self.choose_random_move_from_list(board, [2, 4, 6, 8])

    def is_board_full(self, board):

        for i in range(1, 10):
            if self.is_space_free(board, i):
                return False
        return True


def is_prime():
    prime = [True] * 1000000
    prime[0] = False
    prime[1] = False
    for i in range(2,1000000):
        if prime[i] == True:
            for j in range(i*i, 1000000, i):
                prime[j] = False
    return prime

def is_tprime(n):
    if n == 4:
        return True
    if n < 4 or n%2==0:
        return False
    raiz = n**0.5
    if raiz==int(raiz):
        if is_prime[int(raiz)] == True:
            return True
    return False

is_prime = is_prime()
total_numbers = int(input())
numbers = [int(k) for k in input().split()]
for i in numbers:
    if is_tprime(i)==False:
        print("NO")
    else:
        print("YES")


n = int(input())

def chess(d1):
    for i in range(1,7):
        for j in range(1,7):
            if d1[i][j] == "#":
                if d1[i-1][j-1] == "#" and d1[i-1][j+1] == "#" and d1[i+1][j-1] == "#" and d1[i+1][j+1] == "#":
                    print(i+1,j+1)
                    return
for i in range(n):
    d1 = []
    for j in range(9):
        f = input()
        if j > 0:
            d1.append(f)
    chess(d1)


import cv2
import time
import numpy as np

width = 256
weight = f"./CowFace-{width}_6000.weights"
config = f"./CowFace-{width}.cfg"
size = (width,width)

net = cv2.dnn.readNet(weight, config)
model = cv2.dnn_DetectionModel(net)
model.setInputParams(size=size,scale=1./255,swapRB=True)

img = cv2.imread("detect.jpg")
out_img = np.copy(img)

for i in range(0,11):
    start = time.time()
    classes, scores, boxes = model.detect(img, 0.75, 0.4)
    end = time.time()
    print("{:.6f}".format((end - start)*1000))

    for (classid, score, box) in zip(classes, scores, boxes):
        cv2.rectangle(out_img, box, (0,0,255), 2)
        cv2.imwrite("./out.jpg", out_img)


import sys
import pycryptodomex
ch='s';
while(ch=='s'):
    print('Welcome to ceaser cipher encryptor & Decryptor')

    choice = int(input('Enter choice 1 for Encrypt 2 for decrypt:'))
    if(choice==1):
        key=int(input('please Enter the Shift key'))
        ptext=input('Enter the plaintext')
        ctext=''
        for char in ptext:
            if (char == ' '):
                ctext=ctext+char
            elif (char.isupper()):  #isupper() checks for upper case character
                cext=ctext+chr((ord(char)-65+key)%26+65) #ord(char) will genrate ascii value of charachter
            else:
                ctext=ctext+chr((ord(char)-97+key)%26+97)
        print(ctext)
    else:
        key=int(input('please Enter the Shift key'))
        ctext=input('Enter the Ciphertext')
        ptext=''
        for char in ctext:
            if (char == ' '):
                ptext=ptext+char
            elif (char.isupper()):  #isupper() checks for upper case character
                pext=ptext+chr((ord(char)-65-key)%26+65)  #chr(value) returns Character of that value
            else:
                ptext=ptext+chr((ord(char)-97-key)%26+97)
        print(ptext)
    ch=input('press s to start again else press any other key:')


from msilib.schema import Error
import pandas as pd
import numpy as np
import time
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from bs4 import BeautifulSoup
import warnings
warnings.filterwarnings('ignore')

# df = pd.read_csv('./data_tour/부산관광지440개.csv',encoding='utf-8')
# df['naver_map_review'] = '' # 미리 리뷰 건수 담을 column을 만들어줌
# options = webdriver.ChromeOptions()
# options.add_experimental_option('excludeSwitches', ['enable-logging'])
# wd=webdriver.Chrome('./chromedriver.exe',options=options)

# for i, keyword in enumerate(df['명칭'].tolist()):

#     try:
#         naver_map=wd.get()
#     print("관광지 :", i, f"/ {df.shape[0]} 행", keyword)

def getNavermap(result):

    df = pd.read_csv('./data_tour/관광지명칭.csv',encoding='utf-8')

    options = webdriver.ChromeOptions()
    options.add_experimental_option('excludeSwitches', ['enable-logging'])
    wd = webdriver.Chrome('./chromedriver.exe', options=options)

    for i, keyword in enumerate(df['명칭'].tolist()):

        print('관광지 :', i, f"/ {df.shape[0]}", keyword)

        try:
            wd.get(f'https://map.naver.com/v5/search/{keyword}=14377346.8495072,4186044.6333144,15,0,0,0,dh') # 검색 url 접속 = 검색하기
            time.sleep(3) # 중요

            # wd.switch_to.frame('searchIframe')
            # wd.find_element(By.XPATH,'//*[@id="_pcmap_list_scroll_container"]/ul/li[1]').click()
            # time.sleep(3)

            wd.switch_to.frame('entryIframe')
            wd.find_element(By.XPATH,'//*[@id="app-root"]/div/div/div/div[2]/div[1]')
            time.sleep(3)
            html = wd.page_source
            soup = BeautifulSoup(html, 'html.parser')
            # span 태그에 class 속성 사용 추출하기
            review = soup.find_all('span', attrs={'class':'PXMot'})
            for item in review:
                print(item.get_text())

            result.append([review])

        except:
            try:
                wd.switch_to.frame('searchIframe')
                wd.find_element(By.XPATH,'//*[@id="_pcmap_list_scroll_container"]/ul/li[1]/div[2]/a[1]/div/div/span[1]').click()
                time.sleep(3)
                # 새로운 프레임으로 들어가기위해서 먼저 빠져 나와야함
                wd.switch_to.default_content()
                wd.switch_to.frame('entryIframe')
                wd.find_element(By.XPATH,'//*[@id="app-root"]/div/div/div/div[2]/div[1]')
                time.sleep(3)
                html = wd.page_source
                soup = BeautifulSoup(html, 'html.parser')
                # span 태그에 class 속성 사용 추출
                review = soup.find_all('span',attrs={'class':'PXMot'})
                for item in review:
                        print(item.get_text())
                result.append([review])
            except: pass

def main():
    result = []
    print('네이버맵크롤링 : ')
    getNavermap(result)

    columns = ['review']
    naver_map_review_df = pd.DataFrame(result,columns=columns)
    naver_map_review_df.to_csv('./data_tour/리뷰건수.csv',encoding='utf-8',index=True)
    print('크롤링끝')

if __name__=='__main__':
    main()


from main_functions import create_db_connection, create_server_connection, read_query, execute_query
from years_logic import add_years, add_35_years_or_not

# CONNECTIONS
connection = create_db_connection("localhost", "root", "", "kula_old_data")

# NEW CONNECTION TO NEW DATABASE
connection_kula = create_db_connection("localhost", "root", "", "kula_new")

# READING DATA FROM OLD DATABASE
users_read = "SELECT * FROM c_customer;"
users_table_data = read_query(connection_kula, users_read)

# MIGRATED USER TABLE

for user in users_table_data:
    alternative_contact = user[11]
    contact = user[10]
    deleted_at = user[16]
    created_at = user[13]
    updated_at = user[14]
    document_id = user[7]
    created_by = user[17]
    updated_by = user[18]
    last_name = user[5]

    end_date = add_35_years_or_not(deleted_at, created_at, updated_at)
    # INSERTING THE DATA INTO NEW DB

    if updated_at is None and created_at is not None:
        updated_at = created_at

    # migrate_user = f"UPDATE c_customer SET c_end_date = '{end_date}' WHERE row_id = {user[0]};"
    if created_at is None:
        created_at = updated_at

    if created_by is None:
        created_by = updated_by

    if contact is not None:
        migrate_contact = f"INSERT INTO cpn_customer_phone_numbers VALUES ({user[0]}, {user[1]}, {user[1]}, '{contact}', '', '{created_at}','{updated_at}', '{created_at}', '{end_date}', {created_by}, {updated_by});"
        execute_query(connection_kula, migrate_contact)

    if alternative_contact is not None:
        migrate_contact = f"INSERT INTO cpn_customer_phone_numbers VALUES ({user[0]}, {user[1]}, {user[1]}, '{alternative_contact}', '', '{created_at}','{updated_at}', '{created_at}', '{end_date}', {created_by}, {updated_by});"
        execute_query(connection_kula, migrate_contact)


from rest_framework import serializers
from .models import Election, Ballot
from django.contrib.auth.forms import get_user_model
from django.core.exceptions import ValidationError
from django.utils import timezone
from authentication.utils import Util

class UserSerializer(serializers.ModelSerializer):
    email = serializers.EmailField()
    user_name = serializers.CharField()

    class Meta:
        model = get_user_model()
        fields = ('id', 'email', 'user_name')

class ElectionSerializer(serializers.ModelSerializer):
    winner = UserSerializer(read_only=True)
    voted_voters = UserSerializer(read_only=True, many=True)
    admins = UserSerializer(required=True, many=True)
    candidates = UserSerializer(required=False, many=True)
    voters = UserSerializer(required=False, many=True)

    class Meta:
        model = Election
        fields = '__all__'

    def validate(self, data):
        if data['start_date'] > data['end_date']:
            raise ValidationError("Start date must be less than End date")

        if len(data['admins']) == 0:
            raise ValidationError("Elections must have one or more admins")

        return data

    def create(self, validated_data):
        admins = validated_data.pop('admins', None)
        voters = validated_data.pop('voters', None)
        candidates = validated_data.pop('candidates', None)

        election = Election.objects.create(**validated_data)

        if admins:
            for admin_detail in admins:
                election.admins.add(get_user_model().objects.get(email=admin_detail['email']))
        else:
            raise ValidationError

        if voters:
            for voter_detail in voters:
                election.voters.add(get_user_model().objects.get(email=voter_detail['email']))

        if candidates:
            for candidate_detail in candidates:
                election.candidates.add(get_user_model().objects.get(email=candidate_detail['email']))

        return election

class CandidateSerializer(serializers.Serializer):
    candidate = serializers.PrimaryKeyRelatedField(queryset=get_user_model().objects.all())
    election = serializers.PrimaryKeyRelatedField(queryset=Election.objects.all())

class BallotSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ballot
        fields = '__all__'

    def validate(self, data):
        user = None
        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user

        if user and not user.is_anonymous:
            election = Election.objects.get(pk=data['election'].id)
            if election.voted_voters.filter(pk=user.id).exists():
                raise ValidationError(f"You already voted in this election")
            elif election.end_date < timezone.now():
                raise ValidationError(f"The election has ended")
            else:
                # If voter has not already voted in the election, consider their code and add them
                # to the list of voted voters
                user = get_user_model().objects.get(pk=user.id)
                election.voted_voters.add(user)
                election.save()

                # Send Email
                email_data = {
                    'subject': 'Secure Rank Choice E-Voting - Voting successful',
                    'body': f'Hi {user.user_name},\nYour vote in Election: {election} has been successfully recorded.',
                    'to_email': f'{user.email}',
                }
                Util.send_email(email_data)

        return data


import pygtk
pygtk.require( '2.0' )
import gtk

from Britefury.UI.GtkAccelEntry import GtkAccelEntry

from Britefury.CellEdit.BasicWidgetSingleCellEdit import BasicWidgetSingleCellEdit

class StringCellEditAccelEntry (BasicWidgetSingleCellEdit):
	"""Stringean cell editor base"""

	__valueclass__ = str

	def __init__(self):
		super( StringCellEditAccelEntry, self ).__init__()
		self.entry = GtkAccelEntry()
		self.entry.connect( 'accel-set', self._p_onAccel )
		self._bIgnoreEntry = False
		self._o_setWidgetSensitivity( False )

	def show(self):
		self.entry.show()

	def hide(self):
		self.entry.hide()

	def _o_setWidgetSensitivity(self, bSensitive):
		self.entry.set_sensitive( bSensitive )

	def _o_setWidgetValue(self, value):
		if isinstance( value, str ):
			self._bIgnoreEntry = True
			self.entry.set_accel( value )
			self._bIgnoreEntry = False

	def _p_onAccel(self, entry, accelName):
		if not self._bIgnoreEntry:
			assert self._cell is not None
			if self._cell.bLiteral  and  accelName != self._cell.literalValue:
				self._o_blockCell( accelName )
				self._cell.literalValue = accelName
				self._o_unblockCell()

if __name__ == '__main__':
	from Britefury.Cell.Cell import *
	from Britefury.UI.TestWindow import *
	from Britefury.UI.FormLayout import *
	from Britefury.I18n import i18n

	i18n.initialise()

	cell = StringCell( 'a' )

	entry = StringCellEditAccelEntry()
	entry.show()
	entry.attachCell( cell )

	runTestWindow( entry.entry )


from flask import request

from bija.app import app
from bija.db import BijaDB
from bija.helpers import is_hex_key, is_bech32_key, is_nip05, bech32_to_hex64, request_nip05

DB = BijaDB(app.session)

class Search:

    def __init__(self):
        self.term = None
        self.message = None
        self.results = None
        self.redirect = None

        self.process()

    def process(self):
        if 'search_term' in request.args or len(request.args['search_term'].strip()) < 1:
            self.term = request.args['search_term']
            if self.term[:1] == '@':
                self.by_at()
            elif is_hex_key(self.term):
                self.by_hex()
            elif is_bech32_key('npub', self.term):
                self.by_npub()
            elif is_nip05(self.term):
                self.by_nip05()
            else:
                self.message = "Nothing found. Please try again with a valid public key or nip-05 identifier."
        else:
            self.message = "no search term found!"

    def by_at(self):
        pk = DB.get_profile_by_name_or_pk(self.term[1:])
        if pk is not None:
            self.redirect = '/profile?pk={}'.format(pk.public_key)

    def by_hex(self):
        self.redirect = '/profile?pk={}'.format(self.term)

    def by_npub(self):
        b_key = bech32_to_hex64('npub', self.term)
        if b_key:
            self.redirect = '/profile?pk={}'.format(b_key)
        else:
            self.message = 'invalid npub'

    def by_nip05(self):
        profile = DB.get_pk_by_nip05(self.term)
        if profile is not None:
            self.redirect = '/profile?pk={}'.format(profile.public_key)
        else:
            pk = request_nip05(self.term)
            if pk is not None:
                self.redirect = '/profile?pk={}'.format(pk)
            else:
                self.message = "Nip-05 identifier could not be located"

    def get(self):
        return self.results, self.redirect, self.message


from fastapi import FastAPI
import requests
import gradio as gr
import uvicorn

app = FastAPI()

headers = {
    "Authorization": "Bearer xxxx",
    "Content-Type": "application/json"
}

@app.get("/gpt3")
def get_gpt3_results(prompt: str):
    print(prompt)

    data = {
        "model": "gpt-3.5-turbo",
        "max_tokens": 100,
        "temperature": 0.7,
        "messages": [{"role": "user", "content": prompt}]
    }
    response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=data)
    if response.status_code == 200:
        return response.json()["choices"][0]["message"]["content"]
    else:
        return {"error": "Failed to get GPT-3.5-turbo results."}

@app.get("/dalle2")
def get_dalle2_image(prompt: str):
    data = {
        "prompt": prompt,
        "model": "image-alpha-001",
        "num_images": 1,
        "size": 512*742,
        "response_format": "url"
    }
    response = requests.post("https://api.openai.com/v1/images/generations/dall-e/2", headers=headers, json=data)
    if response.status_code == 200:
        return {"image_url": response.json()["data"][0]["url"]}
    else:
        return {"error": "Failed to get DALL-E 2 image."}

def add_text(history, text):
    history = history + [(text, None)]
    return history, ""

def add_file(history, file):
    history = history + [((file.name,), None)]
    return history

def gpt3_bot(history):
    print("bot history1===",history)
    prompt = history[-1][0]
    print(prompt)
    response = get_gpt3_results(prompt)
    history[-1][1] = response
    print("bot history2===",history)
    return history

def dalle2_bot(history):
    print("bot history1===",history)
    prompt = history[-1][0][0]
    print(prompt)
    response = get_dalle2_image(prompt)
    history[-1][1] = response
    print("bot history2===",history)
    return history

# def bot(history):
#     print("bot history1===",history)
#     response = "**That's cool!**"
#     history[-1][1] = response
#     print("bot history2===",history)
#     return history

with gr.Blocks() as demo:
    chatbot = gr.Chatbot([], elem_id="chatbot").style(height=750)

    with gr.Row():
        with gr.Column(scale=0.85):
            txt = gr.Textbox(
                show_label=False,
                placeholder="Enter text and press enter, or upload an image",
            ).style(container=False)
        with gr.Column(scale=0.15, min_width=0):
            btn = gr.UploadButton("📁", file_types=["image", "video", "audio"])

    txt.submit(add_text, [chatbot, txt], [chatbot, txt]).then(
        gpt3_bot, chatbot, chatbot
    )

    txt_btn = gr.Button(value="Submit")
    txt_btn.click(add_text, [chatbot, txt], [chatbot, txt]).then(
        gpt3_bot, chatbot, chatbot
    )

    btn.upload(add_file, [chatbot, btn], [chatbot]).then(
        dalle2_bot, chatbot, chatbot
    )

app = gr.mount_gradio_app(app, demo, path="/gradio",gradio_api_url="http://localhost:7860/")

if __name__ == "__main__":
    # demo.launch(share=True)
    uvicorn.run(app='app:app', host="localhost", port=7860,reload=True)


from annoy import AnnoyIndex
import sqlite3
from get_audio_features import search_input, search_tracks, choose_right_track, get_audio_features
import ipdb
import pandas as pd
import requests
from authenticate import authenticate

def load_index(path, metric='angular'):
    index = AnnoyIndex(12, metric)
    index.load(path)
    return index

def find_neighbours(index, vector, n=10):
    rownum_list = index.get_nns_by_vector(vector, n)
    return tuple(rownum_list)

def get_recommended_tracks(rownum_list):
    data_path = 'data/spotify.sqlite'
    conn = sqlite3.connect(data_path)
    cursor = conn.cursor()

    query = f"""
        SELECT *
        FROM tracks_data
        WHERE rownum IN {rownum_list};
    """

    cursor.execute(query)
    data = cursor.fetchall()
    print(pd.DataFrame(data))
    recommended_tracks = {'title': [], 'artist': [], 'id': []}
    for track in data:
        recommended_tracks['title'].append(track[2])
        recommended_tracks['artist'].append(track[4])
        recommended_tracks['id'].append(track[1])
    return recommended_tracks

def get_preview_cover(token, ids):
    url = f'https://api.spotify.com/v1/tracks/'
    params = {'market': 'JP', 'ids': f"{','.join(ids)}"}
    header = {'Authorization': f"Bearer {token}"}

    response = requests.get(
        url = url,
        params = params,
        headers = header
    ).json()

    previews = []
    covers = []
    for track in response['tracks']:
        previews.append(track['preview_url'])
        covers.append(track['album']['images'][0]['url'])

    return previews, covers

if __name__ == '__main__':
    token = authenticate()
    title, artist = search_input()
    track_list = search_tracks(token=token, title=title, artist=artist)
    if track_list == None:
        print("No track matched your search. Please try again")
    else:
        if len(track_list['track_id']) > 1:
            track_id = choose_right_track(track_list)
        else:
            track_id = track_list['track_id']
        audio_features = get_audio_features(token, track_id)
        print(audio_features)

        index = load_index('230331-test-4000000_tracks-100_trees-euclidean-norm.ann', 'euclidean')
        rownum_list = find_neighbours(index, audio_features)
        print(rownum_list)
        recommended_tracks = get_recommended_tracks(rownum_list)
        previews, covers = get_preview_cover(token, recommended_tracks['id'])

        for index, id in enumerate(recommended_tracks['id']):
            st.image(covers[index])
            st.markdown(f"{index + 1}. {recommended_tracks['title'][index]} - {recommended_tracks['artist'][index]}")
            st.audio(previews[index], format='audio/mp3')


import singer
from .base_stream import BaseStream
from tap_appfigures.context import Context
from tap_appfigures.exceptions import AppfiguresNotFoundError
from multiprocessing import Pool

LOGGER = singer.get_logger()

class CompanyStream(BaseStream):
    stream_id = 'companies'
    stream_name = 'companies'
    key_properties = ["developer_id"]
    replication_key = "developer_id"
    count = 0

    def sync_records(self, **kwargs):
        application_stream = Context.stream_objects['applications'](self.client)
        company_ids = application_stream.get_company_ids()

        for company_id in company_ids:
            time_extracted = singer.utils.now()
            url = self.client.get_company_url(company_id)

            try:
                record = self.client.get_request(url)
            except AppfiguresNotFoundError as e:
                LOGGER.info(e)

            additional_info = dict(record).get("additional_info", {})
            name = dict(record).get("name", None)
            company_info = additional_info.get("company", {})
            company_metrics = company_info.get("metrics", {})
            location = company_info.get("geo", {})
            category = company_info.get("category", {})
            linkedin = company_info.get("linkedin", {})
            twitter = company_info.get("twitter", {})
            facebook = company_info.get("facebook", {})

            record = {
                "developer_id": company_id,
                "name": name if name else company_info.get("name", None),
                "legal_name": company_info.get("legal_name", None),
                "domain": company_info.get("domain", None),
                "domain_aliases": company_info.get("domain_aliases", []),
                "street_number": location.get("street_number", None),
                "street_name": location.get("street_name", None),
                "city": location.get("city", None),
                "state": location.get("state_code", None),
                "country": location.get("country_code", None),
                "zipcode": location.get("postal_code", None),
                "employee_count": company_metrics.get("employees", None),
                "employee_count_range": company_metrics.get("employees_range", None),
                "annual_revenue": company_metrics.get("annual_revenue", None),
                "estimated_annual_revenue": company_metrics.get("estimated_annual_revenue", None),
                "industry": category.get("industry", None),
                "industry_group": company_metrics.get("industry_group", None),
                "description": company_info.get("description", None),
                "linkedin_handle": linkedin.get("handle", None),
                "twitter_handle": twitter.get("handle", None),
                "twitter_id": twitter.get("id", None),
                "facebook_handle": facebook.get("handle", None),
                "timezone": company_info.get("timezone", None)
            }

            self.write_record(record, time_extracted=time_extracted)
            Context.set_bookmark(self.stream_id, self.replication_key, company_id)
            CompanyStream.count += 1

        LOGGER.info(f"{CompanyStream.count} companies found using Apollo client.")


'''
CursorRuler 1.1.6

A plugin for the Sublime Text editor which marks
the current cursor position(s) using dynamic rulers.

See README.md for details.

'''

import sublime
import sublime_plugin

#
# It's important for us to know if we're running in ST3 or ST2.
#
# Build 3010 and older of the Sublime Text 3 builds do not have the API
# available during program startup.  As of build 3011 `sublime.version()`
# is available during startup.  If we're unable to get the version build
# number we make the assumption that it's 3000.
#
# We're also assuming that if we're not in ST3 then we're in ST2.
#
st = 3000 if sublime.version() == '' else int(sublime.version())

# ------------------------------------------------------------------------------

class CursorRuler(object):
    @classmethod
    def __draw_on_view(cls, view, active_view):
        cursors        = active_view.sel()
        em_width       = active_view.em_width()
        view_size      = active_view.size()
        dynamic_rulers = []

        # Setup rulers for each cursor.
        for cursor in cursors:
            #
            # Get the cursor's true horizontal position.
            #
            # To do this we need to know a few things:
            #
            # The cursor position is usually represented technically as an
            # empty region.  While in this case the region's `a` and `b`
            # properties are the same, in the case of a selection region
            # being made the `b` property more accurately represents where
            # the cursor is at.
            #
            # A cursor's `xpos` is its target horizontal layout position.
            # It is the position where the cursor would be at if it weren't
            # affected by lack of virtual whitespace, word-wrapping, or
            # varying font widths.
            #
            # If it's non-negative then it represents the position the cursor
            # was just at in the previous line.  It also indicates that the
            # cursor was moved vertically with either the up or down arrow key.
            #
            # If it's negative then it's actually not a position but rather
            # an indicator that the cursor was moved horizontally with either
            # the left or right arrow key or repositioned with a mouse click.
            #

            # First we get what would normally be the current cursor position.
            cur_x = view.text_to_layout(cursor.b)[0]

            # We then take into account the strangeness of word-wrapping.
            # It only matters when we're not at the end of the file.

            next_x = view.text_to_layout(cursor.b + 1)[0]
            xpos   = cursor.xpos if st >= 3000 else cursor.xpos()

            if xpos >= 0 and xpos < cur_x and cur_x > next_x and cursor.b < view_size:
                if not cls.indent_subsequent_lines:
                    cur_x = 0
                else:
                    line = view.substr(view.line(cursor))
                    if line:
                        line_length           = len(line)
                        stripped_line_length  = len(line.lstrip())

                        # We keep going if the line is not entirely whitespace.
                        if stripped_line_length > 0:
                            # We find out where the first non-whitespace
                            # character of the line is and we use its position.
                            cur_row         = view.rowcol(cursor.b)[0]
                            beginning_pos   = line_length - stripped_line_length
                            beginning_point = view.text_point(cur_row, beginning_pos)
                            cur_x           = view.text_to_layout(beginning_point)[0]

            # Get the cursor position in terms of columns.
            cur_col = cur_x / em_width

            # Setup the current dynamic rulers to be included
            # with the static rulers.
            dynamic_rulers += [cur_col + offset for offset in cls.cursor_rulers]

        active_rulers = cls.rulers + dynamic_rulers

        if st < 3000:
            #
            # For some reason in ST2 we'll get into some sort of infinite
            # recursion when trying to set the rulers.  Here we only update the
            # "rulers" setting if changes have been made (i.e. a cursor ruler
            # changes location).
            #
            # Note: ST2 uses Python 2 so we can use the convenient `cmp()`
            # function which is unavailable in Python 3.
            #
            if cmp(active_rulers, view.settings().get('rulers')) != 0:
                view.settings().set('rulers', active_rulers)
        else:
            view.settings().set('rulers', active_rulers)

    # ..........................................................................

    @classmethod
    def __setup(cls):
        default_cursor_rulers = [-0.1, 0.2]

        cls.rulers                  =      cls.editor_settings.get('rulers', [])
        cls.indent_subsequent_lines = bool(cls.editor_settings.get('indent_subsequent_lines', True))
        cls.cursor_rulers           =      cls.settings.get('cursor_rulers', default_cursor_rulers)
        cls.synchronized            = bool(cls.settings.get('synchronized', True))

        # Ensure the rulers settings are valid lists.
        if not isinstance(cls.rulers, list):
            cls.rulers = []
        if not isinstance(cls.cursor_rulers, list):
            cls.cursor_rulers = default_cursor_rulers

        #
        # We shouldn't draw our own rulers when our plugin is ignored.
        # We need to check for this because if our plugin is active it will,
        # until the next time Sublime Text is restarted, stay active after
        # being disabled or being manually added to `ignored_packages` in
        # the user settings.
        #

        # For some reason the `sublime` module is sometimes not available.
        if sublime is None:
            ignored_packages = []
        else:
            ignored_packages = sublime.load_settings('Preferences.sublime-settings').get('ignored_packages', [])

        cls.enabled = 'CursorRuler' not in ignored_packages and bool(cls.settings.get('enabled', True))

    # ..........................................................................

    @classmethod
    def draw(cls, view):
        if cls.synchronized:
            # Draw the dynamic rulers for every view of the same buffer
            # as the active view.
            view_buffer_id = view.buffer_id()
            for window in sublime.windows():
                for v in window.views():
                    if (v.buffer_id() == view_buffer_id):
                        cls.__draw_on_view(v, view)
        else:
            # Draw the dynamic rulers for the current view.
            cls.__draw_on_view(view, view)

    # ..........................................................................

    @classmethod
    def init(cls):
        plugin_name = 'CursorRuler'

        cls.editor_settings = sublime.load_settings('Preferences.sublime-settings')
        cls.settings        = sublime.load_settings(plugin_name + '.sublime-settings')

        # In ST3 the `add_on_change()` was not implemented until build 3013.
        if st < 3000 or st >= 3013:
            cls.editor_settings.add_on_change(plugin_name.lower() + '-reload', cls.__setup)
            cls.settings.add_on_change('reload', cls.__setup)

        cls.__setup()

    # ..........................................................................

    @classmethod
    def is_enabled(cls, view):
        return cls.enabled and not view.settings().get('is_widget', False)

    # ..........................................................................

    @classmethod
    def reset(cls, view):
        if cls.synchronized:
            # Reset all the views of the same buffer.
            view_buffer_id = view.buffer_id()
            for window in sublime.windows():
                for v in window.views():
                    if (v.buffer_id() == view_buffer_id):
                        v.settings().set('rulers', cls.rulers)
        else:
            # Reset the current view.
            view.settings().set('rulers', cls.rulers)

    # ..........................................................................

    @classmethod
    def reset_all(cls):
        # Remove the rulers we created and restore any regular rulers.
        for window in sublime.windows():
            for view in window.views():
                if not view.settings().get('is_widget', False):
                    view.settings().set('rulers', cls.rulers)

# ------------------------------------------------------------------------------

class CursorRulerToggleCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        if CursorRuler.is_enabled(self.view):
            # It's important that we turn off `enabled` before resetting.
            # Otherwise, the dynamic rulers will stick around and not
            # get cleared.
            CursorRuler.enabled = False
            CursorRuler.reset_all()
        else:
            CursorRuler.enabled = True
            CursorRuler.draw(self.view)

        CursorRuler.settings.set('enabled', CursorRuler.enabled)
        sublime.save_settings('CursorRuler.sublime-settings')

# ------------------------------------------------------------------------------

class CursorRulerWrapLinesCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        if CursorRuler.is_enabled(self.view):
            # Temporarily turn off CursorRuler.
            CursorRuler.reset(self.view)
            CursorRuler.enabled = False

            # Do our line wrapping without the unwanted
            # influence of the dynamic cursor rulers.
            self.view.run_command('wrap_lines')

            # Reactivate CursorRuler.
            CursorRuler.draw(self.view)
            CursorRuler.enabled = True
        else:
            self.view.run_command('wrap_lines')

# ------------------------------------------------------------------------------

class CursorRulerListener(sublime_plugin.EventListener):
    def on_activated(self, view):
        if not view.is_loading() and CursorRuler.is_enabled(view):
            CursorRuler.draw(view)
            view.settings().add_on_change('command_mode', self.on_command_mode_change)

    def on_close(self, view):
        CursorRuler.reset(view)

    def on_deactivated(self, view):
        if CursorRuler.is_enabled(view):
            CursorRuler.reset(view)

    def on_load(self, view):
        # In ST2 the initialization phase needs to happen here
        # for static rulers to not disappear.
        if st < 3000:
            CursorRuler.init()

        if CursorRuler.is_enabled(view):
            CursorRuler.draw(view)
        else:
            CursorRuler.reset(view)

    def on_selection_modified(self, view):
        # For some reason the `sublime` module is sometimes not available.
        if sublime is None: return

        active_window = sublime.active_window()
        if active_window is None: return

        # The view parameter doesn't always match the active view
        # the cursor is in.  This happens when there are multiple
        # views of the same file.
        active_view = active_window.active_view()

        # An empty window has no active views.  A newly-opened window
        # created by the "New Window" command is empty.  When the
        # `close_windows_when_empty` user setting is true a non-empty
        # window can be left empty by closing its contained views.
        if active_view is None: return

        if CursorRuler.is_enabled(active_view):
            CursorRuler.draw(active_view)

    def on_command_mode_change(self):
        self.on_selection_modified(None)

# ------------------------------------------------------------------------------

# In ST3 this will get called automatically once the full API becomes available.
def plugin_loaded():
    CursorRuler.init()

# ------------------------------------------------------------------------------

def plugin_unloaded():
    CursorRuler.reset_all()

# ------------------------------------------------------------------------------

# In ST2 this prevents an error from happening if this particular file
# is saved.  This also prevents a missing attribute error from occurring
# at startup.
if st < 3000:
    plugin_loaded()


"""
题目描述
在数组中的两个数字，如果前面一个数字大于后面的数字，则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
输入描述:
题目保证输入的数组中没有的相同的数字

数据范围：

    对于%50的数据,size<=10^4

    对于%75的数据,size<=10^5

    对于%100的数据,size<=2*10^5
归并排序,
f(nums)
f(nums[前])，f(nums[后])--已经排好序了
merge（f(nums[前])，f(nums[后])）
"""
def f(data):
    if not data:
        return 0
    count=[0]
    def my_merge(data_first, data_second):
        nums=[]
        # 与归并排序不同，这里是一边排序一边记录逆序对
        first_index, second_index = len(data_first) - 1, len(data_second) - 1
        while(first_index>=0 and second_index>=0):
            if data_first[first_index]<=data_second[second_index]:
                nums.append(data_second[second_index])
                second_index-=1
            else:
                nums.append(data_first[first_index])
                count[0]+=second_index+1
                first_index-=1
        if first_index<0:
            nums.extend(data_second[:second_index+1][::-1])
        else:
            nums.extend(data_first[:first_index+1][::-1])
        return nums[::-1]
    def guibing_sort(data):
        if len(data)<=1:
            return data
        else:
            return my_merge(guibing_sort(data[0:len(data)//2]),guibing_sort(data[len(data)//2:]))
    print(guibing_sort(data))
    return count[0]
nums=[7,5,6,4]
print(f(nums))
def f(a,b):
    return a+b
def f(s):
    return s
print(f(1,2))
print(f(3))

51_数组中的逆序对.py


import requests
import json

def get_prometheus_metrics(url):
    # Tworzenie zapytania do Prometheus API
    response = requests.get(url)
    data = response.json()

    # Przetwarzanie danych odpowiedzi
    metrics = []
    for result in data['data']['result']:
        metric = result['metric']
        value = result['value']
        metrics.append({
            'metric': metric,
            'value': value
        })

    return metrics

def save_metrics_to_file(metrics, file_path):
    # Zapisywanie metryk do pliku
    with open(file_path, 'w') as file:
        json.dump(metrics, file)

# Ustawienia Prometheus i pliku
query_name = 'kafka_topic_partitions'
prometheus_url = f'http://localhost:9090/api/v1/query?query={query_name}'
output_file = '../scripts/prometheus_metrics.json'

# Pobieranie metryk z Prometheus i zapisywanie ich do pliku
metrics = get_prometheus_metrics(prometheus_url)
save_metrics_to_file(metrics, output_file)

print('Metryki zostały zapisane w pliku:', output_file)


import numpy as np

with open("./day_22.in") as fin:
    raw_data = fin.read().strip().split("\n")

def within_bounds(x_range, y_range, z_range):
    for b in x_range, y_range, z_range:
        if not (0 <= b[0] and b[1] <= 100):
            return False
    return True

steps = []

for line in raw_data:
    parts = line.split(" ")
    switch = parts[0] == "on"
    bounds = []
    for axis in parts[1].split(","):
        axis = axis.split("..")
        bounds.append((int(axis[0][2:]) + 50, int(axis[1]) + 50))

    steps.append((switch, bounds))

grid = np.zeros((101, 101, 101), dtype=bool)

for switch, bounds in steps:
    x_range, y_range, z_range = bounds
    if not within_bounds(x_range, y_range, z_range):
        continue

    for x in range(x_range[0], x_range[1] + 1):
        for y in range(y_range[0], y_range[1] + 1):
            for z in range(z_range[0], z_range[1] + 1):
                grid[x, y, z] = switch

ans = 0
for x in grid.flatten():
    ans += x
print(ans)