from rsf.proj import *

#SConscript('../fetch/SConstruct')
# SConstript will always rerun oher directory, I think because env changes.
# perhaps scons sees PWD or DATAPATH has changed.  This works:

SConscript('../fetch/SConstruct')

# to look at first breaks on shots with 0 time delay:
# <allshots.su  suwind key=ep min=3577 max=3607 |  suximage perc=90

# view the observer notes:
pdfread = WhereIs('acroread') or WhereIs('kpdf') or WhereIs('evince') or \
    WhereIs('xpdf') or WhereIs('gv') or WhereIs('open')
if pdfread:
   Flow('observerlog','../fetch/32obslog.pdf',
          pdfread + ' ${SOURCES[0]}',stdin=0)

# convert, and view previous processing stack
file='checkstack'
Flow([file, file+'_hdr', file+'.bin', file+'.asc'],
     '../fetch/CSDS32_1.SGY',
     '''
     sfsegyread  tfile=${TARGETS[1]} bfile=${TARGETS[2]} hfile=${TARGETS[3]}
     ''')

Result('checkstack','checkstack',
       'sfgrey title="checkstack" perc=90')
Result('zoomcheckstack','checkstack',
       '''
       sfwindow min1=0 max1=3  |
       sfgrey title="zoom checkstack" perc=90
       ''')

# sfwindow pads all traces to the same time length
segyread='''
         sfsegyread tfile=${TARGETS[1]} bfile=${TARGETS[2]} hfile=${TARGETS[3]}
         | sfwindow max1=12.28
         '''

rawsegy=['U32A_01','U32A_02','U32A_03','U32A_04','U32A_05',
         'U32A_06','U32A_07','U32A_08','U32A_09','U32A_10',
         'U32A_11','U32A_12','U32A_13','U32A_14','U32A_15',
         'U32A_16','U32A_17','U32A_18','U32A_19','U32A_20',
	 'U32A_21']

# after reading the observer logs, running segyread and running surange
# and sugethw a few times I learned two files have some special problems
# that need to be fixed:
# 'U32A_04' needs to have fldr 688 and 689 removed
# 'U32A_17' needs to have fldr 500-510 renumberred to 700-710

# this is the list of segy files that do not need fixes:
easysegy=['U32A_01','U32A_02','U32A_03','U32A_05',
         'U32A_06','U32A_07','U32A_08','U32A_09','U32A_10',
         'U32A_11','U32A_12','U32A_13','U32A_14','U32A_15',
         'U32A_16','U32A_18','U32A_19','U32A_20',
	 'U32A_21']

# there are also 'U32B_01','U32B_02','U32B_03'
# and  'U32C_01','U32C_02','U32C_03'
# and 'U32_01'
# The line is collected in 3 parts. 32, 32a, and 32b.  There is plenty
# to use on line 32A, so no attempt is made to process the other parts of
# the line

for file in easysegy  :
    Flow([file, file+'_hdr', file+'.bin', file+'.asc'],
         '../fetch/'+file+'.SGY',
         '''
         sfsegyread tfile=${TARGETS[1]} bfile=${TARGETS[2]} hfile=${TARGETS[3]}
         | sfwindow max1=12.28
         ''')

    Flow(file+'.txt',file+'_hdr','sfheaderattr | tee ${TARGETS[0]}',stdout=-1)

# now handle the tapes that need fixes (U32A_04 and U32A_17).
# 'U32A_04' needs to have fldr 688 and 689 removed
# 'U32A_17' needs to have fldr 500-510 renumberred to 700-710

# for U32A_04, make temporary files U32A_04t.rsf U32A_04t_hdr.rsf and run it
# through sftahsort | sftahwrite remove the unwanted fldr's.  first sort key
# tracr is the trace number on the reel, so traces will remain in same order
# as input

file='U32A_04'
Flow([file+'t', file+'t_hdr', file+'.bin',  file+'.asc'],
     '../fetch/'+file+'.SGY',
     '''
     sfsegyread tfile=${TARGETS[1]} bfile=${TARGETS[2]} hfile=${TARGETS[3]}
     | sfwindow max1=12.28
     ''')

# sftahsort will select a range on the header.  Put tracr first will keep traces
# in original order.  fldr:690,99999 will elliminate the low numberred shots
# 688 and 689.
Flow([file, file+'_hdr'],[file+'t', file+'t_hdr'],
     '''
     sftahsort input=${SOURCES[0]} \
               sort="tracr fldr:690,99999" \
     | sftahwrite output=${TARGETS[0]} \
               mode=seq \
     ''',stdin=0,stdout=0)
Flow(file+'.txt',file+'_hdr','sfheaderattr | tee ${TARGETS[0]}',stdout=-1)

# 'U32A_17' needs to have fldr 500-510 renumberred to 700-710.  Again make
# temporary files U32A_17t.rsf and U32A_17t_hdr.rsf and use a custom python
# program (sftahfix_hdr_17) to renumber these fldr's.
file='U32A_17'
Flow([file+'t', file+'t_hdr', file+'.bin',  file+'.asc'],
     '../fetch/'+file+'.SGY',
     '''
     sfsegyread tfile=${TARGETS[1]} bfile=${TARGETS[2]} hfile=${TARGETS[3]}
     | sfwindow max1=12.28
     ''')
Flow([file, file+'_hdr'],[file+'t', file+'t_hdr','./sftahfix_hdr_17.py'],
     '''
     sftahread input=${SOURCES[0]} \
     | ./sftahfix_hdr_17.py \
     | sftahwrite output=${TARGETS[0]} \
               mode=seq \
     ''',stdin=0,stdout=0)
Flow(file+'_list1',file+'_hdr','sfheaderattr | tee ${TARGETS[0]}',stdout=-1)

# concatinate the input rsf files to create line.rsf (all traces before
# loading headers)
numsegy=len(rawsegy)
print (rawsegy)
print (numsegy)

print ('numsegy=%d\n'%numsegy)
Flow('line',rawsegy,'sfcat axis=2 ${SOURCES[:%d]}'%numsegy, stdin=0)

# use python's list comprehension to make rawsegy_hdr list from the rawsegy list
rawsegy_hdr=[file+'_hdr'  for file in rawsegy]
print ('rawsegy_hdr=',rawsegy_hdr)

# concatinate the input _hdr.rsf files to make line_hdr.rsf
numsegy=len(rawsegy)
Flow('line_hdr',rawsegy_hdr,'sfcat axis=2 ${SOURCES[:%d]}'%numsegy, stdin=0)

# make simple lists and displays before loading trace headers
Flow('list1.txt','line_hdr','sfheaderattr | tee ${TARGETS[0]}',stdout=-1)

#allshots is the name of the file after geometry is loaded in headers

# display the first 3000 traces, notice shots have different recording delay
Result('first','line',
       'sfwindow n2=3000 | sfgrey perc=90')

# display a 160 traces selected to show different recording delays
Result('zoomfirst','line',
       '''
       sfwindow min2=48141 max2=48300 min1=0 max1=3 |
       sfgrey perc=90
       ''')

# make movie of 10 shots (48 traces/shot)
Result('firstmovie','line',
       '''
       sfwindow n2=4800 |sfput n2=48 n3=10
       | sfgrey title="first 10 shots" perc=20
       ''')

# display 160 traces
Result('firstrec24','line',
       '''
       sfwindow min2=48141 max2=48300 min1=0 max1=6 |
       sfgrey perc=90
       ''')

# The near trace gather (ntg) does not have the recording delay applied, so
# the deep water portion of the line is displayed without the 1, 2, 3, or 4
# seconds delay applied.

Flow('ntg','line',
       'sfput n2=48 n3=4792 | sfwindow  min2=48 max2=48')

# sftahsort is faster because headers are used to select traces,
# but tracr is reel by reel.  no key to keep traces in original order
#Flow('ntg ntg_hdr','line line_hdr',
#     '''
#     sftahsort sort="tracr tracf:48,48" input=${SOURCES[0]} \
#     | sftahwrite output=${TARGETS[0]} mode=seq \
#     ''',stdin=0,stdout=0)

Result('ntg','ntg',
       'sfgrey perc=90 title=ntg')

# make zoomable near trace gather (ntg) display
Flow('nothing','ntg','sfimage perc=97')

#allshots is the name of the file after geometry is loaded in headers
Flow('allshots.rsf allshots_hdr.rsf',
     'line.rsf line_hdr.rsf ./sftahloadgeom.py',
     '''
     sftahread input=${SOURCES[0]} \
     | ./sftahloadgeom.py \
     | sftahheadermath outputkey=sstat output=delrt \
     | sftahheadermath outputkey=gstat output=0     \
     | sftahstatic sign=-1 \
     | sftahwrite output=$TARGET mode=seq \
     ''',stdin=0,stdout=0)

#print summary of trace headers
Flow('allshots_hdr.txt','allshots_hdr',
     'sfheaderattr | tee ${TARGETS[0]}',stdout=-1)

# make fold plot using offset, cdp and trid.  trid is used as a dummy
Flow('foldplot.rsf','allshots_hdr.rsf',
     '''
     sffold
         verbose=1 \
         o1=470 n1=71 d1=50 label1=offset \
	 o2=101 n2=5578 d2=1  label2=cdp \
         o3=1 n3=1 d3=1 label3=trid
     ''')

# plot (offset,cdp) trace distribution.
Result('foldplot',' sfgrey title="cdp,offset trace distribution" ')
# zoom (offset,cdp) trace distribution plot.  Notice some missed shots
Result('zoomfoldplot','foldplot',
       '''
       sfwindow min2=800 max2=1400
        | sfgrey  title="cdp,offset trace distribution. shooting dir left"
       ''')

# apply time delay and check on near trace gather
Flow('ntgdelay ntgdelay_hdr','allshots allshots_hdr',
     '''
     sftahsort sort="fldr tracf:48,48" input=$SOURCE \
     | sftahwrite output=$TARGET mode=seq \
     ''',stdin=0,stdout=0)
Result('ntgdelay','ntgdelay',
       'sfgrey perc=90 title=ntgdelay')

# remove 51 ms delay and plot data to check work
# after nmo waterbottom multiple should be twice waterbottom time and
# reverse polarity. On sfimage display mouse button 2 to turn print on of
# cursor (cdp,t,amplitude).  Zoom and time onset of black on water bottom.
# Zoom and time onset of white on watbot multiple.  On first trace I measure
# wat bot at 5.086s and multipelat 10.1785.  6 ms off. Pretty close.
Flow('ntg_static ntg_static_hdr','ntgdelay ntgdelay_hdr',
     '''
     sftahsort sort="fldr:1,1000 cdp:1,999999 tracf:48,48" input=$SOURCE \
     | sftahheadermath outputkey=sstat output=51 \
     |  sftahstatic sign=1 \
     | sftahgain tpow=1 \
     | sftahpef maxlag=.100 \
     | sftahnmo tnmo=0 vnmo=1500 \
     | sftahwrite output=$TARGET mode=seq \
     ''',stdin=0,stdout=0)

# plot a zoomable near trace gather (ntg) plot
Flow('ntg_static.txt','ntg_static',
     'sfimage perc=97',stdout=0)

# make movie of 20 shotpoints
Result('secondmovie','allshots',
       '''
       sfwindow n2=9600
       | sfput n2=48 n3=200
       | sfgrey
       ''')
# make movie of 20 shotpoints with tpow applied
Result('thirdmovie','allshots',
       '''
       sfwindow n2=9600
       | sfput n2=48 n3=200
       | sftpow tpow=1.0
       | sfgrey title="shots with tpow=1.0" perc=99
       ''')

# sort to cdp gathers
Flow('cdps.rsf cdps_hdr.rsf','allshots.rsf allshots_hdr.rsf',
     '''
     sftahsort sort="cdp:1,999999 offset" input=$SOURCE \
     | sftahheadermath outputkey=sstat output=51 \
     |  sftahstatic sign=1 \
     | sftahgain tpow=1.5 \
     | sftahmute xmute=0,4000 tmute=0,4 \
     | sftahpef maxlag=.100 \
     | sftahwrite output=$TARGET mode=seq \
     ''',stdin=0,stdout=0)

# Velocity analysis would be nice.  Best example may be oren's
# teapotdome paper.

# need to have space variant velocity for decent result because water depth
# varies so much.  Best example maybe in teapotdome/vels.
# For now I will just put a single velocity function from cdp 4851.

# stack the cdp gathers
Flow('stack.rsf stack_hdr.rsf','cdps.rsf cdps_hdr.rsf',
     '''
     sftahread input=$SOURCE \
     | sftahnmo \
        tnmo=0.10779,4.53796,5.34639,6.13326,7.30401,7.93825,8.9572,12.319 \
	vnmo=1497.16,1506.74,1546.42,1661.37,1892,2060,2288,2384.21 \
     | sftahstack key=cdp \
     | sftahwrite output=$TARGET mode=seq \
     ''',stdin=0,stdout=0)

# display the stack
Result('stack','stack',
       '''
       sfgrey title="stack"  perc=90
       ''')
Result('zoomstack','stack',
       '''
       sfwindow min1=3 max1=10 min2=3000 | sfgrey title="stack"  perc=90
       ''')
Result('zoomstack1','stack',
       '''
       sfwindow min1=0 max1=7 max2=3000 | sfgrey title="stack"  perc=90
       ''')

End()


import heapq
import sys, os, io, atexit

input = lambda: sys.stdin.readline().rstrip('\r\n')
stdout = io.BytesIO()
sys.stdout.write = lambda s: stdout.write(s.encode("ascii"))
atexit.register(lambda: os.write(1, stdout.getvalue()))

# 221002 9370 미확인 도착지

# 정답코드

def dijkstar(start):

    queue = []
    heapq.heappush(queue, (0, start))

    distance[start] = 0

    while queue:
        dist, node = heapq.heappop(queue)

        if distance[node] == dist:
            for next in graph[node]:
                dist = distance[node] + next[1]

                if dist < distance[next[0]]:
                    distance[next[0]] = dist
                    heapq.heappush(queue, (dist, next[0]))

    return

tc = int(input())

for _ in range(tc):
    N, M, T = map(int, input().split())
    S, G, H = map(int, input().split())

    graph = [[] for _ in range(N + 1)]
    for _ in range(M):
        node1, node2, weight = map(int, input().split())
        if (node1 == G and node2 == H) or (node1 == H and node2 == G):
            weight -= 0.1

        graph[node1].append((node2, weight))
        graph[node2].append((node1, weight))

    candidates = []
    for _ in range(T):
        candidates.append(int(input()))

    distance = [sys.maxsize for _ in range(N + 1)]
    dijkstar(S)

    ans = []
    for candidate in candidates:
        if type(distance[candidate]) == float:
            ans.append(candidate)
    ans.sort()

    print(*ans)

백준/Gold/9370. 미확인 도착지/미확인 도착지.py


from selenium import webdriver
import arrow
from time import sleep
import os
import re
import pyautogui as pi
from unidecode import unidecode
from _comandos_banco import CRUD

ar = arrow.now().format('DD/MM/YYYY')
key_words = ['TEMPERO','CALDINHO','CONSERVA','TABLETE', 'CONGELADO', 'COZIDO', 'INSTANTANEO', 'LATA', 'PAPINHA', 'PRONTO', 'INSTANTANEA']
produtos = ['papel higienico', 'molho de tomate', 'acucar', 'arroz', 'feijao',  'sal',  'farinha', 'macarrao', 'cafe', 'detergente' ]

for f in produtos:
    continuar = True
    navegador = webdriver.Chrome()
    navegador.get(f'https://www.bistek.com.br/catalogsearch/result/index/?q={f}&product_list_limit=all')
    navegador.fullscreen_window()
    sleep(2)

    xpath_link = '//*[contains(concat( " ", @class, " " ), concat( " ", "product-item-link", " " ))]'
    xpath_image = '//*[contains(concat( " ", @class, " " ), concat( " ", "product-image-photo", " " ))]'
    xpath_price = '//*[@id="maincontent"]/div[3]/div[1]/div[3]/div[2]/ol/li[8]/div/div[2]/div[1]/span[2]/span[1]'
    xpath_name = '//*[contains(concat( " ", @class, " " ), concat( " ", "product-item-link", " " ))]'

    links = []
    names = []
    prices = []
    imgs = []

    # ---------------------------------------- LINKS -------------------------------------------- #

    # link_elements = navegador.find_elements('xpath', xpath_link)
    # for link_el in link_elements:
    #     href = link_el.get_attribute('href')
    #     links.append(href)

    # # ------------------------------------- NOMES PRODUTOS ------------------------------------------ #

    # name_elements = navegador.find_elements('xpath', xpath_name)
    # for name_el in name_elements:
    #     name = unidecode(name_el.text)
    #     name = re.sub(r"[^a-zA-Z0-9- ]","",name)
    #     names.append(name)

    # ---------------------------------------- PREÇOS PRODUTOS --------------------------------------- #

    price_elements = navegador.find_elements('xpath', '//*[contains(concat( " ", @class, " " ), concat( " ", "weee", " " ))]')
    for price_el in price_elements:
        price_el = price_el.find_element('xpath','//*[contains(concat( " ", @class, " " ), concat( " ", "price", " " ))]')
        price = price_el.text
        bkprice = price.split('\n')
        bkprice[0] = bkprice[0].replace('R$', '').replace(' ', '').replace(',','.')
        prices.append(bkprice[0])

    # ---------------------------------------- IMAGENS PRODUTOS -------------------------------------- #

    image_elements = navegador.find_elements('xpath', xpath_image)
    for image_el in image_elements:
        href = image_el.get_attribute('src')
        imgs.append(href)

    # --------------------------------------- INSERÇÃO NO BANCO --------------------------------------- #

    for i in prices:
        print(i)

    for i in  imgs:
        print(i)

    navegador.quit()


# Приложение проводит логирование своей работы с ротацией лог-файлов
# при достижении размера файла 1 мегабайт.
# При этом логгируются все полученные запросы и ответы приложения,
# информация о добавлении в БД новой записи, либо об изменении существующих.
# Также логируются результаты опроса статус кодов сайтов
# - записывается результат по каждому сайту отдельно
# и общий итог каждой проверки.

import logging
from logging.handlers import RotatingFileHandler

formatter = logging.Formatter(
    '[%(asctime)s] %(levelname)s in %(module)s: %(message)s')
# Настройки логгирования запросов и ответов,
# добавления в БД новой записи, либо изменения существующей.

all_actions_handler = RotatingFileHandler(
    'logs/all_actions.log',
    maxBytes=1024 * 1024, backupCount=1)

all_actions_handler.setFormatter(formatter)
all_actions_handler.setLevel(logging.DEBUG)

all_actions_logger = logging.getLogger('all_actions')
all_actions_logger.setLevel(logging.DEBUG)
all_actions_logger.addHandler(all_actions_handler)

# Настройки логгирования опроса статус кодов сайтов,
# - записывается результат по каждому сайту отдельно
# и общий итог каждой проверки.

status_check_handler = RotatingFileHandler(
    'logs/status_check.log',
    maxBytes=1024 * 1024, backupCount=1)
status_check_handler.setFormatter(formatter)
status_check_handler.setLevel(logging.DEBUG)

status_check_logger = logging.getLogger('status_check')
status_check_logger.setLevel(logging.DEBUG)
status_check_logger.addHandler(status_check_handler)


words = ["round" , "dream", "magnet" , "tweet" , "tweet", "trick", "kiwi"]
flag = False # 더미 데이터 : 기본값이 False

for idx in range(1, len(words)):
    print(idx)

    # 지금의 나

    if words[idx-1][-1] != words[idx][0]:
        print('실패', idx, words[idx])
        flag = True

    else:
    #    성공했을 때 => 겹침
        for sub_idx in range(idx):
            pre_word = words[sub_idx]
            me_word = words[idx]
            if pre_word == me_word:           # True 일 때 Break를 원한다면
                print('실패', idx, words[idx])
                flag = True
                break

    if flag:
        break

실습4차_기본함수_구조_및_조건,_반복문을_활용한_함수_구성에_대한_이해/홈워크_python_04_hw01_P_Ver.2.py


def linear(lst, k, n):
    for i in range(0, 8):
        if(lst[i] == k):
            return i
    return -1
lst = [1, 4, 5, 7, 21, 12, 13, 98]
k = 7
n = len(lst)

result = linear(lst, k, n)
if(result == -1):
    print("Element no present")
else:
    print("Element is present")


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

# visit http://127.0.0.1:8050/ in your web browser.

# Load libraries
import dash
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
import data_load_and_transformer as dlt
import graph_formater as grf
import app_layout

# Styles - CERULEAN (!), COSMO, CYBORG, DARKLY, FLATLY, JOURNAL, LITERA, LUMEN, LUX, MATERIA (!),
# MINTY, PULSE (!), SANDSTONE (!), SIMPLEX, SKETCHY, SLATE, SOLAR, SPACELAB (!), SUPERHERO, UNITED (!), YETI (!)
external_stylesheets = [dbc.themes.PULSE]

app = dash.Dash(__name__, external_stylesheets=external_stylesheets,  # , external_stylesheets=external_stylesheets
                meta_tags=[{'name': 'viewport', 'content': 'width=device-width, initial-scale=1.0, maximum-scale=1.2, '
                                                           'minimum-scale=0.5,'}])
server = app.server

# APPLICATION LAYOUT
app.layout = app_layout.layout()

# ------------------- CALLBACKS ------------------------------------------------------------------
@app.callback(
    [Output(component_id='telecides-unit', component_property='figure'),
     Output(component_id='telecides-sub-unit', component_property='figure'),
     Output(component_id='telecides-student', component_property='figure'),
     Output(component_id='num_units', component_property='children'),
     Output(component_id='num_sub', component_property='children'),
     Output(component_id='num_students', component_property='children'),
     Output(component_id='num_pairs', component_property='children'),
     Output(component_id="loading-output-2", component_property='children')],
    [Input(component_id='courses_dropdown', component_property='value')]
)
def update_telecides(value):
    """
    Load, clean, and visualize data from a Telecides dataset.

    Parameters:
    value (str): The filename of the dataset to load.

    Returns:
    A tuple containing the following items:
    - fig_sectionid: A plotly figure showing the distribution of section IDs.
    - fig_lessonid: A plotly figure showing the distribution of lesson IDs.
    - fig_user_id: A plotly figure showing the distribution of user IDs.
    - subjects: A pandas DataFrame containing the counts of each subject.
    - num_students: An integer representing the number of unique students.
    - num_pairs: An integer representing the number of unique lesson pairs.
    - sum: A pandas DataFrame containing the sum of watch_time for each section.
    - value (str): Webhook URL.
    """
    if value is None:
        # PreventUpdate prevents ALL outputs updating
        raise dash.exceptions.PreventUpdate

    # Load and clean data
    df = dlt.loader(value)
    cleaned_df = dlt.cleaner(df)

    # Create figures
    fig_sectionid = grf.create_graph('sectionid', df, cleaned_df)
    fig_lessonid = grf.create_graph('lessonid', df, cleaned_df)
    fig_user_id = grf.create_graph('user_id', df, cleaned_df)

    # Compute summary statistics
    num_sub = cleaned_df['lessonid'].nunique()
    num_students = cleaned_df['user_id'].nunique()
    num_units, num_pairs = dlt.group_dataframe('sectionid', df, cleaned_df)[1:3]

    return fig_sectionid, fig_lessonid, fig_user_id, num_pairs, num_sub, num_students, num_units, value

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

if __name__ == '__main__':
    app.run_server(debug=True)


# Задача 4. Използвайки файла Books.csv, помолете потребителя да въведе начална и
# крайна година. Покажете всички книги, издадени между тези две години.

import csv

def search_book_of_years(file_name, year1, year2) :
    have_book = False
    with open(file_name, mode='+r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for row in reader:
            if row[2] >= year1 and row[2]<=year2:
                have_book = True
                print(row[0])
        else:
            if not (have_book):
                print(f'Няма налични книги този диапазон от години {year1} - {year2}')

year1 = input('Въведете начална година:')
year2 = input('Въведете крайна година:')
search_book_of_years('HomeWork\HW lab18- 10 05 2023\Books.csv', year1, year2)


"""bench URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

from django.urls import path
import uuid
from datetime import timedelta
from django.utils import timezone
from django.http import HttpResponse
import django
from bench.models import PgSession,MySession,MgSession,CaSession
from django.core.cache import cache
import json

SESSION_LIFETIME = 3600

def generate_token():
    return str(uuid.uuid4())

def generate_sample():
    code = str(uuid.uuid4())
    now = timezone.now().strftime('%Y-%m-%d %H:%M:%S')
    data = {
        "created_at":now,
        "cilent":'api_client',
        "scope":['database','image','file'],
        'refresh_code':code
    }
    return data

def get_session_expired_at():
    now = timezone.now()+timedelta(days=1)

    return now

def index(request):
    return HttpResponse(django.VERSION)

'''
create table my_session(
    token char(64) primary key,
    data varchar(2048) null,
    expired_at timestamp null
);
'''
def mysql(request):
    token = generate_token()
    data = generate_sample()
    expired_at = get_session_expired_at()

    #insert new session
    session = MySession(token=token,data=data,expired_at=expired_at)
    session.save(using='mysql')

    #find session
    session = MySession.objects.using('mysql').get(token=token)

    #update session
    expired_at = get_session_expired_at()
    MySession.objects.using('mysql').filter(token=token).update(data=data,expired_at=expired_at)

    return HttpResponse("")

'''
create table session(
    token text primary key,
    data jsonb null,
    expired_at timestamp null
);
'''
def postgresql(requset):
    token = generate_token()
    data = generate_sample()
    expired_at = get_session_expired_at()

    #insert new session
    session = PgSession(token=token,data=data,expired_at=expired_at)
    session.save(using='pg')

    #find session
    session = PgSession.objects.using('pg').get(token=token)

    #update session
    expired_at = get_session_expired_at()
    PgSession.objects.using('pg').filter(token=token).update(data=data,expired_at=expired_at)

    return HttpResponse("")

def redis(request):
    token = generate_token()
    data = generate_sample()

    #insert new session
    cache.set(token,data,SESSION_LIFETIME)

    #find session
    session = cache.get(token)

    #update session
    cache.set(token,data,SESSION_LIFETIME)

    return HttpResponse("")

def mongodb(requset):
    token = generate_token()
    data = generate_sample()
    expired_at = get_session_expired_at()

    #insert new session
    session = MgSession(token=token,data=data,expired_at=expired_at)
    session.save()

    #find session
    session = MgSession.objects(token=token)

    #update session
    expired_at = get_session_expired_at()
    MgSession.objects(token=token).update(data=data,expired_at=expired_at)

    return HttpResponse("")

'''
create table ca_session(
    "token" text primary key,
    data text,
    expired_at timestamp
);
'''
def cassandra(request):
    token = generate_token()
    data = generate_sample()
    expired_at = get_session_expired_at()

    #insert new session
    session = CaSession(token=token,data=json.dumps(data),expired_at=expired_at)
    session.save()

    #find session
    session = CaSession.objects.get(token=token)

    #update session
    expired_at = get_session_expired_at()
    CaSession.objects.filter(token=token).update(data=json.dumps(data),expired_at=expired_at)

    return HttpResponse("")

urlpatterns = [
    path('',index),
    path('postgresql',postgresql),
    path('mysql',mysql),
    path('redis',redis),
    path('mongodb',mongodb),
    path('cassandra',cassandra)
]


# SVM法で分離直線を求める
import numpy as np
from matplotlib import pyplot as plt

#データを用意
xx = np.array([
[1, 2],
[2, 4],
[3, 4],
[2, 1],
[4, 2],
[4, 3],
])
y = np.array([-1, -1, -1, 1, 1, 1])

# 最適方向ベクトルを計算する
nn = 6
coef = np.empty([nn, nn])
for i in range(nn-1):
    for j in range(nn):
        if i==j:
            coef[i,j] = 2*y[i]*y[j]*np.dot(xx[i], xx[j])
        else:
            coef[i,j] = y[i]*y[j]*np.dot(xx[i], xx[j])
for j in range(nn):
    coef[nn-1,j] = y[j]
d = np.array([2, 2, 2, 2, 2, 0])
alpha = np.linalg.solve(coef,d)
for i in range(nn):
    print("alpha"+str(i)+"=", alpha[i])
mm = 2
wstar = np.empty(mm)
for m in range(mm):
    wstar[m] = 0
    for i in range(nn):
        wstar[m] += alpha[i]*y[i]*xx[i,m]
    print("wstar"+str(m)+"=", wstar[m])

# 切片を計算する
xs = np.array([
[1, 2],
[3, 4],
[2, 1],
[4, 3],
])
ys = np.array([-1, -1, 1, 1])
bs = ys-np.dot(wstar,xs.T)
b = bs.mean()
print("b=", b)

# 訓練データと分離直線のグラフを描く
xx1 = xx[y==-1]
xx2 = xx[y==1]
pdata1 = np.array(xx1)
pdata2 = np.array(xx2)
plt.scatter(pdata1[:,0], pdata1[:,1], marker="x", s=60, linewidth="2", label="Negative Class")
plt.scatter(pdata2[:,0], pdata2[:,1], marker="o", s=60, linewidth="2", label="Positive Class")
kk = 6
x1 = np.empty(kk)
x2 = np.empty(kk)
for i in range(kk):
    x1[i] = i
    x2[i] = -(wstar[0]*x1[i]-b)/wstar[1]

plt.title("SVM Result of Training Data")
plt.xlabel("x1")
plt.ylabel("x2")
plt.grid()
plt.plot(x1, x2, marker=".")
plt.legend()
plt.show()


# 계속 고민하다 답지보고 풀었음
# 주기를 파악하니 쉽게 이해됨 ㅇㅇ
import sys
n = int(sys.stdin.readline())
mod = 1000000
p = mod//10*15 # 주기
l = [0,1]
for i in range(2, p):
    l.append(l[i-1] + l[i-2])
    l[i] %= mod
print(l[n%p])


from logging import getLogger

import requests
from django.conf.urls.static import static
from django.utils.translation import ugettext_lazy as _

from bitcaster.exceptions import PluginSendError
from bitcaster.utils.language import classproperty

from .. import serializers
from ..base import (CoreDispatcher, DispatcherOptions,
                    MessageType, SubscriptionOptions,)
from ..registry import dispatcher_registry

logger = getLogger(__name__)

class SlackWebhookMessage(MessageType):
    pass

class SlackWebhookOptions(DispatcherOptions):
    url = serializers.URLField(help_text=_('Your custom Slack webhook URL.'))
    bot_name = serializers.CharField(required=False,
                                     allow_blank=True,
                                     help_text=_('The name used when publishing messages.')
                                     )
    icon_url = serializers.URLField(required=False,
                                    allow_blank=True,
                                    help_text='''The url of the icon to appear beside your bot (32px png), leave empty for none.
You may use {}'''.format(static('logos/bitcaster32.png')))
    # channel = serializers.CharField(help_text='Optional #channel name or @user')

class SlackWebhookSubscriptionOptions(SubscriptionOptions):
    recipient = serializers.CharField(validators=[])

@dispatcher_registry.register
class SlackWebhook(CoreDispatcher):
    options_class = SlackWebhookOptions
    message_class = SlackWebhookMessage
    subscription_class = SlackWebhookSubscriptionOptions
    icon = 'slack.png'
    __help__ = """To use this plugin you need to enable the `Incoming WebHooks`
 application in you Slack console.
Navigate to https://<YOUR_SPACE>.slack.com/apps/" and enable `Incoming WebHooks`.

"""
    __core__ = True

    @classproperty
    def name(cls):
        return 'SlackWebHook'

    def _get_connection(self):
        s = requests.Session()

        s.headers = {'user-agent': 'bitcaster'}
        return s

    def emit(self, address, subject, message, *args, **kwargs):
        try:
            # url = "https://slack.com/api/chat.postMessage"
            logger.debug(f"Processing '{address}'")
            conn = self._get_connection()
            ret = conn.post(self.config['url'],
                            json={'username': self.config['bot_name'],
                                  'icon_url': self.config['icon_url'],
                                  'channel': address,
                                  'text': message,
                                  }
                            )
            if ret.status_code != 200:
                raise PluginSendError(ret.content.decode())
            return address
        except Exception as e:
            logger.exception(e)
            raise PluginSendError(e) from e

    def test_connection(self, raise_exception=False):
        conn = self._get_connection()
        return conn


from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from .models import Person, Resume, Blog, WeekTip
from .serializers import PersonSerializer, PersonListSerializer, BlogPostListSerializer, WeekTipSerializer

# Create your views here.

@csrf_exempt
def person_list(request):
    if request.method == 'GET':
        persons = Person.objects.all()
        serializer = PersonListSerializer(persons, many=True)
        return JsonResponse(serializer.data, safe=False)
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = PersonSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

@csrf_exempt
def person_item(request, pk):
    try:
        person = Person.objects.get(pk=pk)
    except Person.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = PersonSerializer(person)
        return JsonResponse(serializer.data, safe=False)

def blog_list(request):
    if request.method == 'GET':
        blogPosts = Blog.objects.filter(weektip__isnull=True)
        serializer = BlogPostListSerializer(blogPosts, many=True)
        return JsonResponse(serializer.data, safe=False)
    else:
        return HttpResponse(status=403)

def latest_weektip(request):
    if request.method == 'GET':
        weekTip = WeekTip.objects.last()
        if not weekTip:
            return JsonResponse({}, safe=False)
        else:
            serializer = WeekTipSerializer(weekTip)
            return JsonResponse(serializer.data, safe=False)


#
# @lc app=leetcode.cn id=1078 lang=python3
#
# [1078] Bigram 分词
#
from typing import List
# @lc code=start
class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
        _f = text.split(" ")
        res = [_f[i+2] for i in range(len(_f)-2) if _f[i] == first and _f[i+1]==second]
        return res

# @lc code=end

x = Solution().findOcurrences(text = "we will we will rock you", first = "we", second = "will")
print(x)


# -*- coding: utf-8 -*-
#
"""
Unit tests for data related operations.
"""

import tempfile
import copy
import numpy as np

import tensorflow as tf

import texar.tf as tx
from texar.tf.data import SpecialTokens

# pylint: disable=too-many-locals, too-many-branches, protected-access
# pylint: disable=invalid-name

class PairedTextDataTest(tf.test.TestCase):
    """Tests paired text data class.
    """

    def setUp(self):
        tf.test.TestCase.setUp(self)

        # Create test data
        vocab_list = ['This', 'is', 'a', 'word', '词']
        vocab_file = tempfile.NamedTemporaryFile()
        vocab_file.write('\n'.join(vocab_list).encode("utf-8"))
        vocab_file.flush()
        self._vocab_file = vocab_file
        self._vocab_size = len(vocab_list)

        src_text = ['This is a sentence from source .', '词 词 。 source']
        src_text_file = tempfile.NamedTemporaryFile()
        src_text_file.write('\n'.join(src_text).encode("utf-8"))
        src_text_file.flush()
        self._src_text_file = src_text_file

        tgt_text = ['This is a sentence from target .', '词 词 。 target']
        tgt_text_file = tempfile.NamedTemporaryFile()
        tgt_text_file.write('\n'.join(tgt_text).encode("utf-8"))
        tgt_text_file.flush()
        self._tgt_text_file = tgt_text_file

        self._hparams = {
            "num_epochs": 50,
            "batch_size": 3,
            "source_dataset": {
                "files": [self._src_text_file.name],
                "vocab_file": self._vocab_file.name,
            },
            "target_dataset": {
                "files": self._tgt_text_file.name,
                "vocab_share": True,
                "eos_token": "<TARGET_EOS>"
            }
        }

    def _run_and_test(self, hparams, proc_shr=False, length_inc=None,
                      discard_src=False):
        # Construct database
        text_data = tx.data.PairedTextData(hparams)
        self.assertEqual(
            text_data.source_vocab.size,
            self._vocab_size + len(text_data.source_vocab.special_tokens))

        iterator = text_data.dataset.make_initializable_iterator()
        text_data_batch = iterator.get_next()

        with self.test_session() as sess:
            sess.run(tf.global_variables_initializer())
            sess.run(tf.local_variables_initializer())
            sess.run(tf.tables_initializer())
            sess.run(iterator.initializer)

            if proc_shr:
                tgt_eos = b'<EOS>'
            else:
                tgt_eos = b'<TARGET_EOS>'

            while True:
                try:
                    # Run the logics
                    data_batch_ = sess.run(text_data_batch)
                    self.assertEqual(set(data_batch_.keys()),
                                     set(text_data.list_items()))
                    # Test matching
                    src_text = data_batch_['source_text']
                    tgt_text = data_batch_['target_text']
                    if proc_shr:
                        for src, tgt in zip(src_text, tgt_text):
                            np.testing.assert_array_equal(src[:3], tgt[:3])
                    else:
                        for src, tgt in zip(src_text, tgt_text):
                            np.testing.assert_array_equal(src[:3], tgt[1:4])
                    self.assertTrue(
                        tgt_eos in data_batch_['target_text'][0])

                    if length_inc:
                        for i in range(len(data_batch_['source_text'])):
                            text_ = data_batch_['source_text'][i].tolist()
                            self.assertEqual(
                                text_.index(b'<EOS>') + 1,
                                data_batch_['source_length'][i] - length_inc[0])
                        for i in range(len(data_batch_['target_text'])):
                            text_ = data_batch_['target_text'][i].tolist()
                            self.assertEqual(
                                text_.index(tgt_eos) + 1,
                                data_batch_['target_length'][i] - length_inc[1])

                    if discard_src:
                        src_hparams = text_data.hparams.source_dataset
                        max_l = src_hparams.max_seq_length
                        max_l += text_data._decoder[0].added_length
                        for l in data_batch_[text_data.source_length_name]:
                            self.assertLessEqual(l, max_l)

                except tf.errors.OutOfRangeError:
                    print('Done -- epoch limit reached')
                    break

    def test_default_setting(self):
        """Tests the logics of the text data.
        """
        self._run_and_test(self._hparams)

    def test_shuffle(self):
        """Tests toggling shuffle.
        """
        hparams = copy.copy(self._hparams)
        hparams["shuffle"] = False
        self._run_and_test(hparams)

    def test_processing_share(self):
        """Tests sharing processing.
        """
        hparams = copy.copy(self._hparams)
        hparams["target_dataset"]["processing_share"] = True
        self._run_and_test(hparams, proc_shr=True)

    def test_other_transformations(self):
        """Tests use of other transformations
        """
        def _transform(x, data_specs):  # pylint: disable=invalid-name
            x[data_specs.decoder.length_tensor_name] += 1
            return x

        hparams = copy.copy(self._hparams)
        hparams["source_dataset"].update(
            {"other_transformations": [_transform, _transform]})
        hparams["target_dataset"].update(
            {"other_transformations": [_transform]})
        self._run_and_test(hparams, length_inc=(2, 1))

    def test_length_filter(self):
        """Tests filtering by length.
        """
        hparams = copy.copy(self._hparams)
        hparams["source_dataset"].update(
            {"max_seq_length": 4,
             "length_filter_mode": "discard"})
        self._run_and_test(hparams, discard_src=True)

    # def test_sequence_length(self):
    #    hparams = {
    #        "batch_size": 64,
    #        "num_epochs": 1,
    #        "shuffle": False,
    #        "allow_smaller_final_batch": False,
    #        "source_dataset": {
    #            "files": "../../../data/yelp/sentiment.dev.sort.0",
    #            "vocab_file": "../../../data/yelp/vocab",
    #            "bos_token": SpecialTokens.BOS,
    #            "eos_token": SpecialTokens.EOS,
    #        },
    #        "target_dataset": {
    #            "files": "../../../data/yelp/sentiment.dev.sort.1",
    #            "vocab_share": True,
    #        },
    #    }
    #    data = tx.data.PairedTextData(hparams)

    #    iterator = tx.data.TrainTestDataIterator(val=data)
    #    text_data_batch = iterator.get_next()

    #    with self.test_session() as sess:
    #        sess.run(tf.global_variables_initializer())
    #        sess.run(tf.local_variables_initializer())
    #        sess.run(tf.tables_initializer())
    #        iterator.switch_to_val_data(sess)

    #        while True:
    #            try:
    #                data_batch_ = sess.run(text_data_batch)
    #                src = data_batch_["source_text_ids"]
    #                src_len = data_batch_["source_length"]
    #                self.assertEqual(src.shape[1], np.max(src_len))
    #                tgt = data_batch_["target_text_ids"]
    #                tgt_len = data_batch_["target_length"]
    #                self.assertEqual(tgt.shape[1], np.max(tgt_len))
    #            except tf.errors.OutOfRangeError:
    #                break

if __name__ == "__main__":
    tf.test.main()


import pandas as pd
import os
def modifiedCsv(fileName):
    df = pd.read_csv(fileName+".csv")
    df2 = df[87650:]
    df2.to_csv(fileName+"-modified.csv",index=False);
    return

if __name__ == "__main__":
    # modifiedCsv("pune");
    data = ["pune","delhi","bombay","hyderabad","jaipur","nagpur","bengaluru","kanpur"]
    for i in data:
        modifiedCsv(i);
        os.remove(i+".csv")


import csv, sqlite3
from datetime import datetime
import math

'''
this class holds the business logic  of the application for biking route we built.
We get requests and analyze them. If the database isn't built yet it will be built
and then the Database object will calculate different routes by measurments we created.
'''
class Database:
    '''
    building the database on initialize if not already built
    '''
    def __init__(self):

        def countTableRows():
            return cur.execute("select count(*) from BikeShare").fetchone()

        conn = sqlite3.connect('database.db')
        cur = conn.cursor()
        cur.execute("CREATE TABLE IF NOT EXISTS BikeShare ("
                         "TripDuration INT,"
                         "StartTime DATE,"
                         "StopTime DATE,"
                         "StartStationID INT,"
                         "StartStationName TEXT,"
                         "StartStationLatitude FLOAT,"
                         "StartStationLongitude FLOAT,"
                         "EndStationID INT,"
                         "EndStationName TEXT,"
                         "EndStationLatitude FLOAT,"
                         "EndStationLongitude FLOAT,"
                         "BikeID INT,"
                         "UserType TEXT,"
                         "BirthYear INT,"
                         "Gender INT,"
                         "TripDurationinmin INT)")
        if countTableRows()[0] == 0:
            with open('BikeShare.csv', 'rt') as fin:
                dr = csv.DictReader(fin)
                to_db = [(i['TripDuration'], i['StartTime'], i['StopTime'], i['StartStationID'], i['StartStationName'], i['StartStationLatitude'], i['StartStationLongitude'], i['EndStationID'], i['EndStationName'], i['EndStationLatitude'], i['EndStationLongitude'], i['BikeID'], i['UserType'], i['BirthYear'], i['Gender'], i['TripDurationinmin']) for i in dr]
            cur.executemany("INSERT INTO BikeShare (TripDuration, StartTime, StopTime, StartStationID, StartStationName, StartStationLatitude, StartStationLongitude, EndStationID, EndStationName, EndStationLatitude, EndStationLongitude, BikeID, UserType, BirthYear, Gender, TripDurationinmin)"
                            " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", to_db)
        conn.commit()
        conn.close()
    '''
    this function gets relevant records from the database and responsible to get rankings and send results
    :param currentLocation- the place the user starts at
    :param spendTime- time in minutes to spend biking
    :param numRecommendations- the number of results to choose from
    :return  a list of tupples (destination location name, score in our rankings)
    '''
    def getRecommendations(self, currentLocation, spendTime, numRecommendations):
        conn = sqlite3.connect('database.db')
        cur = conn.cursor()
        res = cur.execute("select * from BikeShare "
                          "where StartStationName like '" + currentLocation +

                          "' and TripDurationinmin <= " + str(spendTime)
                          # "' and EndStationName like '" + currentLocation +
                          #" limit " + str(numRecommendations)
                          ).fetchall()
        conn.close()
        return self.orderByMostRecommended(res,self.ratingOption1,spendTime,numRecommendations);
    '''
    the function purpose is to add ratings and sort by it
    :param res- list of records to look at
    :param ratingFunc- the function chosen for calculating rating
    :param spendTime- the number in minutes the user want to bike (comes as string)
    :param numRecommendations- the number of results the user wants (comes as string)
    :return  a list of tupples (destination location name, score in our rankings)
    '''
    def orderByMostRecommended(self,res,ratingFunc,spendTime,numRecommendations):
        resultsWithRatings={}
        for row in res:
            resultsWithRatings[row[8]]=ratingFunc(row,spendTime)
        return sorted(resultsWithRatings.items(), key=lambda item: item[1],reverse=True)[:int(numRecommendations)]

    '''
        add rate for one record. using the hour he searched (and database record's start hour),
        distance in coordinates and similarity to time spending wanted.
        :param row- a possible location chosen
        :param spendTime- the number of results the user wants
        :return  rating in range [0,100]
    '''
    def ratingOption1(self, row,spendTime):
        rowStartTime=row[1]
        rowTripDurationinmin = int(row[15])
        rowStartStationLatitude = row[5]
        rowEndStationLatitude = row[9]
        rowStartStationLongitude = row[6]
        rowEndStationLongitude = row[10]

        #each normalize create number in [0,1] where the highest is the best
        rowHourInString=rowStartTime.split(" ")[1].split(":")[0]
        deltaHour=abs(datetime.now().hour - int(rowHourInString))
        normalizedDeltaHour= 1 - 2*(deltaHour/24)
        deltaSpendTime= abs(rowTripDurationinmin-int(spendTime))
        normalizedDeltaSpendTime=  4/(4+deltaSpendTime)
        distance=math.sqrt( (rowStartStationLatitude-rowEndStationLatitude)**2 + (rowStartStationLongitude-rowEndStationLongitude)**2) #auclidian distnace
        normalizedDistance=1/(1+distance)
        return (normalizedDeltaHour+normalizedDeltaSpendTime+normalizedDistance)*100/3 #to get score between 0 and 100

'''
this function is provided for all models who wants to use this backend so they
can alert users on wrong arguments.
:param userStart- the location the user starts in
:param userTime- the time the user wants to spend biking
:param userAmount- the number of wanted results
:return None if no errors else return error text that is informative to user.
'''
def checkUserInput(userStart, userTime, userAmount):
    if userStart=="" or userStart==None:
        return "you did not insert your starting point"
    if userTime=="" or userTime==None:
        return "you did not insert the time you want to spend"
    if userAmount == "" or userAmount == None:
        return "you did not insert the number of wanted location recommendations"
    try:
        userTime=int(userTime)
    except ValueError:
        return "please enter spending time in minutes by numbers only"
    try:
        userAmount=int(userAmount)
    except ValueError:
        return "please enter the number for location recommendation amount"

    if(userTime<1):
        return "we don't offer locations for this riding time"
    if (userAmount < 1):
        return "the number of locations is invalid"
    return None


target = "xilinx"
action = "simulation"
sim_tool = "modelsim"
top_module = "main"
syn_device = "XC6VLX130T"

#files = [ "golay_tb.vhd" ]

#include_dirs = [ "../../sim", "../../sim/wr-hdl" ]

modules = { "local" : ["../"]}
#modules = { "local" : ["../../top/bare_top",
#                       "../../ip_cores/general-cores",
#                       "../../ip_cores/wr-cores"] }

files = [ "main.sv" ]
include_dirs = [ "../sim" ]


description = """
Equilibrium position in an array is a position at which the sum of elements before it is equal to the sum of elements after it. Given an array arr, your task is to determine at which position equilibrium first occurs in the array. If there is no equilibrium position, the answer should be -1.

Example

    For arr = [5], the output should be

    equilibriumPoint(arr) = 1.

    Explanation: Since this array only has one element, the equilibrium point is at position 1.

    For arr = [10, 5, 3, 5, 2, 2, 6, 8], the output should be

    equilibriumPoint(arr) = 4.

    Explanation: The equilibrium point is at position 4, because the sum of elements before it - (10 + 5 + 3) - is equal to the sum of elements after it - (2 + 2 + 6 + 8).

Input/Output

    [time limit] 4000ms (py3)

    [input] array.integer arr

    Guaranteed constraints:

    1 ≤ arr.length ≤ 105,

    -1000 ≤ arr[i] ≤ 1000.

    [output] integer

    The first equilibrium position in arr, or -1.

"""

def test():
    #testeql(equilibriumPoint([2, 3, -5, 100]), 4)
    #testeql(equilibriumPoint([5]), 1)
    #testeql(equilibriumPoint([10, 5, 3, 5, 2, 2, 6, 8]), 4)
    #testeql(equilibriumPoint([2, 3, -5, 100]), 4)
    testeql(equilibriumPoint([1, 3, 5, 2, 3]), -1)

def equilibriumPointTLE(arr):
    # time limit exceeded
    # The reason is that the temporary sums are recomputed at every
    # step, leading to a very inefficient process
    eqPtZeroBased = 0
    while eqPtZeroBased < len(arr):
        if sum(arr[:eqPtZeroBased]) == sum(arr[eqPtZeroBased+1:]):
            return eqPtZeroBased + 1
        eqPtZeroBased += 1
    return -1

def equilibriumPoint(arr):
    eqPtZeroBased = 0
    leftSum = 0
    rightSum = sum(arr) - arr[eqPtZeroBased]

    while eqPtZeroBased < len(arr):
        if leftSum == rightSum:
            return eqPtZeroBased + 1
        elif eqPtZeroBased == len(arr) - 1:
            return -1
        else:
            eqPtZeroBased += 1
            leftSum += arr[eqPtZeroBased-1]
            rightSum -= arr[eqPtZeroBased]
    return -1


from kiutils.symbol import SymbolLib, Symbol, SymbolPin

def print_footprint(PN_dict):
    pin_nr = int(max([int(k) for k in PN_dict["pins"].keys()])) # get the nr of pins
    return_string = []
    left_pins_max_length = max([len(PN_dict["pins"][str(k+1)]) for k in range(pin_nr//2)])
    left_pin_nr_length = len(str(pin_nr//2))
    right_pin_nr_length = len(str(pin_nr))
    for k in range(pin_nr//2):
        return_string.append(PN_dict["pins"][str(k+1)].upper().rjust(left_pins_max_length)+' |['+(str(k+1)+']').rjust(left_pin_nr_length+1)+'   '+'['+(str(pin_nr-k)).rjust(right_pin_nr_length)+']| '+PN_dict["pins"][str(pin_nr-k)].upper())

    return_string.insert(0,(' '*(left_pins_max_length))+' +'+('-'*(7+right_pin_nr_length+left_pin_nr_length))+'+')
    return_string.append((' '*(left_pins_max_length))+" +"+('-'*(7+right_pin_nr_length+left_pin_nr_length))+"+")

    for k in return_string:
        print(k)

    return '\n'.join(return_string)

def get_PN_text(ret_dict,PN):
    footprint = (print_footprint(ret_dict[PN]))
    #temp = '#'+PN+'\n' + ('='*len(PN))+'\n\n'
    temp = "*Description*: "+ret_dict[PN]["description"]+'\n\n'
    temp += "*Datasheet*: "+ret_dict[PN]["datasheet"]+'\n\n'
    temp += "*Pinout*: "+'\n'+'\n\n```\n'+footprint+'\n```\n'
    return temp

file_position = "./test/74xx.kicad_sym"

symbolLib = SymbolLib().from_file(file_position)

ret_dict = {}

for k in symbolLib.symbols:
    print(k.entryName)
    print("***********")
    for j in k.units:
        print(j.entryName)
        if(j.entryName not in ret_dict.keys()):
            ret_dict[j.entryName]={}
            ret_dict[j.entryName]["pins"]={}
            ret_dict[j.entryName]["name"]=k.entryName
            ret_dict[j.entryName]["description"]=""
            ret_dict[j.entryName]["datasheet"]=""
            for l in k.properties:
                if(l.key == "Datasheet"):
                    ret_dict[j.entryName]["datasheet"]=l.value
                if(l.key == "ki_description"):
                    ret_dict[j.entryName]["description"]=l.value

        # Finding the pin number
        if(len(j.pins)>0):
            print([int(pnr.number) for pnr in j.pins])
            pin_nr = max([int(pnr.number) for pnr in j.pins])
        #if(pin_nr % 2 != 0):
        #    pin_nr= pin_nr+1 # meaning the last pin is NC, it only holds with DIP or SOP packages

        for i in j.pins:
            ret_dict[j.entryName]["pins"][i.number]=i.name

        for i in range(1,pin_nr):
            if(str(i) not in ret_dict[j.entryName]["pins"].keys()):
                ret_dict[j.entryName]["pins"][str(i)]="NC"

# WRITE Files

for pn in ret_dict.keys():
    try:
        print(pn)
        temp = get_PN_text(ret_dict,pn)
        f = open('./PNs/'+pn+'.md','w')
        f.write(temp)
        f.close()
    except(KeyError):
        print("Error in the keys of "+pn)

print(ret_dict["74LS92"])
temp = get_PN_text(ret_dict,"74LS92")


from channels.routing import route_class
from channels.generic.websockets import JsonWebsocketConsumer
import random
from stroopapp.models import Constants

class TaskTracker(JsonWebsocketConsumer):
    url_pattern = (r'^/tasktracker/(?P<player>[0-9]+)$')

    def prepare_task(self):
        color_text, color_color = random.sample(Constants.colors, 2)
        return {'color_text': color_text,
                'color_color': color_color
                }

    def connect(self, message, **kwargs):
        response = self.prepare_task()
        self.send(response)

    def receive(self, text=None, bytes=None, **kwargs):
        print('ANSWER:', text)
        response = self.prepare_task()

        self.send(response)

channel_routing = [
    route_class(TaskTracker, path=TaskTracker.url_pattern),
]


import requests
import argparse

from bs4 import BeautifulSoup

def get_page(lang_source, lang_target, word):
    url = f"https://context.reverso.net/translation/{lang_source.strip().lower()}-{lang_target.strip().lower()}/{word}"
    headers = {'User-Agent': 'Mozilla/5.0'}
    page = requests.get(url, headers=headers)
    assert page.status_code != 404
    return page

def translation(page):
    soup = BeautifulSoup(page.content, 'html.parser')
    translation_content = soup.find('div', id='translations-content').find_all('a')
    words = []
    for translations in translation_content:
        words.append(translations.text.strip())
    sentences_src, sentences_target = \
        soup.find_all('div', {"class": "src ltr"}), \
        soup.find_all('div', {"class": ["trg ltr", "trg rtl arabic", "trg rtl"]})
    sentences_pair = list(zip(map(lambda sent: sent.text.strip(), sentences_src),
                              map(lambda sent: sent.text.strip(), sentences_target)))
    return words, sentences_pair

def print_translation(words, sentences_pair, lang_target, word):
    print(f"\n{lang_target} Translations:")
    print(words[0])
    print(f"\n{lang_target} Examples:")
    src, trg = sentences_pair[0]
    print(src)
    print(trg)
    with open(f"{word}.txt", 'a', encoding='utf-8') as f:
        f.write(f"{lang_target} Translations:\n{words[0]}\n\n{lang_target} Examples:\n{src}\n{trg}\n\n")

def main():
    parser = argparse.ArgumentParser(description="Multilingual Online Translator")
    parser.add_argument("source", help="Source language")
    parser.add_argument("target", help="Target language")
    parser.add_argument("word", help="Type the word you want to translate. \"all\" for all languages.")
    args = parser.parse_args()
    languages = ["Arabic", "German", "English", "Spanish", "French",
                 "Hebrew", "Japanese", "Dutch", "Polish", "Portuguese",
                 "Romanian", "Russian", "Turkish"]
    lang_source = args.source
    lang_target = args.target
    word = args.word.strip().lower()

    if lang_target != "all":
        try:
            page = get_page(lang_source, lang_target, word)
            words, sentences_pair = translation(page)
            print_translation(words, sentences_pair, lang_target, word)
        except AssertionError:
            print(f"Sorry, unable to find {word}")
        except AttributeError:
            print(f"\nSorry, the program doesn't support {lang_target}\n\n")
        except ConnectionError:
            print("Something wrong with your internet connection")
    else:
        for lang in languages:
            if lang.lower() == lang_source:
                continue
            try:
                page = get_page(lang_source, lang, word)
                words, sentences_pair = translation(page)
                print_translation(words, sentences_pair, lang, word)
            except AssertionError:
                print(f"Sorry, unable to find {word}")
            except AttributeError:
                print(f"\nSorry, the program doesn't support {lang_target}\n\n")

if __name__ == '__main__':
    main()


import collections
import math
import copy

import pyexcel_ods3
import pyexcel_xls

from openglider.glider.cell import DiagonalRib
from openglider.utils.table import Table

class GliderSpreadsheet(object):
    """
    Tabular representation of a glider for easy manipulation
    """
    def __init__(self, glider2d):
        self.glider2d = glider2d
        self.sheets = collections.OrderedDict([
            ("Geometry", Table()),
            ("Cell Elements", Table()),
            ("Rib Elements", Table()),
            ("Airfoils", Table()),
            ("Balloonings", Table()),
            ("Parametric", Table()),
            ("Lines", Table()),
            ("Data", Table())
        ])

    @classmethod
    def read_ods(cls, filepath):
        data = pyexcel_ods3.get_data(filepath)
        return cls.from_dict(data)

    @classmethod
    def read_xls(cls, filepath):
        data =pyexcel_xls.get_data(filepath)
        return cls.from_dict(data)

    @classmethod
    def from_dict(cls, dct):
        # unpack sheets:
        pass

    def update(self):
        self.set_geometry()
        self.set_cell_parts()
        self.set_rib_parts()
        #self.set_lines()
        #self.set_airfoils()
        #self.set_balloonings()
        #self.set_parametric()
        #self.set_data()

    def set_geometry(self):
        header = ["Ribs", "Chord", "Le x (m)", "Le y (m)", "Arc", "AOA", "Z-rotation", "Y-rotation", "profile-merge", "ballooning-merge"]
        geometry = [header]
        shape = self.glider2d.shape.get_half_shape()
        arc_angles_rad = self.glider2d.arc.get_cell_angles(self.glider2d.shape.rib_x_values) + [0]
        arc_angles = [0] + [angle*180/math.pi for angle in arc_angles_rad]

        aoa_int = self.glider2d.aoa.interpolation(num=100)
        profile_int = self.glider2d.profile_merge_curve.interpolation(num=100)
        ballooning_int = self.glider2d.ballooning_merge_curve.interpolation(num=100)

        for rib_no, x in enumerate(self.glider2d.shape.rib_x_values):
            chord = shape.chords[rib_no]
            front = shape.front[rib_no]
            x = front[0]
            y = -front[1]
            arc_diff = arc_angles[rib_no+1] - arc_angles[rib_no]

            row = [rib_no+1,
                   float(chord),
                   float(x),
                   float(y),
                   float(arc_diff),
                   float(aoa_int(x)*180/math.pi),
                   0,
                   0,
                   float(profile_int(x)),
                   float(ballooning_int(x))]

            geometry.append(row)

        self.sheets["Geometry"] = geometry

    @staticmethod
    def _get_columns(name, row_num, col_num):
        lst = [["" for i in range(row_num+1)] for j in range(col_num)]
        lst[0][0] = name
        return lst

    def set_cell_parts(self):

        row_num = self.glider2d.shape.half_cell_num
        elems = self.glider2d.elements

        columns = [["Cell No."] + [i+1 for i in range(row_num)]]

        # cuts
        # group by type
        cut_types = {}
        for cut in elems["cuts"]:
            cut_type = cut["type"]
            cut_types.setdefault(cut_type, [[]]*row_num)
            for cell_no in cut["cells"]:
                cut_types[cut_type][cell_no].append(copy.copy(cut))

        for cut_type, cells in cut_types.items():
            while any(len(cell) for cell in cells):
                columns_cut = self._get_columns(cut_type, row_num, 2)

                def find_next(x_last=None, cell_start=0):
                    for i, cuts in enumerate(cells[cell_start:]):
                        for cut in cuts:
                            if cut["left"] == x_last or x_last is None:
                                cuts.remove(cut)
                                return cell_start+i, cut

                res = find_next()

                while res:
                    cell_no, cut = res
                    columns_cut[0][cell_no+1] = cut["left"]
                    columns_cut[1][cell_no+1] = cut["right"]

                    res = find_next(cut["right"], cell_no+1)

                columns += columns_cut

        # Diagonals
        for diagonal in elems["diagonals"]:
            diagonal = copy.copy(diagonal)
            cols = self._get_columns("QR", row_num, 6)

            cells = diagonal.pop("cells")
            _diagonal = DiagonalRib(**diagonal)

            for cell_no in cells:
                # center_left, center_right, width_left, width_right, height_left, height_right

                cols[0][cell_no+1] = _diagonal.center_left
                cols[1][cell_no+1] = _diagonal.center_right
                cols[2][cell_no+1] = _diagonal.width_left
                cols[3][cell_no+1] = _diagonal.width_right
                cols[4][cell_no+1] = _diagonal.left_front[1]
                cols[5][cell_no+1] = _diagonal.right_front[1]

            columns += cols

        # Straps
        for strap in elems["straps"]:
            cols = self._get_columns("VEKTLAENGE", row_num, 2)
            for cell_no in strap["cells"]:
                cols[0][cell_no+1] = strap["left"]
                cols[0][cell_no+1] = strap["right"]

        # Material
        max_parts = max([len(c) for c in elems["materials"]])
        cols = [["MATERIAL"] + ["" for i in range(row_num)] for j in range(max_parts)]

        for cell_no, cell in enumerate(elems["materials"]):
            for part_no, part in enumerate(cell):
                cols[part_no][cell_no+1] = part

        columns += cols

        self.sheets["Cell Elements"] = list(zip(*columns))

    def set_rib_parts(self):

        row_num = self.glider2d.shape.half_cell_num + 1
        elems = self.glider2d.elements
        columns = [["Rib No."] + [i+1 for i in range(row_num)]]

        # holes
        for hole in elems["holes"]:
            hole_cols = self._get_columns("HOLE", row_num, 2)
            for rib_no in hole["ribs"]:
                hole_cols[0][rib_no+1] = hole["pos"]
                hole_cols[1][rib_no+1] = hole["size"]

            columns += hole_cols

        # attachment points
        per_rib = [self.glider2d.lineset.get_upper_nodes(rib_no) for rib_no in range(self.glider2d.shape.half_rib_num)]
        max_points = max([len(p) for p in per_rib])
        header = ["AHP", "", ""] * max_points
        attachment_points = [header]

        for rib_no, nodes in enumerate(per_rib):
            nodes.sort(key=lambda node: node.rib_pos)
            row = ["", "", ""] * max_points
            for node_no, node in enumerate(nodes):
                row[node_no*3] = node.name
                row[node_no*3+1] = node.rib_pos
                row[node_no*3+2] = node.force
            attachment_points.append(row)

        columns += list(zip(*attachment_points))

        # rigidfoils
        rigidfoils = elems.get("rigidfoils", [])
        rigidfoils.sort(key=lambda r: r["start"])
        for rigidfoil in rigidfoils:
            rigid_cols = self._get_columns("RIGIDFOIL", row_num, 3)
            for rib_no in rigidfoil["ribs"]:
                rigid_cols[0][rib_no+1] = rigidfoil["start"]
                rigid_cols[1][rib_no+1] = rigidfoil["end"]
                rigid_cols[2][rib_no+1] = rigidfoil["distance"]

            columns += rigid_cols

        self.sheets["Rib Elements"] = list(zip(*columns))

    def set_lines(self):
        table = self.glider2d.lineset.get_table()
        self.sheets["Lines"] = table

    def set_airfoils(self):
        table = Table()
        for airfoil in self.glider2d.profiles:
            x = [p[0] for p in airfoil]
            y = [p[1] for p in airfoil]

            x.insert(0, airfoil.name)
            y.insert(0, "")

            table.add_columns(x, y)

        self.sheets["Airfoils"] = table

    def set_balloonings(self):
        table = Table()
        for ballooning in self.glider2d.balloonings:
            upper = ballooning.controlpoints[0]
            lower = ballooning.controlpoints[1]

            x = [p[0] for p in upper+lower]
            y = [p[1] for p in upper+lower]

            x.insert(0, ballooning.name or "ballooning")
            y.insert(0, "")

            table.add_columns(x, y)

        self.sheets["Balloonings"] = table

    def _transpose_columns(self, data, name):
        x = [p[0] for p in data]
        y = [p[1] for p in data]
        x.insert(0, name)
        y.insert(0, "")

        return x, y

    def set_parametric(self):
        table = Table()

        table.add_columns(*self._transpose_columns(self.glider2d.arc.curve, "Arc"))
        table.add_columns(*self._transpose_columns(self.glider2d.shape.front_curve, "Front"))
        table.add_columns(*self._transpose_columns(self.glider2d.shape.back_curve, "Back"))
        table.add_columns(*self._transpose_columns(self.glider2d.shape.rib_distribution, "Dist"))
        table.add_columns(*self._transpose_columns(self.glider2d.aoa, "AOA"))
        table.add_columns(*self._transpose_columns(self.glider2d.profile_merge_curve, "Profile_merge"))
        table.add_columns(*self._transpose_columns(self.glider2d.ballooning_merge_curve, "Ballooning_merge"))

        self.sheets["Parametric"] = table

    def set_data(self):
        data = {
            "SPEED": self.glider2d.speed,
            "GLIDE": self.glider2d.glide,
            "CELLS": self.glider2d.shape.cell_num
        }

        self.sheets["Data"] = data.items()

    def write_ods(self, filepath):
        pyexcel_ods3.save_data(filepath, self.sheets)


"""LambdaResolverDataSource module."""

# Standard library imports
import textwrap

# Related third party imports
from aws_cdk import (
    aws_appsync as appsync,
    aws_lambda as lambda_,
    core,
)

# Local application/library specific imports
# -

class LambdaResolverDataSource(core.Construct):
    """Construct for a Lambda Resolver and Data Source."""

    def __init__(
        self,
        scope: core.Construct,
        construct_id: str,
        params,
    ) -> None:
        """Initialize LambdaResolverDataSource Class."""
        super().__init__(scope, construct_id)

        # Create the Lambda Function
        self.function = lambda_.Function(
            scope=self,
            id=f'{construct_id}-function',
            function_name=construct_id,
            runtime=lambda_.Runtime.PYTHON_3_8,
            code=lambda_.Code.asset('playground_api'),
            handler=f"lambda_handler.{params['lambda_handler']}",
            environment=params['environment'] or {},
        )

        # Create a Data Source for this function
        data_source = appsync.LambdaDataSource(
            scope=self,
            id=f'{construct_id}_data_source'.replace('-', '_'),  # No dashes allowed
            lambda_function=self.function,
            api=params['api'],
        )

        # Create the request mapping template with the provided scopes
        required_scopes = "', '".join(params['required_scopes'])
        scope_check_template = textwrap.dedent(
            """\
                #set($requiredScopes = ['{required_scopes}'])
                #set($userScopes = $context.identity.claims.get("scope").split(" "))

                #foreach ($requiredScope in $requiredScopes)
                    #if(!$userScopes.contains($requiredScope))
                        $utils.error("Scope '$requiredScope' is required")
                    #end
                #end
                {
                    "version" : "2017-02-28",
                    "operation": "Invoke",
                    "payload": {
                        "arguments": $util.toJson($context.args),
                        "selectionSetList": $utils.toJson($context.info.selectionSetList)
                    }
                }
            """
        ).replace('{required_scopes}', required_scopes)

        # Bring it all together in a resolver. This will attach the Lambda Data Source
        # and Request Template to the given field in the GraphQL Schema.
        data_source.create_resolver(
            type_name=params['type_name'],
            field_name=params['field_name'],
            request_mapping_template=appsync.MappingTemplate.from_string(
                template=scope_check_template
            )
        )


import requests
from .models import TestResponse
from typing import Union,Dict

class Test():
    def get(self,url:str,headers:Dict[str,Union[str,int,float,bytes]],encoding:str) -> Union[TestResponse,str]:
        try:
            response = requests.get(url=url, headers=headers)
            response.encoding = encoding
            return TestResponse(_content=response)
        except Exception as e:
            return "error:%s" % str(e)

    def post(self,url:str,data:Dict[str,Union[str,int,float,bytes]],headers:Dict[str,Union[str,int,float,bytes]],encoding:str) -> Union[TestResponse,str]:
        try:

            proxies = {
                "http": "http://82.114.93.210:8080"
            }
            response = requests.post(url=url, headers=headers, data=data,proxies=proxies)
            response.encoding = encoding
            return TestResponse(_content=response)
        except Exception as e:
            return "error:%s" % str(e)


from __future__ import print_function

import csv

def read_csv(filename, constructor):
    fp = open(filename)
    reader = csv.reader(fp)

    header = next(reader)
    names = [s.lower() for s in header]

    objs = [make_object(t, names, constructor) for t in reader]
    fp.close()

    return objs

def write_csv(filename, header, data):
    fp = open(filename, "w")
    writer = csv.writer(fp)
    writer.writerow(header)

    for t in data:
        writer.writerow(t)
    fp.close()

def print_cols(cols):
    for i, col in enumerate(cols):
        print(i, col[0], col[1])

def make_col_dict(cols, names):
    col_dict = {}
    for name, col in zip(names, cols):
        col_dict[name] = col
    return col_dict

def make_object(row, names, constructor):
    obj = constructor()
    for name, val in zip(names, row):
        func = constructor.convert.get(name, int)
        try:
            val = func(val)
        except:
            pass
        setattr(obj, name, val)
    obj.clean()
    return obj


from flask import current_app
from sqlalchemy import text

from api.models import CodeTableVersioned
from api.utils.helpers import find_model_from_table_name

class CodeService:
    """Service to manage Fee related operations."""

    @classmethod
    def find_code_values_by_type(
            cls,
            code_type: str,
            filters: dict = {}
    ):  # pylint: disable=dangerous-default-value
        """Find code values by code type."""
        current_app.logger.debug(f'<find_code_values_by_type : {code_type}')
        model: CodeTableVersioned = find_model_from_table_name(code_type)
        response = {'codes': []}
        filters = {k: v for k, v in filters.items() if hasattr(model, k)}
        order_by_fields = ["id"]
        if hasattr(model, 'is_active'):
            filters['is_active'] = True
        if hasattr(model, 'is_deleted'):
            filters['is_deleted'] = False
        if hasattr(model, 'sort_order'):
            order_by_fields.insert(0, "sort_order")
        for row in model.query.filter_by(**filters).order_by(text(",".join(order_by_fields))):
            response['codes'].append(row.as_dict())

        current_app.logger.debug('>find_code_values_by_type')
        return response

    @classmethod
    def find_code_value_by_type_and_code(
            cls,
            code_type: str,
            code: str
    ):
        """Find code values by code type and code."""
        current_app.logger.debug(f'<find_code_value_by_type_and_code : {code_type} - {code}')
        model: CodeTableVersioned = find_model_from_table_name(code_type)
        current_app.logger.debug('>find_code_value_by_type_and_code')
        return model.find_by_id(code).as_dict()


#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
# All Functions created by ApTr13 for obtaining the results of a Swiss Tournamnet

import psycopg2
from contextlib import contextmanager

def connect():
    """Connect to the PostgreSQL database.  Returns a database connection."""
    try:
        return psycopg2.connect("dbname=tournament")
    except:
        print("Oops.... Connection Failed :(")

"""***
TRIED IMPLEMENTING THIS CURSOR FUNCTION AS SUGGESTED BY PROJECT REVIEWER...
BUT IT PRODUCED MANY ERRORS...
WILL SURELY WORKOUT function decorators & contextlib IN NEAR FUTURE..
THANKS... :D
***
@contextmanager
def get_cursor():
    DB = connect()
    a = DB.cursor()
    try:
        yield a
    except:
        print "Error connecting to Cursor in psql...."
    else:
        DB.commit()
    finally:
        a.close()
        DB.close()
"""

def deleteMatches():
    """Remove all the match records from the database."""
    DB = connect()
    a = DB.cursor()
    a.execute("DELETE FROM Matches")
    DB.commit()
    DB.close()

def deletePlayers():
    """Remove all the player records from the database."""
    DB = connect()
    a = DB.cursor()
    a.execute("DELETE FROM Players")
    DB.commit()
    DB.close()

def countPlayers():
    """Returns the number of players currently registered."""
    DB = connect()
    a = DB.cursor()
    a.execute("SELECT count(*) as num FROM Players")
    count = a.fetchall()
    DB.close()
    return count[0][0]

def registerPlayer(name):
    """Adds a player to the tournament database.

    The database assigns a unique serial id number for the player.  (This
    should be handled by your SQL database schema, not in your Python code.)

    Args:
      name: the player's full name (need not be unique).
    """
    DB = connect()
    a = DB.cursor()
    a.execute("INSERT INTO Players (Name) VALUES (%s)",(name,))
    DB.commit()
    DB.close()

def playerStandings():
    """Returns a list of the players and their win records, sorted by wins.

    The first entry in the list should be the player in first place, or a player
    tied for first place if there is currently a tie.

    Returns:
      A list of tuples, each of which contains (id, name, wins, matches):
        id: the player's unique id (assigned by the database)
        name: the player's full name (as registered)
        wins: the number of matches the player has won
        matches: the number of matches the player has played
    """
    """
        THIS QUERY WORKS ON VIEWS. TWO VIEWS *Wins* & *Loses*
        COMBINED TO GET RESULTS IN THE VIEW *Standings*
    """
    DB = connect()
    a = DB.cursor()
    a.execute("SELECT * FROM Standings")
    b = a.fetchall()
    DB.close()
    return b

def reportMatch(winner, loser):
    """Records the outcome of a single match between two players.

    Args:
      winner:  the id number of the player who won
      loser:  the id number of the player who lost
    """
    DB = connect()
    a = DB.cursor()
    a.execute("INSERT INTO Matches (WinID, LoseID) VALUES (%s,%s)",(winner, loser,))
    DB.commit()
    DB.close()

def swissPairings():
    """Returns a list of pairs of players for the next round of a match.

    Assuming that there are an even number of players registered, each player
    appears exactly once in the pairings.  Each player is paired with another
    player with an equal or nearly-equal win record, that is, a player adjacent
    to him or her in the standings.

    Returns:
      A list of tuples, each of which contains (id1, name1, id2, name2)
        id1: the first player's unique id
        name1: the first player's name
        id2: the second player's unique id
        name2: the second player's name
    """
    """
        FIRST A TEMPORARY VIEW *Swiss* IS CREATED, FROM WHICH
        THE GIVEN SELECT QUERY FILTERS THE PAIRINGS

        The Temporary view is created so that Serial number (Sr) can be used
        for the conditions in WHERE clause to create tuples with two ids &
        two names of players at nearly-equally position in table.
    """
    DB = connect()
    a = DB.cursor()
    a.execute("SELECT a.Id, a.Name, b.Id, b.Name FROM Swiss as a, Swiss as b WHERE b.Sr = a.Sr + 1 AND a.Sr%2 = 1 ")
    b = a.fetchall()
    DB.close()
    return b


"""Tests for the legacy Protocol API module core implementations."""
import pytest
from decoy import Decoy

from opentrons.types import Location, Point
from opentrons.drivers.types import HeaterShakerLabwareLatchStatus
from opentrons.hardware_control import SynchronousAdapter, SyncHardwareAPI
from opentrons.hardware_control.types import Axis
from opentrons.hardware_control.modules import HeaterShaker
from opentrons.hardware_control.modules.types import (
    HeaterShakerModuleModel,
    TemperatureStatus,
    SpeedStatus,
)
from opentrons.protocol_api.core.legacy.module_geometry import (
    HeaterShakerGeometry,
)
from opentrons.protocol_api.core.legacy.legacy_protocol_core import (
    LegacyProtocolCore,
)
from opentrons.protocol_api.core.legacy.legacy_module_core import (
    LegacyHeaterShakerCore,
    create_module_core,
    CannotPerformModuleAction,
    NoTargetTemperatureSetError,
)

SyncHeaterShakerHardware = SynchronousAdapter[HeaterShaker]

@pytest.fixture
def mock_geometry(decoy: Decoy) -> HeaterShakerGeometry:
    """Get a mock heater-shaker geometry."""
    return decoy.mock(cls=HeaterShakerGeometry)

@pytest.fixture
def mock_sync_module_hardware(decoy: Decoy) -> SyncHeaterShakerHardware:
    """Get a mock module hardware control interface."""
    return decoy.mock(name="SyncHeaterShakerHardware")  # type: ignore[no-any-return]

@pytest.fixture
def mock_sync_hardware_api(decoy: Decoy) -> SyncHardwareAPI:
    """Get a mock sync hardware API."""
    return decoy.mock(cls=SyncHardwareAPI)

@pytest.fixture
def mock_protocol_core(
    decoy: Decoy, mock_sync_hardware_api: SyncHardwareAPI
) -> LegacyProtocolCore:
    """Get a mock protocol core."""
    mock_protocol_core = decoy.mock(cls=LegacyProtocolCore)
    decoy.when(mock_protocol_core.get_hardware()).then_return(mock_sync_hardware_api)
    return mock_protocol_core

@pytest.fixture
def subject(
    mock_geometry: HeaterShakerGeometry,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    mock_protocol_core: LegacyProtocolCore,
) -> LegacyHeaterShakerCore:
    """Get a legacy module implementation core with mocked out dependencies."""
    return LegacyHeaterShakerCore(
        requested_model=HeaterShakerModuleModel.HEATER_SHAKER_V1,
        geometry=mock_geometry,
        sync_module_hardware=mock_sync_module_hardware,
        protocol_core=mock_protocol_core,
    )

def test_create(
    decoy: Decoy,
    mock_geometry: HeaterShakerGeometry,
    mock_protocol_core: LegacyProtocolCore,
) -> None:
    """It should be able to create a magnetic module core."""
    mock_module_hardware_api = decoy.mock(cls=HeaterShaker)
    result = create_module_core(
        geometry=mock_geometry,
        module_hardware_api=mock_module_hardware_api,
        requested_model=HeaterShakerModuleModel.HEATER_SHAKER_V1,
        protocol_core=mock_protocol_core,
    )

    assert isinstance(result, LegacyHeaterShakerCore)

def test_get_current_temperature(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should report the current temperature."""
    decoy.when(mock_sync_module_hardware.temperature).then_return(42.0)
    result = subject.get_current_temperature()
    assert result == 42.0

def test_get_target_temperature(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should report the target temperature."""
    decoy.when(mock_sync_module_hardware.target_temperature).then_return(42.0)
    result = subject.get_target_temperature()
    assert result == 42.0

def test_get_temperature_status(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should report the temperature status."""
    decoy.when(mock_sync_module_hardware.temperature_status).then_return(
        TemperatureStatus.COOLING
    )
    result = subject.get_temperature_status()
    assert result == TemperatureStatus.COOLING

def test_get_current_speed(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should report the current speed."""
    decoy.when(mock_sync_module_hardware.speed).then_return(321)
    result = subject.get_current_speed()
    assert result == 321

def test_get_target_speed(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should report the target speed."""
    decoy.when(mock_sync_module_hardware.target_speed).then_return(321)
    result = subject.get_target_speed()
    assert result == 321

def test_get_speed_status(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should report the speed status."""
    decoy.when(mock_sync_module_hardware.speed_status).then_return(
        SpeedStatus.ACCELERATING
    )
    result = subject.get_speed_status()
    assert result == SpeedStatus.ACCELERATING

def test_get_labware_latch_status(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should report the labware latch status."""
    decoy.when(mock_sync_module_hardware.labware_latch_status).then_return(
        HeaterShakerLabwareLatchStatus.OPENING
    )
    result = subject.get_labware_latch_status()
    assert result == HeaterShakerLabwareLatchStatus.OPENING

def test_set_target_temperature(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should set the target temperature with the hardware."""
    subject.set_target_temperature(42.0)

    decoy.verify(mock_sync_module_hardware.start_set_temperature(42.0), times=1)

def test_wait_for_target_temperature(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should wait for the target temperature with the hardware."""
    decoy.when(subject.get_target_temperature()).then_return(42.0)

    subject.wait_for_target_temperature()

    decoy.verify(mock_sync_module_hardware.await_temperature(42.0), times=1)

def test_wait_for_temperature_no_target(
    decoy: Decoy,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should raise a NoTargetTemperatureSetError."""
    decoy.when(subject.get_target_temperature()).then_return(None)

    with pytest.raises(NoTargetTemperatureSetError):
        subject.wait_for_target_temperature()

def test_set_and_wait_for_shake_speed(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    mock_geometry: HeaterShakerGeometry,
    mock_sync_hardware_api: SyncHardwareAPI,
    mock_protocol_core: LegacyProtocolCore,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should set and wait for the target speed with the hardware."""
    decoy.when(subject.get_labware_latch_status()).then_return(
        HeaterShakerLabwareLatchStatus.IDLE_CLOSED
    )
    decoy.when(mock_protocol_core.get_last_location()).then_return(
        Location(point=Point(x=1, y=2, z=3), labware=None)
    )
    decoy.when(
        mock_geometry.is_pipette_blocking_shake_movement(
            Location(point=Point(x=1, y=2, z=3), labware=None)
        )
    ).then_return(True)

    subject.set_and_wait_for_shake_speed(1337)

    decoy.verify(
        mock_sync_hardware_api.home(axes=[Axis.Z, Axis.A]),
        mock_protocol_core.set_last_location(None),
        mock_sync_module_hardware.set_speed(rpm=1337),
    )

def test_set_and_wait_for_shake_speed_no_prep(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    mock_geometry: HeaterShakerGeometry,
    mock_sync_hardware_api: SyncHardwareAPI,
    mock_protocol_core: LegacyProtocolCore,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should set and wait for the target speed with the hardware."""
    decoy.when(subject.get_labware_latch_status()).then_return(
        HeaterShakerLabwareLatchStatus.IDLE_CLOSED
    )
    decoy.when(mock_protocol_core.get_last_location()).then_return(
        Location(point=Point(x=1, y=2, z=3), labware=None)
    )
    decoy.when(
        mock_geometry.is_pipette_blocking_shake_movement(
            Location(point=Point(x=1, y=2, z=3), labware=None)
        )
    ).then_return(False)

    subject.set_and_wait_for_shake_speed(1337)

    decoy.verify(mock_sync_hardware_api.home(axes=[Axis.Z, Axis.A]), times=0)
    decoy.verify(mock_sync_module_hardware.set_speed(rpm=1337), times=1)

@pytest.mark.parametrize(
    "latch_status",
    [
        HeaterShakerLabwareLatchStatus.IDLE_UNKNOWN,
        HeaterShakerLabwareLatchStatus.UNKNOWN,
        HeaterShakerLabwareLatchStatus.CLOSING,
        HeaterShakerLabwareLatchStatus.IDLE_OPEN,
        HeaterShakerLabwareLatchStatus.OPENING,
    ],
)
def test_set_and_wait_for_shake_speed_raises(
    decoy: Decoy,
    latch_status: HeaterShakerLabwareLatchStatus,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should raise a CannotPerformModuleAction when latch is not closed."""
    decoy.when(subject.get_labware_latch_status()).then_return(latch_status)

    with pytest.raises(CannotPerformModuleAction):
        subject.set_and_wait_for_shake_speed(rpm=1337)

def test_open_labware_latch(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    mock_geometry: HeaterShakerGeometry,
    mock_sync_hardware_api: SyncHardwareAPI,
    mock_protocol_core: LegacyProtocolCore,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should open the labware latch with the hardware."""
    decoy.when(subject.get_speed_status()).then_return(SpeedStatus.IDLE)
    decoy.when(mock_protocol_core.get_last_location()).then_return(
        Location(point=Point(x=1, y=2, z=3), labware=None)
    )
    decoy.when(
        mock_geometry.is_pipette_blocking_latch_movement(
            Location(point=Point(x=1, y=2, z=3), labware=None)
        )
    ).then_return(True)

    subject.open_labware_latch()

    decoy.verify(
        mock_sync_hardware_api.home(axes=[Axis.Z, Axis.A]),
        mock_protocol_core.set_last_location(None),
        mock_sync_module_hardware.open_labware_latch(),
    )

def test_open_labware_latch_no_prep(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    mock_geometry: HeaterShakerGeometry,
    mock_sync_hardware_api: SyncHardwareAPI,
    mock_protocol_core: LegacyProtocolCore,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should open the labware latch with the hardware."""
    decoy.when(subject.get_speed_status()).then_return(SpeedStatus.IDLE)
    decoy.when(mock_protocol_core.get_last_location()).then_return(
        Location(point=Point(x=1, y=2, z=3), labware=None)
    )
    decoy.when(
        mock_geometry.is_pipette_blocking_latch_movement(
            Location(point=Point(x=1, y=2, z=3), labware=None)
        )
    ).then_return(False)

    subject.open_labware_latch()

    decoy.verify(mock_sync_hardware_api.home(axes=[Axis.Z, Axis.A]), times=0)
    decoy.verify(
        mock_sync_module_hardware.open_labware_latch(),
        times=1,
    )

@pytest.mark.parametrize(
    "speed_status",
    [
        SpeedStatus.DECELERATING,
        SpeedStatus.ACCELERATING,
        SpeedStatus.HOLDING,
        SpeedStatus.ERROR,
    ],
)
def test_open_labware_latch_raises(
    decoy: Decoy,
    speed_status: SpeedStatus,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should raise a CannotPerformModuleAction when heater-shaker is not idle."""
    decoy.when(subject.get_speed_status()).then_return(speed_status)

    with pytest.raises(CannotPerformModuleAction):
        subject.open_labware_latch()

def test_close_labware_latch(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should close the labware latch with the hardware."""
    subject.close_labware_latch()

    decoy.verify(mock_sync_module_hardware.close_labware_latch(), times=1)

def test_deactivate_shaker(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should stop shaking with the hardware."""
    subject.deactivate_shaker()

    decoy.verify(mock_sync_module_hardware.deactivate_shaker(), times=1)

def test_deactivate_heater(
    decoy: Decoy,
    mock_sync_module_hardware: SyncHeaterShakerHardware,
    subject: LegacyHeaterShakerCore,
) -> None:
    """It should stop heating with the hardware."""
    subject.deactivate_heater()

    decoy.verify(mock_sync_module_hardware.deactivate_heater(), times=1)


# type: ignore
import setuptools

# read description from README.md
with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

data_files = []

setuptools.setup(
    name="zxlive",
    version="0.1",
    author="Aleks Kissinger",
    author_email="aleks0@gmail.com",
    description="An interactive tool for the ZX calculus",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/Quantomatic/zxlive",
    project_urls={
        "Bug Tracker": "https://github.com/Quantomatic/zxlive/issues",
    },
    license="Apache2",
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: Apache Software License",
        "Operating System :: OS Independent",
    ],
    packages=["zxlive"],
    package_data={'': ['*.svg']},
    data_files=data_files,
    install_requires=["PySide2>=5.14", "pyzx>=0.7.3"],
    python_requires=">=3.7",
    entry_points={'console_scripts': 'zxlive=zxlive.app:main'},
)


#!/usr/bin/env python
import Tkinter as tk
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(13 , GPIO.OUT)
master = tk.Tk()
master.title('LED_Control1')
master.geometry("300x100")
LED_STATE = False
def onoff():
	global LED_STATE
	if LED_STATE == True:
		LED_STATE = False
	else:
		LED_STATE = True
	GPIO.output(13 , LED_STATE)
button = tk.Button(master , text = 'Press to turn on / off' , bg = 'blue' , command = onoff).pack()
master.mainloop()


#!/usr/bin/python
# -*- coding: UTF-8 -*-
import numpy as np
import pygame as pg
import Common
import PopupBase as PB
import ButtonBase as BB

class LevelSelectPopup(PB.PopupBase):
	def __init__(self,):
		super(LevelSelectPopup, self).__init__();

	def initBtns(self):
		PB.PopupBase.initBtns(self);
		btnPos = [(200,220),(400,220),(200,300),(400,300)];
		for level in range(0,4):
			btnLabelStr = Common.LEVELSTR[level];
			levelBtn = BB.ButtonBase("btn_1.png",self.onLevelBtnClicked,callbackData={'level':level},btnLabelStr=btnLabelStr);
			self.addChildNode(self,levelBtn,btnPos[level],"center");

	def initBg(self):
		PB.PopupBase.initBg(self);
		secondBgFileName_ = Common.initFileNameInDir(self.imageDir_,"newGamePopup.png");
		backg2 = pg.image.load(secondBgFileName_);
		rectObj = backg2.get_rect();
		rectObj.center = (300, 200);
		self.blit(backg2,rectObj);

	def initContent(self):
		fontFile = Common.initFileNameInDir(Common.initFileNameInDir(Common.WORKDIR,"fonts"),"Assimilate.TTF");
		fontObj = pg.font.Font(fontFile, 46);
		textSurfaceObj = fontObj.render("New Game", True, (0,0,0));
		textRectObj = textSurfaceObj.get_rect();
		textRectObj.center = (300, 140);
		self.blit(textSurfaceObj,textRectObj);

	def onLevelBtnClicked(self,data):
		self.destroy();
		import GameEventBroadcaster as GB
		broadcaster = GB.GameEventBroadcaster.getControler();
		broadcaster.envokeEvent("GAME_EVENT_NEW_GAME",data);


#!/usr/bin/python3

"""Creating a function."""

def text_indentation(text):
    """Defining a function that prints a text with
    2 new lines after each of these characters: ., ? and :
    """
    if not isinstance(text, str):
        raise TypeError("text must be a string")
    s = text[:]
    for d in ".?:":
        list_ = s.split(d)
        s = ""
        for i in list_:
            i = i.strip(" ")
            s = i + d if s == "" else s + "\n\n" + i + d
    print(s[:-3], end="")


import numpy as np
import pandas as pd
from abc import ABC, abstractmethod

class SegmentationPairwiseMetric(ABC):
	@staticmethod
	def _check_header(s: pd.DataFrame):
		if s.columns[:3].tolist() != ["chr", 'start', 'end']:
			raise ValueError("Segmentation comparison is available only between dataframes containing 'chr', 'start' and 'end' columns")

	@abstractmethod
	def compare_segments(self, s1: pd.DataFrame, s2: pd.DataFrame):
		pass

	def compare(self,
				s1: pd.DataFrame,
				s2: pd.DataFrame,
				by_chrom=False,
				estimator=None):
		self._check_header(s1)
		self._check_header(s2)
		result = {}
		for chrom in set(s1.chr).intersection(set(s2.chr)):
			chrom_metric = self.compare_segments(s1[s1.chr == chrom], s2[s2.chr == chrom])
			result[chrom] = chrom_metric
		if by_chrom:
			return result
		else:
			vals = list(result.values())
			if estimator is None:
				return np.mean(vals)
			else:
				return estimator(vals)

def moc(cds_p, cds_q):
	"""Measure of concordance between two TAD sets, as defined in https://www.nature.com/articles/s41588-018-0338-y
	If P and Q are two sets of TADs, Np and Nq are the number of TADs in the two sets respectively:

				|-- 1 	if Np = Nq = 1
	MoC(P, Q) = |
				|-- 1 / (SQRT(NpNq) - 1) * (SUM_{i: 1->Np}SUM_{j: 1-> Nq} ( ||Fij||**2 / (||Pi||*||Qj||) )) otherwise

	where Pi and Qj are two individual TADs in P and Q having size ||Pi|| and ||Qj|| respectively (measured in base pairs).
	Finally, ||Fij|| is the size (n. base pairs) of overlap between Pi and Pj.

	This function takes as input two sets of TADs, defined as a list of tuples [(start, end), ...].
	TADs have to belong to the same chromosome, for obvious reasons.
	"""

	def __fill_gaps(tads):
		fills = []
		sorted_tads = sorted(tads, key = lambda x: x[0])
		prev = None
		for t in sorted_tads:
			if prev is not None:
				if t[0] > prev:
					fills.append( (prev, t[0]) )
				elif t[0] < prev:
					raise ValueError(f"Overlapping regions")
			prev = t[1]
		return fills

	def __make_same_limits(tads1, tads2):
		sorted_tads1 = sorted(tads1, key = lambda x: x[0])
		sorted_tads2 = sorted(tads2, key = lambda x: x[0])
		min1, min2 = sorted_tads1[0][0], sorted_tads2[0][0]
		if min1 != min2:
			if min1 < min2:
				sorted_tads2 = [(min1, min2)] + sorted_tads2
			else:
				sorted_tads1 = [(min2, min1)] + sorted_tads1
		max1, max2 = sorted_tads1[-1][1], sorted_tads2[-1][1]
		if max1 != max2:
			if max1 > max2:
				sorted_tads2.append( (max2, max1) )
			else:
				sorted_tads1.append( (max1, max2) )
		return sorted_tads1, sorted_tads2

	def __get_overlap(cd_i, cd_j):
		return max(0, min(cd_i[1], cd_j[1]) - max(cd_i[0], cd_j[0]))

	def __get_size(cd):
		return cd[1] - cd[0]

	def __aggregate_overlaps(cds_p, cds_q):
		r = 0
		for cd_i in cds_p:
			for cd_j in cds_q:
				r += (__get_overlap(cd_i, cd_j)**2)/(__get_size(cd_i)*__get_size(cd_j))
		return r

	cds_p, cds_q = __make_same_limits(cds_p + __fill_gaps(cds_p), cds_q + __fill_gaps(cds_q))
	moc = None
	Np = len(cds_p)
	Nq = len(cds_q)
	if Np == Nq == 1:
		moc = 1
	else:
		moc = (1/(np.sqrt(Np*Nq) - 1))*(__aggregate_overlaps(cds_p, cds_q) - 1)
	return moc

class MeasureOfConcordance(SegmentationPairwiseMetric):

	def compare_segments(self, s1: pd.DataFrame, s2: pd.DataFrame):
		tads1 = list(s1[['start', 'end']].to_records(index=False))
		tads2 = list(s2[['start', 'end']].to_records(index=False))
		return moc(tads1, tads2)


from PyQt4 import QtGui
from datetime import datetime

class FiberPropertiesWindow(QtGui.QDialog):

    def __init__(self, fibers, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self._fibers = fibers
        self.setWindowTitle(self.tr("Fiber Properties"))

        self.nameInput = QtGui.QLineEdit()
        self.authorInput = QtGui.QLineEdit()
        self.crdateLabel = QtGui.QLabel()
        self.tstampLabel = QtGui.QLabel()
        self.descriptionInput = QtGui.QPlainTextEdit()

        formLayout = QtGui.QFormLayout()
        formLayout.addRow(QtGui.QLabel(self.tr("Name")),
                          self.nameInput)
        formLayout.addRow(QtGui.QLabel(self.tr("Author")),
                          self.authorInput)
        formLayout.addRow(QtGui.QLabel(self.tr("Created")),
                          self.crdateLabel)
        formLayout.addRow(QtGui.QLabel(self.tr("Modified")),
                          self.tstampLabel)
        formLayout.addRow(QtGui.QLabel(self.tr("Description")),
                          self.descriptionInput)

        buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok |
                                           QtGui.QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        layout = QtGui.QVBoxLayout()
        layout.addLayout(formLayout)
        layout.addWidget(buttonBox)
        self.setLayout(layout)

    def exec_(self):
        self.nameInput.setText(self._fibers["name"])
        self.authorInput.setText(self._fibers["author"])
        self.crdateLabel.setText(datetime.fromtimestamp(
            self._fibers["crdate"]).strftime('%Y-%m-%d %H:%M:%S'))
        self.tstampLabel.setText(datetime.fromtimestamp(
            self._fibers["tstamp"]).strftime('%Y-%m-%d %H:%M:%S'))
        self.descriptionInput.setPlainText(self._fibers["description"])
        super().exec_()

    def accept(self):
        if self._fibers["name"] != self.nameInput.text():
            self._fibers["name"] = self.nameInput.text()
            self.parent().setDirty(True)
        if self._fibers["author"] != self.authorInput.text():
            self._fibers["author"] = self.authorInput.text()
            self.parent().setDirty(True)
        if self._fibers["description"] != self.descriptionInput.toPlainText():
            self._fibers["description"] = self.descriptionInput.toPlainText()
            self.parent().setDirty(True)
        super().accept()