import os
import platform
import random
import string

from flask import Flask, request, jsonify

import ioiprint.settings as settings
import ioiprint.modifier as modifier
from ioiprint.print import print_file, JOB_PRIORITY_HIGH
from ioiprint.contestant_data import get_contestant_data
from ioiprint.utils import create_temp_directory, generate_print_id
from ioiprint.metrics import get_metrics

app = Flask('ioiprint')

def _real_ip():
    return request.headers.get('X-Real-IP', request.remote_addr)

@app.route('/healthcheck', methods=['GET'])
def healthcheck():
    return 'OK'

@app.route('/mass', methods=['POST'])
def mass():
    temp_directory = create_temp_directory()
    original_pdf_path = os.path.join(temp_directory, 'original.pdf')
    request.files['pdf'].save(original_pdf_path)

    printer = request.form.get('printer', settings.printer_for_mass())
    count = int(request.form['count'])
    for _ in range(count):
        print_file(original_pdf_path, printer, 'mass')
    return "OK"

@app.route('/translation', methods=['POST'])
def translation():
    temp_directory = create_temp_directory()
    original_pdf_path = os.path.join(temp_directory, 'original.pdf')
    request.files['pdf'].save(original_pdf_path)

    country_code = request.form['country_code']
    country_name = request.form['country_name']
    cover_page = int(request.form['cover_page']) > 0
    count = int(request.form['count'])

    if cover_page:
        final_pdf_path = modifier.make_translation_pdf(
            original_pdf_path,
            country_code,
            country_name,
            temp_directory
        )
    else:
        final_pdf_path = original_pdf_path

    job_name = 'translation:%s'%country_code
    for _ in range(count):
        print_file(final_pdf_path, settings.printer_for_translation(), job_name)
    return "OK"

@app.route('/staff_call', methods=['POST'])
def staff_call():
    req_data = request.get_json()
    message = req_data['message']
    contestant = req_data['contestant']
    contestant_id = req_data['contestant']['id']
    desk = req_data['desk']
    desk_zone = req_data['desk'].get('zone')

    temp_directory = create_temp_directory()
    pdf_path = modifier.make_staff_call_pdf(
        message=message,
        contestant=contestant,
        desk=desk,
        temp_directory=temp_directory,
    )

    job_name = 'staff_call:%s'%contestant_id
    print_file(pdf_path, settings.printer_for_contestant(desk_zone),
               job_name, job_priority=JOB_PRIORITY_HIGH)
    return jsonify({'status': 'OK'})

@app.route('/contestant', methods=['POST'])
def contestant():
    temp_directory = create_temp_directory()
    original_pdf_path = os.path.join(temp_directory, 'original.pdf')
    request.files['pdf'].save(original_pdf_path)

    contestant_data = get_contestant_data(_real_ip())
    contestant_id = (contestant_data['contestant'] or {}).get('id', '')
    desk_zone = (contestant_data['desk'] or {}).get('zone')

    print_id = generate_print_id()
    hostname = platform.uname().node

    final_pdf_path = modifier.make_contestant_pdf(
        pdf_file_path=original_pdf_path,
        contestant=contestant_data['contestant'],
        desk=contestant_data['desk'],
        print_id=print_id,
        temp_directory=temp_directory,
    )

    job_name = 'contestant:%s:%s'%(contestant_id, print_id)
    metric_name = 'contestant:%s'%(contestant_id)
    print_file(
        file_path=final_pdf_path,
        printer=settings.printer_for_contestant(desk_zone),
        job_name=job_name,
        metric_name=metric_name
    )
    return "Queued as %s on %s"%(print_id, hostname)

@app.route('/password', methods=['POST'])
def password():
    req_data = request.get_json()
    title = req_data['title']
    users = req_data['users']

    temp_directory = create_temp_directory()
    pdf_path = modifier.make_password_pdf(
        title=title,
        users=users,
        temp_directory=temp_directory,
    )

    job_name = 'password'
    print_file(pdf_path, settings.printer_for_mass(), job_name)
    return jsonify({'status': 'OK'})

@app.route('/metrics', methods=['GET'])
def metrics():
    metrics = get_metrics()
    result = ''
    for job_type, count_by_key in metrics.items():
        prometheus_key = 'ioiprint_%s_jobs'%(job_type)
        result += '''# HELP {prometheus_key} It shows how many {job_type} jobs are called
# TYPE {prometheus_key} counter
'''.format(prometheus_key=prometheus_key, job_type=job_type)
        for job_value, count in count_by_key.items():
            prometheus_key = 'ioiprint_%s_jobs'%(job_type)
            result += '''{prometheus_key}{{{job_type}="{job_value}"}} {count}
'''.format(prometheus_key=prometheus_key, job_type=job_type, job_value=job_value, count=count)
    return result


import sys

def map(func, l):
	return [func(i) for i in l]

def parseCase(instrm):
	firstCol = int(instrm.readline().strip())
	firstMat = []
	for i in range(4):
		row = instrm.readline().strip().split(" ")
		firstMat.append(map(int, row))
	secCol = int(instrm.readline().strip())
	secMat = []
	for i in range(4):
		row = instrm.readline().strip().split(" ")
		secMat.append(map(int, row))
	return (firstCol, secCol, firstMat, secMat)

def solveCase(input):
	(firstRow, secRow, firstMat, secMat) = input
	firstRow = firstMat[firstRow-1]
	secRow = secMat[secRow-1]
	both = []
	for el in secRow:
		if (firstRow.count(el)>0):
			both.append(el)
	if (len(both) == 0):
		return "Volunteer cheated!"
	if (len(both) == 1):
		return both[0]
	else:
		return "Bad magician!"

if __name__=="__main__":
	instrm = open(sys.argv[1])
	cases = int(instrm.readline().strip())
	for i in range(cases):
		input = parseCase(instrm)
		print("Case #" + str(i+1) +": "+str(solveCase(input)))
	instrm.close()


def find_bounds(events):
    min_x, max_x = 0, 0
    min_y, max_y = 0, 0
    min_z, max_z = 0, 0

    for event in events:
        x, y, z = event.fields['world_position']

        if x < min_x:
            min_x = x

        elif x > max_x:
            max_x = x

        if y < min_y:
            min_y = y

        elif y > max_y:
            max_y = y

        if z < min_z:
            min_z = z

        elif z > max_z:
            max_z = z

    return dict(min_x=min_x, max_x=max_x, min_y=min_y, max_y=max_y)

def bin_events(events, bounds, cell_dimensions):
    """Group together all events into n^3 bins"""
    min_x = bounds['min_x']
    min_y = bounds['min_y']
    min_z = bounds['min_z']

    for event in events:
        world = event.fields['world_position']

        x_bin = int(world.x // cell_dimensions.x)
        y_bin = int(world.y // cell_dimensions.y)
        z_bin = int(world.z // cell_dimensions.z)

        event.fields['bin'] = x_bin, y_bin, z_bin


from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.event_firing_webdriver import EventFiringWebDriver
from webdriver_manager.chrome import ChromeDriverManager

from selenium_automation.webdriver_event_listener.event_listener import EventListener

class TestListenerReport:
    def setup_class(cls):
        global driver
        edriver = webdriver.Chrome(ChromeDriverManager().install())
        driver = EventFiringWebDriver(edriver, EventListener())
        driver.maximize_window()
        driver.get("https://www.saucedemo.com/")
        driver.implicitly_wait(2)

    def test_1(self):
        driver.find_element(By.ID, "user-name").send_keys("standard_user")
        driver.find_element(By.ID, "password").send_keys("secret_sauce")
        driver.find_element(By.CSS_SELECTOR, "input[data-test='login-button']").click()
        assert driver.find_element(By.CLASS_NAME, "title").text == "PRODUCTS"
        driver.back()
        driver.forward()

    def teardown_class(cls):
        driver.quit()


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

import gensim
import os
import collections
import smart_open
import random

# Set file names for train and test data
test_data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data'])
lee_train_file ='abstracts.cor'
lee_test_file = 'test.cor'
print("corpus: " + lee_train_file)
def read_corpus(fname, tokens_only=False):
    with smart_open.smart_open(fname, encoding="iso-8859-1") as f:
        for i, line in enumerate(f):
            if tokens_only:
                yield gensim.utils.simple_preprocess(line)
            else:
                # For training data, add tags
                yield gensim.models.doc2vec.TaggedDocument(gensim.utils.simple_preprocess(line), [i])

train_corpus = list(read_corpus(lee_train_file))
test_corpus = list(read_corpus(lee_test_file, tokens_only=True))

model = gensim.models.doc2vec.Doc2Vec(vector_size=20, min_count=0, epochs=100, dbow_words=1)
model.build_vocab(train_corpus)
model.infer_vector(['only', 'you', 'can', 'prevent', 'forest', 'fires'])

ranks = []
second_ranks = []
for doc_id in range(len(train_corpus)):
    inferred_vector = model.infer_vector(train_corpus[doc_id].words)
    sims = model.docvecs.most_similar([inferred_vector], topn=len(model.docvecs))
    rank = [docid for docid, sim in sims].index(doc_id)
    ranks.append(rank)

    second_ranks.append(sims[1])
collections.Counter(ranks)  # Results vary between runs due to random seeding and very small corpus

print('Document ({}): {}\n'.format(doc_id, ' '.join(train_corpus[doc_id].words)))
print(u'SIMILAR/DISSIMILAR DOCS PER MODEL %s:\n' % model)
for label, index in [('MOST', 0), ('SECOND-MOST', 1), ('MEDIAN', len(sims)//2), ('LEAST', len(sims) - 1)]:
    print(u'%s %s: %s\n' % (label, sims[index], ' '.join(train_corpus[sims[index][0]].words)))
    # Pick a random document from the corpus and infer a vector from the model
for i in range(50):
    try:

        doc_id = random.randint(0, len(train_corpus) - 1)

        # Compare and print the second-most-similar document
        print('Train Document ({}): {}\n'.format(doc_id, ' '.join(train_corpus[doc_id].words)))
        sim_id = second_ranks[doc_id]
        print('Similar Document {}: «{}»\n'.format(sim_id, ' '.join(train_corpus[sim_id[0]].words)))
    except:
        continue

# # Pick a random document from the test corpus and infer a vector from the model
# doc_id = random.randint(0, len(test_corpus) - 1)
# inferred_vector = model.infer_vector(test_corpus[doc_id])
# sims = model.docvecs.most_similar([inferred_vector], topn=len(model.docvecs))

# # Compare and print the most/median/least similar documents from the train corpus
# print('Test Document ({}): «{}»\n'.format(doc_id, ' '.join(test_corpus[doc_id])))
# print(u'SIMILAR/DISSIMILAR DOCS PER MODEL %s:\n' % model)
# for label, index in [('MOST', 0), ('MEDIAN', len(sims)//2), ('LEAST', len(sims) - 1)]:
#     print(u'%s %s: «%s»\n' % (label, sims[index], ' '.join(train_corpus[sims[index][0]].words)))


import numpy as np
import matplotlib.pyplot as plt
import pdb
# 解决中文显示问题
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

"旅行商问题 ( TSP , Traveling Salesman Problem )"
coordinates = np.array([[565.0, 575.0], [25.0, 185.0], [345.0, 750.0], [945.0, 685.0], [845.0, 655.0],
                   [880.0, 660.0], [25.0, 230.0], [525.0, 1000.0], [580.0, 1175.0], [650.0, 1130.0],
                   [1605.0, 620.0], [1220.0, 580.0], [1465.0, 200.0], [1530.0, 5.0], [845.0, 680.0],
                   [725.0, 370.0], [145.0, 665.0], [415.0, 635.0], [510.0, 875.0], [560.0, 365.0],
                   [300.0, 465.0], [520.0, 585.0], [480.0, 415.0], [835.0, 625.0], [975.0, 580.0],
                   [1215.0, 245.0], [1320.0, 315.0], [1250.0, 400.0], [660.0, 180.0], [410.0, 250.0],
                   [420.0, 555.0], [575.0, 665.0], [1150.0, 1160.0], [700.0, 580.0], [685.0, 595.0],
                   [685.0, 610.0], [770.0, 610.0], [795.0, 645.0], [720.0, 635.0], [760.0, 650.0],
                   [475.0, 960.0], [95.0, 260.0], [875.0, 920.0], [700.0, 500.0], [555.0, 815.0],
                   [830.0, 485.0], [1170.0, 65.0], [830.0, 610.0], [605.0, 625.0], [595.0, 360.0],
                   [1340.0, 725.0], [1740.0, 245.0]])

# 得到距离矩阵的函数
def getdistmat(coordinates):
    num = coordinates.shape[0]  # 52个坐标点
    distmat = np.zeros((52, 52))  # 52X52距离矩阵
    for i in range(num):
        for j in range(i, num):
            distmat[i][j] = distmat[j][i] = np.linalg.norm(coordinates[i] - coordinates[j])
    return distmat

def initpara():
    alpha = 0.99
    t = (1, 100)
    markovlen = 1000
    return alpha, t, markovlen

num = coordinates.shape[0]
distmat = getdistmat(coordinates)  # 得到距离矩阵

solutionnew = np.arange(num)
# valuenew = np.max(num)

solutioncurrent = solutionnew.copy()
valuecurrent = 99000  # np.max这样的源代码可能同样是因为版本问题被当做函数不能正确使用，应取一个较大值作为初始值
# print(valuecurrent)

solutionbest = solutionnew.copy()
valuebest = 99000  # np.max
alpha, t2, markovlen = initpara()
t = t2[1]

result = []  # 记录迭代过程中的最优解
while t > t2[0]:
    for i in np.arange(markovlen):

        # 下面的两交换和三角换是两种扰动方式，用于产生新解
        if np.random.rand() > 0.5:  # 交换路径中的这2个节点的顺序
            # np.random.rand()产生[0, 1)区间的均匀随机数
            while True:  # 产生两个不同的随机数
                loc1 = np.int(np.ceil(np.random.rand() * (num - 1)))
                loc2 = np.int(np.ceil(np.random.rand() * (num - 1)))
                ## print(loc1,loc2)
                if loc1 != loc2:
                    break
            solutionnew[loc1], solutionnew[loc2] = solutionnew[loc2], solutionnew[loc1]
        else:  # 三交换
            while True:
                loc1 = np.int(np.ceil(np.random.rand() * (num - 1)))
                loc2 = np.int(np.ceil(np.random.rand() * (num - 1)))
                loc3 = np.int(np.ceil(np.random.rand() * (num - 1)))

                if ((loc1 != loc2) & (loc2 != loc3) & (loc1 != loc3)):
                    break

            # 下面的三个判断语句使得loc1<loc2<loc3
            if loc1 > loc2:
                loc1, loc2 = loc2, loc1
            if loc2 > loc3:
                loc2, loc3 = loc3, loc2
            if loc1 > loc2:
                loc1, loc2 = loc2, loc1

            # 下面的三行代码将[loc1,loc2)区间的数据插入到loc3之后
            tmplist = solutionnew[loc1:loc2].copy()
            solutionnew[loc1:loc3 - loc2 + 1 + loc1] = solutionnew[loc2:loc3 + 1].copy()
            solutionnew[loc3 - loc2 + 1 + loc1:loc3 + 1] = tmplist.copy()

        valuenew = 0
        for i in range(num - 1):
            valuenew += distmat[solutionnew[i]][solutionnew[i + 1]]
        valuenew += distmat[solutionnew[0]][solutionnew[51]]
        # print (valuenew)
        if valuenew < valuecurrent:  # 接受该解

            # 更新solutioncurrent 和solutionbest
            valuecurrent = valuenew
            solutioncurrent = solutionnew.copy()

            if valuenew < valuebest:
                valuebest = valuenew
                solutionbest = solutionnew.copy()
        else:  # 按一定的概率接受该解
            if np.random.rand() < np.exp(-(valuenew - valuecurrent) / t):
                valuecurrent = valuenew
                solutioncurrent = solutionnew.copy()
            else:
                solutionnew = solutioncurrent.copy()
    t = alpha * t
    result.append(valuebest)
    print(t)  # 程序运行时间较长，打印t来监视程序进展速度

# 用来显示结果
plt.plot(np.array(result))
plt.ylabel("最佳值")
plt.xlabel("时间")
plt.show()


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

import turtle
import tkinter

pen = turtle.Turtle()
scr = turtle.Screen()
# pen.rotate(45)
# pen.write("values", font=('Arial', 12, 'normal'))
c = scr.getcanvas()
c.create_text(100, 100, angle=90, text='fuck')
pen.hideturtle()
scr.mainloop()


import time
import random

ThunderMountain = "Closed"
StarTours = "Closed"
PhantomManour = "Closed"
day = 1
hour = 0
ThunderMountainPeople = 0
StarToursPeople = 0
PhantomManourPeople = 0
while True:
    time.sleep(0.5)
    print (("Day ") + (str(day)))
    print ("Hour = " + str(hour))
    hour = hour + 1
    if hour == 10:
        ThunderMountain = "Open"
        print ("Thunder Mountain is open!")
        ThunderMountainPeople = random.randint(0,400)
        print((str((ThunderMountainPeople))) + (" people are in the queue"))
    if hour == 11:
        StarTours = "Open"
        print ("Star Tours is open!")
        StarToursPeople = random.randint(0,150)
        print((str((StarToursPeople))) + (" people are in the queue"))
    if hour == 13:
        PhantomManour = "Open"
        PhantomManourPeople = random.randint(0,400)
        print((str((PhantomManourPeople))) + (" people are in the queue"))
    if hour == 22:
        ThunderMountain = "Closed"
        StarTours = "Closed"
        PhantomManour = "Closed"
    if hour == 24:
        hour = 0
        day = day + 1
        print (("Day ") + (str(day)))


#!/usr/bin/python3
#-----------------------------------------------------------
#  Extracts metadata from HST Photo Database
#  Wed 27 Nov 2019 03:58:49 PM CST
#-----------------------------------------------------------

import requests
from bs4 import BeautifulSoup
import sys
import dateparser
import datetime
import re

#accno = "72-3113"   # - entry with three element date
#accno = "95-22-87"  # - entry with two element date
#accno = "2009-1504" # - entry with single element date
#accno = "2006-487"  # - entry with no date
#accno = "80-16"     # - entry with no date or rights statement

accno = sys.argv[1]

url = 'https://www.trumanlibrary.gov/photograph-records/' + accno

response = requests.get(url, timeout=5)
html = response.content

soup = BeautifulSoup(html,'lxml')

#### Extract Title #####

print("Title: " + str(soup.h1.text).strip())

alltext = soup.get_text()

#### Extract Description #####

left = (alltext.find("Description"))
right = (alltext.find("Date(s)"))

Description = (alltext[left+11:right].strip())
print(" ")
print("Description: " + Description)

#### Extracts Date #####

x = (alltext.find("Date(s)"))     # extracts text only

D1=(alltext[x+12:x+30].rstrip())  # extracts date string as D1

D2 = dateparser.parse(D1)   # parses D1 date string into date variable D2

try:
    D2 = datetime.datetime(D2.year, D2.month, D2.day)

    D2 = datetime.datetime(D2.year, D2.month, D2.day)
    #, settings={'STRICT_PARSING': True}

    print(" ")
    w = (len(re.findall(r'\w+', D1)))
    D2 = (D2.year,D2.month,D2.day)
    print("Date: " + D1)

    if w == 1:
        print(str(D2[0]) + ":01:01")
    elif w == 2:
        print(str(D2[0]) + ":" + str('{:02d}'.format(D2[1]) + ":01"))
    else:
        print(str(D2[0]) + ":" + str('{:02d}'.format(D2[1]))+ ":" + str('{:02d}'.format(D2[2])))

except AttributeError:
    print(" ")
    print("Date: No Date string for this item in HST PDB")

#### Extract Rights Statement #####

Rights = soup.find('div', {'class': "field field--name-field-rights-undetermined-text field--type-markup field--label-hidden field__item"})

print(" ")

try:
    print("Rights: " + Rights.text)
except AttributeError:
    print("Rights: No Rights information included for this item in HST PDB")


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 28 16:12:23 2019
通过learning curve判断迭代效果，通过validation curve寻找最优lambda
@author: 34276
"""
import ex5
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt

data = sio.loadmat('ex5data1.mat')
X, y, Xtest, ytest, Xval, yval = data['X'], data['y'], data['Xtest'], data['ytest'], data['Xval'], data['yval']
X, Xval, Xtest = np.insert(X, 0, 1, axis=1), np.insert(Xval, 0, 1, axis=1), np.insert(Xtest, 0, 1, axis=1)

#使用训练集和验证集直接汇总learning curve，lamb为0
J_train, J_val = ex5.learningCurve(X, y, Xval, yval, 0)
ex5.plotLC(J_train, J_val)#J_train较大，欠拟合

#对训练集和验证集都进行多项式化之后绘制learning curve，lamb为0
X_poly = ex5.polyFeatures(X, 8)
Xval_poly = ex5.polyFeatures(Xval, 8)
Xtest_poly = ex5.polyFeatures(Xtest, 8)
J_train, J_val = ex5.learningCurve(X_poly, y, Xval_poly, yval, 0)
ex5.plotLC(J_train, J_val)#J_train几乎为0，过拟合

#通过绘制validation curve得到最优lamb
lambda_vec, J_train, J_val = ex5.validationCurve(X_poly, y, Xval_poly, yval)
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(lambda_vec, J_train, label='Traning Data')
ax.plot(lambda_vec, J_val, label='Validation Data')
ax.set_xlabel('lamda')
ax.set_ylabel('error')
ax.set_title('Validation Curves')
plt.legend(loc='upper right')

#使用最优lamb绘制learning curve
best_lamb = lambda_vec[np.argmin(J_val)]
J_train, J_val = ex5.learningCurve(X_poly, y, Xval_poly, yval, best_lamb)
ex5.plotLC(J_train, J_val)#J_train较小，拟合效果较好


import os
from ESP.settings import TOPDIR,CODEDIR
import datetime,logging
from ESP.esp.models import config
locals = config.objects.all()
LOCALSITE='HVMA' # hack!
for l in locals:
    if l.institution_name in os.listdir(TOPDIR):
        LOCALSITE=l.institution_name

###################################

###################################
def getJavaInfo():
    javadir="/usr/java/jdk1.5.0_09/bin/"
#    javadir="/usr/bin/"
    javaclass=" /home/ESP/ESP/sendMsgs:/home/ESP/axis-1_4/activation.jar:/usr/local/axis-1_4/lib/axis.jar:/usr/local/axis-1_4/lib/commons-logging-1.0.4.jar:/usr/local/axis-1_4/lib/commons-discovery-0.2.jar:/usr/local/axis-1_4/lib/jaxrpc.jar:/usr/local/axis-1_4/lib/wsdl4j-1.5.1.jar:/usr/local/axis-1_4/lib/saaj.jar:/usr/local/axis-1_4/lib/axis-ant.jar:/usr/local/axis-1_4/lib/log4j-1.2.8.jar:/home/ESP/axis-1_4/mail.jar:/home/ESP/ESP/sendMsgs/bcdc.jar "
    sendMsgcls = 'sendMsg'
    return (javadir, javaclass,sendMsgcls)

###############################
def getLogging(appname,debug=0):
    logdir = os.path.join(TOPDIR,LOCALSITE, 'logs/')
    if not os.path.isdir(logdir):
        os.mkdir(logdir)

    appname = logdir+appname
    debug=debug
    today=datetime.datetime.now().strftime('%Y%m%d')
    if debug:
        logging.basicConfig(level=logging.DEBUG,
                     format='%(asctime)s %(levelname)s %(message)s',
                     datefmt='%a, %d %b %Y %H:%M:%S',
                     filename='%s.%s.log' % (appname,today),
                     filemode='a')

    else:
        logging.basicConfig(level=logging.INFO,
                     format='%(asctime)s %(levelname)s %(message)s',
                     datefmt='%a, %d %b %Y %H:%M:%S',
                     filename='%s.%s.log' % (appname,today),
                     filemode='a')

    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('%(levelname)-4s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)

    return logging


import os
import csv
import sys
import glob
import win32com.client
from docx import Document
import tqdm

def doc_to_docx(doc_file, docx_file):
    # Initialize Word.Application
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = False

    # Open the .doc file and save it as .docx
    doc = word.Documents.Open(doc_file)
    doc.SaveAs(docx_file, FileFormat=16)  # 16 = wdFormatDocumentDefault
    doc.Close()

    # Close Word
    word.Quit()

def docx_table_to_csv(docx_file, output_folder):
    # Load the document
    doc = Document(docx_file)

    # Iterate through tables in the document
    for i, table in enumerate(doc.tables):
        # Prepare the output CSV file
        output_file = os.path.join(output_folder, f"{os.path.splitext(os.path.basename(docx_file))[0]}_table_{i}.csv")

        # Write table data to the CSV file
        with open(output_file, 'w', newline='', encoding='utf-8') as csvfile:
            writer = csv.writer(csvfile)

            for row in table.rows:
                writer.writerow([cell.text for cell in row.cells])

# Set input folder and output folder
input_folder = "doc_files"
output_folder = "csv_files"

# Check if running on Windows
if sys.platform != "win32":
    print("This script requires the win32com library, which is only available on Windows.")
    sys.exit(1)

# Process each Word file in the input folder
for filename in os.listdir(input_folder):
    if filename.endswith(".doc"):
        current_dir = os.getcwd()

        doc_file = os.path.join(current_dir, input_folder, filename)
        docx_file = os.path.join(current_dir, input_folder, f"{os.path.splitext(filename)[0]}.docx")

        # Convert .doc to .docx
        print(doc_file)
        doc_to_docx(doc_file, docx_file)

        # Extract tables to CSV files
        docx_table_to_csv(docx_file, output_folder)

        # Optionally, remove the .docx file after processing
    #    os.remove(docx_file)


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

import hashlib
from datetime import datetime

from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline
from scrapy.utils.python import to_bytes
from scrapy.http import Request
from LINEBlogScraper.items import LineblogscraperItem

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

class LineblogscraperPipeline(object):

    def process_item(self, item, spider):
        return item

class ValidationPipeline(object):

    ITEM = LineblogscraperItem()

    def process_item(self, item, spider):

        for key in self.ITEM.fields.keys():

            if key in ['article_tag', 'image_urls', 'images']:
                continue

            if not item[key]:
                raise DropItem('Missing {}'.format(key.split(' ')))

        return item

class FormatArticleBody(object):

    def process_item(self, item, spider):
        item['article_body'] = self.remove_non_break_space(item['article_body'])
        item['article_body'] = self.remove_tab(item['article_body'])
        item['article_body'] = self.remove_space(item['article_body'])
        item['article_body'] = self.remove_newline_code(item['article_body'])

        return item

    def remove_non_break_space(self, sentence_list):
        return [s.replace('\xa0', '') for s in sentence_list]

    def remove_space(self, sentence_list):
        return [s.replace(' ', '') for s in sentence_list]

    def remove_tab(self, sentence_list):
        return [s.replace('\t', '') for s in sentence_list]

    def remove_newline_code(self, sentence_list):
        sentence_list = [s.replace('\n', '').replace('\r', '') for s in sentence_list]
        while sentence_list.count('') > 0:
            sentence_list.remove('')

        return sentence_list

class FormatArticleTitle(object):

    def process_item(self, item, spider):

        item['article_title'] = self.remove_newline_code(item['article_title'])
        item['article_title'] = self.remove_space(item['article_title'])

        return item

    def remove_newline_code(self, s):
        return s.replace('\n', '').replace('\r', '')

    def remove_space(self, s):
        return s.replace(' ', '')

class LineBlogImagesPipeline(ImagesPipeline):

    def get_media_requests(self, item, info):

        tdatetime = datetime.strptime(item['article_datetime'],
                                      '%Y-%m-%dT%H:%M:%S%z')
        date = tdatetime.strftime('%Y-%m-%d')

        return [Request(x, meta={'author': item['author'],
                                 'date': date})
                for x in item.get(self.images_urls_field, [])]

    def file_path(self, request, response=None, info=None):
        # start of deprecation warning block (can be removed in the future)
        def _warn():
            from scrapy.exceptions import ScrapyDeprecationWarning
            import warnings
            warnings.warn('ImagesPipeline.image_key(url) and file_key(url) methods are deprecated, '
                          'please use file_path(request, response=None, info=None) instead',
                          category=ScrapyDeprecationWarning, stacklevel=1)

        # check if called from image_key or file_key with url as first argument
        if not isinstance(request, Request):
            _warn()
            url = request
        else:
            url = request.url

        # detect if file_key() or image_key() methods have been overridden
        if not hasattr(self.file_key, '_base'):
            _warn()
            return self.file_key(url)
        elif not hasattr(self.image_key, '_base'):
            _warn()
            return self.image_key(url)
        # end of deprecation warning block

        author = request.meta['author']
        date = request.meta['date']

        image_guid = hashlib.sha1(to_bytes(url)).hexdigest()  # change to request.url after deprecation
        return 'full/%s/%s/%s.jpg' % (author, date, image_guid)


import unittest
from unittest import TestCase
from xml.etree import ElementTree as ET

from osgeo import gdal

from aws.osml.gdal import NITFDESAccessor

class TestNITFDESAccessor(TestCase):
    def test_get_segments_by_name(self):
        ds = gdal.Open("./test/data/sicd_example_1_PFA_RE32F_IM32F_HH-0-0.NITF")
        des_accessor = NITFDESAccessor(ds.GetMetadata("xml:DES"))
        xml_segments = des_accessor.get_segments_by_name("XML_DATA_CONTENT")
        assert len(xml_segments) == 1
        assert isinstance(xml_segments[0], ET.Element)

    def test_extract_des_header(self):
        ds = gdal.Open("./test/data/sicd_example_1_PFA_RE32F_IM32F_HH-0-0.NITF")
        des_accessor = NITFDESAccessor(ds.GetMetadata("xml:DES"))
        xml_segments = des_accessor.get_segments_by_name("XML_DATA_CONTENT")

        des_header = NITFDESAccessor.extract_des_header(xml_segments[0])
        assert des_header is not None
        assert des_header.startswith("01UUS")
        assert len(des_header) == 946

if __name__ == "__main__":
    unittest.main()


def bubbleSort(arr):
    n = len(arr)
    for i in range(n - 1):
        for j in range(n - 1):
            if (arr[i] < arr[j]):
                arr[j], arr[i] = arr[i], arr[j]
    return arr

lista = [7, 6, 4, 9, 8, 2, 3, 0, 10, 1, 5]
print(lista, "não ordenada")

lista = bubbleSort(lista)
print(lista, "lista ordenada")


import os
import json
import torchaudio
from tqdm import tqdm
from glob import glob

from utils.util import has_existed

def main(output_path, dataset_path):
    print("-" * 10)
    print("Dataset splits for ljspeech...\n")

    save_dir = os.path.join(output_path, "ljspeech")
    ljspeech_path = dataset_path

    wave_files = glob(ljspeech_path + "/wavs/*.wav")

    train_output_file = os.path.join(save_dir, "train.json")
    test_output_file = os.path.join(save_dir, "test.json")

    if has_existed(train_output_file):
        return

    utts = []

    for wave_file in tqdm(wave_files):
        res = {
            "Dataset": "ljspeech",
            "Singer": "female1",
            "Uid": "{}".format(wave_file.split("/")[-1].split(".")[0]),
        }
        res["Path"] = wave_file
        assert os.path.exists(res["Path"])

        waveform, sample_rate = torchaudio.load(res["Path"])
        duration = waveform.size(-1) / sample_rate
        res["Duration"] = duration

        if duration <= 1e-8:
            continue

        utts.append(res)

    test_length = len(utts) // 20

    train_utts = []
    train_index_count = 0
    train_total_duration = 0

    for i in tqdm(range(len(utts) - test_length)):
        tmp = utts[i]
        tmp["index"] = train_index_count
        train_index_count += 1
        train_total_duration += tmp["Duration"]
        train_utts.append(tmp)

    test_utts = []
    test_index_count = 0
    test_total_duration = 0

    for i in tqdm(range(len(utts) - test_length, len(utts))):
        tmp = utts[i]
        tmp["index"] = test_index_count
        test_index_count += 1
        test_total_duration += tmp["Duration"]
        test_utts.append(tmp)

    print("#Train = {}, #Test = {}".format(len(train_utts), len(test_utts)))
    print(
        "#Train hours= {}, #Test hours= {}".format(
            train_total_duration / 3600, test_total_duration / 3600
        )
    )

    # Save
    os.makedirs(save_dir, exist_ok=True)
    with open(train_output_file, "w") as f:
        json.dump(train_utts, f, indent=4, ensure_ascii=False)
    with open(test_output_file, "w") as f:
        json.dump(test_utts, f, indent=4, ensure_ascii=False)


"""
cell_builder.py
Neuron Cell Builder
"""
import logging
from neuron_ui import neuron_utils
from neuron_ui import neuron_geometries_utils
from neuron_ui.singleton import Singleton
from jupyter_geppetto.geppetto_comm import GeppettoCoreAPI as G
from jupyter_geppetto.geppetto_comm import GeppettoJupyterModelSync

@Singleton
class CellBuilder:

    def __init__(self):
        logging.debug('Initializing Cell Builder')

        self.geometry = None
        self.segment = None
        section_diam_panel = neuron_utils.add_text_field_with_label('Section Diam', None)
        section_length_panel = neuron_utils.add_text_field_with_label('Section Length', None)

        segment_diam_panel = neuron_utils.add_text_field_with_label(
            'Segment Diam', None)

        # Get textfields from panels
        self.section_diam = section_diam_panel.items[1]
        self.section_length = section_length_panel.items[1]
        self.segment_diam = segment_diam_panel.items[1]
        self.save_button = neuron_utils.add_button('Save', self.modify_segment)

        self.cellBuilderPanel = neuron_utils.add_panel('Cell Builder', items=[
            segment_diam_panel, section_diam_panel, section_length_panel, self.save_button], widget_id='cellBuilderPanel', position_x=955, position_y=374, width = 340, height = 190)
        self.cellBuilderPanel.register_to_event(
            [GeppettoJupyterModelSync.events_controller._events['Select']], self.updateValues)
        self.cellBuilderPanel.on_close(self.close)
        self.cellBuilderPanel.display()

    def close(self, component, args):
        self.cellBuilderPanel.unregister_to_event(
            [GeppettoJupyterModelSync.events_controller._events['Select']], self.updateValues)

        # Close Jupyter object
        self.cellBuilderPanel.close()
        del self.cellBuilderPanel

        # Destroy this class
        CellBuilder.delete()
        # del RunControl._instance

    def shake_panel(self):
        self.cellBuilderPanel.shake()

    def updateValues(self, dataId, geometry_identifier, point):
        try:
            logging.debug('Updating values for Cell Builder')

            for geometry in GeppettoJupyterModelSync.current_model.geometries_raw:
                if geometry.id == geometry_identifier:
                    logging.debug('Loading values for geometry ' +
                                  str(geometry_identifier))
                    GeppettoJupyterModelSync.current_model.highlight_visual_group_element(geometry.python_variable["section"].name())

                    # Update segment and geometry
                    distance_to_selection, section_length = neuron_geometries_utils.calculate_distance_to_selection(
                        geometry, point)
                    distance_to_selection_normalised = distance_to_selection/section_length
                    self.segment = geometry.python_variable[
                        "section"](distance_to_selection_normalised)
                    self.geometry = geometry

                    # Update values
                    self.segment_diam.sync_value =  str(
                        self.segment.diam)
                    self.section_diam.sync_value = str(
                        geometry.python_variable["section"].diam)
                    self.section_length.sync_value = str(
                        geometry.python_variable["section"].L)

                    return True
            return False
        except Exception as exception:
            logging.exception(
                "Unexpected error executing callback for component:")
            raise

    def modify_segment(self, triggeredComponent, args):
        logging.debug('Modifying segment')
        self.geometry.python_variable[
            "section"].diam = float(self.section_diam.sync_value)
        self.geometry.python_variable[
            "section"].L = float(self.section_length.sync_value)
        self.segment = float(self.segment_diam.sync_value)

        # Recreating Scene
        neuron_geometries_utils.extractGeometries(reload=True)


from rich import print as rprint
from rich.table import Table

def fillMatrix(matrix):
    cloneMatrix = matrix

    rprint('\n[yellow bold]Advertencia: \n- Inserte los números que desee separados por coma. \n- En caso de escribir menos números que el tamaño de la fila el resto serán rellenados con 0\n')

    for fila in range(len(matrix)):
        numbers = input(f'>>> Inserte los números de la fila {fila}: ')

        # separar los números por comas
        # utilizar 'strip()' para eliminar los espacios en blanco alrededor del número
        separatedNumbers = [num.strip() for num in numbers.split(',') if num.strip() != '']

        if len(separatedNumbers) > 0:
            # recorrer cada uno de los números insertados
            for numIndex in range(len(separatedNumbers)):
                # verificar que es un número
                if not separatedNumbers[numIndex].isnumeric():
                    rprint(f'[bold red] {separatedNumbers[numIndex]} no es un número')
                # verificar que el número se puede insertar mientras que no supere el tamaño de la fila
                elif numIndex < len(cloneMatrix[fila]):
                    cloneMatrix[fila][numIndex] = float(separatedNumbers[numIndex])

    # imprimir matriz en consola
    table = Table()

    # añadir columnas
    table.add_column('')
    for column in range(len(cloneMatrix[0])):
        table.add_column(f'Columna {column + 1}')

    for rowIndex in range(len(cloneMatrix)):
        # añadir filas
        stringNums = [str(num) for num in cloneMatrix[rowIndex]]
        table.add_row(f'Fila {rowIndex + 1}', *stringNums)

    rprint('\n', table)


# import sqlite3
# conn = sqlite3.connect("somedatabase")
# curs = conn.cursor()
# curs.execute()
# conn.commit()
# conn.close()

import sqlite3

def convert(value):
    if value.startswith('~'):
        return value.strip("~")
    if not value:
        value = "0"
    return float(value)

s = "~07276~^~HORMEL SPAM ... PORK W/ HAM MINCED CND~^^~1 serving~^^~~^0^^^"
conn = sqlite3.connect("food.db")
curs = conn.cursor()

curs.execute("""
CREATE TABLE IF NOT EXISTS food (
id        TEXT PRIMARY KEY,
desc      TEXT,
water     FLOAT,
kcal      FLOAT,
protein   FLOAT,
fat       FLOAT,
ash       FLOAT,
carbs     FLOAT,
fiber     FLOAT,
sugar     FLOAT
)
""")

query = 'INSERT INTO food VALUES(?,?,?,?,?,?,?,?,?,?)'

fields = s.split('^')
vals = [convert(f) for f in fields[:len(fields)]]
curs.execute(query,vals)

conn.commit()
conn.close()

conn = sqlite3.connect("food.db")
curs = conn.cursor()

query = "SELECT * FROM food"
curs.execute(query)
conn.commit()
conn.close()


from typing import Optional

import torch
import torch.nn as nn
import torchaudio

class MelSpec(nn.Module):
    """log-Mel scale spectrogram.
    """
    def __init__(self,
                 strides: int,
                 windows: int,
                 mel: int,
                 fmin: int = 0,
                 fmax: Optional[int] = 8000,
                 sr: int = 16000):
        """Initializer.
        Args:
            strides: hop length, the number of the frames between adjacent windows.
            windows: length of the windows.
            mel: size of the mel filterbanks.
            fmin, fmax: minimum, maximum frequency,
                if fmax is None, use half of the sample rate as default.
            sr: sample rate.
        """
        super().__init__()
        self.strides, self.windows = strides, windows
        # [mel, windows // 2 + 1]
        # use slaney-scale mel filterbank for `librosa.filters.mel` compatibility.
        self.register_buffer(
            'melfilter',
            torchaudio.functional.melscale_fbanks(
                windows // 2 + 1,
                fmin, fmax, mel, sr,
                norm='slaney', mel_scale='slaney').T,
            persistent=False)
        # [windows], use hann window
        self.register_buffer(
            'hann', torch.hann_window(windows), persistent=False)

    def forward(self, audio: torch.Tensor) -> torch.Tensor:
        """Generate the log-mel scale spectrogram.
        Args:
            audio: [torch.float32; [B, T]], audio signal, [-1, 1]-ranged.
        Returns:
            [torch.float32; [B, mel, T / strides]], log-mel spectrogram
        """
        # [B, windows // 2 + 1, T / strides, 2]
        fft = torch.stft(
            audio, self.windows, self.strides,
            window=self.hann,
            center=True, pad_mode='reflect', return_complex=False)
        # [B, windows // 2 + 1, T / strides]
        mag = torch.sqrt(fft.square().sum(dim=-1) + 1e-7)
        # [B, mel, T / strides]
        return torch.log(torch.matmul(self.melfilter, mag) + 1e-7)


# In bubble sort the worst case is O(n square)
# Bubble Sort
def bubble_sort(elements):
    k=len(elements)
    for i in range(0,k):
        for j in range(len(elements)-1-i):
            if elements[j]>elements[j+1]:
                elements[j],elements[j+1]=elements[j+1],elements[j]
        k-=1

elements=[38,9,29,7,2,15,28]  # [2, 7, 9, 15, 28, 29, 38]

# We can alse pass list of words
elements=['Dog','Flemingo','Eagle','Bull','Antelope','Chameleon']
# ['Antelope', 'Bull', 'Chameleon', 'Dog', 'Eagle', 'Flemingo']
# It'll return the list of elements sorted in Alphabetical Order..
# It compares each element in the list by its starting letter's ASCII value..

bubble_sort(elements)
print(elements)

Data Structures and Algorithms/Algorithms/Sorting Techniques/Bubble Sort.py


from collections import deque

def neighbours(N, x, y):
    # returns a list of valid positions a knight can jump to from an initial position (x,y)
    # valid position means not outside the N x N chessboard
    # (x,y) is provided in 0-based index
    dx = [ 2, 2,-2,-2, 1, 1,-1,-1]
    dy = [ 1,-1, 1,-1, 2,-2, 2,-2]
    output = []
    for j in range(len(dx)):
        new_x = x + dx[j]
        new_y = y + dy[j]
        if 0 <= new_x < N and 0 <= new_y < N:
            output.append((new_x, new_y))
    return output

N = int(input()) # chessboard length
chessboard = [] # initialize grid

# Get game grid from user
for i in range(N):
    row = []
    row.extend(input())
    chessboard.append(row)
    if 'K' in row:
        source = (i, row.index('K'))

chessboard[source[0]][source[1]] = 0 # set knight's initial position to 0

# BFS
# BFS works as all neighbours are 1 move away (1 weight)
queue = deque()
queue.append(source) # enqueue initial knight position

while queue:
    front = queue.popleft() # dequeue front of queue
    for neighbour in neighbours(N, front[0], front[1]):
        if chessboard[neighbour[0]][neighbour[1]] == '#': continue # blocked cell
        if chessboard[neighbour[0]][neighbour[1]] == '.': # not visited yet
            queue.append(neighbour) # enqueue neighbour
            chessboard[neighbour[0]][neighbour[1]] = chessboard[front[0]][front[1]] + 1 # +1 distance (move) away
        else: # already visited, update shortest path
            if chessboard[neighbour[0]][neighbour[1]] > chessboard[front[0]][front[1]] + 1:
                chessboard[neighbour[0]][neighbour[1]] = chessboard[front[0]][front[1]] + 1

if chessboard[0][0] == '.':
    print(-1) # not visited
else:
    print(chessboard[0][0]) # 0-based indexing


from selenium import webdriver
import unittest
import time
import datetime

class bing_soso_po(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.browser = webdriver.Chrome(executable_path="/Users/lindafang/PycharmProjects/seleniumforpython2020/driver/chromedriver78")
        cls.browser.get('https://cn.bing.com/')
        cls.browser.maximize_window()
        cls.browser.implicitly_wait(10)
        assert '微软 Bing 搜索 ' in cls.browser.title

    @classmethod
    def tearDownClass(cls):
        if(cls.browser!=None):
            print("环境销毁")
            print("运行时间总计:"+str(datetime.datetime.now()))
            cls.browser.quit()

    def test_soso(self):
        elem = self.browser.find_element_by_id('sb_form_q')
        elem.click()
        elem.clear()
        elem.send_keys('seleniumhq')
        elec = self.browser.find_element_by_id('sb_form_go')
        elec.click()
        self.browser.get_screenshot_as_file(str(datetime.datetime.now())+"_sousuo.png")
        time.sleep(3)
        assert 'selenium' in self.browser.page_source

if __name__ == '__main__':
    unittest.main()


import asyncio
import websockets

SEND_ID = "python"
RECEIVE_ID = "js"
SERVER_ADRESS = "localhost"
SERVER_PORT = 8000
ID_MESSAGE_DELIMITER = "/"

ERROR_CODE = "404"
OK_CODE = "200"

# Simple server that can receives and store messages to send them

message_buffer = [None]

async def handler(websocket, path):
    entry = await websocket.recv()
    (source_ID, data) = entry.split(ID_MESSAGE_DELIMITER)

    if (source_ID == SEND_ID):
        message_buffer[0] = data
        print(f"Data received from {source_ID} as:  {data}! Saved to buffer...")

        await websocket.send(OK_CODE)
    elif source_ID == RECEIVE_ID:
        if(message_buffer[0] == None):
            await websocket.send(ERROR_CODE)
        else:
            await websocket.send(message_buffer[0])
            print(f"Sent data from buffer: {message_buffer[0]}")
            message_buffer[0] = None
    else:
        raise Exception(f"Wrong source ID: {source_ID}")

    return data

start_server = websockets.serve(handler, SERVER_ADRESS, SERVER_PORT)
print(f"Starting server at address {SERVER_ADRESS}:{SERVER_PORT}")

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()


def solution(n):
    to124 = [0,'1','2','4']
    idx=[]

    while 1:
        a,b = divmod(n,3)
        if b:
            idx.append(b)
            n=a
        else:
            idx.append(3)
            n=a-1
        if n<1:
            break

    return ''.join([to124[x] for x in idx][::-1])
#100점

if __name__ == "__main__":
    print(solution(1)) # 1
    print(solution(2)) # 2
    print(solution(3)) # 4
    print(solution(4)) # 11

'''
def change124(n):
    num = ['1','2','4']
    answer = ""

    while n > 0:
        n -= 1
        answer = num[n % 3] + answer
        n //= 3

    return answer

def change124(n):
    if n<=3:
        return '124'[n-1]
    else:
        q, r = divmod(n-1, 3)
        return change124(q) + '124'[r]

def change124(n):
    return '' if n == 0 else change124((n - 1) // 3) + "412"[n % 3]
'''


import random

class Anagramas:
    def __init__(self, caminho, posicao):
        self.posicao = posicao
        self._arquivo = caminho
        self.imprimir_cabecalho(self.posicao)
        self.executar_rodadas()

    @staticmethod
    def imprimir_linha(tamanho):
        print('=' * tamanho)

    @staticmethod
    def embaralha(palavra):
        a = random.sample(palavra, len(palavra))  # randomiza a palavra
        d = ''.join(a).upper()  # insere como string
        return d  # retorna o string da palavra randomizada

    @staticmethod
    def fazer_leitura(caminho):
        arquivo = open(caminho, mode='r', encoding='utf-8')  # abre e lê o arquivo
        palavras = arquivo.readlines()  # após a leitura, transforma todas as linhas em um list
        arquivo.close()  # fecha o arquivo
        return palavras

    @staticmethod
    def mostrar_anagrama(anagrama, tamanho):
        print(f'Anagrama: {anagrama}'.center(tamanho))

    @staticmethod
    def mostra_resultado(chance, tentativas, pontuacao):
        print(f'Chances: {chance} de {tentativas}.')
        print(f'Pontuação: {pontuacao} pontos.')

    @staticmethod
    def mostrar_fim_do_programa(pontuacao):
        print('Acabaram suas chances!')
        print(f'A sua pontuação foi de {pontuacao} pontos.')
        print('Fim do jogo :)')

    def imprimir_cabecalho(self, posicao):
        self.imprimir_linha(posicao)
        print("Descubra a qual palavra o anagrama abaixo se refere!".center(posicao))
        print('A cada rodada é gerado um novo anagrama!'.center(posicao))
        print('Você tem 5 chances para acertar as palavras!'.center(posicao))
        print('A cada acerto você ganha 1 ponto!'.center(posicao))
        print('E a cada erro perde 1 chance e 1 ponto!'.center(posicao))
        self.imprimir_linha(posicao)

    def escolher_palavrar(self):
        palavras = self.fazer_leitura(self._arquivo)
        palavra_escolhida = palavras[random.randint(0, len(palavras) - 1)]  # .upper()
        return palavra_escolhida.strip()  # strip() para remover o '\n' das palavras

    def gerar_anagrama(self, palavra):
        anagrama = self.embaralha(palavra)
        return anagrama

    def novo_anagrama(self):
        palavra_escolhida = self.escolher_palavrar()
        anagrama = self.gerar_anagrama(palavra_escolhida)
        return palavra_escolhida, anagrama

    def jogar_novamente(self):
        entrada = input('Deseja jogar novamente? (S / N): ').strip().upper()
        if entrada == 'S': Anagramas(self._arquivo, self.posicao)
        else: print('Obrigado por jogar! :)')

    def executar_rodadas(self):
        tentativas = 5
        chance = 5
        pontuacao = 0

        while chance != 0:
            palavra_escolhida, anagrama = self.novo_anagrama()  # escolhe a palavra e gera o anagrama

            self.mostrar_anagrama(anagrama, self.posicao)  # imprime o anagrama centralizado na posição desejada
            self.imprimir_linha(self.posicao)

            entrada = input('Descubra a qual palavra o anagrama se refere e insira aqui: ').strip()
            self.imprimir_linha(self.posicao)

            if entrada.upper() == palavra_escolhida.upper():  # acertou
                pontuacao += 1

                print('Parabéns! Você acertou!')
                self.mostra_resultado(chance, tentativas, pontuacao)
                self.imprimir_linha(self.posicao)
            else:  # errou
                chance -= 1
                if pontuacao > 0: pontuacao -= 1
                print(f'Você errou a palavra! A palavra era {palavra_escolhida.upper()}.')
                self.mostra_resultado(chance, tentativas, pontuacao)
                self.imprimir_linha(self.posicao)

            if (chance == 0):  # acabaram as chances
                self.mostrar_fim_do_programa(pontuacao)
                self.imprimir_linha(self.posicao)
                self.jogar_novamente()

def main():
    Anagramas('palavras.txt', 75)

if __name__ == '__main__':
    main()


def find_smallest(arr):
    smallest = arr[0]
    smallest_index = 0
    for i in range(1, len(arr)):
        if arr[i] < smallest:
            smallest = arr[i]
            smallest_index = i
    return smallest_index

def selection_sort(arr):
    sorted_arr = []
    for i in range(len(arr)):
        smallest = find_smallest(arr)
        sorted_arr.append(arr.pop(smallest))
    return sorted_arr

def main():
    a = [3, 8, 2, 4, 10, 11, 1]
    print('Unsorted: ', a)
    b = selection_sort(a)
    print('Sorted: ', b)

if __name__ == '__main__':
    main()


import math
import pygame

# it's messy but gets the job done
# performing calculations on 2160 objects is as hefty of a task as it might seem.

SCREENWIDTH, SCREENHEIGHT = 900,770

WAVECOUNT = 2

EQUILIBRIUM_LINE_1_YCOORD = SCREENHEIGHT//7
EQUILIBRIUM_LINE_2_YCOORD = 3*(SCREENHEIGHT//7)
EQUILIBRIUM_LINE_3_YCOORD = 11*(SCREENHEIGHT//14)

white = (255,255,255)
black = (0,0,0)

class Point(pygame.sprite.Sprite):
    def __init__(self,x,y,vel, group):
        super().__init__()
        self.image = pygame.Surface([3,3])
        self.rect = self.image.get_rect()
        self.image.fill(white)

        self.rect.centerx = x
        self.rect.centery = y
        self.dx = vel

        group.add(self)

    def update(self):
        if self in progressive:
            self.rect.x -= self.dx
            if self.rect.x < 90:
                self.rect.x = SCREENWIDTH-92
            if self.rect.x > SCREENWIDTH-92:
                self.rect.x = 90

        if self in stationary:
            alist = [f.rect.centery for f in progressive if f.rect.centerx == self.rect.centerx]
            if len(alist) == 2:
                coord1 = EQUILIBRIUM_LINE_2_YCOORD-alist[0]
                coord2 = EQUILIBRIUM_LINE_1_YCOORD-alist[1]
                coord3 = coord1+coord2
                self.rect.centery = EQUILIBRIUM_LINE_3_YCOORD-coord3

pygame.init()
screen = pygame.display.set_mode([SCREENWIDTH,SCREENHEIGHT])

progressive = pygame.sprite.Group()
stationary = pygame.sprite.Group()
clock = pygame.time.Clock()

for f in range(int(WAVECOUNT*360)):
    Point(f+90,(2*(SCREENHEIGHT//14))-int((80*(math.sin(math.radians(f))))), 1, progressive)
    Point(f+90,(6*(SCREENHEIGHT//14))-int((80*(math.sin(math.radians(f))))), -1, progressive)
    Point(f+90,11*(SCREENHEIGHT//14), 0, stationary)

done = False
while not done:
    clock.tick(120)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                done = True

    progressive.update()
    stationary.update()

    screen.fill(black)

    pygame.draw.line(screen, white, (90,EQUILIBRIUM_LINE_1_YCOORD), (SCREENWIDTH-92,EQUILIBRIUM_LINE_1_YCOORD), 1)
    pygame.draw.line(screen, white, (90,EQUILIBRIUM_LINE_2_YCOORD), (SCREENWIDTH-92,EQUILIBRIUM_LINE_2_YCOORD), 1)
    pygame.draw.line(screen, white, (90,EQUILIBRIUM_LINE_3_YCOORD), (SCREENWIDTH-92,EQUILIBRIUM_LINE_3_YCOORD), 1)

    progressive.draw(screen)
    stationary.draw(screen)
    pygame.display.flip()
pygame.quit()


import time

# countdown timer
def countdown(end):
    while end: # while end > 0 for clarity
      mins = end // 60
      secs = end % 60
      timer = '{:02d}:{:02d}'.format(mins, secs)
      print(timer, end="\r") # overwrite previous line
      time.sleep(1)
      end -= 1
    print('Times out!!!')

loop = 1

while loop==1:
  t = input("Enter the time in seconds: ")
  countdown(int(t))
  loop = input("Enter 1 if you want to countdown again: ")

print('Welcome to use again~')


from tensorflow.keras.models import load_model
import nltk
from nltk.stem import WordNetLemmatizer
import random
import json
import pickle
import numpy as np

nltk.download('punkt', quiet=True)
nltk.download('wordnet', quiet=True)

words = []
classes = []
intent_methods = {}
model = load_model(f'test_model.h5')
lemmatizer = WordNetLemmatizer()
words = pickle.load(open(f'test_model_words.pkl', 'rb'))
classes = pickle.load(open(f'test_model_classes.pkl', 'rb'))
intents = json.loads(open(f'intents.json').read())

def _clean_up_sentence( sentence):
    sentence_words = nltk.word_tokenize(sentence)
    sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]
    return sentence_words

def _bag_of_words( sentence, words):
    sentence_words = _clean_up_sentence(sentence)
    bag = [0] * len(words)
    for s in sentence_words:
        for i, word in enumerate(words):
            if word == s:
                bag[i] = 1
    return np.array(bag)

def _predict_class( sentence):
    p = _bag_of_words(sentence, words)
    res = model.predict(np.array([p]))[0]
    ERROR_THRESHOLD = 0.1
    results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD]

    results.sort(key=lambda x: x[1], reverse=True)
    return_list = []
    for r in results:
        return_list.append({'intent': classes[r[0]], 'probability': str(r[1])})
    return return_list

def _get_response( ints, intents_json):
    try:
        tag = ints[0]['intent']
        list_of_intents = intents_json['intents']
        for i in list_of_intents:
            if i['tag']  == tag:
                result = random.choice(i['responses'])
                break
    except IndexError:
        result = "I don't understand!"
    return result

def requested( message):
    ints = _predict_class(message)
    if ints[0]['intent'] in intent_methods.keys():
        intent_methods[ints[0]['intent']]()
    else:
        return _get_response(ints, intents)


# import socket

# # Create a socket object
# client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# # Connect to the server's IP address and port
# server_address = ('127.0.0.1', 12345)
# client_socket.connect(server_address)

# # Receive the welcome message from the server
# welcome_message = client_socket.recv(1024).decode()
# print(welcome_message)

# # Send data to the server
# message = "Hello, server! This is the client."
# client_socket.send(message.encode())

# # Close the client socket
# client_socket.close()

import socket

def display_board(board):
    for row in board:
        print(" ".join(row))

def main():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = ('127.0.0.1', 12345)
    client_socket.connect(server_address)

    welcome_message = client_socket.recv(1024).decode()
    print(welcome_message)

    while True:
        print(client_socket.recv(1024).decode())
        row, col = map(int, input().split())
        client_socket.send(f"{row} {col}".encode())

        board = client_socket.recv(1024).decode().split("\n")
        board = [row.split() for row in board]

        display_board(board)
        client_socket.send(input("Your move (row and column): ").encode())

        win_message = client_socket.recv(1024).decode()
        print(win_message)
        break

    client_socket.close()

if __name__ == "__main__":
    main()


import networkx as nx
from timeit import default_timer as timer
import numpy as np
from .Error import InfeasibleError
from sklearn.utils.extmath import cartesian
import sys

def get_true_keys_in_dict(d):
    """
     get all keys where the value is true
     return list
    """
    keys = []
    for key in d:
        if d[key]:
            keys.append(key)
    return keys

class Model:
    def __init__(self):
        # holds a list of indices where the function should be called
        self.subscribe_list_on = []
        # holds a list of all check constraint functions
        self.subscribe_list_func = []
        self.nof_calls = 0

    def subscribe(self,on,func,*args):
        # add a list of indices to the subscribe list
        self.subscribe_list_on.append(on['idx'])
        # as well as the function call
        self.subscribe_list_func.append((func,args))

    def solved(self,idx):
        """
            Check whether it is solved
            only the idx values have to be solved
        """

        self.nof_found = - self.nof_start_values
        self.nof_missing = 0
        ret = True
        for r in range(len(self.search_space)):
            for c in range(len(self.search_space[r])):
                if 'value' not in self.search_space[r][c] and idx[r][c]:
                    ret = False
                    self.nof_missing += 1
                elif 'value' in self.search_space[r][c]:
                    self.nof_found += 1
        return ret

    def get_backtrack_candidates(self):
        nof_values = sys.maxsize
        best_id = [0,0]
        for r in range(len(self.search_space)):
            for c in range(len(self.search_space[r])):
                if 'values' in self.search_space[r][c] and self.backtracking_space[r][c] == False:
                    l_nof_values = len(self.search_space[r][c]['values'])
                    if l_nof_values < nof_values:
                        nof_values = l_nof_values
                        best_id = [r,c]
        cands = self.search_space[best_id[0]][best_id[1]]['values']
        self.backtracking_space[best_id[0]][best_id[1]] = True
        return {'row':best_id[0],'col':best_id[1],'cands':cands}

    def backtrack(self,solved_idx,counter_bt=0):
        counter_bt += 1
        # save first search_space
        copy_search_space = np.copy(self.search_space)
        # get candidate list
        candidate_list = [self.get_backtrack_candidates()]
        # while candidates in list
        while candidate_list:
            candidate_entry = candidate_list.pop(0)
            cands = candidate_entry['cands']
            row, col = candidate_entry['row'],candidate_entry['col']
            for cand in cands:
                self.search_space = np.copy(copy_search_space)
                self.search_space[row][col] = {'value':cand}
                try:
                    idx = np.full(self.search_space.shape, False, dtype=bool)
                    idx[row,col] = True
                    self.fire(idx)
                    if not self.solved(solved_idx):
                        feasible, counter = self.backtrack(solved_idx,counter_bt)
                        if feasible:
                            return True,counter
                    else:
                        return True,counter_bt
                except InfeasibleError as e:
                    continue
        return False, counter_bt

    def solve(self,idx,no_val=0):
        try:
            self.fire(np.full(self.search_space.shape, True, dtype=bool))
            if not self.solved(idx):
                print("Need to backtrack")
                print("found %d values" % self.nof_found)
                print("%d values are missing" % self.nof_missing)
                feasible,counter = self.backtrack(idx)
                print("Number of backtracks", counter)
                if not feasible:
                    raise InfeasibleError("Infeasible checked backtracking")

        except InfeasibleError as e:
            print(e)
            exit(2)

    def fire(self,idx):
        """
            Check all subscribed indices and check which functions should be
            called
        """
        i = 0
        self.changed = np.full(self.changed.shape, False, dtype=bool)
        for lidx in self.subscribe_list_on:
            if np.any(np.logical_and(lidx,idx)):
                func = self.subscribe_list_func[i][0]
                args = self.subscribe_list_func[i][1]
                try:
                    func(*args)
                except InfeasibleError as e:
                    raise e
                self.nof_calls += 1

            i += 1

        # if something changed because of the initial fire
        # => fire again the changed indices
        if np.any(self.changed):
            try:
                self.fire(self.changed)
            except InfeasibleError as e:
                raise e

    def get_linked_idx(self,linked_to,constraint_type):
        on = self.subscribe_list_on[linked_to]
        nof_true_values = np.sum(on)
        links = []
        for si in range(len(self.subscribe_list_on)):
            args = self.subscribe_list_func[si][1]
            func = args[1]
            if func == constraint_type:
                sum_of_true = np.sum(np.logical_and(self.subscribe_list_on[si],on))
                if sum_of_true == nof_true_values or sum_of_true == np.sum(self.subscribe_list_on[si]):
                    links.append(si)
        return links

    def link(self):
        """
            Links different constraint types together
        """
        for si in range(len(self.subscribe_list_on)):
            on = self.subscribe_list_on[si]
            args = self.subscribe_list_func[si][1]
            func = args[1]
            # if a part is a straight and part of alldifferent
            # get all other straights and link them together
            # => the straight constraints considers what to do with it
            if func == "straight":
                temp_links = self.get_linked_idx(si,"alldifferent")
                links = []
                for t in temp_links:
                    links.extend(self.get_linked_idx(t,"straight"))
                real_links = []
                for l in links:
                    if not np.any(np.logical_and(self.subscribe_list_on[si],self.subscribe_list_on[l])):
                        real_links.append(l)
                self.subscribe_list_func[si][1][0]['links'] = real_links

    def build_search_space(self,grid,values,no_val=0):
        """
            Build the search space
            Each field which has a fixed value is set as 'value'
            and the other fields are assigned with 'values': values
        """
        self.search_space = np.empty(grid.shape,dtype=dict)
        self.backtracking_space = np.full(grid.shape, False, dtype=bool)
        self.changed = np.full(grid.shape, False, dtype=bool)
        sorted_values = sorted(values)
        self.possible_range = values
        self.highest_value = sorted_values[-1]
        self.lowest_value = sorted_values[0]

        self.nof_start_values = 0
        no_val_idx = np.where(grid == no_val)
        no_val_idx_invert = np.where(grid != no_val)
        self.search_space[no_val_idx] = {'values':values[:]}
        for idx in np.transpose(no_val_idx_invert):
            t_idx = tuple(idx)
            self.nof_start_values += 1
            self.search_space[t_idx] = {'value':grid[t_idx]}

    def get_all_reachable_edges(self,G,n,used_edges):
        """
            Get all reachable edges using a start node n
            get only edges which aren't in used_edges
        """

        reachable_edges = []

        queue = [n]
        while len(queue):
            n = queue.pop()
            for s in G.successors(n):
                e = (n,s)
                if e in used_edges:
                    continue
                used_edges[e] = 1
                reachable_edges.append(e)
                queue.append(s)

        return reachable_edges,used_edges

    def alldifferent(self,ss_idx,values):
        G = nx.MultiDiGraph()

        already_know = {}
        for i in range(len(values)):
            if 'values' in values[i]:
                for j in values[i]['values']:
                    G.add_edge('x_'+str(i),j)
            else:
                G.add_edge('x_'+str(i),values[i]['value'])
                already_know[i] = 1

        # get the maximum matching of this graph
        matching = nx.bipartite.maximum_matching(G)

        n_matching = []
        GM = nx.DiGraph()
        possible = np.empty((len(values)),dtype=dict)
        for k in matching:
            if str(k)[:2] == 'x_':
                n_matching.append({k:matching[k]})
                GM.add_edge(k,matching[k])
                possible[int(k[2:])] = {'values':set([matching[k]])}

        if len(n_matching) < len(values):
            raise InfeasibleError("Matching smaller than values")

        # every edge which is not part of the matching is added (reversed)
        for e in G.edges():
            if not GM.has_edge(e[0],e[1]):
                GM.add_edge(e[1],e[0])

        # Use lemmata of Berge
        # find even alternating path
        # find free vertex
        used_edges = {}
        for n in GM.nodes():
            if str(n)[:2] != "x_" and len(GM.predecessors(n)) == 0:
                edges,used_edges = self.get_all_reachable_edges(GM,n,used_edges)

                for e in edges:
                    if str(e[0])[:2] != 'x_':
                        e = (int(e[1][2:]),e[0])
                    else:
                        e = (int(e[0][2:]),e[1])
                    if 'values' not in possible[e[0]]:
                        possible[e[0]] = {'values': set()}
                    possible[e[0]]['values'].add(e[1])

        # find cycles
        scc = nx.strongly_connected_component_subgraphs(GM)
        for scci in scc:
            for e in scci.edges():
                if str(e[0])[:2] != 'x_':
                    e = (int(e[1][2:]),e[0])
                else:
                    e = (int(e[0][2:]),e[1])
                if 'values' not in possible[e[0]]:
                    possible[e[0]] = {'values': set()}
                possible[e[0]]['values'].add(e[1])

        new_possible = []
        new_knowledge = [False]*len(values)
        i = 0
        for p in possible:
            l = list(p['values'])
            if len(l) == 1:
                new_possible.append({'value':l[0]})
                if i not in already_know:
                    new_knowledge[i] = True
            else:
                new_possible.append({'values':l[:]})
                if len(l)<len(values[i]['values']):
                    new_knowledge[i] = True
            i += 1

        return new_knowledge, new_possible

    def array_to_obj(self,array,obj_struct):
        obj = {}
        for x in array:
            obj[x] = obj_struct
        return obj

    def get_straights(self,arr_of_values,len_straight=False,possible=False,used=False,
                    used_pattern=False,all_straights=False,def_used=False):
        """
            get all straights for an array of values
            eg. [[4], [1, 2, 3, 5, 7, 8, 9], [1, 2, 5, 6, 8, 9], [1, 3, 5, 6, 8, 9], [2, 3, 5, 6, 7, 8, 9]]
            return all_straights, new_values and definitely used values
            all_straights: [[4, 1, 2, 3, 5], [4, 1, 2, 5, 3], ... [4, 8, 5, 6, 7], [4, 8, 6, 5, 7]]
            new_values: [{4}, {1, 2, 3, 5, 7, 8}, {8, 1, 2, 5, 6}, {8, 1, 3, 5, 6}, {2, 3, 5, 6, 7, 8}]
            def_used: {1: False, 2: False, 3: False, 4: True, 5: True, 6: False, 7: False, 8: False, 9: False}
        """
        if not used:
            used = self.array_to_obj(self.possible_range,False)
        if not used_pattern:
            used_pattern = []
        if not all_straights:
            all_straights = []
        if not len_straight:
            len_straight = len(arr_of_values)
        if not possible:
            possible = [set() for x in range(len(arr_of_values))]
        if not def_used:
            # assume every digit has to be used
            def_used = self.array_to_obj(self.possible_range,True)

        # take the first entry and iterate over the possible values
        # for each build a new straight (recursive)
        for value in arr_of_values[0]:
            # only use this value if it's not already part of the straight
            if not used[value]:
                copy_used = dict(used)
                copy_used[value] = True

                # set all values which aren't possible anymore to used
                # for example if the straight has a length of 2 and one value is 2
                # only 1 and 3 are possible but not 2 and not 4-...
                for i in range(self.lowest_value,max(self.lowest_value,value-len_straight+1)):
                    copy_used[i] = True
                for i in range(min(self.highest_value+1,value+len_straight),self.highest_value+1):
                    copy_used[i] = True

                copy_used_pattern = used_pattern[:]
                copy_used_pattern.append(value)
                # if there are 2 or more values left
                if len(arr_of_values) > 1:
                    all_straights,possible,def_used = self.get_straights(arr_of_values[1:],len_straight,possible,
                                                            copy_used,copy_used_pattern,all_straights,def_used)
                else:
                    # add the used pattern to all the straights
                    all_straights.append(copy_used_pattern)
                    # check if there are values which are not used in the straight
                    not_used = [x for x in self.possible_range if x not in copy_used_pattern]
                    for nu in not_used:
                        def_used[nu] = False
                    xi = 0
                    # every digit which is used is possible for the defined position
                    for x in copy_used_pattern:
                        possible[xi].add(x)
                        xi += 1
        return all_straights, possible, def_used

    def list2values_structure(self,list_of_values):
        values_struct = []
        for l in list_of_values:
            if len(l) == 1:
                values_struct.append({'value':l[0]})
            else:
                values_struct.append({'values':l})
        return values_struct

    def straight(self, ss_idx, values, opts):
        """
            the straight constraint
            ss_idx: the indices where there has to be a straight
            values: the actual values on these indices
            opts: all options
        """
        fixed_values = []

        fixed_min_val = self.highest_value
        fixed_max_val = self.lowest_value
        len_values = len(values)

        # build and array of already fixed values
        # and get the highest and lowest fixed value
        for i in range(len(values)):
            if 'value' in values[i]:
                fixed_values.append(values[i]['value'])
                if values[i]['value'] > fixed_max_val:
                    fixed_max_val = values[i]['value']
                if values[i]['value'] < fixed_min_val:
                    fixed_min_val = values[i]['value']

        min_val = self.lowest_value
        max_val = self.highest_value

        for i in range(len(values)):
            if 'values' in values[i]:
                c_min = min(values[i]['values'])
                c_max = max(values[i]['values'])
            else:
                c_min = values[i]['value']
                c_max = values[i]['value']
            if c_max+len_values-1 < max_val:
                max_val = c_max+len_values-1
            if c_min-len_values+1 > min_val:
                min_val = c_min-len_values+1

        lowest_possible = min_val
        highest_possible = max_val

        if len(fixed_values):
            # if there is a fixed value we can determine the lowest possible and highest posssible
            # by the length of the straight
            # example: min: 1 max: 3 length: 5 => values 1-5
            # max-length+1 until min+length-1  or lowest_value until highest_value as bounding
            fixed_lowest_possible  = max(fixed_max_val-len_values+1,self.lowest_value)
            lowest_possible = max(lowest_possible,fixed_lowest_possible)
            fixed_highest_possible = min(fixed_min_val+len_values-1,self.highest_value)
            highest_possible = min(highest_possible,fixed_highest_possible)

        # remove impossible
        # example: {1,3,4,6,7,8,9} and {1,3,4,6,7,8} there 1 isn't possible
        # generate arrays:

        new_possible = [False]*len_values
        new_knowledge = [False]*len_values

        arr_of_values = []
        i = 0
        for e in values:
            if 'value' in e:
                arr_of_values.append(np.array([e['value']]))
            else:
                c_new_values = [x for x in e['values'] if  lowest_possible <= x <= highest_possible]
                arr_of_values.append(np.array(c_new_values))
                if len(c_new_values) < len(e['values']):
                    new_knowledge[i] = True
            i += 1

        estimated_nof_straights = np.prod(np.array([len(x) for x in arr_of_values]))

        if estimated_nof_straights > 10000:
            return new_knowledge, self.list2values_structure(arr_of_values)

        if 'links' in opts and len(opts['links']):
            straights, new_values, def_used = self.get_straights(arr_of_values)

            if len(straights) == 0:
                raise InfeasibleError("No straight possible")

            true_keys = get_true_keys_in_dict(def_used)
            if len(true_keys):
                for l in opts['links']:
                    self.check_constraint({'idx':self.subscribe_list_on[l],'against':set(true_keys)},"notInSet")
        else:
            return new_knowledge, self.list2values_structure(arr_of_values)

        # build up the new possible values and the new knowledge we have
        i = 0
        for entry in new_values:
            entry = list(entry)
            if len(entry) > 1:
                if len(entry) < len(values[i]['values']):
                    new_knowledge[i] = True
                if len(entry) == 1:
                    new_possible[i] = {'value':entry[0]}
                else:
                    new_possible[i] = {'values':entry}
            else:
                if 'value' not in values[i]:
                    new_knowledge[i] = True
                new_possible[i] = {'value':entry[0]}

            i += 1

        # update changed and search space
        old_changed = self.changed.copy()
        self.changed[ss_idx] = new_knowledge
        self.changed = np.logical_or(self.changed,old_changed)

        self.search_space[ss_idx] = new_possible

        return new_knowledge, new_possible

    def not_in_set(self,ss_idx,values,against):
        """
            not_in set constraint
            the values shouldn't exist in against
        """
        new_possible = []
        new_knowledge = [False]*len(values)
        i = 0
        for entry in values:
            if 'values' in entry:
                nof_pos = len(entry['values'])
                new_p = set(entry['values'])-against

                if len(new_p) == 1:
                    new_knowledge[i] = True
                    new_possible.append({'value':list(new_p)[0]})
                    continue
                if len(new_p) < nof_pos:
                    new_knowledge[i] = True
                new_possible.append({'values':list(new_p)})
            else:
                new_possible.append({'value':entry['value']})
            i += 1

        # update changed and search space
        old_changed = self.changed.copy()
        self.changed[ss_idx] = new_knowledge
        self.changed = np.logical_or(self.changed,old_changed)

        self.search_space[ss_idx] = new_possible

        return new_knowledge, new_possible

    def check_constraint(self,opts,operator):
            ss_idx = opts['idx']
            values = self.search_space[ss_idx]

            breaked = False
            for v in values:
                if 'values' in v:
                    breaked = True
                    break

            if not breaked:
                return

            try:
                if operator == "notInSet":
                    new_knowledge, new_possible = self.not_in_set(ss_idx,values,opts['against'])

                elif operator == "alldifferent":
                    new_knowledge, new_possible = self.alldifferent(ss_idx,values)

                elif operator == "straight":
                    new_knowledge, new_possible = self.straight(ss_idx,values,opts)

            except InfeasibleError as e:
                raise e

            # update changed and search space
            old_changed = self.changed.copy()
            self.changed[ss_idx] = new_knowledge
            self.changed = np.logical_or(self.changed,old_changed)

            self.search_space[ss_idx] = new_possible

            # some constraints actually need a different constraint:
            try:
                # if we have a straight constraint we also have an alldifferent constraint
                if operator == "straight":
                    self.check_constraint(opts,"alldifferent")

            except InfeasibleError as e:
                raise e

    def get_solution(self):
        grid = [[0]*9 for i in range(9)]
        for r in range(len(self.search_space)):
            for c in range(len(self.search_space[r])):
                if 'value' in self.search_space[r][c]:
                    grid[r][c] = self.search_space[r][c]['value']
        return grid

    def print_search_space(self):
        for r in range(len(self.search_space)):
            row = []
            for c in range(len(self.search_space[r])):
                if 'value' in self.search_space[r][c]:
                    row.append(self.search_space[r][c]['value'])
                else:
                    row.append(self.search_space[r][c]['values'])
            print(row)


# noqa: D100

import random

RULE = 'Find the greatest common divisor of given numbers.'

def find_gcd(number1: int, number2: int) -> int:
    """
    Find GCD for two numbers.

    Args:
        number1: int
        number2: int

    Returns:
        gcd:
    """
    if number2 > number1:
        return find_gcd(number2, number1)
    if number2 == 0:
        return number1
    return find_gcd(number2, number1 % number2)

def generate_task_answer():
    """
    Generate task and answer for gcd game.

    Returns:
        task: two numbers, str.
        answer: str
    """
    initial_gcd = random.randint(2, 9)
    number1 = random.randint(2, 5) * initial_gcd
    number2 = random.randint(4, 9) * initial_gcd
    task = f'{number1} {number2}'
    answer = str(find_gcd(number1, number2))
    return task, answer


# ---
# jupyter:
#   jupytext:
#     formats: ipynb,py:light
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.0
#   kernelspec:
#     display_name: Python 3 (ipykernel)
#     language: python
#     name: python3
# ---

# + [markdown] Collapsed="false" tags=[] jp-MarkdownHeadingCollapsed=true
# # Analysis of the hyperparameter simulations

# + Collapsed="false" tags=[]
import numpy as np
#import lmoments_rm as lr
import scipy
import matplotlib.pyplot as plt
import itertools
import xarray as xr
import pandas as pd

# +
import sys

def is_interactive():
    import __main__ as main
    return not hasattr(main, '__file__')

from sys import argv

if is_interactive():
    params = [0]
else:
    print(argv)
    ss=argv[1:]
    print(ss)
    params = [float(i) for i in ss]

print(params)
print(is_interactive())

# + [markdown] tags=[]
# # Load the data on the fit

# +
#
data1 = pd.read_csv('bhis1_mse.txt',  delim_whitespace=True)
data2 = pd.read_csv('tt2.txt',  delim_whitespace=True)
print(data1['a'][0])

n1 = data2['b'].array
n2=n1[0:150]

# sort data according to cost value
err=data1['g'].array

#i=np.argsort(n2,kind='stable')
#j=np.sort(n2,kind='stable')

i1=np.argsort(err,kind='stable')
j1=np.sort(err,kind='stable')

# list best 20 fits
i1s=i1[0:20]

layers=data1[['d','e','f']]
alayers=layers.to_numpy()

for m in range(0,20):
    print(alayers[i1[m]],j1[m],n2[i1[m]],data1['h'][m],data1['i'][m])
# -

plt.plot(j1[:],n2[i1[:]],'o')

# +
#
data1 = pd.read_csv('bhis0_mse.txt',  delim_whitespace=True)
data2 = pd.read_csv('tt2.txt',  delim_whitespace=True)
print(data1['a'][0])

n1 = data2['b'].array
n2=n1[0:150]

# sort data according to cost value
err=data1['g'].array

#i=np.argsort(n2,kind='stable')
#j=np.sort(n2,kind='stable')

i1=np.argsort(err,kind='stable')
j1=np.sort(err,kind='stable')

# list best 20 fits
i1s=i1[0:20]

layers=data1[['d','e','f']]
alayers=layers.to_numpy()

for m in range(0,20):
    print(alayers[i1[m]],j1[m],n2[i1[m]],data1['h'][m],data1['i'][m])
# -

plt.plot(j1[:],n2[i1[:]],'o')


# -*- coding:utf-8 -*-
# Author: Jason Lee
import socket
import select

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

s.bind(('', 7788))

s.listen(5)

epoll = select.epoll()

epoll.register(s.fileno(), select.EPOLLIN|select.EPOLLET)

connections = {}
addresses = {}

while True:
    #epoll进行fd扫描的地方 -- 未指定超时时间则为阻塞等待
    epoll_list = epoll.poll()
    for fd, events in epoll_list:
        if fd == s.fileno():
            conn, addr = s.accept()
            connections[conn.fileno()] = conn
            addresses[conn.fileno()] = addr

            epoll.register(conn.fileno(), select.EPOLLIN|select.EPOLLET)

        #EPOLLIN(可读)
        #EPOLLOUT(可写)
        #EPOLLET(ET模式，边缘触发) --> LT为水平触发
        elif events == select.EPOLLIN:
            recvData = connections[fd].recv(1024)
            if len(recvData) > 0:
                print(recvData)
            else:
                epoll.unregister(fd)
                connections[fd].close()


import logging

from .base import Phase
from ..items import State

LOG = logging.getLogger("pubtools.pulp")

class Update(Phase):
    """Update phase.

    This phase ensures any per-item mutable fields in Pulp are set to their
    desired values.

    Input queue:
    - items which exist in Pulp but might have some mutable fields which do
      not match desired values.

    Output queue:
    - items which exist in Pulp and have all mutable fields matching their
      desired values.

    Side-effects:
    - mutates unit fields (under pulp_user_metadata) in Pulp.
    """

    def __init__(self, context, pulp_client, in_queue, **_):
        super(Update, self).__init__(
            context, in_queue=in_queue, name="Update items in Pulp"
        )
        self.pulp_client = pulp_client

    def run(self):
        no_update_needed = 0
        update_needed = 0

        for item in self.iter_input():
            if item.pulp_state not in State.NEEDS_UPDATE:
                # This item is already up-to-date in Pulp (or just doesn't support
                # being updated)
                no_update_needed += 1
                self.put_output(item)
            else:
                # This item needs an update.
                update_needed += 1
                self.put_future_output(item.ensure_uptodate(self.pulp_client))

        LOG.info(
            "Update: %s item(s) already up-to-date, %s updating",
            no_update_needed,
            update_needed,
        )


from tornado.web import RequestHandler, url
from tornado.escape import utf8, json_encode

from .flash import FlashMessagesMixin

class Handler(RequestHandler, FlashMessagesMixin):
    """Medoly Request Handler class

    Extends:
        RequestHandler
        FlashMessagesMixin
    """

    def prepare(self):
        """Perpare request process
        """
        self.hooks.run('on_start_request', self)
        self.on_start_request()

    def on_start_request(self):
        """Process hook after ``on_start_request''
        """
        pass

    def get_template_namespace(self):
        """Returns a dictionary to be used as the default template namespace.
        May be overridden by subclasses to add or modify values.
        The results of this method will be combined with additional
        defaults in the `tornado.template` module and keyword arguments
        to `render` or `render_string`.
        """
        namespace = dict(
            handler=self,
            flash=self.get_flashed_messages,
            request=self.request,
            current_user=self.current_user,
            locale=self.locale,
            _=self.locale.translate,
            pgettext=self.locale.pgettext,
            static_url=self.static_url,
            xsrf_form_html=self.xsrf_form_html,
            reverse_url=self.reverse_url
        )
        return namespace

    def jsonify(self, json_obj):
        """Json data write

        Arguments:
            json_obj {object} -- the data can json encoding

        Raises:
            RuntimeError --  run time exception when  request had finshed
        """
        if self._finished:
            raise RuntimeError("Cannot jsonify() after finish().  May be caused "
                               "by using async operations without the "
                               "@asynchronous decorator.")
        chunk = json_encode(json_obj)
        self.set_header("Content-Type", "application/json; charset=UTF-8")
        chunk = utf8(chunk)
        self._write_buffer.append(chunk)

    def render(self, template_name, **kwargs):
        """Renders the template with the given arguments as the response."""
        html = self.render_string(template_name, **kwargs)
        self.finish(html)

    def on_finish(self):
        """Hook pointer process  on request finshing
        """
        self.on_end_request()
        self.hooks.run('on_end_request', self)

    def on_end_request(self):
        """Custom request handler hook on end request
        """
        pass

class RenderHandler(Handler):
    """Render Handler class """

    def initialize(self, template):
        """Initialize and bind tempalte

        Arguments:
            template {str} -- tempalte path
        """
        self.template = template

    def get(self, *args):
        """Render template
        """
        self.render(self.template)


import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, roc_auc_score
import pandas as pd
import numpy as np
from sklearn.utils import shuffle
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LassoCV
from sklearn.model_selection import train_test_split,cross_val_score,KFold,RepeatedKFold,GridSearchCV
from scipy.stats import pearsonr,ttest_ind,levene
from sklearn.ensemble import RandomForestClassifier
from sklearn import svm

fp = '/Users/mac/Documents/clinical.xlsx'
data = pd.read_excel(fp)
data = shuffle(data)
data = data.fillna(0)
data_1 = data.loc[data['Label'].isin([0])] #筛选出Label值为0的行
data_2 = data.loc[data['Label'].isin([1])]

X = data[data.columns[1:]]
y = data['Label']
X = StandardScaler().fit_transform(X)
X = pd.DataFrame(X)
colNames = X.columns #
'''t检验特征筛选'''
index = []
for colName in data.columns[1:]:
    if levene(data_1[colName],data_2[colName])[1] > 0.05:
        if ttest_ind(data_1[colName],data_2[colName])[1]<0.05:
            index.append(colName)
    else:
        if ttest_ind(data_1[colName],data_2[colName],equal_var=False)[1]<0.05:
            index.append(colName)
print(len(index))

'''lasso特征筛选'''
if 'Label' not in index:index = ['Label']+index
data_1 = data_1[index]
data_2 = data_2[index]
data = pd.concat([data_1,data_2])
data = shuffle(data)
data.index = range(len(data)) #打乱后重新标号
X= data[data.columns[1:]]
y = data['Label']
X = X.apply(pd.to_numeric, errors='ignore') #将数据类型转化为数值型
colNames = X.columns
X = X.fillna(0)
X = X.astype(np.float64)
X = StandardScaler().fit_transform(X)
X = pd.DataFrame(X)
X.columns = colNames

alphas = np.logspace(-3,1,50)
model_lassoCV = LassoCV(alphas = alphas,cv=10,max_iter=100000).fit(X,y)
print(model_lassoCV.alpha_)
coef = pd.Series(model_lassoCV.coef_,index = X.columns)
print("Lasso picked "+str(sum(coef!=0)) + "variables and eliminated the other "+str(sum(coef==0)))

index = coef[coef !=0 ].index
X = X[index]
print(coef[coef != 0])  #查看经过t检验和lasso的特征值

'''randomForest分类'''
#将筛选出的特征分为训练集和测试集，其中，测试集占30%
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3)
#模型训练
model_rf = RandomForestClassifier().fit(X_train,y_train)
#效果查看
score_rf = model_rf.score(X_test,y_test)
print(score_rf)

'''svm支持向量机分类（参数优化前）'''
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3)
model_svm = svm.SVC(kernel='rbf',gamma='auto',probability=True).fit(X_train,y_train)
score_svm = model_svm.score(X_test,y_test)
print(score_svm)
'''参数优化params opt:svm'''
#一堆C，在2^-1到2^3中取10个（base不写默认底为10）
Cs = np.logspace(-1,3,10,base = 2)
#一堆γ
gammas = np.logspace(-4,1,50,base = 2)
param_grid = dict(C = Cs, gamma = gammas)
#cv=10  10则交叉验证，可以省略，函数会自动给一个值
grid = GridSearchCV(svm.SVC(kernel='rbf'),param_grid = param_grid,cv=10).fit(X,y)
print(grid.best_params_)
C = grid.best_params_['C']
gamma = grid.best_params_['gamma']
'''svm支持向量机分类（参数优化后）'''
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3)
model_svm = svm.SVC(kernel='rbf',gamma=0.08901572837528345,C = 0.9258747122872903,probability=True).fit(X_train,y_train)
score_svm = model_svm.score(X_test,y_test)
print(score_svm)

'''roc'''
y_probs = model_svm.predict_proba(X) #prob概率，预测X中每个病例属于前一种和后一种的概率
#threshold是阈值  ；y的真实值，y的预测值（第1列（人看是第2列）），把阳性的标签定为1
fpr,tpr,thresholds = roc_curve(y,y_probs[:,1],pos_label=1)

#画图
plt.plot(fpr,tpr,marker = 'o')#以原点来标记点（具体的什么符号代表什么图形差资料）
plt.xlabel('fpr')#横坐标名字
plt.ylabel('tpr')
plt.show()
#auc：roc曲线下面积
auc_score = roc_auc_score(y,model_svm.predict(X))
print(auc_score)


import sys
from openpyxl import Workbook
import NXOpen
import NXOpen.CAM

theSession = NXOpen.Session.GetSession()
workPart = theSession.Parts.Work
theUI = NXOpen.UI.GetUI()
tools = []

def main():
    rootGroup = workPart.CAMSetup.GetRoot(NXOpen.CAM.CAMSetup.View.ProgramOrder)
    obj = NXOpen.CAM.NCGroup.GetMembers(rootGroup)
    parsing_group(obj)
    wb = Workbook()

    ws =  wb.active
    ws.title = "Changed Sheet"

    ws = wb.worksheets[0]
    for i , tool in enumerate(tools):
        ws[f'A{i+1}'] = tool
        #lw(tool)
    wb.save(filename = r'C:\Temp\sample_book.xlsx')

def parsing_group(obj):
    for tagged in obj:
        if not tagged == 'NONE':
            if workPart.CAMSetup.IsGroup(tagged):
                group = NXOpen.CAM.NCGroup.GetMembers(tagged)
                parsing_group(group)
            else:
                add_tool(tagged)

def add_tool(operation):
    cutting_tool = operation.GetParent(NXOpen.CAM.CAMSetup.View.MachineTool)
    cutting_tool = cutting_tool.Name
    if not cutting_tool in tools:
        tools.append(cutting_tool)
    pass

def notinuse():
    num = theUI.SelectionManager.GetNumSelectedObjects()
    objects1 = [NXOpen.CAM.CAMObject.Null] * num

    for i in range(num):

        objects1[i] = theUI.SelectionManager.GetSelectedTaggedObject(i)
        name_op = objects1[i].Name
        cutting_tool = objects1[i].GetParent(NXOpen.CAM.CAMSetup.View.MachineTool)
        cutting_tool_list = cutting_tool.Name

    # Create a Workbook
    wb = Workbook()

    ws =  wb.active
    ws.title = "Changed Sheet"

    ws = wb.worksheets[0]
    ws['A1'] = name_op
    ws['A2'] = cutting_tool_list

    wb.save(filename = r'C:\Temp\sample_book.xlsx')

if __name__ == '__main__':
    main()


import threading

class ZiyadMassenger(threading.Thread):
    def run(self):
        for _ in range(10):
            print(threading.current_thread().getName())

sender = ZiyadMassenger(name="Send out message")
receiver = ZiyadMassenger(name="Receive message")
sender.start()
receiver.start()


#!/Users/tomar/Anaconda3/python.exe
"""
Created on Sat May 27 16:34:21 2017 by tomar
#!/usr/bin/python3
#!/Users/tomar/Anaconda3/python.exe
"""
import sys
import urllib
try:
	import gUtils
	import Users
except:
	sys.path.append("..")
	import gUtils
	import Users
import cgi
import random
import Songs

def renderHtml(x):
	# for greek
	if sys.stdout.encoding == 'UTF_8':
		print(x.encode('UTF_8', 'xmlcharrefreplace').decode('utf8'))
	else:
		print(x.encode('ascii', 'xmlcharrefreplace').decode('utf8'))
def encodeHtml(x):
	return urllib.parse.unquote(x, encoding='utf-8', errors='replace')
print("Content-type: text/html \n")
print('''
<title>SongBook</title>
<LINK REL='StyleSheet' HREF='/python/songs.css?{}'  TYPE='text/css' TITLE='ToMarStyle' MEDIA='screen'>
<LINK REL='StyleSheet' HREF='/python/tomar.css?{}'  TYPE='text/css' TITLE='ToMarStyle' MEDIA='screen'>
<link href='//fonts.googleapis.com/css?family=Didact Gothic' rel='stylesheet'>

<meta name="google-signin-client_id" content="932688745244-i4vfeap5jgu8id5dagrc49786vvs0qrf.apps.googleusercontent.com">

'''.format(random.randrange(9999), random.randrange(9999)))
print('''

    ×

filler

	''')
form = cgi.FieldStorage() # instantiate only once!
gid = form.getvalue('gId', '')	#remove default
name = form.getvalue('gName', '')	#remove default
gMail = form.getvalue('gMail', '')	#remove default
gImg = form.getvalue('gImage', '')	#remove default
oper = form.getvalue('oper','')
#gid = '106932376942135580175'
gUtils.toggleDivFunction()
print('''
<form name="gForm" method="POST" action="#">
<input type="hidden" name="gId" value="{}">
<input type="hidden" name="gName" value="{}">
<input type="hidden" name="gMail" value="{}">
<input type="hidden" name="gImage" value="{}">
<input type="hidden" name="oper">
</form>
'''.format(gid, name, gMail, gImg))
if gid == '':
	gUtils.googleSignIn()
else:
	users = Users.Users()
	authS = users.authenticate(gid, name, gMail, gImg, users.SONGBOOK)		# gets you into songbook public tags
	authA = users.authenticate(gid, name, gMail, gImg, users.ADMIN)			# gets you notes
	authT = users.authenticate(gid, name, gMail, gImg, users.TEA)			# gets you all tags and media
	authF = users.authenticate(gid, name, gMail, gImg, users.FF)			# gets you all tags and media
	if authA[0] == '1':
		perm = 3
	elif authT[0] == '1' and authF[0] == '1':
		perm = 3
	elif authT[0] == '1' or authF[0] == '1':
		perm = 2
	elif authS[0] == '1':
		perm = 1
	else:
		perm = 0
	#perm = 1						#uncomment to test permissions
	print(authS[1])
	if perm > 0:
		print("")
		songbook = Songs.Songs()
		print("")
		renderHtml(songbook.jsFunctions(perm))
		print("
")
		#print("in index, oper is {}, perm is {}
".format(oper, perm))
		if (oper[0] == "N"):
			renderHtml(songbook.displaySong(encodeHtml(oper[1:]), perm))
		else:
			if (oper[0] == "T"):
				results = songbook.displaySongList(songbook.tagDict[oper[1:2]][encodeHtml(oper[2:])], perm)
			elif (oper[0] == "D"):
				results = songbook.displaySongList(songbook.getSongsByDeck(encodeHtml(oper[1:])), perm)
			elif (oper[0] == "M"):
				results = songbook.displaySongList(songbook.marked, perm)
			renderHtml(''.format(results[3]))
			renderHtml(results[0])
	else:
		print('''
Welcome to ToMarGames Friends and Family!

It looks like you've landed on a page you don't have permission to access.
				''')
print('')


import pandas as pd
import numpy as np
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, confusion_matrix

# Load the dataset
url = 'https://raw.githubusercontent.com/SK7here/Movie-Review-Sentiment-Analysis/master/IMDB-Dataset.csv'
data = pd.read_csv(url, nrows=250)

# Download required NLTK resources
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')

# Initialize the lemmatizer
lemmatizer = WordNetLemmatizer()

# Define a function to preprocess the text
def preprocess_text(text):

    # Tokenize the text
    tokens = word_tokenize(text)

    # Remove stopwords and non-alphabetic tokens
    words = [lemmatizer.lemmatize(token.lower()) for token in tokens if token.isalpha() and token.lower() not in stopwords.words('english')]

    # Join the words back into a single string
    preprocessed_text = ' '.join(words)

    return preprocessed_text

# Preprocess the movie reviews
data['preprocessed_review'] = data['review'].apply(preprocess_text)

# Initialize the count vectorizer
vectorizer = CountVectorizer(max_features=5000)

# Fit and transform the preprocessed reviews
X = vectorizer.fit_transform(data['preprocessed_review']).toarray()

# Get the sentiment labels
y = data['sentiment']

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Initialize the Naive Bayes classifier
clf = MultinomialNB()

# Train the classifier
clf.fit(X_train, y_train)

# Make predictions on the test set
y_pred = clf.predict(X_test)

# Calculate the accuracy of the classifier
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')

# Display the confusion matrix
cm = confusion_matrix(y_test, y_pred)
print(f'Confusion Matrix:\n{cm}')

def analyze_sentiment(text, classifier, vectorizer):
    # Preprocess the input text
    preprocessed_text = preprocess_text(text)

    # Convert the preprocessed text to a feature vector
    X_input = vectorizer.transform([preprocessed_text]).toarray()

    # Predict the sentiment using the classifier
    sentiment = classifier.predict(X_input)[0]

    return sentiment

# Example usage of the analyze_sentiment function
new_review = 'A wonderful way to spend time on a too hot summer weekend. This is probably my all-time favorite movie!'
predicted_sentiment = analyze_sentiment(new_review, clf, vectorizer)
print(f'Predicted sentiment: {predicted_sentiment}')