blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30 values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2 values | text stringlengths 12 5.47M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
313e930d7893d93d0315d453173ab7f8abfc18f7 | Python | DomikIAm/codewars_challenges | /Python/5 kyu/Factorial Decomposition/factorialdecomposition_03.py | UTF-8 | 611 | 3.078125 | 3 | [
"MIT"
] | permissive | def decomp(n):
def is_prime(num):
if num < 2:
return False
for i in range(1, num):
if i == 1:
continue
if num % i == 0:
return False
return True
def sub(num, comps):
for i in comps.keys():
while num % i == 0:
num /= i
comps[i] += 1
comps = {}
for i in range(2, n+1):
if i not in comps.keys() and is_prime(i):
comps[i] = 0
sub(i, comps)
return " * ".join([f"{i}^{j}" if j > 1 else f"{i}" for i, j in comps.items()])
| true |
a9974b6a15d199d9cfb1083b3efdcf67eea6024e | Python | jlyons6100/Wallbreakers | /Week_4/reverse_nodes_in_k_group.py | UTF-8 | 1,530 | 3.359375 | 3 | [] | no_license | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def count_remaining(self, cur):
accum = 0
while(cur != None):
cur = cur.next
accum += 1
return accum
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if k > self.count_remaining(head) or k == 1:
return head
ret = None
prev = None
cur = head
now_last = head
nextt = head.next
remainder = None
for x in range(k):
cur.next = prev
prev = cur
ret = prev
cur = nextt
if cur == None:
return ret
if cur.next == None:
remainder = nextt
nextt = cur.next
while(self.count_remaining(cur) >= k):
prev = None
temp_last = cur
entered_loop = True
for x in range(k):
cur.next = prev
prev = cur
cur = nextt
if cur == None:
break
if cur.next == None:
remainder = nextt
nextt = cur.next
now_last.next = prev
now_last = temp_last
if self.count_remaining(cur) == 0:
pass
elif remainder != None:
now_last.next = remainder
else:
now_last.next = cur
return ret | true |
04dd891084a173ce9744524a8376dfae2e27b92b | Python | kys061/InflearnParallelComputing | /step12_sharing_state_2.py | UTF-8 | 1,298 | 3.109375 | 3 | [] | no_license | from multiprocessing import Process, current_process, Value, Array
import os
# 프로세스 메모리 공유 예제(공유o)
# 실행함수
# 강의 예제에서는 메모리 공유까지만 구현.
# 동기화까지 완료한 코드
def generate_update_number(v: int):
with v.get_lock():
for _ in range(5000):
v.value += 1
print(current_process().name, 'data', v.value)
def main():
# 부모 프로세스 아이디
parent_process_id = os.getpid()
# 출력
print(f'Parent process ID: {parent_process_id}')
# 프로세스 리스트 선언
processes = list()
# 프로세스 메모리 공유 변수
# from multiprocess import shared_memory 사용 가능(파이썬 3.8 이상)
# from multiprocess import Manager 사용 가능
# share_numbers = Array('i', range(50)) # 타입, 초기 값
share_value = Value('i', 0)
for _ in range(1, 10):
# 생성
p = Process(target=generate_update_number, args=(share_value,))
# 배열에 담기
processes.append(p)
# 실행
p.start()
# Join
for p in processes:
p.join()
# 최종 프로세스 부모 변수 확인
print('Final Data in parent process', share_value.value)
if __name__ == '__main__':
main()
| true |
b6fab359604749abc60a0b5ac20dafb130595176 | Python | udovisdevoh/superzebre | /Date.py | UTF-8 | 1,792 | 3.265625 | 3 | [] | no_license | #-*- coding: iso-8859-1 -*-
from Tkinter import *
from datetime import timedelta
import time
import datetime
import os
class Date:
def __init__(self,root,side):
self.date = datetime.date.today()
self.frame = Frame(root)
self.buttonWeekBack = Button(self.frame, text = "<<", bd = 5, command = self.weekBack)
self.buttonBack = Button(self.frame, text = "<", bd = 5, command = self.back)
self.buttonWeekNext = Button(self.frame, text = ">>", bd = 5, command = self.weekNext)
self.buttonNext = Button(self.frame, text = ">", bd = 5, command = self.next)
self.dateText = Text(self.frame,height=1,width = 10)
self.dateText.insert(1.0, self.date)
self.buttonWeekBack.pack(side=LEFT,padx=2)
self.buttonBack.pack(side=LEFT,padx=2)
self.dateText.pack(side=LEFT,padx=2)
self.buttonNext.pack(side=LEFT,padx=2)
self.buttonWeekNext.pack(side=LEFT,padx=2)
self.frame.pack(side=side)
def weekBack(self):
self.date=self.date - timedelta(weeks=1)
self.updateDate()
def back(self):
self.date=self.date - timedelta(days=1)
self.updateDate()
def weekNext(self):
self.date=self.date + timedelta(weeks=1)
self.updateDate()
def next(self):
self.date=self.date + timedelta(days=1)
self.updateDate()
def updateDate(self):
self.dateText.delete(1.0,END)
self.dateText.insert(1.0,self.date)
def getDate(self):
return self.date
def setDate(self,date):
self.date=date
self.updateDate()
if __name__ == "__main__":
root = Tk()
d=Date(root,TOP)
root.mainloop() | true |
5b16b10e064809fa050f605fc83d011efe5e3b93 | Python | MehrinAzan/Scientific_Project | /test.py | UTF-8 | 2,952 | 3.03125 | 3 | [] | no_license | import numpy as np
import cv2
import matplotlib as plt
# Skin thickness
# automized ROI cropping
# mask lines on border
pic1 = imread('pic2_cropped.jpg');
pic1_gray = rgb2gray(pic1) #Convert to grayscale
[height, width] = size(pic1_gray) #Number of rows and columns
% loop to define height of ROI depending on height of image
if height < 0.4*width
maxHeight = height*0.4;
else
maxHeight = height*0.15;
end
maxHeight = fix(maxHeight);
I1 = pic1_gray(1:maxHeight, :); %ROI
Isharp = imsharpen(I1); %sharpen image
%increase contrast
edgeThreshold = 0.9;
amount = 0.4;
Isharp = localcontrast(Isharp, edgeThreshold, amount);
Ig = imgaussfilt(Isharp, 1); %gaussian filtering
Ibin = im2bw(Ig, 110/255); %convert to binary
%-----------------------
% rectangular mask for edges
% to ensure that any holes on the edge are detected as holes
[rowsM, columnsM] = size(Ibin);
lineMask = zeros(rowsM, columnsM);
linHorSE = strel('rectangle', [1, columnsM]); % horizontal line for top
linHor = linHorSE.Neighborhood;
linVer1SE = strel('rectangle',[rowsM, 1]); % vertical line for left egde
linVer1=linVer1SE.Neighborhood;
linVer2SE = strel('rectangle',[rowsM, 1]); % vertical line for right edge
linVer2 = linVer2SE.Neighborhood;
lineMask(1, 1:columnsM) = linHor; % horizontal white line at top
lineMask(1:rowsM, 1) = linVer1; % vertical line edge
lineMask(1:rowsM, columnsM) = linVer2; % vertical line edge
Ibw = Ibin + lineMask; % add mask to binary image
%-------------------------
% clean image
Ibwclean = bwareaopen(Ibw, 400); %remove objects with fewer than 400 pixels
Ibwfill = imfill(Ibwclean, 'holes');
%loops to remove unnecessary objects for eventual sum of pixels
[row,column] = size(Ibwfill);
imgSkin = zeros(row, column); %empty matrix
for ccount=2:(column - 1) %column counter. exclude vertical mask lines
for rcount=1:row %row counter
if Ibwfill(rcount,ccount)== 0
break;
else
imgSkin(rcount,ccount)=Ibwfill(rcount,ccount); % fill empty matrix with returned values
end
end
end
[row2, column2] = size(imgSkin);
sumColumn = sum(imgSkin, 1);
totTh = sum(sumColumn); % total thickness of skin in each column in pixels
averageTh = sum(totTh)/column2; %average thickness of skin in pixels
fprintf('The average skin thickness in pixels is %.3f \n', averageTh);
% ---------------
% display images in steps
figure(1);
subplot(6, 1, 1);
imshow(I1);
title('ROI');
subplot(6,1,2);
imshow(Isharp);
title('with Adjustments');
subplot(6,1,3);
imshow(Ig);
title('with Gaussian Filtering');
subplot(6,1,4);
imshow(Ibw);
% c = 2; r = 15; %starting points for boundary
% boundary = bwtraceboundary(Ibw, [r, c], 'N');
% imshow(Ibw)
% hold on;
% plot(boundary(:,2), boundary(:,1), 'r', 'LineWidth', 3) %display boundary
% hold off
title('Binarized');
subplot(6,1,5);
imshow(Ibwfill);
title('Cleaned image');
subplot(6,1,6);
imshow(imgSkin);
title('ROI - Skin Only');
| true |
0d6b83a559bb6e59843b7513ab0bdc9229884c46 | Python | raulsenaferreira/hackathonRioHeatMap | /twitterCrawler/transformTwitter.py | UTF-8 | 2,709 | 2.921875 | 3 | [
"MIT"
] | permissive | import numpy as np
import pickle
import nltk
def readLocality(locality_path = "../dataset/localidades.csv" ):
file = open(locality_path, "r")
localitys = file.readlines()
localitys = [locality.replace("\n","").strip() for locality in localitys]
return localitys
def stemmingArray(words):
stemmer = nltk.stem.RSLPStemmer()
stemWords = []
for word in words:
word = word.replace("\n","")
try:
if(word != ""):
stemWords.append(stemmer.stem(word))
except:
print("Error in word = %s"%(word))
return stemWords
def comparelocality(locality,text):
if(locality in text):
return True
else:
return False
if __name__ == "__main__":
'''
Variables
'''
filesToRead = ['AlertaAssaltoRJ','alertario24hrs','UNIDOSPORJPA']
stealKeywords= stemmingArray(['Roubo', 'Assalto'])
results = {}
for fname in filesToRead:
with open(fname,'rb') as f:
tweets = pickle.load(f)
localitys = readLocality()
for tweet in tweets:
words = stemmingArray(tweet.text.split(' '))
for word in words:
if(word in stealKeywords):
#print("%s = %s"%(word,stealKeywords))
#print(tweet.text)
for locality in localitys:
if(comparelocality(locality, tweet.text)):
try:
results[locality]
except:
results[locality] = {}
try:
results[locality]["size"] = results[locality]["size"] + 1
except:
results[locality]["size"] = 1
try:
results[locality]["tweet"].append({"date":tweet.created_at,"text":tweet.text})
except:
results[locality]["tweet"] = []
break
break
print(results)
| true |
635b19824e4caaa6fc2d71c6ede4e14da1586cd2 | Python | Dochi3/GubSikChae | /CodeBlock.py | UTF-8 | 2,097 | 2.84375 | 3 | [] | no_license | from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QGridLayout
from PyQt5.QtWidgets import QTextEdit, QLabel
from PyQt5.QtGui import QFontMetrics
import time
class CodeBlock(QWidget):
def __init__(self, parent=None, code=str()):
super().__init__()
self.parent = parent
self.focusedTime = time.time()
# GridLayout for CodeBlock
glCodeBlock = QGridLayout()
# Label for focused
self.lbIsFocused = QLabel(" ")
# Label for Block Execute Number
self.lbBlockNumber = QLabel()
self.lbBlockNumber.setAlignment(Qt.AlignTop)
self.setNumber()
# TextEdit for editing code
self.teCodeBox = QTextEdit()
self.teCodeBox.setMinimumWidth(800)
self.teCodeBox.mousePressEvent = self.mousePressEvent
self.teCodeBox.textChanged.connect(self.fixedHeight)
self.fixedHeight()
glCodeBlock.addWidget(self.lbIsFocused, 0, 0)
glCodeBlock.addWidget(self.lbBlockNumber, 0, 1)
glCodeBlock.addWidget(self.teCodeBox, 0, 2)
self.setCode(code)
self.setLayout(glCodeBlock)
def setNumber(self, num=0):
num = str(num) if num > 0 else str()
text = "bn [" + num + "] : "
self.lbBlockNumber.setText(text)
def mousePressEvent(self, event):
self.focusedTime = time.time()
if self.parent:
self.parent.mousePressEvent(event)
def fixedHeight(self):
nRows = max(self.teCodeBox.toPlainText().count('\n') + 1, 5)
qFontMetrics = QFontMetrics(self.teCodeBox.font())
rowHeight = qFontMetrics.lineSpacing() + 5
self.teCodeBox.setFixedHeight(rowHeight * nRows + 10)
def focusIn(self):
self.lbIsFocused.setStyleSheet("QLabel{ background-color : red;}")
def focusOut(self):
self.lbIsFocused.setStyleSheet("QLabel{ background-color : gray;}")
def getCode(self):
return self.teCodeBox.toPlainText()
def setCode(self, code):
self.teCodeBox.setText(code)
| true |
417f1134df2cd2f9c03567d5cf93776ce82c9bc9 | Python | pravsp/problem_solving | /Python/LinkedList/solution/deletenode.py | UTF-8 | 868 | 3.609375 | 4 | [] | no_license | """Delete node solution except tail."""
import __init__
from singlyLinkedList import SinglyLinkedList
from utils.ll_util import LinkedListUtil
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead
"""
nextnode = node.getNextNode()
if not nextnode:
del node
return
node.data = nextnode.data
node.setNextNode(nextnode.getNextNode())
if __name__ == '__main__':
print('Deleting a node form linked list')
llist = SinglyLinkedList()
LinkedListUtil().constructList(llist)
llist.printList()
dataToDelete = input("Enter Node data to delete:")
node = llist.getNode(int(dataToDelete))
# llist.delNode(int(dataToDelete))
Solution().deleteNode(node)
llist.printList()
| true |
73e15c7513d45432fd89572680fcdb068c5a3d1a | Python | QiuBALL/user_reliability-crowdsourcing- | /Experimentation/cal.py | UTF-8 | 210 | 3.3125 | 3 | [] | no_license | # while True:
# a = float(input())
# b = float(input())
# c = float(input())
#
# print((a+b+c)/ 3)
recall = 0.867
precision = 0.746
f1 = 2 * recall * precision / (precision + recall)
print (f1) | true |
2f8a3a51311f06490ee109df1bf57160f7b81527 | Python | mmilkin/challanges | /ema_supercomputer/ema_tests.py | UTF-8 | 511 | 2.59375 | 3 | [] | no_license | from run import two_pluses
def helper_test(suffix):
with open('test_input/%s.txt' % suffix, 'r') as f:
lines = f.readlines()
n, m = lines[0].strip().split(' ')
grid = [
list(line.strip()) for line in lines[1:]
]
out = two_pluses(grid)
with open('test_input/%s_expected.txt' % suffix, 'r') as f:
lines = f.readlines()
assert out == ''.join(lines)
def test_one():
helper_test("one")
def test_two():
helper_test("two")
| true |
13538ed23a08463ea6e81362da3deebbe2f7647f | Python | xzlmark/python-basic | /数据库操作/MongoDB连接Python.py | UTF-8 | 623 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | from pymongo import MongoClient
from bson.objectid import ObjectId #用于id查询
#连接服务器
conn=MongoClient("localhost",27017)
# 连接数据库
db = conn.mydb
# 获取集合
collection = db.student
# 添加文档,插入一条
collection.insert({'name:abc,'age:30''})
# 添加文档,插入多条
collection.insert([{'name:abc,'age:30''},{'name:xzl,'age:31''}])
conn.close()
'''
查询操作,注意:要加双引号,返回的结果是一个字典
'''
res = collection.fin({"age":{"$gt":18}})
for row in res:
print(row)
'''
根据ID查询
'''
res = collection.fin({"_id":ObjectId("?")})
print(res[?])
| true |
bc520af768fec66100fdc828b9b91ea2b62173a0 | Python | ozzi7/Hackerrank-Solutions | /Python/Sets/py-the-captains-room.py | UTF-8 | 325 | 2.765625 | 3 | [] | no_license | if __name__ == '__main__':
k = int(input())
l = list(input().split())
s = set()
potentialcaps = set()
for i in range(0,len(l),1):
if l[i] not in s:
s.add(l[i])
potentialcaps.add(l[i])
else:
potentialcaps.discard(l[i])
print(potentialcaps.pop()) | true |
20a52071efb9992be7bb9413b08fcbefa5f1a8d0 | Python | hsztan/idat-reto-7 | /models/Salon.py | UTF-8 | 1,459 | 2.984375 | 3 | [] | no_license | from config.connection import Connection
class Salon:
def __init__(self, nombre, aescolar):
self.nombre = nombre
self.aescolar = aescolar
@classmethod
def all_salon(cls, data=[]):
try:
conn = Connection('colegio')
records = list(conn.get_all('salon', {}, {
'_id': 0,
'nombre': 1,
'aescolar': 1
}))
for record in records:
print(f'Salon: {record["nombre"]}')
print(f'Año Escolar: {record["aescolar"]}')
print('=====================')
return records
except Exception as e:
print(e)
def insert_salon(self):
try:
conn = Connection('colegio')
conn.insert('salon', {
'nombre': self.nombre,
'aescolar': self.aescolar
})
print(
f'Se registro el salon: {self.nombre}')
except Exception as e:
print(e)
def update_salon(self):
try:
conn = Connection('salon')
conn.update({
'id': 8,
'modelo': 'Motorola'
}, {
'precio': self.precio,
'modelo': 'Motorola 2021'
})
#print(f'Se registro el modelo: {self.modelo} con el precio {self.precio}')
except Exception as e:
print(e)
| true |
fb62aa4b0a0f60d5869d36c8ee11bcb2430aa21b | Python | hevi9/etc-python | /gtk3/learngtk/contextmenu.py | UTF-8 | 854 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env python
from gi.repository import Gtk
def display_menu(widget, event):
if event.button == 3:
menu.popup(None, None, None, None, event.button, event.time)
menu.show_all()
def display_text(widget):
print("Item clicked was %s" % widget.get_child().get_text())
window = Gtk.Window()
window.connect("destroy", lambda q: Gtk.main_quit())
eventbox = Gtk.EventBox()
eventbox.connect("button-release-event", display_menu)
window.add(eventbox)
menu = Gtk.Menu()
menuitem = Gtk.MenuItem(label="MenuItem 1")
menuitem.connect("activate", display_text)
menu.append(menuitem)
menuitem = Gtk.MenuItem(label="MenuItem 2")
menuitem.connect("activate", display_text)
menu.append(menuitem)
menuitem = Gtk.MenuItem(label="MenuItem 3")
menuitem.connect("activate", display_text)
menu.append(menuitem)
window.show_all()
Gtk.main()
| true |
82c118ce6382395df253c19de3ee884101d484ab | Python | mcharnay/cursoPython3 | /string.py | UTF-8 | 9,857 | 4.34375 | 4 | [] | no_license | # comentarios.
#type(variable)
#muestra el tipo de la variable
#\ para salto de línea
#\t salto tab
#si se pone una r ante de las "" o '', toma el texto completo x si hay una \c o \t dentro del texto.
#print(""" sirve para hacer salto de lineas
# sin tener que poner lo de arriba""")
#####################################################################################
#indice de cadenas
#profesor = "Michel Charnay"
#profesor[0]
#arroja M
#si se pone profesor[2:5]
#arroja che
#si se pone profesor[2:]
#arroja desde el indice 2 en adelante
#len(profesor)
#cuenta los caracteres
#arreglos
#arreglo = [1,2,3,4,5]
#arreglo, arroja el arrelgo
#arreglar elemento al arreglo
#arreglo.append(10)
#dentro de arreglo se pueden guardar más arreglos
#para leer datos por teclado:
#input()
#dato = input()
#parsear string a int
#int(variable)
#float(datos)
#para almacernar input decimal con mensajes antes:
#dato =float(input("trintroduce un valor decimal"))
#####################################################################################
#OPERADORES LOGICOS
#True
#False
#and
#or
#==
# !=
# >
# <
# >=
# <=
#Expresiones Anidadas y operadores de asignación
# += suma por el mismo valor y da una respuesta
# -= resta por el mismo valor y da una respuesta
# *= multitplica por el mismo valor y da una respuesta
# /= divide por el mismo valor y da una respuesta
# %= mod por el mismo valor y da una respuesta}
# **= potencia por el mismo valor y da una respuesta
#####################################################################################
#ESTRUCTURAS DE CONTROLS
#IF
"""Hartas lineas de comentario IF
Michel = 10
if Michel == 10:
print('Michel vale 10')
if Michel == 15:
print('Michel vale 15')
"""
#IF ELSE
"""
Michel = 10
if Michel == 10:
print("Michel vale 10")
else:
print("Michel no vale 10")
"""
#ELSE IF
"""
Michel = 10
if Michel == 10:
print('Michel vale 10')
elif Michel == 15:
print('Michel vale 15')
else:
print('No cae en ningún lado')
"""
#WHILE
"""
num = 0
while num <= 3:
num += 1
print('Estoy iterando, van = ',num)
"""
"""
num = 0
while num <= 3:
num += 1
print('Estoy iterando, van = ',num)
break
else:
print('imprimo esto porque se acabó la iteración y es el else')
"""
#ejercicio grande de menu con while
"""
print('elige tu propio camino')
inicio = input('escribe empezar para iniciar el programa: ')
while (inicio == 'empezar'):
print(""" ¿qué camino quieres elegir?
Escribe la opción con número
1 - Quiero que me saludes
2 - Deseo multiplicar porque no se como hacerlo
3 - Quiero salir de este programa, aprendí a como multiplicar""")
opcion = input()
if opcion == '1':
print('te saludo')
elif opcion == '2':
numero1 = float(input('Introduce el número de multiplicar del primero: '))
numero2 = float(input('Introduce el número de multiplicar del segundo: '))
print('El resultado es : ', numero1*numero2)
elif opcion == '3':
print('Excelente desición que hayas tomado mi curso')
else:
print('No elegiste ningún número posible')
"""
#####################################################################################
#FOR
"""
lista = [1,2,3,4,5,6]
indice = 0
for recorrer in lista:
print(recorrer)
"""
#####################################################################################
#TUPLAS, DICCIONARIOS, CONJUNTOS, PILAS Y COLAS.
#TUPLAS
#Conjuntos
"""
con = {5,4,3}
con.add(6)
con
cadena = "texto bla bla bla bla "
set(cadena)
"""
#diccionarios
"""
diccionario = {'nombre' : 'Michel', 'Profesion' : 'Ingeniero'}
type(diccionario)
diccionario['nombre']
diccionario['nombre'] = 'Antoine'
diccionario
del(diccionario['nombre'])
"""
#PILAS
"""
apilar = [1,2,3,4]
apilar.append(3)
apilar.append(6)
apilar.append(8)
apilar.pop()
"""
#COLAS
"""
#Hay que llamar a las librerías de las colas
from collections import deque
colas = deque()
colas
type(colas)
colas = deque(['Michel', 'Estudiantes', 'Familia', 'Coockie'])
colas.pop()
colas.popleft()
"""
#las pilas no se pueden sacar primero, las colas sí.
#####################################################################################
#ENTRADAS O SALIDAS
#INPUTS OUTPUTS
#5 inputs por FOR dentro de un array
"""
listas = []
print("Ingrese 5 números)
for i in range(5):
listas.append(input("INgrese su número: "))
listas
"""
#OUTPUTS
"""
nombre = "Michel"
apellido = "Charnay"
nombreCompleto = "Mi nombre es '{}' y mi apellido es '{}'".format(nombre,apellido)
"""
#####################################################################################
#FUNCIONES
#para definiar una variblae global es : global nombreVariable
"""
def estudiantes():
print("Este es un mensaje de algún estudiante")
estudiantes()
"""
#si tiene un return string
"""
def metodo():
return "asdlkjasld"
print(metodo())
"""
#si tiene un return int
"""
def metodo(a,b):
return a+b
metodo()
"""
#meter valors dentro del método
"""
def estudiantes(valor):
return valor*3
variable = 15
variable = estudiantes(variable)
variable
"""
#meter muchos argumentos y recorrerlos todos
"""
def metodo(*elemento):
for elementos in eleneto:
print(elementos)
metodo('Michel', 'Charnay', 'computadres', 10, [1,2,3])
"""
#meter diccionario y recorrerlo
"""
def nombre_diccionario(*cantidad, **elemento):
b = 0
for cantidades in cantidad:
b+=cantidades
print(b)
for x in elemento:
print(x, " ", lo[x])
nombre_diccionario(1,2,3,4,michel="charnay", Estudiantes='Genios',calificaciones=[7,8,9])
"""
#FUNCIONES RECURSIVAS
#SOn las funciones que se llaman a si misma
"""
def metodo(segundos):
segundos -= 1
if segundo >= 0:
print(segundos)
metodo(segundos)
else:
print('terminó la cuenta atrás')
metodo(10)
"""
#####################################################################################
#ERRORES Y EXCEPCIONES EN PYTHON
#se hacen con try
"""
try:
variable = float(input("Introduce un número: "))
a = 2
print("resultado: ", a*variable)
except:
print("Ingresaste cualquier otra cosa menos la que se pidio")
"""
#otro ejemplo
"""
while(True):
try:
variable = float(input("Introduce un número: "))
a = 2
print("resultado: ",a*variable)
except:
print("Ingresaste mal, otra oportunidad)
else:
print("Bine iniciado :)")
break
finally:
print("Perfecto amigo, terminó todo bien.")
"""
#####################################################################################
#INVOCACIÖN DE EXCEPCIONES
"""
try:
a = input("Número :")
10/a
except Exception as x:
print( type(x).__name__)
"""
#error traducido
"""
try:
a = float(input("Numero : "))
10/a
except TypeError:
print("Esto es una cadena")
except ValueError:
print("La cadena debe ser un número")
except ZeroDivisionError:
print("No se puede dividir por 0")
except Exception as x:
print( type(x).__name__ )
"""
#####################################################################################
#PROGRAMACIÓN ORIENTADA A OBJETOS
#CLASE VACÍA
"""
class Estudiante:
pass
Estudiante = Estudiante()
"""
#Clase con métodos que si se quiere no se ponen
"""
class Fabrica:
def __init__(self,marca,nombre,precio,descripcion,ruedas=None,distribuidor=None):
self.marca = marca
self.nombre = precio
self.descripcion = descripcion
self.ruedas = ruedas
self.distribuidor = distribuidor
Auto = Fabrica('Ford', 'Ranger', 'Camioneta 4x4', 4 )
Auto.nombre
"""
#CLASE CON ATRIBUTOS
"""
class Auto:
Rojo = False
def __init__(self, puertas, color):
self.puertas = puertas
self.color = color
print("Se creò un Auto con Puertas {} y color {}".format(puertas, color))
def Fabricar(self):
self.Rojo = True
def confirmar_fabricacion(self):
if(self.Rojo):
print("Auto Coloreado Rojo")
else:
print("Aun no está coloreado")
a = Auto("2", "Rojo")
"""
#INIT (iniciardor) DEL (BORRADOR)
#si se ejecuta 2 veces, primero se ejecuta el init, después el delete
"""
class Fabrica:
def __init__(self,tiempo,nombre,ruedas):
self.tiempo = tiempo
self.nombre = nombre
self.ruedas = ruedas
print("se creo el auto", self.nombre)
def __del__(self):
print("Se elimino el auto", self.nombre)
def __str__(self):
return "{} se fabrica con exito, en el tiempo {} y tiene esta cantidad {}".format(self.nombre,self.tiempo,self.ruedas)
a = Fabrica(10, "Alvaro", 4)
a = Fabrica(10, "Alvaro", 4)
"""
#ENCAPSULAMIENTO
#llamar métodfos y atributos privadas a travez de métodos y atributos publicos
"""
class encapsulamiento:
__privado_atri = "Soy un atributo provadiu que no se puede acceder"
def __privado_met(self):
print("soy método que no se puede acceder porque es privado")
def publico_atri(self):
return self.__privado_atri
def public_met(self):
return self.__privado_met()
e = encapsulamiento()
e.publico_atri()
"""
#HERENCIA
"""
class Fabrica:
def __init__(self,marca,nombre,precio,descripcion):
self.marca = marca
self.nombre = nombre
self.precio = precio
self.descripcion = descripcion
def __str__(self):
return """\
MARCA\t\t{}
NOMBRE\t\t{}
PRECIO\t\t{}
DESCRIPCION\t\t{} """.format(self.marca, self.nombre, self.precio, self.descripcion)
class Auto(Fabrica):
pass
z = Auto('Ford', 'Ranger', '100.000', 'Camionera')
print(z)
"""
| true |
6f64649007afafb791bf113e1e80c30a72ccace3 | Python | zewuchen/data-analysis | /Grafico (Barras)/Barras Normal 01.py | UTF-8 | 738 | 3.53125 | 4 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
opiniao = ("Ruim/Pessimo", "Regular", "Otima/Boa", "Sem Opinião") #Rótulos do eixo X
x_pos = np.arange(len(opiniao)) #Define o tamanho do eixo X com a quantidade dos rótulos
valores = [82, 14, 3, 1] #Valores de Y
plt.bar(x_pos, valores, align="center", color="r") #Faz o gráfico
plt.xticks(x_pos, opiniao) #Coloca os rótulos no eixo X do gráfico
plt.xlabel("Opiniões") #Label para X
plt.ylabel("Porcentagem") #Label para Y | true |
2cccf320942462ac052a4777879b3d3783845bfd | Python | SyrianSpock/anima-initiative-roller | /roll.py | UTF-8 | 2,961 | 3.296875 | 3 | [] | no_license | import argparse
from collections import namedtuple
from collections.abc import Iterable
import logging
import operator
import random
import yaml
import re
Player = namedtuple('Player', ['name', 'initiative', 'fail'])
def parse_arguments():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('file', type=str, help='File with modifiers.')
parser.add_argument("--japanize", "-j", help="Make things more anime", action='store_true')
return parser.parse_args()
def read_modifiers(yaml_file):
with open(yaml_file) as file:
modifiers = yaml.safe_load(file)
failures = {}
for player in modifiers:
if isinstance(modifiers[player], Iterable):
failures = {player: elem['fail'] for elem in modifiers[player][1:]}
modifiers[player] = modifiers[player][0]
return modifiers, failures
def roll_initiative(name, modifier, fail):
initiative = modifier + roll_open()
return Player(name=name, initiative=initiative, fail=fail)
def roll_open(base_roll=0, success=90, fail=3):
roll = roll_100()
logging.debug("Rolling {}, rolled {}, with success {}".format(base_roll, roll, success))
if roll >= success:
return roll_open(base_roll= roll + base_roll, success=success+1, fail=fail)
else:
res = roll + base_roll
if base_roll == 0 and roll <= fail:
res -= roll_100()
return res
def roll_100():
return random.randint(1,100)
def load_hiragana():
result = dict()
with open('hiragana_table.txt') as f:
for l in f:
hiragana, romaji = l.rstrip().split(' ')
result[romaji] = hiragana
return result
def japanize(hiragana_table, name):
"""
>>> japanize({'ka':'か', 'ya': 'や'}, 'Kaya')
'かや'
>>> japanize({'ka':'か', 'ya': 'や'}, 'Jeff')
'Jeff'
>>> japanize({'ka':'か', 'ya': 'や'}, 'Kayan')
'Kayan'
"""
original_name = name
for romaji in sorted(hiragana_table.keys(), key=len, reverse=True):
name = re.sub(romaji, hiragana_table[romaji], name, flags=re.IGNORECASE)
if re.search(r'[a-zA-Z]', name):
return original_name
return name
def show_initiatives(players, japanize_names):
hiragana = load_hiragana()
for player in players:
if japanize_names and japanize(hiragana, player.name) != player.name:
name = '{} ({})'.format(player.name, japanize(hiragana, player.name))
else:
name = player.name
print('{}:\t{}'.format(name, player.initiative))
def main():
args = parse_arguments()
modifiers, failures = read_modifiers(args.file)
players = [roll_initiative(player, modifiers[player], failures.get(player, 3)) for player in modifiers]
players = sorted(players, key=lambda player: player.initiative, reverse=True)
show_initiatives(players, args.japanize)
if __name__ == '__main__':
main()
| true |
b256cf2c68e90a6347a5ff44dcaeaf821e5e23c7 | Python | brianbirir/harvest-data-validator | /src/helpers/extractor.py | UTF-8 | 2,653 | 2.9375 | 3 | [] | no_license | import os
import json
from src.helpers import logger as app_logger
FILE_TYPES_EXTENSIONS = (".jpg", ".png", ".json")
def fetch_files(folder_path: str) -> list:
""" Returns files from a folder
Parameters
----------
folder_path
path to the folder
Returns
-------
list of found files
"""
retrieved_files = []
if not os.path.exists(folder_path):
raise Exception("Provided data source folder does not exist")
for subdir, dirs, files in os.walk(folder_path):
if len(files) == 0:
raise Exception("No files found")
for filename in files:
filepath = subdir + os.sep + filename
if filepath.endswith(FILE_TYPES_EXTENSIONS):
retrieved_files.append(filepath)
app_logger.info("Files retrieved from folder successfully")
return retrieved_files
def to_json(file: str) -> dict:
""" Decode json file
Parameters
----------
file
Returns
-------
data in dictionary structure
"""
try:
return json.load(file)
except ValueError:
print('Unable to decode JSON file')
def read_file(file_path: str) -> dict:
"""Reads a JSON data file
Parameters
----------
file_path
path to the file
Returns
-------
file content as dictionary object
"""
try:
with open(file_path, "r") as farm_data_file:
return farm_data_file
except IOError:
print("File not found")
def read_data_file(file_path: str) -> dict:
"""Reads a JSON data file
Parameters
----------
file_path
path to the file
Returns
-------
file content as dictionary object
"""
try:
with open(file_path, "r") as farm_data_file:
return json.load(farm_data_file)
except IOError:
print("File not found")
def read_image_file(file_path: str) -> object:
"""Reads an image file
Parameters
----------
file_path
path to the file
Returns
-------
file content
"""
try:
with open(file_path, "r") as farm_data_file:
if farm_data_file.endswith('.png') or farm_data_file.endswith('.jpeg') or farm_data_file.endswith('.jpg'):
return farm_data_file
except IOError:
print("File not found")
def get_measurements_data(raw_data: dict) -> list:
"""Returns measurements of harvest data
Parameters
----------
raw_data
raw data in dictionary format
Returns
-------
harvest measurements
"""
return raw_data["harvest_measurements"]
| true |
9c6e5c931b1c4737235ad48fcda1fca90e5e707a | Python | isensen/PythonBasic | /Tutorials/05_迭代.py | UTF-8 | 1,169 | 4.28125 | 4 | [] | no_license | #coding=utf-8
'''
迭代
'''
__author__ = "i3342th"
#如果给定一个list 或 tuple 我们可以通过 for 循环遍历,这种遍历我们称为迭代 (iteration)
#python 中 迭代 是通过 for ... in 来完成的
#for ... in 不只可用于 list , tuple,还可用于其他可迭代对象上,例如:dict
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print key
#dict 存储不是按顺序来的,所以打印出来顺序是不一定的
#默认dict 用for 迭代的是 key
#如果迭代value,可以用 for value in d.itervalues()
#同时迭代 key value, for k,v in d.iteritems()
for value in d.itervalues():
print value
for k, v in d.iteritems():
print k,'-->',v
#字符串也可以迭代
for ch in 'i3342th':
print ch
#那么如何判断一个对象可迭代呢?
from collections import Iterable
print isinstance('abc',Iterable)
print isinstance(123,Iterable)
#如果要实现类似Java里的下标循环怎么办?
#Python 内置的 enumerate 函数可以把一个list变成索引-元素对
for i, v in enumerate(['i','3','3']):
print i, '-->', v
#for 循环中同时引多个变量
for x, y in [(1,1),(2,4),(3,9)]:
print x,y | true |
94876e55ab6892c79bac4d0793a854a0352ec704 | Python | andrezzadede/Curso_Guanabara_Python_Mundo_3 | /Mundo 3 - Exercícios/93Exercicio - Dicionario.py | UTF-8 | 912 | 4.28125 | 4 | [
"MIT"
] | permissive | # Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogdor e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um dicionario, incluindo o total de gols feitos durante o campeonato.
jogador = dict()
gol = list()
jogador['nome'] = str(input('Nome jogador: '))
partidas = int(input(f'Quantas partidas {"nome"} jogou? '))
for i in range(0,partidas):
gol.append(int(input(f'Quantos gols ele fez na {i+1} partida? ')))
jogador['gols'] = gol[:]
jogador['total'] = sum(gol)
print(jogador)
print('=' * 30)
for k, v in jogador.items():
print(f'O campo {k} tem o valor {v}')
print('=' *30)
print(f'O jogador {jogador["nome"]} jogou {len(jogador["gols"])} partidas')
for i, v in enumerate(jogador['gols']):
print(f'Na partida {i} fez {v} gols')
print(f'Foi o total de {jogador["total"]}')
| true |
78f18c20baae26dadfd2eadda4576df1885e2a22 | Python | Camiloasc1/AlgorithmsUNAL | /DomJudge/practica14/Monedas.py | UTF-8 | 692 | 2.765625 | 3 | [
"MIT"
] | permissive | import sys
coins = [1, 5, 10, 25, 50]
def Calc(Res, i):
if i in Res:
return Res
if i in coins:
Res[i] = 1
else:
Res[i] = 0
# for c in coins[::-1]:
# for c in coins:
for c in xrange(i / 2):
if i - c > 0:
Res[i] += Calc(Res, c)[c] * Calc(Res, i - c)[i - c]
return Res
def read():
Res = {}
Res[0] = 1
for c in xrange(20):
Res[c] = Calc(Res, c)[c]
print 'Res', c, Res[c]
# for c in coins:
# Res[c] = Calc(Res, c)[c]
# print 'Res', c, Res[c]
Q = []
for l in sys.stdin.read().splitlines():
i = int(l)
Res = Calc(Res, i)
print Res[i]
read()
| true |
3b533714296fb094300fe0b48f05036e7d98b981 | Python | PatrycjaPytka/Django2 | /biblioteka/models.py | UTF-8 | 1,559 | 2.59375 | 3 | [] | no_license | from django.db import models
from django.core.validators import MaxValueValidator
from .validators import validate_rok
class Autor(models.Model):
imie = models.CharField(max_length=20, blank=False)
nazwisko = models.CharField(max_length=20, blank=False)
data_urodzenia = models.DateField(null=True, blank=True, default=None)
def __str__(self):
return self.imie + " " + self.nazwisko
class Ksiazka(models.Model):
tytul = models.CharField(max_length=50, blank=False)
rok_wydania = models.IntegerField(blank=False, validators=[validate_rok])
autor = models.ForeignKey(Autor, on_delete=models.CASCADE)
class Meta:
ordering = ['-rok_wydania']
verbose_name = "książka"
verbose_name_plural = "książki"
unique_together = ["tytul", "rok_wydania"]
indexes = [
models.Index(fields = ['tytul'], name = 'tytul_inx'),
models.Index(fields = ['tytul', 'rok_wydania']),
]
permissions = [
('can_update_ksiazka', "Może zmienić książkę")
]
# def save(self, *args, **kwargs):
# if self.rok_wydania > 2020:
# raise ValueError("Rok wydania jest większy niż 2020.")
# super(Ksiazka, self).save(*args, **kwargs)
#swoj validator:
def save(self, *args, **kwargs):
validate_rok(self.rok_wydania)
super(Ksiazka, self).save(*args, **kwargs)
def jest_nowoczesna(self):
return True if self.rok_wydania > 2000 else False
def __str__(self):
return self.tytul | true |
f98ea65feb57472ef09315ed0917dc8c8af75445 | Python | daman-cyngh/Voice-Cloning | /synthesizer/models/modules.py | UTF-8 | 15,675 | 2.546875 | 3 | [] | no_license | import tensorflow as tf
class HighwayNet:
def __init__(self, units, name=None):
self.units = units
self.scope = "HighwayNet" if name is None else name
self.H_layer = tf.layers.Dense(units=self.units, activation=tf.nn.relu, name="H")
self.T_layer = tf.layers.Dense(units=self.units, activation=tf.nn.sigmoid, name="T",
bias_initializer=tf.constant_initializer(-1.))
def __call__(self, inputs):
with tf.variable_scope(self.scope):
H = self.H_layer(inputs)
T = self.T_layer(inputs)
return H * T + inputs * (1. - T)
class CBHG:
def __init__(self, K, conv_channels, pool_size, projections, projection_kernel_size,
n_highwaynet_layers, highway_units, rnn_units, is_training, name=None):
self.K = K
self.conv_channels = conv_channels
self.pool_size = pool_size
self.projections = projections
self.projection_kernel_size = projection_kernel_size
self.is_training = is_training
self.scope = "CBHG" if name is None else name
self.highway_units = highway_units
self.highwaynet_layers = [
HighwayNet(highway_units, name="{}_highwaynet_{}".format(self.scope, i + 1)) for i in
range(n_highwaynet_layers)]
self._fw_cell = tf.nn.rnn_cell.GRUCell(rnn_units, name="{}_forward_RNN".format(self.scope))
self._bw_cell = tf.nn.rnn_cell.GRUCell(rnn_units, name="{}_backward_RNN".format(self.scope))
def __call__(self, inputs, input_lengths):
with tf.variable_scope(self.scope):
with tf.variable_scope("conv_bank"):
conv_outputs = tf.concat(
[conv1d(inputs, k, self.conv_channels, tf.nn.relu, self.is_training, 0.,
"conv1d_{}".format(k)) for k in range(1, self.K + 1)],
axis=-1
)
maxpool_output = tf.layers.max_pooling1d(
conv_outputs,
pool_size=self.pool_size,
strides=1,
padding="same")
proj1_output = conv1d(maxpool_output, self.projection_kernel_size, self.projections[0],
tf.nn.relu, self.is_training, 0., "proj1")
proj2_output = conv1d(proj1_output, self.projection_kernel_size, self.projections[1],
lambda _: _, self.is_training, 0., "proj2")
highway_input = proj2_output + inputs
if highway_input.shape[2] != self.highway_units:
highway_input = tf.layers.dense(highway_input, self.highway_units)
for highwaynet in self.highwaynet_layers:
highway_input = highwaynet(highway_input)
rnn_input = highway_input
outputs, states = tf.nn.bidirectional_dynamic_rnn(
self._fw_cell,
self._bw_cell,
rnn_input,
sequence_length=input_lengths,
dtype=tf.float32)
return tf.concat(outputs, axis=2)
class ZoneoutLSTMCell(tf.nn.rnn_cell.RNNCell):
def __init__(self, num_units, is_training, zoneout_factor_cell=0., zoneout_factor_output=0.,
state_is_tuple=True, name=None):
zm = min(zoneout_factor_output, zoneout_factor_cell)
zs = max(zoneout_factor_output, zoneout_factor_cell)
if zm < 0. or zs > 1.:
raise ValueError("One/both provided Zoneout factors are not in [0, 1]")
self._cell = tf.nn.rnn_cell.LSTMCell(num_units, state_is_tuple=state_is_tuple, name=name)
self._zoneout_cell = zoneout_factor_cell
self._zoneout_outputs = zoneout_factor_output
self.is_training = is_training
self.state_is_tuple = state_is_tuple
@property
def state_size(self):
return self._cell.state_size
@property
def output_size(self):
return self._cell.output_size
def __call__(self, inputs, state, scope=None):
output, new_state = self._cell(inputs, state, scope)
if self.state_is_tuple:
(prev_c, prev_h) = state
(new_c, new_h) = new_state
else:
num_proj = self._cell._num_units if self._cell._num_proj is None else \
self._cell._num_proj
prev_c = tf.slice(state, [0, 0], [-1, self._cell._num_units])
prev_h = tf.slice(state, [0, self._cell._num_units], [-1, num_proj])
new_c = tf.slice(new_state, [0, 0], [-1, self._cell._num_units])
new_h = tf.slice(new_state, [0, self._cell._num_units], [-1, num_proj])
if self.is_training:
c = (1 - self._zoneout_cell) * tf.nn.dropout(new_c - prev_c,
(1 - self._zoneout_cell)) + prev_c
h = (1 - self._zoneout_outputs) * tf.nn.dropout(new_h - prev_h,
(1 - self._zoneout_outputs)) + prev_h
else:
c = (1 - self._zoneout_cell) * new_c + self._zoneout_cell * prev_c
h = (1 - self._zoneout_outputs) * new_h + self._zoneout_outputs * prev_h
new_state = tf.nn.rnn_cell.LSTMStateTuple(c, h) if self.state_is_tuple else tf.concat(1, [c,
h])
return output, new_state
class EncoderConvolutions:
def __init__(self, is_training, hparams, activation=tf.nn.relu, scope=None):
super(EncoderConvolutions, self).__init__()
self.is_training = is_training
self.kernel_size = hparams.enc_conv_kernel_size
self.channels = hparams.enc_conv_channels
self.activation = activation
self.scope = "enc_conv_layers" if scope is None else scope
self.drop_rate = hparams.tacotron_dropout_rate
self.enc_conv_num_layers = hparams.enc_conv_num_layers
def __call__(self, inputs):
with tf.variable_scope(self.scope):
x = inputs
for i in range(self.enc_conv_num_layers):
x = conv1d(x, self.kernel_size, self.channels, self.activation,
self.is_training, self.drop_rate,
"conv_layer_{}_".format(i + 1) + self.scope)
return x
class EncoderRNN:
def __init__(self, is_training, size=256, zoneout=0.1, scope=None):
super(EncoderRNN, self).__init__()
self.is_training = is_training
self.size = size
self.zoneout = zoneout
self.scope = "encoder_LSTM" if scope is None else scope
self._fw_cell = ZoneoutLSTMCell(size, is_training,
zoneout_factor_cell=zoneout,
zoneout_factor_output=zoneout,
name="encoder_fw_LSTM")
self._bw_cell = ZoneoutLSTMCell(size, is_training,
zoneout_factor_cell=zoneout,
zoneout_factor_output=zoneout,
name="encoder_bw_LSTM")
def __call__(self, inputs, input_lengths):
with tf.variable_scope(self.scope):
outputs, (fw_state, bw_state) = tf.nn.bidirectional_dynamic_rnn(
self._fw_cell,
self._bw_cell,
inputs,
sequence_length=input_lengths,
dtype=tf.float32,
swap_memory=True)
return tf.concat(outputs, axis=2)
class Prenet:
def __init__(self, is_training, layers_sizes=[256, 256], drop_rate=0.5, activation=tf.nn.relu,
scope=None):
super(Prenet, self).__init__()
self.drop_rate = drop_rate
self.layers_sizes = layers_sizes
self.activation = activation
self.is_training = is_training
self.scope = "prenet" if scope is None else scope
def __call__(self, inputs):
x = inputs
with tf.variable_scope(self.scope):
for i, size in enumerate(self.layers_sizes):
dense = tf.layers.dense(x, units=size, activation=self.activation,
name="dense_{}".format(i + 1))
x = tf.layers.dropout(dense, rate=self.drop_rate, training=True,
name="dropout_{}".format(i + 1) + self.scope)
return x
class DecoderRNN:
def __init__(self, is_training, layers=2, size=1024, zoneout=0.1, scope=None):
super(DecoderRNN, self).__init__()
self.is_training = is_training
self.layers = layers
self.size = size
self.zoneout = zoneout
self.scope = "decoder_rnn" if scope is None else scope
self.rnn_layers = [ZoneoutLSTMCell(size, is_training,
zoneout_factor_cell=zoneout,
zoneout_factor_output=zoneout,
name="decoder_LSTM_{}".format(i + 1)) for i in
range(layers)]
self._cell = tf.contrib.rnn.MultiRNNCell(self.rnn_layers, state_is_tuple=True)
def __call__(self, inputs, states):
with tf.variable_scope(self.scope):
return self._cell(inputs, states)
class FrameProjection:
def __init__(self, shape=80, activation=None, scope=None):
super(FrameProjection, self).__init__()
self.shape = shape
self.activation = activation
self.scope = "Linear_projection" if scope is None else scope
self.dense = tf.layers.Dense(units=shape, activation=activation,
name="projection_{}".format(self.scope))
def __call__(self, inputs):
with tf.variable_scope(self.scope):
output = self.dense(inputs)
return output
class StopProjection:
def __init__(self, is_training, shape=1, activation=tf.nn.sigmoid, scope=None):
super(StopProjection, self).__init__()
self.is_training = is_training
self.shape = shape
self.activation = activation
self.scope = "stop_token_projection" if scope is None else scope
def __call__(self, inputs):
with tf.variable_scope(self.scope):
output = tf.layers.dense(inputs, units=self.shape,
activation=None, name="projection_{}".format(self.scope))
if self.is_training:
return output
return self.activation(output)
class Postnet:
def __init__(self, is_training, hparams, activation=tf.nn.tanh, scope=None):
super(Postnet, self).__init__()
self.is_training = is_training
self.kernel_size = hparams.postnet_kernel_size
self.channels = hparams.postnet_channels
self.activation = activation
self.scope = "postnet_convolutions" if scope is None else scope
self.postnet_num_layers = hparams.postnet_num_layers
self.drop_rate = hparams.tacotron_dropout_rate
def __call__(self, inputs):
with tf.variable_scope(self.scope):
x = inputs
for i in range(self.postnet_num_layers - 1):
x = conv1d(x, self.kernel_size, self.channels, self.activation,
self.is_training, self.drop_rate,
"conv_layer_{}_".format(i + 1) + self.scope)
x = conv1d(x, self.kernel_size, self.channels, lambda _: _, self.is_training,
self.drop_rate,
"conv_layer_{}_".format(5) + self.scope)
return x
def conv1d(inputs, kernel_size, channels, activation, is_training, drop_rate, scope):
with tf.variable_scope(scope):
conv1d_output = tf.layers.conv1d(
inputs,
filters=channels,
kernel_size=kernel_size,
activation=None,
padding="same")
batched = tf.layers.batch_normalization(conv1d_output, training=is_training)
activated = activation(batched)
return tf.layers.dropout(activated, rate=drop_rate, training=is_training,
name="dropout_{}".format(scope))
def _round_up_tf(x, multiple):
remainder = tf.mod(x, multiple)
x_round = tf.cond(tf.equal(remainder, tf.zeros(tf.shape(remainder), dtype=tf.int32)),
lambda: x,
lambda: x + multiple - remainder)
return x_round
def sequence_mask(lengths, r, expand=True):
max_len = tf.reduce_max(lengths)
max_len = _round_up_tf(max_len, tf.convert_to_tensor(r))
if expand:
return tf.expand_dims(tf.sequence_mask(lengths, maxlen=max_len, dtype=tf.float32), axis=-1)
return tf.sequence_mask(lengths, maxlen=max_len, dtype=tf.float32)
def MaskedMSE(targets, outputs, targets_lengths, hparams, mask=None):
if mask is None:
mask = sequence_mask(targets_lengths, hparams.outputs_per_step, True)
ones = tf.ones(shape=[tf.shape(mask)[0], tf.shape(mask)[1], tf.shape(targets)[-1]],
dtype=tf.float32)
mask_ = mask * ones
with tf.control_dependencies([tf.assert_equal(tf.shape(targets), tf.shape(mask_))]):
return tf.losses.mean_squared_error(labels=targets, predictions=outputs, weights=mask_)
def MaskedSigmoidCrossEntropy(targets, outputs, targets_lengths, hparams, mask=None):
if mask is None:
mask = sequence_mask(targets_lengths, hparams.outputs_per_step, False)
with tf.control_dependencies([tf.assert_equal(tf.shape(targets), tf.shape(mask))]):
losses = tf.nn.weighted_cross_entropy_with_logits(targets=targets, logits=outputs,
pos_weight=hparams.cross_entropy_pos_weight)
with tf.control_dependencies([tf.assert_equal(tf.shape(mask), tf.shape(losses))]):
masked_loss = losses * mask
return tf.reduce_sum(masked_loss) / tf.count_nonzero(masked_loss, dtype=tf.float32)
def MaskedLinearLoss(targets, outputs, targets_lengths, hparams, mask=None):
if mask is None:
mask = sequence_mask(targets_lengths, hparams.outputs_per_step, True)
ones = tf.ones(shape=[tf.shape(mask)[0], tf.shape(mask)[1], tf.shape(targets)[-1]],
dtype=tf.float32)
mask_ = mask * ones
l1 = tf.abs(targets - outputs)
n_priority_freq = int(2000 / (hparams.sample_rate * 0.5) * hparams.num_freq)
with tf.control_dependencies([tf.assert_equal(tf.shape(targets), tf.shape(mask_))]):
masked_l1 = l1 * mask_
masked_l1_low = masked_l1[:, :, 0:n_priority_freq]
mean_l1 = tf.reduce_sum(masked_l1) / tf.reduce_sum(mask_)
mean_l1_low = tf.reduce_sum(masked_l1_low) / tf.reduce_sum(mask_)
return 0.5 * mean_l1 + 0.5 * mean_l1_low
| true |
3af02bde1800a22c622f6e375c842b265f197043 | Python | Yogendrasingh-Rathore/PythonTraining | /Dataclasses.py | UTF-8 | 575 | 3.734375 | 4 | [] | no_license | from dataclasses import dataclass
# Simple DataClass
@dataclass
class Person:
name: str
age: int
p = Person('yuvi', 24)
print(p)
# Default Values DataClass
@dataclass
class Person2:
name: str = 'unknown'
age: int = 0
p = Person2('yuvi', 24)
print(p)
p2 = Person2()
print(p2)
p.occupation = 'soft engg'
print(p.occupation)
# Frozen DataClass
@dataclass(frozen=True) #Program will fail here at p.occupation as frozen is set True
class Person3:
name: str
age: int
p = Person3('yuvi', 99)
print(p)
p.occupation = 'soft engg'
print(p.occupation)
| true |
7b1ff0d0dd6941bd67b5ca8b7970456f207f4e36 | Python | adabbott/Research_Notes | /ml_testbed/1_keras_opt/model_api/trial4_naive/test.py | UTF-8 | 1,538 | 2.78125 | 3 | [] | no_license |
#import tensorflow as tf
##vector = tf.Variable([7., 7.], 'vector')
#vector = tf.constant([[1.0], [2.0], [3.0]])
#
## Make vector norm as small as possible.
#loss = tf.reduce_sum(tf.square(vector))
#optimizer = tf.contrib.opt.ScipyOptimizerInterface(loss, options={'maxiter': 100})
#with tf.Session() as session:
# session.run(tf.global_variables_initializer())
# optimizer.minimize(session, fetches=[loss])
### The value of vector should now be [0., 0.].
#print(vector)
#
#
#x = tf.placeholder(tf.float32, shape=(10, 10))
#y = tf.matmul(x, x)
#
#with tf.Session() as sess:
# rand_array = np.random.rand(10, 10)
# optimizer.minimize(session, feed_dict={x: rand_array} fetches=[loss])
# print(sess.run(y, ))
import tensorflow as tf
from tensorflow.python.ops import variables
from tensorflow.python.ops import array_ops
ScipyOptimizerInterface = tf.contrib.opt.ScipyOptimizerInterface
#vector = tf.Variable([7., 7.], 'vector')
x = variables.Variable(array_ops.ones(5))
loss = tf.reduce_sum(tf.square(x))
optimizer = ScipyOptimizerInterface(loss, options={'maxiter': 5})
sess = tf.Session()
with sess as s:
s.run(variables.global_variables_initializer())
print(optimizer._loss.eval())
optimizer.minimize(s)
print(optimizer._loss.eval())
stuff = sess.run(x)
print(stuff)
#sess.run(tf.global_variables_initializer())
#
#with sess as session:
# optimizer.minimize(session)
#print(optimizer._loss.eval())
#print(optimizer._var_updates)
#print(optimizer._var_updates[0].eval())
| true |
44b7c2679df072ca1b1a70650b4594cdb11a9c5b | Python | bancheng/Stock-market | /测试代码/theano/binbin/jiangnan_lstm/lstm.py | UTF-8 | 4,179 | 2.53125 | 3 | [] | no_license | # -*- coding:utf-8 -*-
import numpy as np
import theano
import theano.tensor as T
class LSTM:
def __init__(self, n_input, n_hidden):
self.n_input = n_input
self.n_hidden = n_hidden
self.f = T.nnet.hard_sigmoid
# forget gate parameters.
initial_Wf = np.asarray(
np.random.uniform(
low=-np.sqrt(1./n_input),
high=np.sqrt(1./n_input),
size=(n_hidden, n_input + n_hidden)),
dtype=theano.config.floatX)
initial_bf = np.zeros((n_hidden), dtype=theano.config.floatX)
self.Wf = theano.shared(value=initial_Wf, name='Wf')
self.bf = theano.shared(value=initial_bf, name='bf')
# Input gate parameters.
initial_Wi = np.asarray(
np.random.uniform(
low=-np.sqrt(1./n_input),
high=np.sqrt(1./n_input),
size=(n_hidden, n_input + n_hidden)),
dtype=theano.config.floatX)
initial_bi = np.zeros((n_hidden), dtype=theano.config.floatX)
self.Wi = theano.shared(value=initial_Wi, name='Wi')
self.bi = theano.shared(value=initial_bi, name='bi')
# Cell gate parameters
initial_Wc = np.asarray(
np.random.uniform(
low=-np.sqrt(1./n_input),
high=np.sqrt(1./n_input),
size=(n_hidden, n_input + n_hidden)),
dtype=theano.config.floatX)
initial_bc = np.zeros((n_hidden), dtype=theano.config.floatX)
self.Wc = theano.shared(value=initial_Wc, name='Wc')
self.bc = theano.shared(value=initial_bc, name='bc')
# Output gate parameters.
initial_Wo = np.asarray(
np.random.uniform(
low=-np.sqrt(1./n_input),
high=np.sqrt(1./n_hidden),
size=(n_hidden, n_input + n_hidden)),
dtype=theano.config.floatX)
initial_bo = np.zeros((n_hidden), dtype=theano.config.floatX)
self.Wo = theano.shared(value=initial_Wo, name='Wi')
self.bo = theano.shared(value=initial_bo, name='bo')
self.params = [self.Wi, self.Wf, self.Wc, self.Wo, self.bi, self.bf, self.bc, self.bo]
self._build()
def _build(self):
x = T.fmatrix('x')
y = T.fmatrix('y')
'''
Compute hidden state in an LSTM
:param x_t: Input vector
:param h_prev: Hidden variable from previous time step.
:param c_prev: Cell state from previous time step.
:return: [new hidden variable, updated cell state]
'''
def _recurrence(x_t, h_tm1, c_tm1):
concated = T.concatenate([x_t, h_tm1])
# Forget gate
f_t = self.f(T.dot(self.Wf, concated)+self.bf)
# Input gate
i_t = self.f(T.dot(self.Wi, concated)+self.bi)
# Cell Update
c_tilde_t = T.tanh(T.dot(self.Wc, concated)+self.bc)
c_t = f_t * c_tm1 + i_t * c_tilde_t
# output gate
o_t = self.f(T.dot(self.Wo, concated)+self.bo)
# Hidden state
h_t = o_t * T.tanh(c_t)
return [h_t, c_t]
[h_t, c_t], _ = theano.scan(
fn=_recurrence,
sequences=x,
truncate_gradient=-1,
outputs_info=[dict(initial=T.zeros(self.n_hidden)),
dict(initial=T.zeros(self.n_hidden))])
o_error = ((y - h_t)**2).sum()
gparams = T.grad(o_error, self.params)
learning_rate = T.scalar('learning_rate')
#decay=T.scalar('decay')
updates = [(param, param - learning_rate * gparam)
for param, gparam in zip(self.params, gparams)]
self.predict = theano.function(
inputs=[x],
outputs=[h_t, c_t]
)
self.error = theano.function(
inputs=[x, y],
outputs=o_error
)
self.sgd_step = theano.function(
inputs=[x, y, learning_rate],
outputs=o_error,
updates=updates
)
def compute_cost(self, x, y):
return self.error(x, y)
| true |
ebb13a6a02a5916395ddec62bc0b93ce9b4885a9 | Python | romeolandry/iris-Klassifikation_ML | /utils.py | UTF-8 | 178 | 2.671875 | 3 | [] | no_license | def match_predicion (prediction, match_class):
list_prediction = []
for val in prediction:
list_prediction.append(match_class.get(val))
return list_prediction | true |
284703b697976ae0d2b956e5a1165a6b4ac9c597 | Python | apottr/nexrad-process | /app.py | UTF-8 | 2,840 | 2.609375 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
import sys
from pathlib import Path
from metpy.io import Level2File
from metpy.plots import add_timestamp
IN_PREFIX="RADAR/{}"
OUT_PREFIX="OUT/{}_sweep-{}.png"
CORE=sys.argv[1]
def save_as_image(d,nexrad):
LAYER1=b"REF"
LAYER2=b"VEL"
f = Level2File(str(nexrad))
# Pull data out of the file
for sweep in range(0,21):
try:
print(f"rendering sweep {sweep}")
# First item in ray is header, which has azimuth angle
az = np.array([ray[0].az_angle for ray in f.sweeps[sweep]])
# 5th item is a dict mapping a var name (byte string) to a tuple
# of (header, data array)
ref_hdr = f.sweeps[sweep][0][4][LAYER1][0]
ref_range = np.arange(ref_hdr.num_gates) * ref_hdr.gate_width + ref_hdr.first_gate
ref = np.array([ray[4][LAYER1][1] for ray in f.sweeps[sweep]])
try:
rho_hdr = f.sweeps[sweep][0][4][LAYER2][0]
rho_range = (np.arange(rho_hdr.num_gates + 1) - 0.5) * rho_hdr.gate_width + rho_hdr.first_gate
rho = np.array([ray[4][LAYER2][1] for ray in f.sweeps[sweep]])
except:
rho_hdr = f.sweeps[sweep][0][4][b"RHO"][0]
rho_range = np.arange(rho_hdr.num_gates) * rho_hdr.gate_width + rho_hdr.first_gate
rho = np.array([ray[4][b"RHO"][1] for ray in f.sweeps[sweep]])
fig, axes = plt.subplots(1, 2, figsize=(15, 8))
for var_data, var_range, ax in zip((ref, rho), (ref_range, rho_range), axes):
# Turn into an array, then mask
data = np.ma.array(var_data)
data[np.isnan(data)] = np.ma.masked
# Convert az,range to x,y
xlocs = var_range * np.sin(np.deg2rad(az[:, np.newaxis]))
ylocs = var_range * np.cos(np.deg2rad(az[:, np.newaxis]))
# Plot the data
ax.pcolormesh(xlocs, ylocs, data, cmap='viridis')
ax.set_aspect('equal', 'datalim')
ax.set_xlim(-275, 275)
ax.set_ylim(-275, 275)
add_timestamp(ax, f.dt, y=0.02, high_contrast=True)
plt.savefig(str(d / OUT_PREFIX.format(f.dt.timestamp(),sweep)))
except:
print(f"sweep {sweep} failed, skipping")
def list_files(d):
directory = d / IN_PREFIX.format("")
for x in directory.iterdir():
yield x
def confirm_dir(d):
return (d / "RADAR").is_dir()
if __name__ == "__main__":
d = Path(__file__).resolve().parent.parent / CORE
if not confirm_dir(d):
sys.exit(1)
for first_file in list_files(d):
print(f"working on {first_file}")
save_as_image(d,first_file)
print(f"finished working on {first_file}");
| true |
f2681a6ec9f2d30489100049a9f0ac9ac849e1cb | Python | eobi/State-of-the-art-CNN-code-template-for-2D-images-with-and-without-transfer-learning | /non inherited weights/app.py | UTF-8 | 3,075 | 3.140625 | 3 | [] | no_license | """
Created on Fri Jan 17 19:32:57 2020
@author: Obi Ebuka David
NOTE: This code learns from the provided dataset. Enjoy
ensure you check the difference btw fit and fit_generator
"""
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
from keras.preprocessing import image
image_to_predict_src = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size=(64, 64))
def load_images():
train_datagen = ImageDataGenerator(rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1. / 255)
training_set = train_datagen.flow_from_directory('dataset/training_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
test_set = test_datagen.flow_from_directory('dataset/test_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
return train_datagen, test_datagen, training_set, test_set
def your_cnn_model():
# Initialising the CNN
model = Sequential()
# Convolution Layer one
model.add(Conv2D(32, (3, 3), input_shape=(64, 64, 3), activation='relu'))
# Pooling
model.add(MaxPooling2D(pool_size=(2, 2)))
# Adding a second convolutional layer
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# Flattening
model.add(Flatten())
# Full connection
model.add(Dense(units=128, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))
# Compiling the CNN
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# load image function call
train_datagen, test_datagen, training_set, test_set = load_images()
model.fit_generator(training_set, steps_per_epoch=8000, epochs=25, validation_data=test_set, validation_steps=2000)
return model
def load_image_and_predict(image_to_predict_src):
prediction = ""
train_datagen, test_datagen, training_set, test_set=load_images()
image_to_predict_src_toarray = image.img_to_array(image_to_predict_src)
image_to_predict_src_toarray = np.expand_dims(image_to_predict_src_toarray, axis=0)
model = your_cnn_model()
result = model.predict(image_to_predict_src_toarray)
training_set.class_indices
if result[0][0] == 1:
prediction = 'dog'
else:
prediction = 'cat'
return prediction
# A call to function do it all
load_image_and_predict(image_to_predict_src)
| true |
208e3c8abdfaed1e65de1e1557faf7a1f7ea7be7 | Python | vrii14/ppl_assignments-1 | /ass1/2.py | UTF-8 | 246 | 3.03125 | 3 | [] | no_license | import random
while 1 :
a = int(input("If you want to roll the dice press 1 if not the 0\n"))
if a == 1:
print(random.choice([1,2,3,4,5,6]))
elif a==0:
break
print("chance done")
else:
print("Invalid operation")
| true |
99b753ec074ee2f8f6ae73d9f2ff117aad748f36 | Python | adamtwig/D4D | /src/archive/testviz.py | UTF-8 | 581 | 3.5625 | 4 | [] | no_license | from numpy import corrcoef, sum, log, arange
from numpy.random import rand
from pylab import pcolor, show, colorbar, xticks, yticks
# generating some uncorrelated data
data = rand(10,100) # each row of represents a variable
# creating correlation between the variables
# variable 2 is correlated with all the other variables
data[2,:] = sum(data,0)
# variable 4 is correlated with variable 8
data[4,:] = log(data[8,:])*0.5
# plotting the correlation matrix
R = corrcoef(data)
pcolor(R)
colorbar()
yticks(arange(0.5,10.5),range(0,10))
xticks(arange(0.5,10.5),range(0,10))
show()
| true |
e54810b29dc178cb63adb3217730c5ff3a4ff63a | Python | hjhbbd/DY-Data | /下载抖音用户的所有视频/Douyin-DownloadAllVideo/ThreadPool.py | UTF-8 | 668 | 2.9375 | 3 | [] | no_license | import queue
import threading
class ThreadPool(object):
def __init__(self, max_workers):
self.queue = queue.Queue()
self.workers = [threading.Thread(target=self._worker) for _ in range(max_workers)]
def start(self):
for worker in self.workers:
worker.start()
def stop(self):
for _ in range(len(self.workers)):
self.queue.put(None)
for worker in self.workers:
worker.join()
def submit(self, job):
self.queue.put(job)
def _worker(self):
while True:
job = self.queue.get()
if job is None:
break
job()
| true |
0bdd4c0917856392e34e425d5255d09b07e1bf8f | Python | AaronWWK/Courses-Taken | /6.00.1x/Lecture13 Plotting/123.py | UTF-8 | 222 | 2.875 | 3 | [] | no_license | import pylab as plt
plt.figure('My')
plt.plot([1,4,56,32],[1,16,78,90])
plt.figure('You')
plt.plot([1,2,3,4],[1,2,3,44])
plt.figure('My')
plt.ylabel('numbers')
plt.figure('You')
plt.clf()
# plt.title('My')
plt.show()
| true |
0d6e29b81deba149c648e14c2e22ab25ff3ebaed | Python | jletienne/jletienne.com | /test.py | UTF-8 | 3,033 | 2.765625 | 3 | [] | no_license | import requests
import sys, os
import json
import re
import datetime
import calendar
def addEvent(start_time = '10 pm', location = 'location', opponent = 'Opponent',year=3000, month=1, day=1, team='None'):
event_date = datetime.date(year, month, day)
gameday = str(event_date)
weekday = calendar.day_name[event_date.weekday()]
URL = 'https://chup-chombas.firebaseio.com/Teams/{}/Events/{}.json'.format(team, gameday)
players = getPlayers(team)
gameinfo = {
'Start_Time': start_time,
'Location': location,
'Opponent': opponent,
'Players': players,
'Date': '{:%b %d, %Y}'.format(event_date),
'Date2': gameday,
'Weekday': weekday,
}
r = requests.put(URL, data=json.dumps(gameinfo))
return URL
def getPlayers(team):
URL = 'https://chup-chombas.firebaseio.com/Teams/{}/Players.json'.format(team)
r = requests.get(URL).json()
return r
def make_regex(x):
ips = x
products = "".join(ips)
return products
def html_source(URL):
return requests.get(URL).text
def add_allen_team(my_team='Red', location='Allen Hockey Rink', URL=None):
game_times = re.findall(make_regex(['<td>(.*)</td>']), html_source(URL))
game_dates = re.findall(make_regex(['<td class="text-center">(.*?)</td>']), html_source(URL))
regex2 = r'<td class=\\"text-left\\"><a href(.*)</a>'
home_team1 = re.findall(make_regex([regex2]), html_source(URL))
home_team2 = re.findall(make_regex(['<tr><td class="text-left"><span class="highlight"></span><a href(.*)</a>']), html_source(URL))
away_team1 = re.findall(make_regex(['<td class="text-left"><a href(.*)</a>']), html_source(URL))
away_team2 = re.findall(make_regex(['([^<tr>])<td class="text-left"><span class="highlight"></span><a href(.*)</a>']), html_source(URL))
regex = r'>(.*)'
away_teams = [re.findall(regex, str(i))[0] for i in away_team1 + [j[1] for j in away_team2]]
home_teams = [re.findall(regex, str(i))[0] for i in home_team1 + home_team2]
x = [[a[0]] + [a[1]] + [1*(a[2] != my_team)*a[2] + 1*(a[3] != my_team)*a[3]] for a in zip(game_times, game_dates, home_teams, away_teams)]
for i in x:
hockey_month = int(datetime.datetime.strptime('2018 ' + i[1].strip(), '%Y %a, %b %d').strftime("%m"))
hockey_day = int(datetime.datetime.strptime('2018 ' + i[1].strip(), '%Y %a, %b %d').strftime("%d"))
addEvent(start_time = i[0], location = location, opponent = i[2],year=2018, month=hockey_month, day=hockey_day, team=my_team)
if __name__ == "__main__":
#print(incrementTrip('Black'))
my_team = 'Red'
location = 'Allen Hockey Rink'
year = 2018
URL = 'http://stats.pointstreak.com/players/print/players-team-schedule.html?teamid=709641&seasonid=17484'
add_allen_team(my_team=my_team, location='Allen Hockey Rink', URL=URL)
#print(aggregate('JL'))
#print type(datetime.date.today())
| true |
d13065623b7ceb40cddc4a9504fe374833f60676 | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_54/273.py | UTF-8 | 541 | 2.84375 | 3 | [] | no_license | import sys
def gcd(a, b):
return a if b == 0 else gcd(b, a%b)
def read_int():
return [int(e) for e in sys.stdin.readline().split()]
C = read_int()[0]
for cases in xrange(1, C+1):
ii = read_int()
N, t = ii[0], ii[1:]
g = reduce(gcd, t)
d, diff = [x/g for x in t], []
for a in d:
for b in d:
if a != b:
diff.append(abs(a-b))
r = reduce(gcd, diff)
if r != 1:
res = g * (r - d[0] % r)
else:
res = 0
print "Case #%d: %d" % (cases, res)
| true |
8fb025d253d46bedf270182c37c215137a1cb95f | Python | ManbokLee/tensor_libs | /SeoulCCTV/iris.py | UTF-8 | 3,466 | 3.078125 | 3 | [] | no_license | # ************************************
# 랜덤 포레스트 알고리즘의 앙상블 기법
# 사이킷런에 내장된 아이리스 데이터셋 활용
# ************************************
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
np.random.seed(0)
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df.head()
df.columns
'''
Index(['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)',
'petal width (cm)'],
dtype='object')
'''
iris.target
iris.target_names
df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
'''
Index(['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)',
'petal width (cm)', 'species'],
dtype='object')
'''
# learning 전에 지도학습 준비를 하기 위해 dataset 분류
df['is_train'] = np.random.uniform(0,1,len(df)) <= .75 # 75%
'''
Index(['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)',
'petal width (cm)', 'species', 'is_train'],
dtype='object')
'''
train, test = df[df['is_train'] == True], df[df['is_train'] == False]
len(train) # 118 개
len(test) # 32 개
features = df.columns[:4]
features
'''
Index(['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)',
'petal width (cm)'],
dtype='object')
'''
y = pd.factorize(train['species'])[0]
y
'''
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2], dtype=int64)
# one-hot encoding
'''
# *************************
# 랜덤 포레스트 분류기를 이용한 학습 단계
# *************************
clf = RandomForestClassifier(n_jobs=2, random_state=0)
clf.fit(train[features], y)
# 테스트셋에 분류기 적용
clf.predict(test[features])
'''
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 1, 1, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int64)
'''
clf.predict_proba(test[features])[0:10]
'''
array([[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.]])
'''
# **********************
# 분류기에 대한 평가
# **********************
preds = iris.target_names[clf.predict(test[features])]
preds[0:5]
test['species'].head()
pd.crosstab(test['species'], preds, rownames=['Actual Species'], colnames=['Predicted Species'])
'''
Predicted Species setosa versicolor virginica
Actual Species
setosa 13 0 0
versicolor 0 5 2
virginica 0 0 12
'''
# ***********************************
# Feature importance: 판단(예측)하는데 있어 요소의 중요성을 수치화한 값
# ***********************************
list(zip(train[features], clf.feature_importances_))
'''
[
('sepal length (cm)', 0.11185992930506346),
('sepal width (cm)', 0.016341813006098178),
('petal length (cm)', 0.36439533040889194),
('petal width (cm)', 0.5074029272799464)
]
'''
| true |
22072eaddf461a695ce940f3863f2560f93d42d7 | Python | jpmulligan/learn-python-the-hard-way | /ex17.py | UTF-8 | 609 | 3.046875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 22 12:08:30 2018
@author: 40261
"""
print("LPTHW exercises complete: ", round((17.0/48.0)*100,1),"%")
from sys import argv
from os.path import exists
script, from_file, to_file = argv
#print(f"Copying from {from_file} to {to_file}")
indata = open(from_file).read()
#print(f"The input file is {len(indata)} bytes long.")
#print("Ready, hit ENTER to continue, CTRL-C to abort.")
#input()
out_file = open(to_file, 'w')
out_file.write(indata)
#print("Alright, all done!")
print(f"Copied {from_file} to {to_file}, {len(indata)} bytes")
out_file.close()
| true |
f084b8e1cdd29ea70efc5b4593a6abc22c0f5d63 | Python | eduardmak/learnp | /lesson2/homework/ocenki_z3.py | UTF-8 | 475 | 3.125 | 3 | [] | no_license |
uch_list = [{'school_class': '4a', 'scores': [3,4,4,5,2]}, {'school_class': '5a', 'scores': [1,2,4,5,2]}]
avg_per_class = [sum(i.get("scores")) / len(i.get("scores")) for i in uch_list]
avg_per_school = sum(avg_per_class) / len(uch_list)
str_avg_ps = " ".join(str(avg_per_class))
str_avg_sch = " ".join(str(avg_per_school))
print("Средние оценки по ученика:" + str_avg_ps[1:-1])
print("Средние оценки по школе: " + str_avg_sch)
| true |
3b31101040dca914881c88ccdf6264456844f407 | Python | dlf412/thunderCopyright | /vddb_async/auto_deploy_tool/http_url_parser.py | UTF-8 | 969 | 3.015625 | 3 | [
"MIT"
] | permissive | #! /usr/bin/env python
def parse (url):
import urllib
import socket
http_conf = {};
start_idx = url.find ('http://');
if (not (start_idx == 0)):
raise Exception ("bad http format (%s)" %url);
start_idx = len ('http://');
try:
host, port = urllib.splitport (url[start_idx:])
#try:
#socket.inet_aton (host)
#except socket.error:
# raise
http_conf['host'] = host
if port is not None:
http_conf['port'] = int (port)
else:
http_conf['port'] = 80
except Exception, msg:
raise Exception ("bad http url format (%s), %s" % (url, msg))
return http_conf
def main ():
import sys;
if (len (sys.argv) == 1):
print 'Usage %s http_url' %sys.argv[0];
print ' http_url format: http://host:port';
sys.exit (1);
print "http conf dict: %s" % parse (sys.argv[1]);
if __name__ == '__main__':
main ();
| true |
be442962641eddc8003d82cced788d4e72213920 | Python | joey100/simpleBBS | /bbs/commentHandler.py | UTF-8 | 1,581 | 2.703125 | 3 | [] | no_license |
def addNode(treeDic,comment):
if comment.parent_comment is None:
treeDic[comment]={}
else:
for k,v in treeDic.items():
if k == comment.parent_comment:
treeDic[comment.parent_comment][comment]={}
else:
addNode(v,comment)
def buildTree(commentObj):
treeDic = {}
for comment in commentObj:
addNode(treeDic,comment)
for k,v in treeDic.items():
print(k,v)
return treeDic
def renderCommentNode(treeDic,margin):
html = ''
for k,v in treeDic.items():
ele = "<div class='comment-node' style='margin-left:%spx'>" % margin + k.comment + "<span style='margin-left:20px'>%s </span>"%k.date \
+ "<span style='margin-left:20px'>%s</span>" %k.user.name \
+ '<span comment-id="%s" '%k.id + 'style="margin-left:20px" class="glyphicon glyphicon-comment add-comment" aria-hidden="true"></span>'\
+"</div>"
html += ele
html += renderCommentNode(v,margin+20)
return html
def renderCommentTree(treeDic):
html = ''
for k,v in treeDic.items():
ele = "<div class='root-comment'>" + k.comment + "<span style='margin-left:20px'>%s </span>"%k.date \
+ "<span style='margin-left:20px'>%s</span>" %k.user.name \
+ '<span comment-id="%s"' %k.id + ' style="margin-left:20px" class="glyphicon glyphicon-comment add-comment" aria-hidden="true"></span>'\
+ "</div>"
html += ele
html += renderCommentNode(v,10)
return html
pass
| true |
787e9301d9d0898e18f9926b206fdc5717a1e724 | Python | connorwarnock/logbox | /models/log.py | UTF-8 | 1,156 | 2.625 | 3 | [] | no_license | import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID
from lib import db
from lib.database import CRUD, Model
from lib.log_parser import LogParser
from .log_event import LogEvent
class Log(Model, CRUD):
__tablename__ = 'logs'
id = db.Column(UUID(as_uuid=True), primary_key=True, server_default=sa.text('uuid_generate_v4()'))
source = db.Column(sa.String())
path = db.Column(sa.String())
ingested = db.Column(sa.Boolean(), server_default='0', nullable=False)
"""
Reads log from path and saves LogEvents
@return list of parsed LogEvent
"""
def ingest(self):
if self.ingested: raise Error('Log has already been ingested, reset first')
raw_log_events = LogParser(self.path).parse()
log_events = []
for raw_log_event in raw_log_events:
log_events.append(self.__save_log_event(raw_log_event))
self.ingested = True
self.save()
return log_events
def __save_log_event(self, raw_log_event):
log_event = LogEvent(log=self, **raw_log_event)
log_event.set_duration()
log_event.save()
return log_event
| true |
7e8508bf27507bab1350608a954b9cc80147a1c2 | Python | hadaytullah/sa_port | /mape/evaluation/average_wait.py | UTF-8 | 1,468 | 3.0625 | 3 | [] | no_license | from mape.evaluation.abstract_evaluation import AbstractEvaluation
from mape.evaluation.meta_data import EvaluationMetaData
import operator
class AverageWait(AbstractEvaluation):
def __init__(self):
super().__init__()
self.evaluation_name = "Average Wait Time"
self.evaluation_unit = "Minute"
self.maximize = False
self.meta_data = EvaluationMetaData(10, operator.le)
def evaluate_(self, ships):
average_wait_time = 0
if len(ships) > 0:
print("WAIT TIMES")
average_wait_time = 0
wait_sum = 0
for index, current_ship in enumerate(ships):
print(" Ship %i served in %i minutes" % (current_ship.unique_id, current_ship.wait))
wait_sum += current_ship.wait
#calculating average
average_wait_time = wait_sum/(60*len(ships))
print("Average Wait: %f hours" % average_wait_time)
#else:
# print ('No average, no ship served.')
return average_wait_time
def evaluate(self, terminal):
ships = terminal.served_ships
ships_count = len(ships)
if ships_count == 0:
return 0.0
wait_sum = 0
for index, current_ship in enumerate(ships):
wait_sum += current_ship.wait
average_wait_time = wait_sum/ships_count
print('Ships served: {}'.format(ships_count))
return average_wait_time
| true |
5cad12807cac015bd95a327b0cc7e075ef08548f | Python | whglamrock/leetcode_series | /leetcode343 Integer Break.py | UTF-8 | 544 | 3.28125 | 3 | [] | no_license |
# write down the biggest integer break from 2 to 15, you will be able to find out
class Solution(object):
def integerBreak(self, n):
if n == 2:
return 1
if n == 3:
return 2
ans = 1
if n%3 == 0:
for i in xrange(n/3):
ans *= 3
elif n%3 == 1:
for i in xrange(n/3-1):
ans *= 3
ans *= 4
elif n%3 == 2:
for i in xrange(n/3):
ans *= 3
ans *= 2
return ans | true |
6479a7f63fe6536ef952b3c941de0e2fea615f74 | Python | pangzy/experiment | /data processing/reassemble.py | UTF-8 | 4,923 | 2.515625 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from collections import defaultdict
from time import strptime, mktime
def pause():
if raw_input("press any key to continue:"):
pass
def reassemble_from_date():
list_dir = os.listdir(os.getcwd())
date_list = []
record_list = []
for item in list_dir:
if os.path.isfile(item) and ".dat" in item:
f = open(item)
lines = f.readlines()
for line in lines:
ls = line.split()
date = ls[0]
if date in date_list:
idx_rl = date_list.index(date)
record_list[idx_rl].append(line)
else:
date_list.append(date)
record_list.append([line])
for i, item in enumerate(record_list):
date = date_list[i]
file_wrt = date+".http"
wf = open(file_wrt, "w")
wf.writelines(item)
wf.close()
def rename_user():
list_dir = os.listdir(os.getcwd())
alphabet = ("A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z")
user_dict = {}
for item in list_dir:
if os.path.isfile(item) and ".http" in item:
f = open(item)
lines = f.readlines()
for line in lines:
ls = line.split()
mac = ls[2]
try:
if mac not in user_dict:
idx_alpha = len(user_dict)
user_dict[mac] = "USER."+alphabet[idx_alpha]
except Exception as e:
print user_dict
pause()
f.close()
print len(user_dict)
exit()
for item in list_dir:
if os.path.isfile(item) and ".http" in item:
f = open(item)
lines = f.readlines()
for i, line in enumerate(lines):
mac = line.split()[2]
lines[i] = line.replace(mac, user_dict[mac])
f.close()
wf = open(item, "w")
wf.writelines(lines)
wf.close()
def find_dup():
list_dir = os.listdir(os.getcwd())
for line in list_dir:
if os.path.isfile(line) and ".http" in line:
f = open(line)
lines = f.readlines()
d = defaultdict(list)
for k, va in [(v, i) for i, v in enumerate(lines)]:
d[k].append(va)
for x in d.items():
if int(x[0].split()[3]) > 1000000 and len(x[1]) > 1:
print line
print x
pause()
def rename_type():
list_dir = os.listdir(os.getcwd())
type_dict = {}
for item in list_dir:
if os.path.isfile(item) and ".http" in item:
f = open(item)
lines = f.readlines()
for line in lines:
content_type = line.split()[4]
if content_type not in type_dict:
if "video/" in content_type:
v = "video"
elif "audio/" in content_type:
v = "audio"
elif "image/" in content_type:
v = "image"
elif "text" in content_type:
v = "text"
elif "application" in content_type:
v = "application"
elif "other" in content_type:
v = "other"
else:
# print content_type
v = "other"
type_dict[content_type] = v
for item in list_dir:
if os.path.isfile(item) and ".http" in item:
f = open(item)
lines = f.readlines()
for i, line in enumerate(lines):
content_type = line.split()[4]
lines[i] = line.replace(content_type, type_dict[content_type])
f.close()
wf = open(item, "w")
wf.writelines(lines)
wf.close()
def sort_by_time():
list_dir = os.listdir(os.getcwd())
for item in list_dir:
if os.path.isfile(item) and ".http" in item:
f = open(item)
lines = f.readlines()
lines.sort(key=lambda i: int(mktime(strptime(i[0:19], "%Y-%m-%d %H:%M:%S"))))
f.close()
wf = open(item, "w")
wf.writelines(lines)
wf.close()
if __name__ == '__main__':
#reassemble_from_date()
rename_user()
#rename_type()
#find_dup()
#sort_by_time()
| true |
8259af9cbb5a9c76d805a9d72a603af0ecc7b99b | Python | abner0908/pythonProject | /practices/re_test_patterns.py | UTF-8 | 685 | 3.484375 | 3 | [] | no_license | import re
def test_patterns(text, patterns = []):
for pattern, desc in patterns:
print("Pattern: {0} ({1})\n".format(pattern, desc))
print(" {0}".format(text))
for match in re.finditer(pattern, text):
start = match.start()
end = match.end()
stars = '*' * start
print(" {0}{1}".format(stars, text[start:end]))
print
return
if __name__ == '__main__':
test_patterns('abbaaabbbbaaaaa',
[ ('ab*', 'a followed by zero or more b'),
('ab+', 'a followed by one or more b'),
('ab?', 'a followed by zero or one b'),
('ab{3}', 'a followed by three b'),
('ab{2,3}', 'a followed by two to three b')
]) | true |
e5a0bd0d801e8326f43f68488061a9dddd4e20d0 | Python | Jason-bolt/projectWork | /pHSensor.py | UTF-8 | 269 | 3.03125 | 3 | [] | no_license | from machine import Pin, ADC
import time
pH = ADC(Pin(33))
gradient = -0.114285714
intercept = 29.771428522
while True:
voltage = (gradient * pH.read()) + intercept
print("With intercept:", voltage)
print("Raw analog:", pH.read())
time.sleep_ms(500)
| true |
04bead6a4ecd3aaaf9ad1f56c3bbfb5dee1c4c90 | Python | cottrell/mylib | /my/oldlib/plotting.py | UTF-8 | 1,032 | 2.6875 | 3 | [] | no_license | import numpy as np
# notes mostly
def meshgrid_from_df(df, **kwargs):
# this is useful because meshgrid is confusing ... is like 'real space' not i,j space ... things are flipped.
df = df.sort_index(axis=1).sort_index(axis=0)
x, y = np.meshgrid(df.index.values, df.columns.values, **kwargs)
z = df.values.T
return x, y, z
def doplot_3d_from_df(df, zlabel=None, fig=None, num=1, kind="wireframe", meshgrid_kwargs={}, **plot_options):
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
if fig is None:
fig = plt.figure(num=num)
ax = plt.axes(projection="3d")
xx, yy, zz = meshgrid_from_df(df, **meshgrid_kwargs)
if kind == "wirefram":
ax.plot_wireframe(xx, yy, zz, **plot_options)
else:
raise Exception("nip")
if df.index.names is not None:
ax.set_xlabel(df.index.names[0])
if df.columns.names is not None:
ax.set_ylabel(df.columns.names[0])
if zlabel is not None:
ax.set_zlabel(zlabel)
return fig, ax
| true |
c32d5e82d026f93ead46ddf62a292ba53aade154 | Python | frestr/Python-obfuscator-3000 | /pyobfs3000.py | UTF-8 | 333 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env python3
from sys import argv
from obfuscator import Obfuscator
def main():
obfs = Obfuscator()
try:
argv[1]
argv[2]
except:
print('Format: ./pyobfs3000.py <in_file> <out_file>')
return
obfs.obfuscate_file(argv[1], argv[2])
if __name__ == '__main__':
main()
| true |
5bfedd4af5ad9d30586881a3e0c66709cca9e793 | Python | zahidzqj/learn_python | /函数/z_匿名函数.py | UTF-8 | 645 | 3.953125 | 4 | [] | no_license | #coding=utf-8
test2 = lambda a,b:a-b
result2 = test2(11,22)#调用匿名函数
print(result2)
infors = [{"name":"laowang","age":21},{"name":"xiaoming","age":20},{"name":"banzhang","age":21}]
infors.sort(key=lambda x:x['age'])
print(infors)
def test_sum(a,b,func):
result = func(a,b)
return result
num1 = test_sum(11,22,lambda x,y:x+y)
print(num1)
def test(a,b,func):
result = func(a,b)
return result
#python2中的方式
func_new = input("请输入一个匿名函数:")#lambda a,b:a*b
#python3中的方式
#func_new = input("请输入一个匿名函数:")
#func_new = eval(func_new)
num = test(11,22,func_new)
print(num)
| true |
b059143d6f3690ca97520762f9ae3ab03177e5a0 | Python | Avivbh/ffxiv_experiment | /ultimatum_game_intro/models.py | UTF-8 | 1,235 | 2.6875 | 3 | [
"MIT"
] | permissive | from otree.api import (
models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,
Currency as c, currency_range
)
import random
doc = """
One player decides how to divide a certain amount between himself and the other
player.
See: Kahneman, Daniel, Jack L. Knetsch, and Richard H. Thaler. "Fairness
and the assumptions of economics." Journal of business (1986):
S285-S300.
"""
class Constants(BaseConstants):
name_in_url = 'ffxiv experiment intro'
players_per_group = None
num_rounds = 1
instructions_template = 'ultimatum_game_intro/Instructions.html'
endowment = c(10000)
class Subsession(BaseSubsession):
pass
class Group(BaseGroup):
question_1_answer = models.IntegerField(
choices=[
[1, 'The proposer will get 3000 gil and the responder will get 7000 gil'],
[2, 'The proposer will get 7000 gil and the responder will get 3000'],
[3, 'None of the above'],
])
question_2_answer = models.IntegerField(
choices=[
[1, 'The proposer will get 3000 gil and the responder will get 7000 gil'],
[2, 'Both players gets 0 gil'],
[3, 'None of the above'],
])
class Player(BasePlayer):
pass
| true |
8b2659f22c629d7de388e33433cb5a6be08f1705 | Python | gobert/ud120-projects | /svm/svm_author_id.py | UTF-8 | 1,688 | 2.984375 | 3 | [] | no_license | #!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()
#########################################################
### your code goes here ###
# features_train = features_train[:len(features_train)/100]
# labels_train = labels_train[:len(labels_train)/100]
from sklearn import svm
clf = svm.SVC(C=10000.0, kernel="rbf")
clf.fit(features_train, labels_train)
print("fitted")
predictions = clf.predict(features_test)
import code; code.interact(local=dict(globals(), **locals()))
print("predicted")
# from sklearn.metrics import accuracy_score
# acc = accuracy_score(labels_test, predictions)
# print("Finished. Accuracy: " + str(acc))
# # get the hyperplane# get the separating hyperplane
# import numpy as np
# w = clf.coef_[0]
# a = -w[0] / w[1]
# xx = np.linspace(0, 0.5)
# yy = a * xx - (clf.intercept_[0]) / w[1]
#
# # draw it
# import matplotlib.pyplot as plt
# plt.plot(xx, yy, 'k-')
# plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
# s=80, facecolors='none')
# plt.scatter(features_train[:, 0], features_train[:, 1], c=labels_train, cmap=plt.cm.Paired) # RdBu_r
# plt.show()
# #########################################################
| true |
d2ebfd09e47a80733c87eecfe508af6dd4c1a51e | Python | saymoniphal/fswd3-tournament-result | /tournament.py | UTF-8 | 7,676 | 3 | 3 | [] | no_license | #!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import contextlib
import time
import psycopg2
import config
@contextlib.contextmanager
def connect():
"""Connect to the PostgreSQL database. Returns a database connection.
Use context manager decorator for database connection for 'with'
statement, avoid repeated codes on connection commit, and close."""
conn = None
try:
params = config.readconfig('database.ini')
conn = psycopg2.connect(database=params['database'])
yield conn
conn.commit()
except:
if conn:
conn.rollback()
raise
finally:
if conn:
conn.close()
@contextlib.contextmanager
def getcursor(conn):
cursor = None
try:
cursor = conn.cursor()
yield cursor
finally:
if cursor:
cursor.close()
def _run_sql(sql, args=None, fetch=True):
"""Connect to PosgreSQL database and execute the query
Args:
sql: sql query to be executed
args: argument for the sql query
Returns:
sql query results
"""
results = []
with connect() as conn, getcursor(conn) as cursor:
cursor = conn.cursor()
cursor.execute(sql, args)
if fetch:
results = cursor.fetchall()
return results
def deleteMatches(tournament=None):
"""Remove the match records in tournament(s) from the database.
Arg:
tournament (optional): the tournament id to remove matches from.
If None, then All match records of all tournaments will be removed.
"""
sql = "DELETE from match"
if tournament:
sql += " WHERE tournament_id=" + tournament
sql += ";"
_run_sql(sql, fetch=False)
def deleteTournaments(tournament=None):
"""Remove the tournament record(s) from the database. If tournament id
is None, then remove all the tournament records."""
if tournament is not None:
sql = "DELETE FROM tournament WHERE id = %s;"
args = (tournament,)
else:
sql = "DELETE FROM tournament;"
args = tuple()
_run_sql(sql, args, fetch=False)
def deleteTournamentPlayers(tournament=None):
if tournament is not None:
sql = "DELETE FROM tournamentplayers where tournament_id = %s;"
args = (tournament,)
else:
sql = "DELETE FROM tournamentplayers;"
args = (tournament,)
_run_sql(sql, args, fetch=False)
def deletePlayers(ids=None):
"""Remove the player(s) records in tournament from the database."""
sql = "DELETE from player"
if ids is not None:
sql += " WHERE id IN ("
valuelist = ['%s' for i in range(len(ids))]
sql += ', '.join(valuelist) + ')'
sql += ";"
_run_sql(sql, ids, fetch=False)
def countPlayers(tournament=None):
"""Returns the number of players registered for tournament(s)."""
nums = 0
sql = "SELECT count(*) as nums from player"
if tournament is not None:
sql += " JOIN tournamentplayers \
ON player.id = tournamentplayers.player_id \
WHERE tournamentplayers.tournament_id = %s"
sql += ";"
args = (tournament,)
res = _run_sql(sql, args)
nums = res[0][0]
return nums
def registerTournament(name, year=None):
"""Add a tournament to the tournament database.
The database assigns a unique serial id number for the tournament.
Args:
name: the tournament's name (need not be unique)
year: the year that the tournament taken place
(current year will be added in case of None)
Returns:
return the tournament id number of last inserted.
"""
sql = "INSERT INTO tournament(name, year) VALUES (%s,%s) \
RETURNING tournament_id;"
if year is None:
year = time.localtime().tm_year
results = _run_sql(sql, [name, year])
return results[0][0]
def getTournamentIDs():
"""Returns list of tournament ids"""
sql = "SELECT tournament_id from tournament;"
return _run_sql(sql)
def registerPlayer(name, **kwargs):
"""Adds a player to the tournament database.
The database assigns a unique serial id number for the player.
Args:
name: the player's full name (need not be unique).
kwargs: a dictionary with key: 'gender', 'dob' as additional information
of the player, could be None
Returns:
The id number of the last inserted player.
"""
sql = "INSERT INTO player (name"
kwargs['name'] = name
namedlist = ['%(name)s']
if 'gender' in kwargs:
namedlist.append('%(gender)s')
sql += ", gender"
if 'dob' in kwargs:
namedlist.append('%(dob)s')
sql += ", dob"
sql += ") values (" + ', '.join(namedlist) + ")"
# need the last inserted id to add to tournamentplayers record
sql += " RETURNING id;"
results = _run_sql(sql, kwargs)
return results[0][0]
def getPlayer(player_id):
"""Return player record"""
sql = "SELECT * FROM player WHERE id = %s;"
return _run_sql(sql, [player_id])
def addPlayerToTournament(player_id, tournament_id):
"""Add player to tournament.
Args:
player_id: the id number of the player
tournament_id: the id number of the tournament.
"""
sql = "INSERT INTO tournamentplayers(tournament_id, player_id) VALUES \
(%s, %s);"
_run_sql(sql, (tournament_id, player_id,), fetch=False)
def playerStandings(tournament):
"""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.
Args:
tournament: the id number of the tournament
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
"""
sql = "SELECT * FROM playerStandings_view;"
return _run_sql(sql)
def reportMatch(winner_id, loser_id, match_round, tournament_id):
"""Records the outcome of a single match between two players in a tournament.
Args:
winner_id: the id number of the winner
loser_id: the id number of the loser
match: round of match
tournament: the id number of the tournament
"""
sql = "INSERT INTO match (winner_id, loser_id, match_round, \
tournament_id) VALUES (%s, %s, %s, %s);"
queryargs = [winner_id, loser_id, match_round, tournament_id]
_run_sql(sql, queryargs, fetch=False)
def swissPairings(tournament):
"""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.
Args:
tournament: the id number of the tournament
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
"""
standings = playerStandings(tournament)
id_names = [(elem[0], elem[1]) for elem in standings]
return [(elem[0][0], elem[0][1], elem[1][0], elem[1][1])
for elem in zip(id_names[::2], id_names[1::2])]
| true |
8873ed462557e6f692f8f610be15766044ff99ae | Python | SushilPudke/PythonTest | /test.py | UTF-8 | 235 | 3.734375 | 4 | [] | no_license | msg="hello! World"
print (msg)
x=5
if x==10:
print("x is ",x)
else:
print("Not match")
'''
Multi Line Comment
sfsf
s
'''
a=input("Enter any no ")
print("Entered no ",a)
nm=input("Enter Your Name ")
print("Entered Name ",nm) | true |
95a01ef80989b6d16b7bf74d10cbd13ebdd08506 | Python | PaulZhu0122/CS303_AI | /Reversi_AI.py | UTF-8 | 2,855 | 3.65625 | 4 | [] | no_license | import numpy as np
import random
import time
COLOR_BLACK = -1
COLOR_WHITE = 1
COLOR_NONE = 0
random.seed(0)
# don't change the class name
class AI(object):
# chessboard_size, color, time_out passed from agent
def __init__(self, chessboard_size, color, time_out):
self.chessboard_size = chessboard_size
# You are white or black
self.color = color
# the max time you should use, your algorithm's run time must not exceed the time limit.
self.time_out = time_out
# You need add your decision into your candidate_list. System will get the end of your candidate_list as your decision .
self.candidate_list = []
self.board_weights = [
[120, -20, 20, 5, 5, 20, -20, 120],
[-20, -40, -5, -5, -5, -5, -40, -20],
[20, -5, 15, 3, 3, 15, -5, 20],
[5, -5, 3, 3, 3, 3, -5, 5],
[5, -5, 3, 3, 3, 3, -5, 5],
[20, -5, 15, 3, 3, 15, -5, 20],
[-20, -40, -5, -5, -5, -5, -40, -20],
[120, -20, 20, 5, 5, 20, -20, 120]
]
# The input is current chessboard.
def go(self, chessboard):
# Clear candidate_list, must do this step
self.candidate_list.clear()
# ==================================================================
# Write your algorithm here
directions = [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]
for i in range (8):
for j in range(8):
if (chessboard[i][j] == 0):
for direction in directions:
x = i + direction[0]
y = j + direction[1]
while (x >= 0 and x < 8 and y >= 0 and y < 8 and chessboard[x][y] == -self.color):
x += direction[0]
y += direction[1]
if (x >= 0 and x < 8 and y >= 0 and y < 8 and chessboard[x][y] == self.color):
if (i,j) not in self.candidate_list:
self.candidate_list.append((i,j))
# Here is the simplest sample:Random decision
# ==============Find new pos========================================
# Make sure that the position of your decision in chess board is empty.
# If not, the system will return error.
# Add your decision into candidate_list, Records the chess board
# You need add all the positions which is valid
# candidate_list example: [(3,3),(4,4)]
# You need append your decision at the end of the candidate_list,
# we will choose the last element of the candidate_list as the position you choose
# If there is no valid position, you must return a empty list. | true |
29c475f7516115b529e0f650ad9dca58bf78997e | Python | matthew-maya-17/CSCI-1100-Computer-Science-1 | /RPI-CS1100-HW/hw8_files_F19/hw8_files_F19/hw8_part1.py | UTF-8 | 939 | 3.21875 | 3 | [] | no_license | import json
import BerryField
import Bear
import Tourist
file = input("Enter the json file name for the simulation => ")
print(file)
#file = "bears_and_berries_1.json"
f = open(file)
data = json.loads(f.read())
bf = (data["berry_field"])
ab = (data["active_bears"])
rb =(data["reserve_bears"])
at = (data["active_tourists"])
rt = (data["reserve_tourists"])
#creates tourist list
tourists = []
for x in range(len(at)):
tourists.append(Tourist.Tourist(at[x][0],at[x][1]))
#creates bear list
bears =[]
for x in range(len(ab)):
bears.append(Bear.Bear(ab[x][0],ab[x][1],ab[x][2]))
#prints everything
berryfield = BerryField.BerryField(bf,tourists,bears)
print("\nField has {} berries.".format(berryfield.totalb()))
print(berryfield)
print("Active Bears:")
for x in range(len(bears)):
print(bears[x])
print("\nActive Tourists:")
for x in range(len(tourists)):
print(tourists[x])
| true |
d23f2755679f789c7a8ba97c38227474e18046cc | Python | aaqingsongyike/Python | /Python_Process/test/demo-02.py | UTF-8 | 507 | 3.671875 | 4 | [] | no_license | #并发
#fork()
import os
import time
#只能在Linux和Mac中使用
ret = os.fork() #fork()的返回值是 等于0(主进程)和大于0(子进程)
print("父进程和子进程都执行")
"""
os.getpid() 获取当前进程的值(pid)
os.getppid() 获取父进程的pid
"""
if ret == 0:
while True:
print("-父进程-%d"%os.getpid())
time.sleep(1)
else:
while True:
print("-子进程-%d-%d"%(os.getppid(), os.getpid()))
time.sleep(2)
| true |
a58668e2e2f2b567a4be003d3f5811dbe52d0428 | Python | rnaidu999/MyLearnings | /Date_Difference.py | UTF-8 | 943 | 3.53125 | 4 | [] | no_license |
from datetime import datetime
from datetime import date
def days_between(d1, d2):
d1 = datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.strptime(d2, "%Y-%m-%d")
return abs((d2 - d1).days)
#dat1=input("Enter Start Date :")
#dat2=input("Enter End Date :")
#print(days_between(dat1,dat2))
d1=date(2014,1,1)
d2=date(2014,1,15)
delta=d2-d1
print(delta.days)
val=['',2,2,'']
val2=[]
val2=[var for var in val if var]
print(val2)
list11=[2,2,3,3,4,4]
list11.remove(2)
print(list11)
#get today time and year
import calendar
from datetime import datetime
currentSecond= datetime.now().second
currentMinute = datetime.now().minute
currentHour = datetime.now().hour
currentDay = datetime.now().day
currentMonth = datetime.now().month
currentYear = datetime.now().year
print (currentHour, currentMinute, currentSecond, currentYear, currentMonth, currentDay)
cal=calendar.TextCalendar()
print (cal.prmonth(currentYear,currentMonth))
| true |
11ae801cc209da44ed9642aac795a943ab69bb77 | Python | SindriSB/Info284 | /Kandidat81/81.py | UTF-8 | 1,170 | 3.4375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
author: 81
"""
#Loads libraries
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.neighbors import KNeighborsRegressor
# Loads dataset
dataset = pd.read_csv('Flaveria.csv')
# Makes new columns with float instead of string objects. Basicly converts the string to float so it possible to run the algorithem.
# So you can both se the string and the float.
dataset['N_level_float'] = dataset['N level'].map({'L':0.0, 'M':1.0, 'H':2})
dataset['species_float'] = dataset['species'].map({'brownii':0.0, 'pringlei':1.0, 'trinervia':2.0, 'ramosissima':3.0, 'robusta': 4.0, 'bidentis':5.0})
# Sets X = N_level_float','species_float and y = 'Plant Weight(g)'
X = dataset[['N_level_float','species_float']].values
y = dataset[['Plant Weight(g)']].values
# Splits the dataset into traing and test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size =0.2, random_state=88)
# Uses the KNeighborsRegressor
my_Regressor = KNeighborsRegressor(n_neighbors=3).fit(X_train, y_train)
#Prints score
print ("Score : {:.3f}".format(my_Regressor.score(X_test, y_test)))
| true |
f2893e28a85157993c8e6cc04c886b95a4983d12 | Python | akakcolin/myDocumentsSyn | /scripts/plot_vasp_ir.py | UTF-8 | 8,280 | 2.96875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#############################################
# #
# plot IR #
# S.Nenon 2015 #
# tiny changed by lzh 2021 #
#############################################
# todo: clean
import sys
import os
import numpy as np
import re
# defining constants for the lorentzian smearing
epsilon = 1e-8
fwhm=15.0
# inspired from Balint Aradi smearing procedure for DOS analysis in DFTB
class Lorentz(object):
"""Lorentzian smearing"""
def __init__(self, gamma, center, coef):
self._gamma = gamma
self._center = center
self._coef = coef
def __call__(self, xx):
dx = xx - self._center
return self._coef/(1+4*(dx**2)/((2*self._gamma)**2))
class Mode():
"""
Structure for storing frequency (self.freq) and eigenvalues (self.values) of each mode. If the frequency is imaginary, it is set to be negative.
"""
def __init__(self,text):
tline = text.split('\n')
if 'f/i' in tline[0]:
fi_factor = -1.0
else:
fi_factor = 1.0
self.freq=float(re.findall(r'Hz\s+(\d+\.\d+)\s+cm-1',tline[0])[0])*fi_factor
tmplist = []
for i in tline[2:]:
if i.strip():
tmplist.append([float(x.strip()) for x in i.split()])
self.values = np.array(tmplist)
def readfile(file):
"""
Transforms the input text file into an array
"""
# get file content
with open(file,'r') as f:
content=[line.strip() for line in f.readlines()]
# remove blank lines
for i in range(len(content)):
if content[i] == '':
del(content[i])
# generate array
values=np.zeros((len(content), 2))
for i in range(len(content)):
tmp= [float(x) for x in content[i].split()]
values[i,0]=tmp[1]
values[i,1]=tmp[2]
return values
def plotIR():
"""
Generates a lorentzian spectrum
"""
gamma=fwhm/2.0
print('Parsing file....')
print ("="*len('Parsing file'))
values=readfile('results.txt')
min_freq=values[-1,0]
max_freq=values[0,0]
freq_step=(max_freq-min_freq)/1000.0
print("\nInitial values")
print ("\tMax. freq.: {0}".format(max_freq))
print ("\tMin. freq.: {0}".format(min_freq))
print ("\tFreq. step: {0} cm-1".format(freq_step))
print ("\nGenerating Lorentzians")
print ("="*len("Generating Lorentzians"))
print ("\tFWHM: {0} cm-1".format(gamma*2))
smearer=[]
for i in values:
smearer.append(Lorentz(gamma,i[0],i[1]))
print ('\tdone...')
print ("\nGenerating spectrum")
print("="*len("Generating spectrum"))
nItem = 1000
result = np.zeros((nItem, 2), dtype=float)
freq = min_freq
lasti=0
for i in range(len(result)):
sys.stdout.write("\r[{0:20s}]".format(int(float(i)/float(len(result))*20)*"#"))
sum = 0.0
for func in smearer:
sum += func(freq)
result[i,0] = freq
result[i,1] = sum
freq += freq_step
with open('spectrum.txt','w') as spec:
for i in result:
if i[1] not in ['inf','nan']:
spec.write("{0:.10f} {1:.10f}\n".format(i[0],i[1]))
print ('\n\tspectrum.txt written')
def parseEigenvectors(nIons, outcar):
"""
Generates a list of modes (frequency, eigenvector) from eigenvectors.txt file
"""
outcar_sp=outcar.split('SQRT(mass)')[1]
EIG_NVIBS = len(re.findall('cm-1',outcar_sp))
EIG_NROWS = (nIons+3)*EIG_NVIBS+3
content = []
for i in outcar_sp.split('\n'):
if '-----------------------------------------------------------------------------------------' in i: break
content.append(i)
eigV = []
buffer = ""
for line in content[4:]:
lst = line.strip()
if not lst:
if buffer != "":
eigV.append(Mode(buffer))
buffer = ""
else:
buffer += '{0}\n'.format(line)
return eigV
def parsePolar(nIons,outcar):
"""
Generates a list of arrays containing Born Charges from born.txt file
"""
# ================== Get born Charges =====================
bornLines = 4 * nIons + 1
# get born charges fix for vasp6
outcar_sp=outcar.split('cummulative output)')[1]
bCharges=[]
outcar_lines = outcar_sp.split('\n')
bCharges.extend(outcar_lines[2:bornLines+1])
Polar = []
buffer = ""
start = False
for line in bCharges:
lst = line.strip()
if 'ion' in lst:
if start:
pol = []
for i in buffer.split('\n'):
if i.strip():
pol.append([float(x.strip()) for x in i.split()[1:]])
Polar.append(np.array(pol))
buffer = ""
else:
start = True
else:
buffer += '{0}\n'.format(line)
pol = []
for i in buffer.split('\n'):
if i.strip():
pol.append([float(x.strip()) for x in i.split()[1:]])
Polar.append(np.array(pol))
return Polar
def calcIntensities(nIons,eigV,polar):
"""
Computes the IR intensities
"""
with open('exact.res.txt','w') as outfile:
for mm in range(len(eigV)):
int = 0.0
eigVals = eigV[mm].values
freq = eigV[mm].freq
for alpha in range(3):
sumpol = 0.0
for atom in range(nIons):
tmpval = eigVals[atom,3]*polar[atom][alpha,0]\
+ eigVals[atom,4]*polar[atom][alpha,1]\
+ eigVals[atom,5]*polar[atom][alpha,2]
sumpol += tmpval
int += sumpol**2
outfile.write('{0:03d} {1:.5f} {2:.5f}\n'.format(mm+1,freq,int))
def normalize():
"""
Normalizes the IR intensities
"""
with open('exact.res.txt','r') as infile:
values = np.array([y.strip().split() for y in infile.readlines() if y],dtype=float)
maxval = max(values[:,2])
values[:,2] /= maxval
with open('results.txt','w') as outfile:
for val in values:
outfile.write('{0:>5d} {1:>10.5f} {2:10.5f}\n'.format(int(val[0]), val[1], val[2]))
if __name__ == "__main__":
print( 'Opening OUTCAR file')
print ("="*len('Opening OUTCAR file'))
nionsR = re.compile(r'NIONS\s+=\s+(\d+)')
try:
with open('OUTCAR','r') as buffer:
outcar=buffer.read()
except:
sys.exit('OUTCAR file not found. Please try again in the folder containing OUTCAR')
# test born charges
if not re.search('BORN',outcar):
sys.exit('Born charges are not present in OUTCAR')
nIons = int(re.findall(nionsR,outcar)[0])
print ('\tParsing eigenvectors')
eigV = parseEigenvectors(nIons,outcar)
print ('\n\n\tParsing Born charges')
polar = parsePolar(nIons,outcar)
print ('\n\nCalculating intensities')
print ("="*len('Calculating intensities'))
calcIntensities(nIons,eigV,polar)
print ('\texact.res.txt written\n\nNormalizing')
print ("="*len('Normalizing'))
normalize()
print ('\tresults.txt written\n')
plotIR()
print ('\nGenerating gnuplot script')
print ("="*len('Generating gnuplot script'))
with open('spectrum.gnu','w') as gnu:
gnu.write("#set term aqua enhanced font 'Helvetica,20' # comment for pdf output\n")
gnu.write("set term pdf color enhanced font 'Helvetica,18' size 16cm,12cm # uncom")
gnu.write("ment for pdf output\nset output 'spectrum.pdf' #uncomment for pdf output\n\n")
gnu.write("\n#scales\n#set xrange[100:1000]\n#set yrange[0:1]\n\n")
gnu.write("set xlabel 'Frequency (cm^{-1})'\n")
gnu.write("set ylabel 'Normalized intensity'\n")
gnu.write("set grid nopolar\n")
gnu.write("set grid layerdefault lt 0 linecolor 0 linewidth 0.500, lt 0 linecolor 0 linewidth 0.500\n")
gnu.write("p 'results.txt' u 2:3 w i t'Normalized IR spectrum','spectrum.txt' w l t'Lorentzian smearing'\n")
print ('\tspectrum.gnu written\n\nSuccessfull termination !')
os.system("gnuplot spectrum.gnu")
print("\n generate spectrum.pdf, have fun")
| true |
63e68d2a6eb2027b62eec3761ee5706dceb5af08 | Python | Cahersan/django-formulator | /formulator/__init__.py | UTF-8 | 263 | 2.625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
VERSION = (0, 2, 0, 'dev')
__version__ = '.'.join((str(each) for each in VERSION[:4]))
def get_version():
"""
Returns shorter version (digit parts only) as string.
"""
return '.'.join((str(each) for each in VERSION[:4]))
| true |
ce78aff2fd8d641037ad824290d2a90d787523f8 | Python | owhyy/automate-the-boring-stuff-2e | /Ch3/collatz.py | UTF-8 | 356 | 4.03125 | 4 | [] | no_license |
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
print(3 * number + 1)
return 3 * number + 1
def read():
try:
number = int(input())
while(number != 1):
number = collatz(number)
except ValueError:
print('Error: Invalid paramter (expected int)')
read()
| true |
09ea6b977a63aff6af688c3f43178f09f56a3099 | Python | Clipsey/PI-Drone-Camera | /Working-Demo-Stuff/Test_Bench.py | UTF-8 | 1,371 | 2.515625 | 3 | [] | no_license | import pygame
import Drone_Controller_Module
import Drone_Webcam_Module
import time
import threading
import socket
drone_quit = False
def ControllerThreadLoop(Controller):
global drone_quit
while Controller.done == False and drone_quit == False:
try:
Controller.RunSingleIteration()
time.sleep(0.05)
except KeyboardInterrupt:
drone_quit = True
exit()
drone_quit = True
exit()
def CameraThreadLoop(Camera):
global drone_quit
while Camera.done == False and drone_quit == False:
try:
Camera.RunSingleIteration()
time.sleep(0.04)
except (KeyboardInterrupt, socket.error):
drone_quit = True
exit()
drone_quit = True
exit()
pygame.init()
Controller = Drone_Controller_Module.Drone_Receiver('',1881, False)
#ControllerThreadLoop(Controller)
Drone_Cam = Drone_Webcam_Module.Drone_Webcam('192.168.137.1',9001)
Control_thread = threading.Thread(target=ControllerThreadLoop,args=(Controller,))
Camera_thread = threading.Thread(target=CameraThreadLoop,args=(Drone_Cam,))
Control_thread.start()
input("Press Enter to start Webcam Thread")
Camera_thread.start()
Control_thread.join()
Camera_thread.join()
Controller.ClassClose()
Drone_Cam.ClassClose()
pygame.quit()
exit() | true |
2596d563338342d256225de606c600ff6257c8c8 | Python | lienordni/ProjectEuler | /45.py | UTF-8 | 321 | 3.390625 | 3 | [] | no_license | import math
def tri(x):
return (-1+math.sqrt(1+8*x))/2==int((-1+math.sqrt(1+8*x))/2)
def pent(x):
return (1+math.sqrt(1+24*x))/6==int((1+math.sqrt(1+24*x))/6)
def hexa(x):
return int((1+math.sqrt(1+8*x))/4)
i=2
while True:
if(pent(i*(2*i-1)) and tri(i*(2*i-1))):
print(i*(2*i-1))
print()
i+=1 | true |
4cf03066983aad1c58761950d96ea9d60a2c265c | Python | ryannewman2828/Documented-Learning | /Algorithms/Sequences/Merge Sort/MergeSort.py | UTF-8 | 795 | 3.546875 | 4 | [] | no_license | #!/usr/bin/python
import random
maxNum = 1000000
# The array that is to be sorted
arr = [int(maxNum * random.random()) for i in range(10000)]
def merge(listA, listB):
listReturn = []
while len(listA) > 0 or len(listB) > 0:
if len(listA) == 0:
listReturn.extend(listB)
listB.clear()
elif len(listB) == 0:
listReturn.extend(listA)
listA.clear()
elif listA[0] < listB[0]:
listReturn.append(listA.pop(0))
else:
listReturn.append(listB.pop(0))
return listReturn
def mergeSort(array):
if len(array) == 1:
return array
listA = mergeSort(array[:len(array) // 2])
listB = mergeSort(array[len(array) // 2:])
return merge(listA, listB)
print(mergeSort(arr))
| true |
f7fa6a7519c347da064547a547b3ca8d0d96af13 | Python | denny0323/EM_Project | /Seq2Seq/sm_tool.py | UTF-8 | 5,335 | 2.515625 | 3 | [] | no_license | import numpy as np
import pandas as pd
from hanspell import spell_checker
from collections import defaultdict
import operator
import re
#### data_loading function
def loading_data(data_name):
# data format : csv
corpus = pd.read_csv(data_name, sep=",", names=None, encoding='cp949')
corpus = pd.DataFrame(corpus)
docno = corpus['no']
res = corpus['res']
code = corpus['code']
# for doc in corpus:
# if type(doc[0]) is not str or type(doc[1]) is not str:
# continue
# if len(doc[0]) > 0 and len(doc[1]) > 0:
# tmpcode = normalize(doc[0], english=eng, number=num, punctuation=punc)
# tmpress = normalize(doc[1], english=eng, number=num, punctuation=punc)
# code.append(tmpcode)
# ress.append(tmpress)
return docno, res, code
#### correction function
def spellchecker(doc):
for i in range(0, len(doc)):
try:
doc[i]=doc[i].replace("\t"," ") # 탭을 공백 하나로 대체
doc[i]=" ".join(doc[i].split()) # 중복된 공백 제거
result=spell_checker.check(doc[i])
doc[i]=result.checked
except:
doc[i]=doc[i] # 교정이 안된 데이터는 그대로
return doc
#### word dictionary
def make_dict_all_cut(res, code, minlength, maxlength, jamo_delete=False):
dict = defaultdict(lambda: [])
ress = res + ' ' + code
for doc in ress:
for idx, word in enumerate(re.findall(r"[\w']+", doc)):
if len(word) > minlength:
normalizedword = word[:maxlength]
if jamo_delete:
tmp = []
for char in normalizedword:
if ord(char) < 12593 or ord(char) > 12643:
tmp.append(char)
normalizedword = ''.join(char for char in tmp)
if word not in dict[normalizedword]:
dict[normalizedword].append(word)
dict = sorted(dict.items(), key=operator.itemgetter(0))
words = []
for i in range(len(dict)):
word = [] # normalized voca list
word.append(dict[i][0])
for w in dict[i][1]:
if w not in word:
word.append(w)
words.append(word)
words.append(['<PAD>'])
words.append(['<S>'])
words.append(['<E>'])
words.append(['<UNK>'])
# word_to_ix, ix_to_word 생성
ix_to_word = {i: ch[0] for i, ch in enumerate(words)}
word_to_ix = {}
for idx, words in enumerate(words):
for word in words:
word_to_ix[word] = idx
print('Data 갯수 : %s, 단어 갯수 : %s'
% (len(ress), len(ix_to_word)))
return word_to_ix, ix_to_word
#### making input function
def make_inputs(rawinputs, rawtargets, word_to_ix, encoder_size, decoder_size, shuffle=True):
rawinputs = np.array(rawinputs)
rawtargets = np.array(rawtargets)
if shuffle:
shuffle_indices = np.random.permutation(np.arange(len(rawinputs)))
rawinputs = rawinputs[shuffle_indices]
rawtargets = rawtargets[shuffle_indices]
encoder_input = []
decoder_input = []
targets = []
target_weights = []
for rawinput, rawtarget in zip(rawinputs, rawtargets):
tmp_encoder_input = [word_to_ix[v] for idx, v in enumerate(rawinput.split()) if
idx < encoder_size and v in word_to_ix]
encoder_padd_size = max(encoder_size - len(tmp_encoder_input), 0)
encoder_padd = [word_to_ix['<PAD>']] * encoder_padd_size
encoder_input.append(list(reversed(tmp_encoder_input + encoder_padd)))
tmp_decoder_input = [word_to_ix[v] for idx, v in enumerate(rawtarget.split()) if
idx < decoder_size - 1 and v in word_to_ix]
decoder_padd_size = decoder_size - len(tmp_decoder_input) - 1
decoder_padd = [word_to_ix['<PAD>']] * decoder_padd_size
decoder_input.append([word_to_ix['<S>']] + tmp_decoder_input + decoder_padd)
targets.append(tmp_decoder_input + [word_to_ix['<E>']] + decoder_padd)
tmp_targets_weight = np.ones(decoder_size, dtype=np.float32)
tmp_targets_weight[-decoder_padd_size:] = 0
target_weights.append(list(tmp_targets_weight))
return encoder_input, decoder_input, targets, target_weights
#### doclength check function
def check_doclength(docs, sep=True):
max_document_length = 0
for doc in docs:
if sep:
words = doc.split()
document_length = len(words)
else:
document_length = len(doc)
if document_length > max_document_length:
max_document_length = document_length
return max_document_length
#### making batch function
def make_batch(encoder_inputs, decoder_inputs, targets, target_weights):
encoder_size = len(encoder_inputs[0])
decoder_size = len(decoder_inputs[0])
encoder_inputs, decoder_inputs, targets, target_weights = \
np.array(encoder_inputs), np.array(decoder_inputs), np.array(targets), np.array(target_weights)
result_encoder_inputs = []
result_decoder_inputs = []
result_targets = []
result_target_weights = []
for i in range(encoder_size):
result_encoder_inputs.append(encoder_inputs[:, i])
for j in range(decoder_size):
result_decoder_inputs.append(decoder_inputs[:, j])
result_targets.append(targets[:, j])
result_target_weights.append(target_weights[:, j])
return result_encoder_inputs, result_decoder_inputs, result_targets, result_target_weights
| true |
78cfd31f76adb1c5db9667cde9a3ec3b10354e80 | Python | bitsapien/anuvaad | /public/phase-2-20160620022203/PYTHON/do-you-even-swap.py | UTF-8 | 290 | 3.703125 | 4 | [] | no_license | #!/usr/bin/python
# Name : Do You Even Swap
# input:
# a : given integer
# t : number of swaps
elements = raw_input().strip().split(' ')
a = int(elements[0])
t = int(elements[1])
# write your code here
# store your results in `result`
# output
# Dummy Data
result = 4321
print(result)
| true |
ae23c4cd0dbc9b67b9cd7c5d7920d7c78b40a883 | Python | majidgourkani/python | /learn 2/begginer/25.py | UTF-8 | 584 | 3.484375 | 3 | [] | no_license | import datetime as dt
def add(a,b,c):
return a+b+c
print(add(2,5,8))
#####################################################
def addj(*nums):
total = 0
for n in nums:
total += n
return total
print(addj(65,65,89,646,87,9,223,9))
print(addj(651,98,65,1))
print(addj(1,2,3,4,4,56,7,9,9,7,9,9,6,23,1,86,245,8,369,3))
#####################################################
def req_time( mes , time = dt.datetime.now() ):
print("{:} ,time {:}".format(mes , time))
req_time("it's morning")
req_time("it's morning" , "Feb 22nd 2017 10:25:08")
| true |
37d73e166ecde77d6afab32afaf707959a808017 | Python | Aasthaengg/IBMdataset | /Python_codes/p03472/s012623524.py | UTF-8 | 968 | 2.59375 | 3 | [] | no_license | import sys
stdin = sys.stdin
inf = 1 << 60
mod = 1000000007
sys.setrecursionlimit(10 ** 7)
ni = lambda: int(ns())
nin = lambda y: [ni() for _ in range(y)]
na = lambda: list(map(int, stdin.readline().split()))
nan = lambda y: [na() for _ in range(y)]
nf = lambda: float(ns())
nfn = lambda y: [nf() for _ in range(y)]
nfa = lambda: list(map(float, stdin.readline().split()))
nfan = lambda y: [nfa() for _ in range(y)]
ns = lambda: stdin.readline().rstrip()
nsn = lambda y: [ns() for _ in range(y)]
ncl = lambda y: [list(ns()) for _ in range(y)]
nas = lambda: stdin.readline().split()
import math
n, h = na()
a = []
b = []
for i in range(n):
_a, _b = na()
a.append(_a)
b.append(_b)
a.sort(reverse=True)
b.sort(reverse=True)
i = 0
cnt = 0
while h > 0:
if i < n and a[0] < b[i]:
h -= b[i]
i += 1
cnt += 1
else:
cnt += math.ceil(h / a[0])
break
print(cnt) | true |
c057846db5bbd243d3e24108b32c2ef53e384c3a | Python | Luolingwei/LeetCode | /OA/Amazon/QAmazon_Longest Palindrone Substring.py | UTF-8 | 444 | 2.84375 | 3 | [] | no_license | class Solution:
def longestPalindrome(self, s: str) -> str:
N=len(s)
l,r=0,0
def check(i,j):
while i>=0 and j<N and s[i]==s[j]:
i-=1
j+=1
return i+1,j-1
for i in range(len(s)):
a,b=check(i,i)
if b-a>r-l:
l,r=a,b
a,b=check(i,i+1)
if b-a>r-l:
l,r=a,b
return s[l:r+1] | true |
595d74d4fbb4b4159c8ebc5471047a123a60b51a | Python | andrewp-as-is/markdown-table.py | /tests/markdown-table/examples/Table.py | UTF-8 | 222 | 2.65625 | 3 | [
"Unlicense"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import markdown_table
columns = ["name","__doc__"]
matrix = [
["name1","desc1"],
["name2","desc2"],
]
table = markdown_table.Table(columns,matrix)
print(str(table))
| true |
cf5a0129b4cb312360b47148a1fd056406af1f12 | Python | Sparshith/hackerrank-solutions | /CrackingTheCodingInterview/arrays_left_rotation.py | UTF-8 | 1,097 | 4.28125 | 4 | [] | no_license | '''
A left rotation operation on an array of size shifts each of the array's elements unit to the left. For example, if left rotations are performed on array , then the array would become .
Given an array of integers and a number, , perform left rotations on the array. Then print the updated array as a single line of space-separated integers.
'''
'''
Referred articles:
http://www.geeksforgeeks.org/array-rotation/
'''
def GCD(a, b):
if(b == 0):
return a
else:
return GCD(b, a%b)
def array_left_rotation(array, numElements, numRotations):
gcd = GCD(numElements, numRotations)
for i in range(gcd):
j = i
temp = array[i]
while 1:
k = j + numRotations
if(k >= numElements):
k = k - numElements
if(k == i):
break
array[j] = array[k]
j = k
array[j] = temp
return array
n, k = map(int, input().strip().split(' '))
a = list(map(int, input().strip().split(' ')))
answer = array_left_rotation(a, n, k)
print(*answer, sep=' ')
| true |
d5ea4cf163f94be2f4aba28108c75eb846f6b91e | Python | wangkailovebaojiakun/Test_Python_OpenCV | /Python-OpenCV/Arithmetic Operations on Images/Image_Blending.py | UTF-8 | 497 | 2.828125 | 3 | [] | no_license | #coding:utf-8
#Image Blending 图像融合
import cv2
import numpy as np
import os
#Both images should be of same depth and type,
#or second image can just be a scalar value(标量值).
#read logo and image
path = os.getcwd()
parent_path = os.path.dirname(path)
logo_path = parent_path + '/IMAGES/logo.jpg'
logo = cv2.imread(logo_path)
im_path = parent_path + '/IMAGES/sex.jpg'
img = cv2.imread(im_path)
#add weighted
dst = cv2.addWeighted(img,0.7,logo,0.3,0)
cv2.imshow('dst',dst)
cv2.waitKey()
| true |
7efe8c87dd7868e5dddbca6249cdc7be150e5e0b | Python | marcusfreire0504/mememakertwitter | /Robo.py | UTF-8 | 10,304 | 3.046875 | 3 | [
"MIT"
] | permissive | import datetime
import os
import random
import re
import shutil
import time
import pytz
import requests
import tweepy
class Robo:
"""
Este é o robô com suas funções pré-determinadas para efetuar a autenticação e publicação de Tweets com imagens e vídeos.
"""
def __init__(self, nome, versao):
"""
Função chamada ao iniciar o robô, aqui será definido seu nome e sua versão.
"""
super().__init__()
self.nome = nome
self.versao = versao
print("{} ligando na versão {}!".format(self.nome, str(self.versao)))
def __del__(self):
"""
Quando o robô for "deletado" aparecerá uma mensagem.
"""
print("{} desligando...".format(self.nome))
def __repr__(self):
"""
Quando o objeto classe Robo for chamado retornará seu nome e sua versão.
"""
return "{} ({})".format(self.nome, str(self.versao))
def configurar_autenticacao(
self, consumer_key, consumer_secret_key, access_token, access_token_secret
):
"""
Receberá as chaves de autenticação para realizar a autenticação no Twitter.
"""
self.consumer_key = consumer_key
self.consumer_secret_key = consumer_secret_key
self.access_token = access_token
self.access_token_secret = access_token_secret
print("Chaves configuradas com sucesso.")
def iniciar_robo(self):
"""
Irá iniciar o robô com as chaves recebidas, caso ocorra algum erro será mostrado.
"""
autenticacao = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret_key)
autenticacao.set_access_token(self.access_token, self.access_token_secret)
try:
self.api = tweepy.API(autenticacao)
print("Robô iniciado!")
except Exception as e:
print("Ocorreu um erro ao iniciar o robô.")
print("Erro: {}".format(str(e)))
def postar_meme(self):
"""
Ao ser chamada irá selecionar randomicamente algum meme da pasta Memes e irá enviar ao Twitter, em seguida apagará da pasta Memes.
"""
trends = [
trend["name"] for trend in self.api.trends_place(23424768)[0]["trends"][0:5]
]
while True:
memes = os.listdir("Memes")
if len(memes) <= 0:
print("Não há memes para ser postado.")
break
else:
meme_arquivo = random.choice(memes)
try:
twitter_meme_id = self.api.media_upload("Memes/" + meme_arquivo)
self.api.update_status(
status=" ".join(trends),
media_ids=[twitter_meme_id.media_id_string],
)
print("Um meme foi postado.")
os.remove("Memes/" + meme_arquivo)
break
except Exception as e:
print("Não foi possível postar o meme.")
print("Erro: {}".format(str(e)))
os.remove("Memes/" + meme_arquivo)
def mecanismo(self):
"""
Ao ser chamada irá iniciar um evento infinito que irá verificar o horário de acordo com a postagem de memes do iFunny.
Caso o horário bata com a postagem de novos memes no iFunny (08:00, 10:00, 12:00, 14:00, 16:00, 18:00, 20:00, 22:00) irá baixar os 20 novos memes e de 6 em 6 minutos irá postá-los no Twitter.
Por que 6 minutos? Pois no intervalo de 2 horas o iFunny posta 20 memes, ou seja, 2 horas são 120 minutos, 20 memes para serem postados em 2 horas são 120/20 = 6 minutos a cada meme.
"""
self.ifunny = iFunny()
while True:
tempo = datetime.datetime.now()
timezone = pytz.timezone("America/Sao_Paulo")
tempo = tempo.astimezone(timezone)
horarios_ifunny = [8, 10, 12, 14, 16, 18, 20, 22]
minutos_postar = [0, 6, 12, 18, 24, 30, 36, 42, 48, 54]
if (
tempo.hour in horarios_ifunny
and tempo.minute == 0
and tempo.second == 0
):
self.ifunny.pegar_memes()
if tempo.minute in minutos_postar and tempo.second == 0:
self.postar_meme()
class iFunny:
"""
Esta classe está determinada para criar a pasta onde salvar os últimos 20 memes (imagens/vídeos).
"""
def __init__(self):
"""
Ao criar o objeto será verificado a existência da pasta de memes, caso não exista irá cria-la.
Caso a pasta exista, irá deleta-la e apagar todo seu conteúdo.
"""
super().__init__()
if not os.path.exists("Memes"):
os.mkdir("Memes")
else:
shutil.rmtree("Memes")
time.sleep(0.5)
os.mkdir("Memes")
def pegar_memes(self):
"""
Chamando este método irá salvar os últimos 20 memes postados no iFunny BR dentro da pasta Memes.
Caso ocorra algum erro, retornará False, caso contrário, retornará True.
"""
pagina = requests.get(
url="https://br.ifunny.co/",
headers={
"Host": "br.ifunny.co",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-User": "?1",
"Sec-Fetch-Dest": "document",
"Referer": "https://br.ifunny.co/",
},
)
if pagina.status_code == 200:
print("Pegando memes no iFunny.")
memes_id = re.findall(
'<div class="post" data-id="(.*)" data-test', pagina.text
)[0:20]
for meme_id in memes_id:
meme_pagina = requests.get(
url="https://br.ifunny.co/picture/" + meme_id,
headers={
"Host": "br.ifunny.co",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-User": "?1",
"Sec-Fetch-Dest": "document",
"Referer": "https://br.ifunny.co/",
},
)
if meme_pagina.status_code == 200:
meme_imagem_nome = re.search(
'<meta property="og:image" content="https://imageproxy.ifunny.co/crop:x-20,resize:320x,crop:x800,quality:90x75/images/(\w+.jpg)"/>',
meme_pagina.text,
).group(1)
meme_imagem = requests.get(
"https://imageproxy.ifunny.co/crop:x-20/images/"
+ meme_imagem_nome,
stream=True,
)
meme_salvar = open("Memes/" + meme_imagem_nome, "wb")
meme_imagem.raw.decode_content = True
shutil.copyfileobj(meme_imagem.raw, meme_salvar)
meme_salvar.close()
elif meme_pagina.status_code == 404:
try:
meme_pagina = requests.get(
url="https://br.ifunny.co/video/" + meme_id,
headers={
"Host": "br.ifunny.co",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-User": "?1",
"Sec-Fetch-Dest": "document",
"Referer": "https://br.ifunny.co/",
},
)
meme_video_nome = re.search(
'<meta property="og:video:url" content="https://img.ifunny.co/videos/(\w+.mp4)"/>',
meme_pagina.text,
).group(1)
meme_video = requests.get(
"https://img.ifunny.co/videos/" + meme_video_nome,
stream=True,
)
meme_salvar = open("Memes/" + meme_video_nome, "wb")
meme_video.raw.decode_content = True
shutil.copyfileobj(meme_video.raw, meme_salvar)
meme_salvar.close()
except:
pass
else:
print("Ocorreu algum erro ao acessar o iFunny.")
return False
if __name__ == "__main__":
mememaker = Robo(nome="Meme Maker", versao=1.0)
mememaker.configurar_autenticacao(
consumer_key="",
consumer_secret_key="",
access_token="",
access_token_secret="",
)
mememaker.iniciar_robo()
mememaker.mecanismo()
| true |
b55daaef5c0f74914e48bf2c0a4705acef4f6f17 | Python | limapedro2002/PEOO_Python | /Projeto M4/Gabriela, Yasmin, Wellen e Sarah/produto.py | UTF-8 | 2,608 | 3.8125 | 4 | [] | no_license | #adicionar #listar #deletar #atualizar
class Produto:
def __init__(self, nome = None, marca = None, preço = None, cod = None):
self.nome = nome
self.marca = marca
self.preço = preço
self.cod = cod
self.lista_produtos = []
def adicionar(self, nome, marca, preço, cod):
self.nome += 1
self.lista_produtos.append(Produto(self.nome, marca, preço, cod))
print(self.nome, marca, preço, cod)
return f'Produto adicionado!'
def listar(self):
if len(self.lista_produtos) != 0:
texto = ""
for item in self.lista_produtos:
print(item.nome,item.marca,item.preço,item.cod)
texto += f' Nome: {item.nome}, Marca: {item.marca}, Preço: {item.preço}, ID do produto: {item.cod}\n'
return texto
else:
return 'Lista sem produtos'
def deletar(self,cod):
cond = 0
for produto in self.lista_produtos:
if (cod) == produto.nome:
cond = 1
texto = f'Removendo o produto {produto.nome}, {produto.marca}, {produto.preço}, {produto.cod}'
self.lista_produtos.remove(produto)
return texto
if not cond:
return f'Não há tal produto {cod}'
def atualizar(self,cod,**kwargs):
cod = 0
for n,c in kwargs.items():
if (n == 'nome do produto'):
cod = int(c)
break
for item in self.lista_produtos:
if (item.nome == cod):
for n,c in kwargs.items():
if (n == 'marca'):
item.marca = c
for n,c in kwargs.items():
print("Atualizado",n,c)
if (n == 'preço'):
item.preço = c
if (n == 'ID do produto'):
item.cod = c
self.lista_produtos.insert(item.nome,item)
self.lista_produtos.remove(item)
return f'Seus produtos foram atualizados'
if (__name__ == '__main__'):
p = Produto()
print(p.adicionar('Sorvete','Sterbom', 'R$ 15,00', '006'))
print(p.adicionar('Leite','Betânia', 'R$ 5,00', '098'))
print(p.adicionar('Pão integral','Wickbold', 'R$ 8,00', '032'))
p.listar()
p.atualizar(nome = 'macarrão', marca = 'Adria', cod = '013', valor = 'R$ 8,00')
p.listar()
p.atualizar(nome = 'requeijão', marca = 'Nestle', cod = '056', valor = 'R$ 7,50')
p.listar()
| true |
c05a27cb8a6912ea6f30d37b3795e71d2c7cc62a | Python | priyarora4/Adaptive-learning | /part_a/knn.py | UTF-8 | 2,950 | 3.09375 | 3 | [] | no_license | from sklearn.impute import KNNImputer
from utils import *
import matplotlib.pyplot as plt
def knn_impute_by_user(matrix, valid_data, k):
""" Fill in the missing values using k-Nearest Neighbors based on
student similarity. Return the accuracy on valid_data.
See https://scikit-learn.org/stable/modules/generated/sklearn.
impute.KNNImputer.html for details.
:param matrix: 2D sparse matrix
:param valid_data: A dictionary {user_id: list, question_id: list,
is_correct: list}
:param k: int
:return: float
"""
nbrs = KNNImputer(n_neighbors=k)
# We use NaN-Euclidean distance measure.
mat = nbrs.fit_transform(matrix)
acc = sparse_matrix_evaluate(valid_data, mat)
print("user | k: {} Validation Accuracy: {}".format(k, acc))
return acc
def knn_impute_by_item(matrix, valid_data, k):
""" Fill in the missing values using k-Nearest Neighbors based on
question similarity. Return the accuracy on valid_data.
:param matrix: 2D sparse matrix
:param valid_data: A dictionary {user_id: list, question_id: list,
is_correct: list}
:param k: int
:return: float
"""
nbrs = KNNImputer(n_neighbors=k)
# We use NaN-Euclidean distance measure.
mat = nbrs.fit_transform(matrix.T)
acc = sparse_matrix_evaluate(valid_data, mat.T)
print("item | k: {} Validation Accuracy: {}".format(k, acc))
return acc
def main():
sparse_matrix = load_train_sparse("../data").toarray()
val_data = load_valid_csv("../data")
test_data = load_public_test_csv("../data")
print("Sparse matrix:")
print(sparse_matrix)
print("Shape of sparse matrix:")
print(sparse_matrix.shape)
user_acc = []
question_acc = []
k_range = range(1, 27, 5)
for k in k_range:
user_acc.append(knn_impute_by_user(sparse_matrix, val_data, k))
question_acc.append(knn_impute_by_item(sparse_matrix, val_data, k))
# Plot With User Based Filtering
max_k = k_range[int(np.argmax(user_acc))]
plt.plot(k_range, user_acc)
plt.xlabel("Values of K")
plt.ylabel("Validation Accuracy")
plt.xticks(k_range)
plt.title("User Based Filtering: kNN Validation Accuracy vs K Values")
plt.savefig('../plots/CSC311Final1auser.png')
plt.show()
test_acc = knn_impute_by_user(sparse_matrix, test_data, max_k)
print("user: k = {} | test accuracy: {}".format(max_k, test_acc))
# Plot With Item Based Filtering
max_k = k_range[int(np.argmax(question_acc))]
plt.plot(k_range, question_acc)
plt.xlabel("Values of K")
plt.ylabel("Validation Accuracy")
plt.xticks(k_range)
plt.title("Item Based Filtering: kNN Validation Accuracy vs K Values")
plt.savefig('../plots/CSC311Final1aitem.png')
plt.show()
test_acc = knn_impute_by_item(sparse_matrix, test_data, max_k)
print("item: k = {} | test accuracy: {}".format(max_k, test_acc))
if __name__ == "__main__":
main()
| true |
65606af09cc9e6c7f47c40c94a51d78ca25692cd | Python | bourque/stak | /stak/tests/test_example.py | UTF-8 | 2,406 | 2.671875 | 3 | [
"BSD-2-Clause"
] | permissive | def test_primes():
from ..example_mod import primes
assert primes(10) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
def test_deprecation():
import warnings
warnings.warn(
"This is deprecated, but shouldn't raise an exception, unless "
"enable_deprecations_as_exceptions() called from conftest.py",
DeprecationWarning)
'''
def test_hselect_basic():
from ..hselect import Hselect
from astropy.table import Table
import numpy as np
test_dir = "/eng/ssb/iraf_transition/test_data/"
data_rows = [('/eng/ssb/iraf_transition/test_data/iczgs3y5q_flt.fits', 1, 'ELECTRONS/S'),
('/eng/ssb/iraf_transition/test_data/iczgs3y5q_flt.fits', 2, 'ELECTRONS/S')]
correct_table = Table(rows=data_rows, names=('Filename', 'ExtNumber', 'BUNIT'),
dtype=('S80', 'int64', 'S68'))
hobj = Hselect(test_dir+'iczgs3y5q_flt.fits', 'BUNIT', extension='1,2')
for colname in correct_table.colnames:
assert np.all(correct_table[colname] == hobj.table[colname])
def test_hselect_wildcard():
from ..hselect import Hselect
from astropy.table import Table
import numpy as np
test_dir = "/eng/ssb/iraf_transition/test_data/"
data_rows = [('/eng/ssb/iraf_transition/test_data/iczgs3y5q_flt.fits', 0,
'iczgs3y5q_flt.fits', 'SCI')]
correct_table = Table(rows=data_rows, names=('Filename', 'ExtNumber', 'FILENAME', 'FILETYPE'),
dtype=('S80', 'int64', 'S68', 'S68'))
hobj = Hselect(test_dir+'iczgs3y5q_*.fits', 'FILE*', extension='0')
for colname in correct_table.colnames:
assert np.all(correct_table[colname] == hobj.table[colname])
def test_eval_keyword_greaterthen_equal():
from ..hselect import Hselect
from astropy.table import Table
import numpy as np
test_dir = "/eng/ssb/iraf_transition/test_data/"
data_rows = [('/eng/ssb/iraf_transition/test_data/iczgs3y5q_flt.fits', 0,
652.937744)]
correct_table = Table(rows=data_rows, names=('Filename', 'ExtNumber', 'EXPTIME'),
dtype=('S80', 'int64', 'float64'))
hobj = Hselect(test_dir + 'icz*', 'BUNIT,EXPTIME', expr="EXPTIME >= 620")
for colname in correct_table.colnames:
assert np.all(correct_table[colname] == hobj.table[colname])
# array values - numpy.allclose(), might want to use
'''
| true |
244c9d1cc8dbb84aa7883ffdbb0fb73970f5ac2d | Python | fjpiao/pyclass | /pythonthread/thread/lock.py | UTF-8 | 374 | 3.4375 | 3 | [] | no_license | from threading import Thread,Lock
a=b=0#全局变量两个线程都读写
lock=Lock()#锁对象
def value():
while Ture:
lock.acquire()#加锁 另一个线程也要加锁
if a !=b:
print('a=%d,b=%d'%(a,b))
lock.release()
t=Thread(target=value)
t.start()
while True:
with lock:
a+=1
b+=1
t.join() | true |
19b8db5422629b271d85121bdce7e72dbec865a5 | Python | MaxValue/Python-Tools | /gxep/gxep | UTF-8 | 5,513 | 2.765625 | 3 | [] | no_license | #!/usr/bin/env python3
# coding: utf-8
#
import re, os, argparse, time
from lxml import html, etree
parser = argparse.ArgumentParser(argument_default=False, usage="%(prog)s [OPTION]... --pattern='PATTERN' FILE...\n or: %(prog)s [OPTION]... --file=PFILE FILE...\nSearch for PATTERN in each FILE.\nA FILE of “-” stands for standard input.\nIf no FILE is given, recursive searches examine the working directory,\n and nonrecursive searches read standard input.\nWith --file, match against any patterns in PFILE.\nBy default, %(prog)s prints the matching lines.", epilog="Report bugs to: m.fuxjaeger@gmail.com\n%(prog)s home page: <https://github.com/MaxValue/Python-Tools/>\nFull documentation at: <https://github.com/MaxValue/Python-Tools/wiki/>", formatter_class=argparse.RawDescriptionHelpFormatter)
requiredArguments = parser.add_argument_group("Required")
parserGroup_query = requiredArguments.add_mutually_exclusive_group(required=True)
#type=argparse.FileType('r', encoding="utf-8")
parserGroup_query.add_argument("-f", "--file", type=argparse.FileType('r', encoding='utf-8'), metavar="FILE", help="Obtain patterns from FILE, one per line. If this option is used multiple times, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing.")
parserGroup_query.add_argument("-p", "--pattern", nargs='?', help="Obtain patterns from FILE, one per line. If this option is used multiple times, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing.")
optionalArguments = parser.add_argument_group("Optionals")
parserGroup_type = optionalArguments.add_mutually_exclusive_group()
parserGroup_type.add_argument("-X", "--xml", action="store_true", default=True, help="Interpret FILE as XML document. This is the default.")
parserGroup_type.add_argument("-Y", "--html", action="store_true", help="Interpret FILE as HTML document.")
parserGroup_filematchInversion = optionalArguments.add_mutually_exclusive_group()
parserGroup_filematchInversion.add_argument("-L", "--files-without-match", action="store_true", help="Suppress normal output; instead print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match.")
parserGroup_filematchInversion.add_argument("-l", "--files-with-matches", action="store_true", help="Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.")
parserGroup_recursion = optionalArguments.add_mutually_exclusive_group()
parserGroup_recursion.add_argument("-r", "--recursive", action="store_true", help="Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, %(prog)s searches the working directory.")
parserGroup_recursion.add_argument("-R", "--dereference-recursive", action="store_true", help="Read all files under each directory, recursively. Follow all symbolic links, unlike -r.")
parser.add_argument("checkpath", nargs='+', default=["./"], help="The file or files to check against the given XPaths. Expects directory by default.")
args = parser.parse_args()
re_patternStart = re.compile(r"^\S", re.IGNORECASE)
try:
for i, pathname in enumerate(args.checkpath):
clean_path = os.path.expanduser(pathname)
if not os.path.exists(clean_path):
parser.error("{}: No such file or directory".format(pathname))
if os.path.isfile(clean_path):
args.checkpath[i] = [("", [], [clean_path])]
elif os.path.isdir(clean_path):
if args.recursive or args.dereference_recursive:
args.checkpath[i] = os.walk(top=clean_path, followlinks=args.dereference_recursive) #fails if dir/file does not exist (or it fails when opening the file)
else:
print("{prog}: -r not specified; ommitting directory '{dirname}'".format(prog=parser.prog, dirname=clean_path))
del args.checkpath[i]
else:
parser.exit("TODO: Read from STDIN")
patterns = []
if args.file:
lines = args.file.read().splitlines()
current_pattern = ""
for line in lines:
if re_patternStart.match(line):
if not current_pattern == "":
patterns.append(current_pattern)
current_pattern = line
else:
if not current_pattern == "":
current_pattern += line
if not current_pattern == "":
patterns.append(current_pattern)
else:
patterns.append(args.pattern)
for directory_walker in args.checkpath:
for walk_tuple in directory_walker:
for raw_filename in walk_tuple[2]:
this_filename = os.path.join(walk_tuple[0], raw_filename)
with open(this_filename, encoding="utf-8") as this_file:
if args.html:
tree = html.fromstring(this_file.read())
else:
tree = etree.fromstring(this_file.read())
for pattern in patterns:
xpath_match = tree.xpath(pattern)
if len(xpath_match) == 0 and args.files_without_match:
print(this_filename)
elif len(xpath_match) != 0 and not args.files_without_match:
if args.files_with_matches:
print(this_filename)
else:
for result in xpath_match:
print("{filename}:{match}".format(filename=this_filename, match=result))
except KeyboardInterrupt as e:
exit("")
except etree.XMLSyntaxError as e:
if args.xml:
parser.error("{}: not an XML file. Try using --html".format(this_filename))
else:
parser.error("{}: could not be parsed. Probably really badly malformed HTML.".format(this_filename))
| true |
a4827a0c695ebb309f477ca6356c35d83228dc3e | Python | DhanaMani1983/Python | /Iterator.py | UTF-8 | 613 | 4.34375 | 4 | [] | no_license | '''
Iterators are used to loop an iterable but one item at a time
each time it remember the last value and gives the next value
'''
#lst = [5,9,3,1,7]
#it = iter(lst)
#print (it.next())
#print (it.next())
# own iterator
class TopTen:
def __init__(self):
self.num = 1
def __iter__(self):
return self
def __next__(self):
if (self.num <= 10):
val = self.num
self.num += 1
return val
else:
raise StopIteration
values = TopTen()
print(next(values))
for i in values:
print(i)
| true |
81b9992f53105ed58cc125a784255060f6edc900 | Python | alinghi/PracticeAlgorithm | /baekjoon/5585.py | UTF-8 | 131 | 3.03125 | 3 | [
"MIT"
] | permissive | N=int(input())
l=[500,100,50,10,5,1]
N=1000-N
ans=0
for coin in l:
if N>=coin:
ans+=N//coin
N=N%coin
print(ans) | true |
20310425fcbb2d7c4a948c66b11c9fbb6f97829d | Python | AaronDweck/all-Python-folders | /turtle test.py | UTF-8 | 81 | 2.6875 | 3 | [] | no_license |
from turtle import *
pen1 = Pen()
pen2 = Pen()
pen1.screen.bgcolor("#5D5732")
| true |
5c1568b178b6c77cda27662e172f2029a8287127 | Python | qijiamin/learn-python | /test1-07.py | GB18030 | 947 | 3.515625 | 4 | [] | no_license | # -*- coding:utf-8 -*-
#########ѧϢ############
#:
#ѧ:1403050116
#༶ͨ14-1
##############Ŀ###############
#
#############################
import math
a=input('a:')
#dx=0.1
f1=(math.pow(3+0.1,a)-math.pow(3,a))/0.1
print 'f1=',f1
#dx=0.01
f2=(math.pow(3+0.01,a)-math.pow(3,a))/0.01
print 'f1=',f1,'f2=',f2
#dx=0.001
f3=(math.pow(3+0.001,a)-math.pow(3,a))/0.001
print 'f1=',f1,'f2=',f2,'f3=',f3
#dx=0.0001
f4=(math.pow(3+0.0001,a)-math.pow(3,a))/0.0001
print 'f1=',f1,'f2=',f2,'f3=',f3,'f4=',f4
a=3
#dx=0.1
f1=(math.pow(3*a+0.1*a,a-1)-math.pow(3*a,a-1))/0.1
print 'f1=',f1
#dx=0.01
f2=(math.pow(3*a+0.01*a,a-1)-math.pow(3*a,a-1))/0.01
print 'f1=',f1,'f2=',f2
#dx=0.001
f3=(math.pow(3*a+0.001*a,a-1)-math.pow(3*a,a-1))/0.001
print 'f1=',f1,'f2=',f2,'f3=',f3
#dx=0.0001
f4=(math.pow(3*a+0.0001*a,a-1)-math.pow(3*a,a-1))/0.0001
print 'f1=',f1,'f2=',f2,'f3=',f3,'f4=',f4 | true |
067b3a1b0573b3b06ed1881e1ad5cac23699abea | Python | adrian-soch/Pacemaker-Project | /DCM/graph/ExperimentDCM.py | UTF-8 | 75,876 | 2.890625 | 3 | [
"MIT"
] | permissive | #Imports
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import sqlite3
#Creating sqlite3 database
db = sqlite3.connect("DCM.sqlite", detect_types= sqlite3.PARSE_DECLTYPES)
#Create seperate table for each state within database
db.execute("CREATE TABLE IF NOT EXISTS AOO (user TEXT NOT NULL, password TEXT NOT NULL, aoo_lowerRateLimitEntry INTEGER NOT NULL, aoo_upperRateLimitEntry INTEGER NOT NULL, aoo_atrialAmplitudeEntry REAL NOT NULL, aoo_atrialPulseWidthEntry INTEGER NOT NULL, userLog TEXT NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS VOO (user TEXT NOT NULL, password TEXT NOT NULL, voo_lowerRateLimitEntry INTEGER NOT NULL, voo_upperRateLimitEntry INTEGER NOT NULL, voo_ventricularAmplitudeEntry REAL NOT NULL, voo_ventricularPulseWidthEntry INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS AAI (user TEXT NOT NULL, password TEXT NOT NULL, aai_lowerRateLimitEntry INTEGER NOT NULL, aai_upperRateLimitEntry INTEGER NOT NULL, aai_atrialAmplitudeEntry REAL NOT NULL, aai_atrialPulseWidthEntry INTEGER NOT NULL,"
" aai_atrialSensitivityEntry REAL NOT NULL, aai_ARPEntry INTEGER NOT NULL, aai_APVARPEntry INTEGER NOT NULL, aai_hysteresisEntry INTEGER NOT NULL, aai_rateSmoothingEntry INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS VVI (user TEXT NOT NULL, password TEXT NOT NULL, vvi_lowerRateLimitEntry INTEGER NOT NULL, vvi_upperRateLimitEntry INTEGER NOT NULL, vvi_ventricularAmplitudeEntry REAL NOT NULL, vvi_ventricularPulseWidthEntry INTEGER NOT NULL,"
" vvi_ventricularSensitivityEntry REAL NOT NULL, vvi_ARPEntry INTEGER NOT NULL, vvi_hysteresisEntry INTEGER NOT NULL, vvi_rateSmoothingEntry INTEGER NOT NULL)")
#Current User
currentuser = ''
#Initializing all global variables with "0"
#AOO
aoo_lowerRateLimitEntry,aoo_upperRateLimitEntry,aoo_atrialAmplitudeEntry,aoo_atrialPulseWidthEntry = "0","0","0","0"
userLog = ""
#VOO
voo_lowerRateLimitEntry,voo_upperRateLimitEntry,voo_ventricularAmplitudeEntry,voo_ventricularPulseWidthEntry = "0","0","0","0"
#AAI
aai_lowerRateLimitEntry,aai_upperRateLimitEntry,aai_atrialAmplitudeEntry,aai_atrialPulseWidthEntry,aai_atrialSensitivityEntry,aai_ARPEntry,aai_APVARPEntry,aai_hysteresisEntry,aai_rateSmoothingEntry = "0","0","0","0","0","0","0","0","0"
#VVI
vvi_lowerRateLimitEntry,vvi_upperRateLimitEntry,vvi_ventricularAmplitudeEntry,vvi_ventricularPulseWidthEntry,vvi_ventricularSensitivityEntry,vvi_ARPEntry,vvi_hysteresisEntry,vvi_rateSmoothingEntry = "0","0","0","0","0","0","0","0"
#Creating Initial Welcome Frame
class WelcomeFrame:
def __init__(self, master):
#General paramters
self.master = master
self.master.configure(background='grey')
self.frame = tk.Frame(self.master)
self.master.title("DCM")
self.master.resizable(width=False, height=False)
#Label details
self.label_welcome = tk.Label(self.master, text="Welcome")
self.label_welcome.config(font=("Helvetica",34))
self.label_welcome.configure(background='grey')
self.label_welcome.grid(row=1,column=2,columnspan =1,padx = 200, pady = 20)
#Next window button
self.nxtbtn = tk.Button(self.master, text="Next", width=12, command=self._nxt_btn_clicked)
self.nxtbtn.grid(row=3,column=2,columnspan =1,padx = 200, pady = 20)
self.nxtbtn.focus()
#Return button binding
self.master.bind('<Return>', self.return_bind)
#Return Button method
def return_bind(self, event):
self._nxt_btn_clicked()
#Method to create new window
def new_window(self,window):
self.newWindow = tk.Toplevel(self.master)
self.app = window(self.newWindow)
#Method to transition to loginframe
def _nxt_btn_clicked(self):
self.master.withdraw()
self.new_window(LoginFrame)
#Method to cleanup closing window
def on_exit(self):
exit()
#Login Frame window
class LoginFrame:
def __init__(self, master):
#General parameters
self.master = master
self.master.configure(background='grey')
self.frame = tk.Frame(self.master)
self.master.title("USER LOGIN")
self.master.resizable(width=False, height=False)
#Label details
self.label_username = tk.Label(self.master, text="Username")
self.label_username.configure(background='grey')
self.label_password = tk.Label(self.master, text="Password")
self.label_password.configure(background='grey')
#Window positioning
self.master.rowconfigure(0, pad=3)
self.master.rowconfigure(1, pad=3)
self.master.rowconfigure(2, pad=3)
self.master.rowconfigure(3, pad=3)
self.master.rowconfigure(4, pad=3)
self.master.rowconfigure(5, pad=3)
#Enter username/password details
self.entry_username = tk.Entry(self.master)
self.entry_password = tk.Entry(self.master, show="*")
self.entry_username.focus()
self.label_username.grid(row=0, sticky='e', pady=5)
self.label_password.grid(row=1, sticky='e', pady=10)
self.entry_username.grid(row=0, column=1, columnspan = 1,sticky='w')
self.entry_password.grid(row=1, column=1, columnspan = 1,sticky='w')
#Add user and login button details
self.logbtn = tk.Button(self.master, text="Login", width=12, command=self._login_btn_clicked)
self.logbtn.grid(columnspan=2, padx = 80, pady = 0)
self.add_userbtn = tk.Button(self.master, text="Add user",width =12, command=self._add_user_btn_clicked)
self.add_userbtn.grid(columnspan =2,padx = 80, pady = 10)
self.login_successful = False
self.master.protocol("WM_DELETE_WINDOW", self.on_exit)
#Return button bind
self.master.bind('<Return>', self.return_bind)
#Return button method
def return_bind(self, event):
self._login_btn_clicked()
#Method to cleanup closing application
def on_exit(self):
if messagebox.askyesno("Exit", "Do you want to quit the application?"):
exit()
#Method to create new window
def new_window(self,window):
self.newWindow = tk.Toplevel(self.master)
self.app = window(self.newWindow)
#Method to add transition to add new user screen
def _add_user_btn_clicked(self):
self.entry_username.delete(0, 'end')
self.entry_password.delete(0, 'end')
self.new_window(AddUserWindow)
#Method to for login button
def _login_btn_clicked(self):
global currentuser
username = self.entry_username.get()
password = self.entry_password.get()
self.entry_username.delete(0, 'end')
self.entry_password.delete(0, 'end')
#Query Database to find username and password
cursor = db.execute("SELECT user FROM aoo WHERE (user = ?) and (password = ?)", (username,password))
row = cursor.fetchone()
if row:
#If username is found then they become the current user
currentuser = username
self.master.withdraw()
self.new_window(MainWindow)
else:
#Otherwise the username/password is wrong
messagebox.showerror("Error", "Username/Password is Incorrect")
#Add new user class window
class AddUserWindow:
def __init__(self, master):
#Setting default window parameters
self.master = master
self.master.geometry('300x200')
self.quitButton = tk.Button(self.master, text = 'Quit', width = 12, command = self.close_windows)
self.label_username = tk.Label(self.master, text="Enter New Username")
self.label_password = tk.Label(self.master, text="Enter New Password")
self.label_password2 = tk.Label(self.master, text="Confirm Password")
self.entry_username = tk.Entry(self.master)
self.entry_password = tk.Entry(self.master, show="*")
self.entry_password2 = tk.Entry(self.master, show="*")
self.entry_username.focus()
#Adjusting window and button spacing
self.label_username.grid(row=0, sticky='e', pady=5)
self.label_password.grid(row=1, sticky='e', pady=10)
self.label_password2.grid(row=2, sticky='w', pady=10)
self.entry_username.grid(row=0, column=1, columnspan = 1,sticky='w')
self.entry_password.grid(row=1, column=1, columnspan = 1,sticky='w')
self.entry_password2.grid(row=2, column=1, columnspan = 1,sticky='w')
self.add_userbtn = tk.Button(self.master, text="Add user",width =12, command=self._add_user_btn_clicked)
self.add_userbtn.grid(row=3,column=1,pady=10)
self.quitButton = tk.Button(self.master, text = 'Back', width = 12, command = self.close_windows)
self.quitButton.grid(row=4,column=1,pady=5)
self.master.protocol("WM_DELETE_WINDOW", self.on_exit)
#Method for clean exit
def on_exit(self):
self.master.destroy()
#Method for clicking add user
def _add_user_btn_clicked(self):
username = self.entry_username.get()
password = self.entry_password.get()
password2 = self.entry_password2.get()
self.entry_username.delete(0, 'end')
self.entry_password.delete(0, 'end')
self.entry_password2.delete(0, 'end')
#Password verification
if(password == password2):
#Query to find user already exists in the database
cursor = db.execute("SELECT user FROM aoo WHERE (user = ?)", (username,))
row = cursor.fetchone()
#Query to find total number of users
checker = db.execute('SELECT * FROM aoo')
counter = len(checker.fetchall())
#Verify there are no errors
if (len(username) < 1 or len(password) < 1):
messagebox.showerror("Error", "Missing Username and/or Password")
elif row:
messagebox.showerror("Error", "User exists")
elif (counter > 9):
messagebox.showerror("Error", "Maximum allowed user limit reached")
#If everything is good create the user in the 4 tables
else:
db.execute("INSERT INTO aoo VALUES(?, ?, ?, ?, ?, ?, ?)", (username, password, 60, 120, 3.5, 1.5, "log"))
db.execute("INSERT INTO voo VALUES(?, ?, ?, ?, ?, ?)", (username, password, 60, 120, 3.5, 1.5))
db.execute("INSERT INTO aai VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (username, password, 60, 120, 3.5, 1.5, 3.3, 250, 200, 0, 0))
db.execute("INSERT INTO vvi VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (username, password, 60, 120, 3.5, 1.5, 3.3, 250, 0, 0))
messagebox.showinfo("Success", "User Added")
self.quitButton.focus()
db.commit()
#Passwords don't match
else:
messagebox.showerror("Error", "Passwords do not match")
#Method for closing window
def close_windows(self):
self.master.destroy()
#Class for main window
class MainWindow:
def __init__(self, master):
#General window setup
self.content = tk.Entry()
self.master = master
self.master.geometry('650x570')
self.master.protocol("WM_DELETE_WINDOW", self.on_exit)
self.menubar = tk.Menu(self.master)
self.filemenu = tk.Menu(self.menubar, tearoff=0)
self.master.config(menu=self.menubar)
self.frame = tk.Frame(self.master)
# Tabs created for AOO, VOO, AAI, and VVI
self.tab_parent = ttk.Notebook(self.master)
self.aoo = ttk.Frame(self.tab_parent)
self.voo = ttk.Frame(self.tab_parent)
self.aai = ttk.Frame(self.tab_parent)
self.vvi = ttk.Frame(self.tab_parent)
self.tab_parent.add(self.aoo, text = "AOO")
self.tab_parent.add(self.voo, text = "VOO")
self.tab_parent.add(self.aai, text = "AAI")
self.tab_parent.add(self.vvi, text = "VVI")
#Retrieve all relevant data from tables for currentuser
global currentuser
aoocursor = db.execute("SELECT * FROM aoo WHERE (user = ?)", (currentuser,));aoorow = aoocursor.fetchall()
voocursor = db.execute("SELECT * FROM voo WHERE (user = ?)", (currentuser,));voorow = voocursor.fetchall()
aaicursor = db.execute("SELECT * FROM aai WHERE (user = ?)", (currentuser,));aairow = aaicursor.fetchall()
vvicursor = db.execute("SELECT * FROM vvi WHERE (user = ?)", (currentuser,));vvirow = vvicursor.fetchall()
#Global Variables setup with current user parameters
#AOO
global aoo_lowerRateLimitEntry,aoo_upperRateLimitEntry,aoo_atrialAmplitudeEntry,aoo_atrialPulseWidthEntry,userLog
aoo_lowerRateLimitEntry = str(aoorow[0][2])
aoo_upperRateLimitEntry = str(aoorow[0][3])
aoo_atrialAmplitudeEntry = str(aoorow[0][4])
aoo_atrialPulseWidthEntry = str(aoorow[0][5])
userLog = str(aoorow[0][6])
#VOO
global voo_lowerRateLimitEntry,voo_upperRateLimitEntry,voo_ventricularAmplitudeEntry,voo_ventricularPulseWidthEntry
voo_lowerRateLimitEntry = str(voorow[0][2])
voo_upperRateLimitEntry = str(voorow[0][3])
voo_ventricularAmplitudeEntry = str(voorow[0][4])
voo_ventricularPulseWidthEntry = str(voorow[0][5])
#AAI
global aai_lowerRateLimitEntry,aai_upperRateLimitEntry,aai_atrialAmplitudeEntry,aai_atrialPulseWidthEntry,aai_atrialSensitivityEntry,aai_ARPEntry,aai_APVARPEntry,aai_hysteresisEntry,aai_rateSmoothingEntry
aai_lowerRateLimitEntry = str(aairow[0][2])
aai_upperRateLimitEntry = str(aairow[0][3])
aai_atrialAmplitudeEntry = str(aairow[0][4])
aai_atrialPulseWidthEntry = str(aairow[0][5])
aai_atrialSensitivityEntry = str(aairow[0][6])
aai_ARPEntry = str(aairow[0][7])
aai_APVARPEntry = str(aairow[0][8])
aai_hysteresisEntry = str(aairow[0][9])
aai_rateSmoothingEntry = str(aairow[0][10])
#VVI
global vvi_lowerRateLimitEntry,vvi_upperRateLimitEntry,vvi_ventricularAmplitudeEntry,vvi_ventricularPulseWidthEntry,vvi_ventricularSensitivityEntry,vvi_ARPEntry,vvi_hysteresisEntry,vvi_rateSmoothingEntry
vvi_lowerRateLimitEntry = str(vvirow[0][2])
vvi_upperRateLimitEntry = str(vvirow[0][3])
vvi_ventricularAmplitudeEntry = str(vvirow[0][4])
vvi_ventricularPulseWidthEntry = str(vvirow[0][5])
vvi_ventricularSensitivityEntry = str(vvirow[0][6])
vvi_ARPEntry = str(vvirow[0][7])
vvi_hysteresisEntry = str(vvirow[0][8])
vvi_rateSmoothingEntry = str(vvirow[0][9])
#AOO BEGIN-----------------------------------------------------------------------------------------------------------------------------
#Setup buttons
self.aooLowerRateLimitButton = tk.Button(self.aoo, text = "Set", command= lambda: self.setValue("aooLowerRateLimit"))
self.aooUpperRateLimitButton = tk.Button(self.aoo, text = "Set", command= lambda: self.setValue("aooUpperRateLimit"))
self.aooAtrialAmplitudeButton = tk.Button(self.aoo, text = "Set", command= lambda: self.setValue("aooAtrialAmplitude"))
self.aooAtrialPulseWidthButton = tk.Button(self.aoo, text = "Set", command= lambda: self.setValue("aooAtrialPulseWidth"))
#Setup labels for inputs
self.aooLowerRateLimitLabel = tk.Label(self.aoo, text = "Lower Rate Limit")
self.aooUpperRateLimitLabel = tk.Label(self.aoo, text = "Upper Rate Limit")
self.aooAtrialAmplitudeLabel = tk.Label(self.aoo, text = "Atrial Amplitude")
self.aooAtrialPulseWidthLabel = tk.Label(self.aoo, text = "Atrial Pulse Width")
#Setup labels to display values
self.aooLowerRateLimitValue = tk.Label(self.aoo, text = "Current Value: " + aoo_lowerRateLimitEntry)
self.aooUpperRateLimitValue = tk.Label(self.aoo, text = "Current Value: " + aoo_upperRateLimitEntry)
self.aooAtrialAmplitudeValue = tk.Label(self.aoo, text = "Current Value: " + aoo_atrialAmplitudeEntry)
self.aooAtrialPulseWidthValue = tk.Label(self.aoo, text = "Current Value: " + aoo_atrialPulseWidthEntry)
#Spinbox for setup
self.aooLowerRateLimitEntry = tk.Spinbox(self.aoo,from_=30,to=175,increment=5)
self.aooUpperRateLimitEntry = tk.Spinbox(self.aoo,from_=50,to=175,increment=5)
self.aooAtrialAmplitudeEntry = tk.Spinbox(self.aoo,from_=0.5,to=7.0,format="%.1f",increment=0.1)
self.aooAtrialPulseWidthEntry = tk.Spinbox(self.aoo,from_=0.05,to=1.9,format="%.2f",increment=0.1)
#Adjust positioning
self.aooLowerRateLimitLabel.grid(row=0, column=0, padx=15, pady=15)
self.aooLowerRateLimitEntry.grid(row=0, column=1, padx=15, pady=15)
self.aooLowerRateLimitButton.grid(row=0, column=2, padx=15, pady=15)
self.aooLowerRateLimitValue.grid(row=0, column=3, padx=15, pady=15)
self.aooUpperRateLimitLabel.grid(row=1, column=0, padx=15, pady=15)
self.aooUpperRateLimitEntry.grid(row=1, column=1, padx=15, pady=15)
self.aooUpperRateLimitButton.grid(row=1, column=2, padx=15, pady=15)
self.aooUpperRateLimitValue.grid(row=1, column=3, padx=15, pady=15)
self.aooAtrialAmplitudeLabel.grid(row=2, column=0, padx=15, pady=15)
self.aooAtrialAmplitudeEntry.grid(row=2, column=1, padx=15, pady=15)
self.aooAtrialAmplitudeButton.grid(row=2, column=2, padx=15, pady=15)
self.aooAtrialAmplitudeValue.grid(row=2, column=3, padx=15, pady=15)
self.aooAtrialPulseWidthLabel.grid(row=3, column=0, padx=15, pady=15)
self.aooAtrialPulseWidthEntry.grid(row=3, column=1, padx=15, pady=15)
self.aooAtrialPulseWidthButton.grid(row=3, column=2, padx=15, pady=15)
self.aooAtrialPulseWidthValue.grid(row=3, column=3, padx=15, pady=15)
#AOO END-------------------------------------------------------------------------------------------------------------------------------
#VOO BEGIN-----------------------------------------------------------------------------------------------------------------------------
#Setup buttons
self.vooLowerRateLimitButton = tk.Button(self.voo, text = "Set", command= lambda: self.setValue("vooLowerRateLimit"))
self.vooUpperRateLimitButton = tk.Button(self.voo, text = "Set", command= lambda: self.setValue("vooUpperRateLimit"))
self.vooAtrialAmplitudeButton = tk.Button(self.voo, text = "Set", command= lambda: self.setValue("vooAtrialAmplitude"))
self.vooAtrialPulseWidthButton = tk.Button(self.voo, text = "Set", command= lambda: self.setValue("vooAtrialPulseWidth"))
#Setup labels for inputs
self.vooLowerRateLimitLabel = tk.Label(self.voo, text = "Lower Rate Limit")
self.vooUpperRateLimitLabel = tk.Label(self.voo, text = "Upper Rate Limit ")
self.vooAtrialAmplitudeLabel = tk.Label(self.voo, text = "Ventricular Amplitude")
self.vooAtrialPulseWidthLabel = tk.Label(self.voo, text = "Ventricular Pulse Width")
#Setup labels to display values
self.vooLowerRateLimitValue = tk.Label(self.voo, text = "Current Value: "+ voo_lowerRateLimitEntry)
self.vooUpperRateLimitValue = tk.Label(self.voo, text = "Current Value: "+ voo_upperRateLimitEntry)
self.vooAtrialAmplitudeValue = tk.Label(self.voo, text = "Current Value: "+ voo_ventricularAmplitudeEntry)
self.vooAtrialPulseWidthValue = tk.Label(self.voo, text = "Current Value: "+ voo_ventricularPulseWidthEntry)
#Spinbox for setup
self.vooLowerRateLimitEntry = tk.Spinbox(self.voo,from_=30,to=175,increment=5)
self.vooUpperRateLimitEntry = tk.Spinbox(self.voo,from_=50,to=175,increment=5)
self.vooAtrialAmplitudeEntry = tk.Spinbox(self.voo,from_=0.5,to=7.0,format="%.1f",increment=0.1)
self.vooAtrialPulseWidthEntry = tk.Spinbox(self.voo,from_=0.05,to=1.9,format="%.2f",increment=0.1)
#Adjust positioning
self.vooLowerRateLimitLabel.grid(row=0, column=0, padx=15, pady=15)
self.vooLowerRateLimitEntry.grid(row=0, column=1, padx=15, pady=15)
self.vooLowerRateLimitButton.grid(row=0, column=2, padx=15, pady=15)
self.vooLowerRateLimitValue.grid(row=0, column=3, padx=15, pady=15)
self.vooUpperRateLimitLabel.grid(row=1, column=0, padx=15, pady=15)
self.vooUpperRateLimitEntry.grid(row=1, column=1, padx=15, pady=15)
self.vooUpperRateLimitButton.grid(row=1, column=2, padx=15, pady=15)
self.vooUpperRateLimitValue.grid(row=1, column=3, padx=15, pady=15)
self.vooAtrialAmplitudeLabel.grid(row=2, column=0, padx=15, pady=15)
self.vooAtrialAmplitudeEntry.grid(row=2, column=1, padx=15, pady=15)
self.vooAtrialAmplitudeButton.grid(row=2, column=2, padx=15, pady=15)
self.vooAtrialAmplitudeValue.grid(row=2, column=3, padx=15, pady=15)
self.vooAtrialPulseWidthLabel.grid(row=3, column=0, padx=15, pady=15)
self.vooAtrialPulseWidthEntry.grid(row=3, column=1, padx=15, pady=15)
self.vooAtrialPulseWidthButton.grid(row=3, column=2, padx=15, pady=15)
self.vooAtrialPulseWidthValue.grid(row=3, column=3, padx=15, pady=15)
#VOO END-------------------------------------------------------------------------------------------------------------------------------
#AAI BEGIN-----------------------------------------------------------------------------------------------------------------------------
#Setup buttons
self.aaiLowerRateLimitButton = tk.Button(self.aai, text = "Set", command= lambda: self.setValue("aaiLowerRateLimit"))
self.aaiUpperRateLimitButton = tk.Button(self.aai, text = "Set", command= lambda: self.setValue("aaiUpperRateLimit"))
self.aaiAtrialAmplitudeButton = tk.Button(self.aai, text = "Set", command= lambda: self.setValue("aaiAtrialAmplitude"))
self.aaiAtrialPulseWidthButton = tk.Button(self.aai, text = "Set", command= lambda: self.setValue("aaiAtrialPulseWidth"))
self.aaiAtrialSensitivityButton = tk.Button(self.aai, text = "Set", command= lambda: self.setValue("aaiAtrialSensitivity"))
self.aaiARPButton = tk.Button(self.aai, text = "Set", command= lambda: self.setValue("aaiARP"))
self.aaiAPVARPButton = tk.Button(self.aai, text = "Set", command= lambda: self.setValue("aaiAPVARP"))
self.aaiHysteresisButton = tk.Button(self.aai, text = "Set", command= lambda: self.setValue("aaiHysteresis"))
self.aaiRateSmoothingButton = tk.Button(self.aai, text = "Set", command= lambda: self.setValue("aaiRateSmoothing"))
#Setup labels for inputs
self.aaiLowerRateLimitLabel = tk.Label(self.aai, text = "Lower Rate Limit")
self.aaiUpperRateLimitLabel = tk.Label(self.aai, text = "Upper Rate Limit ")
self.aaiAtrialAmplitudeLabel = tk.Label(self.aai, text = "Atrial Amplitude")
self.aaiAtrialPulseWidthLabel = tk.Label(self.aai, text = "Atrial Pulse Width")
self.aaiAtrialSensitivityLabel = tk.Label(self.aai, text = "Atrial Sensitivity")
self.aaiARPLabel = tk.Label(self.aai, text = "ARP")
self.aaiAPVARPLabel = tk.Label(self.aai, text = "APVARP")
self.aaiHysteresisLabel = tk.Label(self.aai, text = "Hysteresis")
self.aaiRateSmoothingLabel = tk.Label(self.aai, text = "Rate Smoothing")
#Setup labels to display values
self.aaiLowerRateLimitValue = tk.Label(self.aai, text = "Current Value: "+ aai_lowerRateLimitEntry)
self.aaiUpperRateLimitValue = tk.Label(self.aai, text = "Current Value: "+ aai_upperRateLimitEntry)
self.aaiAtrialAmplitudeValue = tk.Label(self.aai, text = "Current Value: "+ aai_atrialAmplitudeEntry)
self.aaiAtrialPulseWidthValue = tk.Label(self.aai, text = "Current Value: "+ aai_atrialPulseWidthEntry)
self.aaiAtrialSensitivityValue = tk.Label(self.aai, text = "Current Value: "+ aai_atrialSensitivityEntry)
self.aaiARPValue = tk.Label(self.aai, text = "Current Value: "+ aai_ARPEntry)
self.aaiAPVARPValue = tk.Label(self.aai, text = "Current Value: "+ aai_APVARPEntry)
self.aaiHysteresisValue = tk.Label(self.aai, text = "Current Value: "+ aai_hysteresisEntry)
self.aaiRateSmoothingValue = tk.Label(self.aai, text = "Current Value: "+ aai_rateSmoothingEntry)
#Spinbox for setup
self.aaiLowerRateLimitEntry = tk.Spinbox(self.aai,from_=30,to=175,increment=5)
self.aaiUpperRateLimitEntry = tk.Spinbox(self.aai,from_=50,to=175,increment=5)
self.aaiAtrialAmplitudeEntry = tk.Spinbox(self.aai,from_=0.5,to=7.0,format="%.1f",increment=0.1)
self.aaiAtrialPulseWidthEntry = tk.Spinbox(self.aai,from_=0.05,to=1.9,format="%.2f",increment=0.1)
self.aaiAtrialSensitivityEntry = tk.Spinbox(self.aai,from_=0.25,to=10.0,format="%.2f",increment=0.25)
self.aaiARPEntry = tk.Spinbox(self.aai,from_=150,to=500,increment=10)
self.aaiAPVARPEntry = tk.Spinbox(self.aai,from_=150,to=500,increment=10)
self.aaiHysteresisEntry = tk.Entry(self.aai)
self.aaiRateSmoothingEntry = tk.Spinbox(self.aai,from_=0,to=25,increment=3)
#Adjust positioning
self.aaiLowerRateLimitLabel.grid(row=0, column=0, padx=15, pady=15)
self.aaiLowerRateLimitEntry.grid(row=0, column=1, padx=15, pady=15)
self.aaiLowerRateLimitButton.grid(row=0, column=2, padx=15, pady=15)
self.aaiUpperRateLimitLabel.grid(row=1, column=0, padx=15, pady=15)
self.aaiUpperRateLimitEntry.grid(row=1, column=1, padx=15, pady=15)
self.aaiUpperRateLimitButton.grid(row=1, column=2, padx=15, pady=15)
self.aaiAtrialAmplitudeLabel.grid(row=2, column=0, padx=15, pady=15)
self.aaiAtrialAmplitudeEntry.grid(row=2, column=1, padx=15, pady=15)
self.aaiAtrialAmplitudeButton.grid(row=2, column=2, padx=15, pady=15)
self.aaiAtrialPulseWidthLabel.grid(row=3, column=0, padx=15, pady=15)
self.aaiAtrialPulseWidthEntry.grid(row=3, column=1, padx=15, pady=15)
self.aaiAtrialPulseWidthButton.grid(row=3, column=2, padx=15, pady=15)
self.aaiAtrialSensitivityLabel.grid(row=4, column=0, padx=15, pady=15)
self.aaiAtrialSensitivityEntry.grid(row=4, column=1, padx=15, pady=15)
self.aaiAtrialSensitivityButton.grid(row=4, column=2, padx=15, pady=15)
self.aaiARPLabel.grid(row=5, column=0, padx=15, pady=15)
self.aaiARPEntry.grid(row=5, column=1, padx=15, pady=15)
self.aaiARPButton.grid(row=5, column=2, padx=15, pady=15)
self.aaiAPVARPLabel.grid(row=6, column=0, padx=15, pady=15)
self.aaiAPVARPEntry.grid(row=6, column=1, padx=15, pady=15)
self.aaiAPVARPButton.grid(row=6, column=2, padx=15, pady=15)
self.aaiHysteresisLabel.grid(row=7, column=0, padx=15, pady=15)
self.aaiHysteresisEntry.grid(row=7, column=1, padx=15, pady=15)
self.aaiHysteresisButton.grid(row=7, column=2, padx=15, pady=15)
self.aaiRateSmoothingLabel.grid(row=8, column=0, padx=15, pady=15)
self.aaiRateSmoothingEntry.grid(row=8, column=1, padx=15, pady=15)
self.aaiRateSmoothingButton.grid(row=8, column=2, padx=15, pady=15)
self.aaiLowerRateLimitValue.grid(row=0, column=3, padx=15, pady=15)
self.aaiUpperRateLimitValue.grid(row=1, column=3, padx=15, pady=15)
self.aaiAtrialAmplitudeValue.grid(row=2, column=3, padx=15, pady=15)
self.aaiAtrialPulseWidthValue.grid(row=3, column=3, padx=15, pady=15)
self.aaiAtrialSensitivityValue.grid(row=4, column=3, padx=15, pady=15)
self.aaiARPValue.grid(row=5, column=3, padx=15, pady=15)
self.aaiAPVARPValue.grid(row=6, column=3, padx=15, pady=15)
self.aaiHysteresisValue.grid(row=7, column=3, padx=15, pady=15)
self.aaiRateSmoothingValue.grid(row=8, column=3, padx=15, pady=15)
#AAI END-------------------------------------------------------------------------------------------------------------------------------
#VVI BEGIN-----------------------------------------------------------------------------------------------------------------------------
#Setup buttons
self.vviLowerRateLimitButton = tk.Button(self.vvi, text = "Set", command= lambda: self.setValue("vviLowerRateLimit"))
self.vviUpperRateLimitButton = tk.Button(self.vvi, text = "Set", command= lambda: self.setValue("vviUpperRateLimit"))
self.vviAtrialAmplitudeButton = tk.Button(self.vvi, text = "Set", command= lambda: self.setValue("vviAtrialAmplitude"))
self.vviAtrialPulseWidthButton = tk.Button(self.vvi, text = "Set", command= lambda: self.setValue("vviAtrialPulseWidth"))
self.vviAtrialSensitivityButton = tk.Button(self.vvi, text = "Set", command= lambda: self.setValue("vviAtrialSensitivity"))
self.vviARPButton = tk.Button(self.vvi, text = "Set", command= lambda: self.setValue("vviARP"))
self.vviHysteresisButton = tk.Button(self.vvi, text = "Set", command= lambda: self.setValue("vviHysteresis"))
self.vviRateSmoothingButton = tk.Button(self.vvi, text = "Set", command= lambda: self.setValue("vviRateSmoothing"))
#Setup labels for inputs
self.vviLowerRateLimitLabel = tk.Label(self.vvi, text = "Lower Rate Limit")
self.vviUpperRateLimitLabel = tk.Label(self.vvi, text = "Upper Rate Limit ")
self.vviAtrialAmplitudeLabel = tk.Label(self.vvi, text = "Ventricular Amplitude")
self.vviAtrialPulseWidthLabel = tk.Label(self.vvi, text = "Ventricular Pulse Width")
self.vviAtrialSensitivityLabel = tk.Label(self.vvi, text = "Ventricular Sensitivity")
self.vviARPLabel = tk.Label(self.vvi, text = "VRP")
self.vviHysteresisLabel = tk.Label(self.vvi, text = "Hysteresis")
self.vviRateSmoothingLabel = tk.Label(self.vvi, text = "Rate Smoothing")
#Setup labels to display values
self.vviLowerRateLimitValue = tk.Label(self.vvi, text = "Current Value: "+ vvi_lowerRateLimitEntry)
self.vviUpperRateLimitValue = tk.Label(self.vvi, text = "Current Value: "+ vvi_upperRateLimitEntry)
self.vviAtrialAmplitudeValue = tk.Label(self.vvi, text = "Current Value: "+ vvi_ventricularAmplitudeEntry)
self.vviAtrialPulseWidthValue = tk.Label(self.vvi, text = "Current Value: "+ vvi_ventricularPulseWidthEntry)
self.vviAtrialSensitivityValue = tk.Label(self.vvi, text = "Current Value: "+ vvi_ventricularSensitivityEntry)
self.vviARPValue = tk.Label(self.vvi, text = "Current Value: "+ vvi_ARPEntry)
self.vviHysteresisValue = tk.Label(self.vvi, text = "Current Value: "+ vvi_hysteresisEntry)
self.vviRateSmoothingValue = tk.Label(self.vvi, text = "Current Value: "+ vvi_rateSmoothingEntry)
#Spinbox for setup
self.vviLowerRateLimitEntry = tk.Spinbox(self.vvi,from_=30,to=175,increment=5)
self.vviUpperRateLimitEntry = tk.Spinbox(self.vvi,from_=50,to=175,increment=5)
self.vviAtrialAmplitudeEntry = tk.Spinbox(self.vvi,from_=0.5,to=7.0,format="%.1f",increment=0.1)
self.vviAtrialPulseWidthEntry = tk.Spinbox(self.vvi,from_=0.05,to=1.9,format="%.2f",increment=0.1)
self.vviAtrialSensitivityEntry = tk.Spinbox(self.vvi,from_=0.25,to=10.0,format="%.2f",increment=0.25)
self.vviARPEntry = tk.Spinbox(self.vvi,from_=150,to=500,increment=10)
self.vviHysteresisEntry = tk.Entry(self.vvi)
self.vviRateSmoothingEntry = tk.Spinbox(self.vvi,from_=0,to=25,increment=3)
#Adjust positioning
self.vviLowerRateLimitLabel.grid(row=0, column=0, padx=15, pady=15)
self.vviLowerRateLimitEntry.grid(row=0, column=1, padx=15, pady=15)
self.vviLowerRateLimitButton.grid(row=0, column=2, padx=15, pady=15)
self.vviUpperRateLimitLabel.grid(row=1, column=0, padx=15, pady=15)
self.vviUpperRateLimitEntry.grid(row=1, column=1, padx=15, pady=15)
self.vviUpperRateLimitButton.grid(row=1, column=2, padx=15, pady=15)
self.vviAtrialAmplitudeLabel.grid(row=2, column=0, padx=15, pady=15)
self.vviAtrialAmplitudeEntry.grid(row=2, column=1, padx=15, pady=15)
self.vviAtrialAmplitudeButton.grid(row=2, column=2, padx=15, pady=15)
self.vviAtrialPulseWidthLabel.grid(row=3, column=0, padx=15, pady=15)
self.vviAtrialPulseWidthEntry.grid(row=3, column=1, padx=15, pady=15)
self.vviAtrialPulseWidthButton.grid(row=3, column=2, padx=15, pady=15)
self.vviAtrialSensitivityLabel.grid(row=4, column=0, padx=15, pady=15)
self.vviAtrialSensitivityEntry.grid(row=4, column=1, padx=15, pady=15)
self.vviAtrialSensitivityButton.grid(row=4, column=2, padx=15, pady=15)
self.vviARPLabel.grid(row=5, column=0, padx=15, pady=15)
self.vviARPEntry.grid(row=5, column=1, padx=15, pady=15)
self.vviARPButton.grid(row=5, column=2, padx=15, pady=15)
self.vviHysteresisLabel.grid(row=6, column=0, padx=15, pady=15)
self.vviHysteresisEntry.grid(row=6, column=1, padx=15, pady=15)
self.vviHysteresisButton.grid(row=6, column=2, padx=15, pady=15)
self.vviRateSmoothingLabel.grid(row=7, column=0, padx=15, pady=15)
self.vviRateSmoothingEntry.grid(row=7, column=1, padx=15, pady=15)
self.vviRateSmoothingButton.grid(row=7, column=2, padx=15, pady=15)
self.vviLowerRateLimitValue.grid(row=0, column=3, padx=15, pady=15)
self.vviUpperRateLimitValue.grid(row=1, column=3, padx=15, pady=15)
self.vviAtrialAmplitudeValue.grid(row=2, column=3, padx=15, pady=15)
self.vviAtrialPulseWidthValue.grid(row=3, column=3, padx=15, pady=15)
self.vviAtrialSensitivityValue.grid(row=4, column=3, padx=15, pady=15)
self.vviARPValue.grid(row=5, column=3, padx=15, pady=15)
self.vviHysteresisValue.grid(row=6, column=3, padx=15, pady=15)
self.vviRateSmoothingValue.grid(row=7, column=3, padx=15, pady=15)
#VVI END-------------------------------------------------------------------------------------------------------------------------------
#Track the process
self.logTitle = tk.Label(self.aoo, text = "History")
self.logTitle.grid(row=0, column=4, padx=15, pady=15)
self.aooLog = tk.Label(self.aoo, text = userLog)
self.aooLog.grid(row=1, column=4, padx=15, pady=15)
self.logTitle = tk.Label(self.voo, text = "History")
self.logTitle.grid(row=0, column=4, padx=15, pady=15)
self.vooLog = tk.Label(self.voo, text = userLog)
self.vooLog.grid(row=1, column=4, padx=15, pady=15)
self.logTitle = tk.Label(self.aai, text = "History")
self.logTitle.grid(row=0, column=4, padx=15, pady=15)
self.aaiLog = tk.Label(self.aai, text = userLog)
self.aaiLog.grid(row=1, column=4, padx=15, pady=15)
self.logTitle = tk.Label(self.vvi, text = "History")
self.logTitle.grid(row=0, column=4, padx=15, pady=15)
self.vviLog = tk.Label(self.vvi, text = userLog)
self.vviLog.grid(row=1, column=4, padx=15, pady=15)
#Position tabs properly
self.tab_parent.pack(expand = 1, fill='both')
#Setup confirm buttons
self.confirmButton = tk.Button(self.aoo, text = 'Confirm', width = 20, command = lambda: self.confirmChanges("aooConfirm"))
self.confirmButton.grid(row = 4, column = 1)
self.confirmButton = tk.Button(self.voo, text = 'Confirm', width = 20, command = lambda: self.confirmChanges("vooConfirm"))
self.confirmButton.grid(row = 4, column = 1)
self.confirmButton = tk.Button(self.aai, text = 'Confirm', width = 20, command = lambda: self.confirmChanges("aaiConfirm"))
self.confirmButton.grid(row = 9, column = 1)
self.confirmButton = tk.Button(self.vvi, text = 'Confirm', width = 20, command = lambda: self.confirmChanges("vviConfirm"))
self.confirmButton.grid(row = 8, column = 1)
#Setup logoff button
self.quitButton = tk.Button(self.aoo, text = 'LogOff', width = 12, command = self.logOff)
self.quitButton.grid(row=5,column=1,pady=5)
self.quitButton = tk.Button(self.voo, text = 'LogOff', width = 12, command = self.logOff)
self.quitButton.grid(row=5,column=1,pady=5)
self.quitButton = tk.Button(self.aai, text = 'LogOff', width = 12, command = self.logOff)
self.quitButton.grid(row=10,column=1,pady=5)
self.quitButton = tk.Button(self.vvi, text = 'LogOff', width = 12, command = self.logOff)
self.quitButton.grid(row=10,column=1,pady=5)
#Confirm changes method
def confirmChanges(self,value):
if (value == "aooConfirm"):
if messagebox.askyesno("Confirmation", "Upload these changes?"):
messagebox.showinfo("Done", "Success")
userLog = "aoo has done"
self.aooLog.config(text=userLog)
self.vooLog.config(text=userLog)
self.aaiLog.config(text=userLog)
self.vviLog.config(text=userLog)
db.execute("UPDATE aoo SET userLog = ? WHERE (user = ?)", (userLog, currentuser))
db.commit()
elif (value == "vooConfirm"):
if messagebox.askyesno("Confirmation", "Upload these changes?"):
messagebox.showinfo("Done", "Success")
userLog = "voo has done"
self.aooLog.config(text=userLog)
self.vooLog.config(text=userLog)
self.aaiLog.config(text=userLog)
self.vviLog.config(text=userLog)
db.execute("UPDATE aoo SET userLog = ? WHERE (user = ?)", (userLog, currentuser))
db.commit()
elif (value == "aaiConfirm"):
if messagebox.askyesno("Confirmation", "Upload these changes?"):
messagebox.showinfo("Done", "Success")
userLog = "aai has done"
self.aooLog.config(text=userLog)
self.vooLog.config(text=userLog)
self.aaiLog.config(text=userLog)
self.vviLog.config(text=userLog)
db.execute("UPDATE aoo SET userLog = ? WHERE (user = ?)", (userLog, currentuser))
db.commit()
elif (value == "vviConfirm"):
if messagebox.askyesno("Confirmation", "Upload these changes?"):
messagebox.showinfo("Done", "Success")
userLog = "vvi has done"
self.aooLog.config(text=userLog)
self.vooLog.config(text=userLog)
self.aaiLog.config(text=userLog)
self.vviLog.config(text=userLog)
db.execute("UPDATE aoo SET userLog = ? WHERE (user = ?)", (userLog, currentuser))
db.commit()
#New window method
def new_window(self,window):
self.newWindow = tk.Toplevel(self.master)
self.app = window(self.newWindow)
#Method to set value
def setValue(self,value):
#Global Variables
#AOO
global aoo_lowerRateLimitEntry,aoo_upperRateLimitEntry,aoo_atrialAmplitudeEntry,aoo_atrialPulseWidthEntry
#VOO
global voo_lowerRateLimitEntry,voo_upperRateLimitEntry,voo_ventricularAmplitudeEntry,voo_ventricularPulseWidthEntry
#AAI
global aai_lowerRateLimitEntry,aai_upperRateLimitEntry,aai_atrialAmplitudeEntry,aai_atrialPulseWidthEntry,aai_atrialSensitivityEntry,aai_ARPEntry,aai_APVARPEntry,aai_hysteresisEntry,aai_rateSmoothingEntry
#VVI
global vvi_lowerRateLimitEntry,vvi_upperRateLimitEntry,vvi_ventricularAmplitudeEntry,vvi_ventricularPulseWidthEntry,vvi_ventricularSensitivityEntry,vvi_ARPEntry,vvi_hysteresisEntry,vvi_rateSmoothingEntry
#Currentuser
global currentuser
#AOO
#aooLowerRateLimit
if(value == "aooLowerRateLimit"):
temp = self.aooLowerRateLimitEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure upper limit is larger than lower limit
elif(int(self.aooLowerRateLimitEntry.get()) >= int(aoo_upperRateLimitEntry) and int(aoo_upperRateLimitEntry) != 0 ):
messagebox.showinfo("Error","Please ensure your lower rate limit is lower than your upper rate limit")
pass
#Ensure value is in limited range
elif(int(temp) < 30 or int(temp) > 175):
messagebox.showinfo("Error","The range is between 30 and 175")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aoo_lowerRateLimitEntry = temp
self.aooLowerRateLimitValue.config(text="Current Value: " + aoo_lowerRateLimitEntry)
db.execute("UPDATE aoo SET aoo_lowerRateLimitEntry = ? WHERE (user = ?)", (aoo_lowerRateLimitEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#aooUpperRateLimit
if(value == "aooUpperRateLimit"):
temp = self.aooUpperRateLimitEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure upper limit is larger than lower limit
elif(int(aoo_lowerRateLimitEntry) >= int(self.aooUpperRateLimitEntry.get()) and int(aoo_lowerRateLimitEntry) != 0 ):
messagebox.showinfo("Error","Please ensure your lower rate limit is lower than your upper rate limit")
pass
#Ensure value is in limited range
elif(int(temp) < 50 or int(temp) > 175):
messagebox.showinfo("Error","The range is between 50 and 175")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aoo_upperRateLimitEntry = temp
self.aooUpperRateLimitValue.config(text="Current Value: " + aoo_upperRateLimitEntry)
db.execute("UPDATE aoo SET aoo_upperRateLimitEntry = ? WHERE (user = ?)", (aoo_upperRateLimitEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#aooAtrialAmplitude
if(value == "aooAtrialAmplitude"):
temp = self.aooAtrialAmplitudeEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
float(temp)
if (temp == '' or float(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(float(temp) < 0 or float(temp) > 7.0):
messagebox.showinfo("Error","The range is between 0(off) and 7.0")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aoo_atrialAmplitudeEntry = temp
self.aooAtrialAmplitudeValue.config(text="Current Value: " + aoo_atrialAmplitudeEntry)
db.execute("UPDATE aoo SET aoo_atrialAmplitudeEntry = ? WHERE (user = ?)", (aoo_atrialAmplitudeEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#aooAtrialPulseWidth
if(value == "aooAtrialPulseWidth"):
temp = self.aooAtrialPulseWidthEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
float(temp)
if (temp == '' or float(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(float(temp) < 0.05 or float(temp) > 1.9):
messagebox.showinfo("Error","The range is between 0.05 and 1.9")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aoo_atrialPulseWidthEntry = temp
self.aooAtrialPulseWidthValue.config(text="Current Value: " + aoo_atrialPulseWidthEntry)
db.execute("UPDATE aoo SET aoo_atrialPulseWidthEntry = ? WHERE (user = ?)", (aoo_atrialPulseWidthEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#VOO
#vooLowerRateLimit
if(value == "vooLowerRateLimit"):
temp = self.vooLowerRateLimitEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure upper limit is larger than lower limit
elif(int(self.vooLowerRateLimitEntry.get()) >= int(voo_upperRateLimitEntry) and int(voo_upperRateLimitEntry) != 0 ):
messagebox.showinfo("Error","Please ensure your lower rate limit is lower than your upper rate limit")
pass
#Ensure value is in limited range
elif(int(temp) < 30 or int(temp) > 175):
messagebox.showinfo("Error","The range is between 30 and 175")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
voo_lowerRateLimitEntry = temp
self.vooLowerRateLimitValue.config(text="Current Value: " + voo_lowerRateLimitEntry)
db.execute("UPDATE voo SET voo_lowerRateLimitEntry = ? WHERE (user = ?)", (voo_lowerRateLimitEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#vooUpperRateLimit
if(value == "vooUpperRateLimit"):
temp = self.vooUpperRateLimitEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure upper limit is larger than lower limit
elif(int(voo_lowerRateLimitEntry) >= int(self.vooUpperRateLimitEntry.get()) and int(voo_lowerRateLimitEntry) != 0 ):
messagebox.showinfo("Error","Please ensure your lower rate limit is lower than your upper rate limit")
pass
#Ensure value is in limited range
elif(int(temp) < 50 or int(temp) > 175):
messagebox.showinfo("Error","The range is between 50 and 175")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
voo_upperRateLimitEntry = temp
self.vooUpperRateLimitValue.config(text="Current Value: " + voo_upperRateLimitEntry)
db.execute("UPDATE voo SET voo_upperRateLimitEntry = ? WHERE (user = ?)", (voo_upperRateLimitEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#vooAtrialAmplitude
if(value == "vooAtrialAmplitude"):
temp = self.vooAtrialAmplitudeEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
float(temp)
if (temp == '' or float(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(float(temp) < 0 or float(temp) > 7.0):
messagebox.showinfo("Error","The range is between 0(off) and 7.0")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
voo_ventricularAmplitudeEntry = temp
self.vooAtrialAmplitudeValue.config(text="Current Value: " + voo_ventricularAmplitudeEntry)
db.execute("UPDATE voo SET voo_ventricularAmplitudeEntry = ? WHERE (user = ?)", (voo_ventricularAmplitudeEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#vooAtrialPulseWidth
if(value == "vooAtrialPulseWidth"):
temp = self.vooAtrialPulseWidthEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
float(temp)
if (temp == '' or float(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(float(temp) < 0.05 or float(temp) > 1.9):
messagebox.showinfo("Error","The range is between 0.05 and 1.9")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
voo_ventricularPulseWidthEntry = temp
self.vooAtrialPulseWidthValue.config(text="Current Value: " + voo_ventricularPulseWidthEntry)
db.execute("UPDATE voo SET voo_ventricularPulseWidthEntry = ? WHERE (user = ?)", (voo_ventricularPulseWidthEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#AAI
#aaiLowerRateLimit
if(value == "aaiLowerRateLimit"):
temp = self.aaiLowerRateLimitEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure upper limit is larger than lower limit
elif(int(self.aaiLowerRateLimitEntry.get()) >= int(aai_upperRateLimitEntry) and int(aai_upperRateLimitEntry) != 0 ):
messagebox.showinfo("Error","Please ensure your lower rate limit is lower than your upper rate limit")
pass
#Ensure value is in limited range
elif(int(temp) < 30 or int(temp) > 175):
messagebox.showinfo("Error","The range is between 30 and 175")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aai_lowerRateLimitEntry = temp
self.aaiLowerRateLimitValue.config(text="Current Value: " + aai_lowerRateLimitEntry)
db.execute("UPDATE aai SET aai_lowerRateLimitEntry = ? WHERE (user = ?)", (aai_lowerRateLimitEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#aaiUpperRateLimit
if(value == "aaiUpperRateLimit"):
temp = self.aaiUpperRateLimitEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure upper limit is larger than lower limit
elif(int(aai_lowerRateLimitEntry) >= int(self.aaiUpperRateLimitEntry.get()) and int(aai_lowerRateLimitEntry) != 0 ):
messagebox.showinfo("Error","Please ensure your lower rate limit is lower than your upper rate limit")
pass
#Ensure value is in limited range
elif(int(temp) < 50 or int(temp) > 175):
messagebox.showinfo("Error","The range is between 50 and 175")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aai_upperRateLimitEntry = temp
self.aaiUpperRateLimitValue.config(text="Current Value: " + aai_upperRateLimitEntry)
db.execute("UPDATE aai SET aai_upperRateLimitEntry = ? WHERE (user = ?)", (aai_upperRateLimitEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#aaiAtrialAmplitude
if(value == "aaiAtrialAmplitude"):
temp = self.aaiAtrialAmplitudeEntry .get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
float(temp)
if (temp == '' or float(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(float(temp) < 0 or float(temp) > 7.0):
messagebox.showinfo("Error","The range is between 0(off) and 7.0")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aai_atrialAmplitudeEntry = temp
self.aaiAtrialAmplitudeValue.config(text="Current Value: " + aai_atrialAmplitudeEntry)
db.execute("UPDATE aai SET aai_atrialAmplitudeEntry = ? WHERE (user = ?)", (aai_atrialAmplitudeEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#aaiAtrialPulseWidth
if(value == "aaiAtrialPulseWidth"):
temp = self.aaiAtrialPulseWidthEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
float(temp)
if (temp == '' or float(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(float(temp) < 0.05 or float(temp) > 1.9):
messagebox.showinfo("Error","The range is between 0.05 and 1.9")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aai_atrialPulseWidthEntry = temp
self.aaiAtrialPulseWidthValue.config(text="Current Value: " + aai_atrialPulseWidthEntry)
db.execute("UPDATE aai SET aai_atrialPulseWidthEntry = ? WHERE (user = ?)", (aai_atrialPulseWidthEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#aaiAtrialSensitivity
if(value == "aaiAtrialSensitivity"):
temp = self.aaiAtrialSensitivityEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
float(temp)
if (temp == '' or float(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(float(temp) < 0.25 or float(temp) > 10.0):
messagebox.showinfo("Error","The range is between 0.25 and 10.0")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aai_atrialSensitivityEntry = temp
self.aaiAtrialSensitivityValue.config(text="Current Value: " + aai_atrialSensitivityEntry)
db.execute("UPDATE aai SET aai_atrialSensitivityEntry = ? WHERE (user = ?)", (aai_atrialSensitivityEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#aaiARP
if(value == "aaiARP"):
temp = self.aaiARPEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(int(temp) < 150 or int(temp) > 500):
messagebox.showinfo("Error","The range is between 150 and 500")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aai_ARPEntry = temp
self.aaiARPValue.config(text="Current Value: " + aai_ARPEntry)
db.execute("UPDATE aai SET aai_ARPEntry = ? WHERE (user = ?)", (aai_ARPEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#aaiAPVARP
if(value == "aaiAPVARP"):
temp = self.aaiAPVARPEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(int(temp) < 150 or int(temp) > 500):
messagebox.showinfo("Error","The range is between 150 and 500")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aai_APVARPEntry = temp
self.aaiAPVARPValue.config(text="Current Value: " + aai_APVARPEntry)
db.execute("UPDATE aai SET aai_APVARPEntry = ? WHERE (user = ?)", (aai_APVARPEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#aaiHysteresis
if(value == "aaiHysteresis"):
temp = self.aaiHysteresisEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aai_hysteresisEntry = temp
self.aaiHysteresisValue.config(text="Current Value: " + aai_hysteresisEntry)
db.execute("UPDATE aai SET aai_hysteresisEntry = ? WHERE (user = ?)", (aai_hysteresisEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#aaiRateSmoothing
if(value == "aaiRateSmoothing"):
temp = self.aaiRateSmoothingEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(int(temp) < 0 or int(temp) > 25):
messagebox.showinfo("Error","The range is between 0(off) and 25")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
aai_rateSmoothingEntry = temp
self.aaiRateSmoothingValue.config(text="Current Value: " + aai_rateSmoothingEntry)
db.execute("UPDATE aai SET aai_rateSmoothingEntry = ? WHERE (user = ?)", (aai_rateSmoothingEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#VVI
#vviLowerRateLimit
if(value == "vviLowerRateLimit"):
temp = self.vviLowerRateLimitEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure upper limit is larger than lower limit
elif(int(self.vviLowerRateLimitEntry.get()) >= int(vvi_upperRateLimitEntry) and int(vvi_upperRateLimitEntry) != 0 ):
messagebox.showinfo("Error","Please ensure your lower rate limit is lower than your upper rate limit")
pass
#Ensure value is in limited range
elif(int(temp) < 30 or int(temp) > 175):
messagebox.showinfo("Error","The range is between 30 and 175")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
vvi_lowerRateLimitEntry = temp
self.vviLowerRateLimitValue.config(text="Current Value: " + vvi_lowerRateLimitEntry)
db.execute("UPDATE vvi SET vvi_lowerRateLimitEntry = ? WHERE (user = ?)", (vvi_lowerRateLimitEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#vviUpperRateLimit
if(value == "vviUpperRateLimit"):
temp = self.vviUpperRateLimitEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure upper limit is larger than lower limit
elif(int(vvi_lowerRateLimitEntry) >= int(self.vviUpperRateLimitEntry.get()) and int(vvi_lowerRateLimitEntry) != 0 ):
messagebox.showinfo("Error","Please ensure your lower rate limit is lower than your upper rate limit")
pass
#Ensure value is in limited range
elif(int(temp) < 50 or int(temp) > 175):
messagebox.showinfo("Error","The range is between 50 and 175")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
vvi_upperRateLimitEntry = temp
self.vviUpperRateLimitValue.config(text="Current Value: " + vvi_upperRateLimitEntry)
db.execute("UPDATE vvi SET vvi_upperRateLimitEntry = ? WHERE (user = ?)", (vvi_upperRateLimitEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#vviAtrialAmplitude
if(value == "vviAtrialAmplitude"):
temp = self.vviAtrialAmplitudeEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
float(temp)
if (temp == '' or float(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(float(temp) < 0 or float(temp) > 7.0):
messagebox.showinfo("Error","The range is between 0(off) and 7.0")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
vvi_ventricularAmplitudeEntry = temp
self.vviAtrialAmplitudeValue.config(text="Current Value: " + vvi_ventricularAmplitudeEntry)
db.execute("UPDATE vvi SET vvi_ventricularAmplitudeEntry = ? WHERE (user = ?)", (vvi_ventricularAmplitudeEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#vviAtrialPulseWidth
if(value == "vviAtrialPulseWidth"):
temp = self.vviAtrialPulseWidthEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
float(temp)
if (temp == '' or float(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(float(temp) < 0.05 or float(temp) > 1.9):
messagebox.showinfo("Error","The range is between 0.05 and 1.9")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
vvi_ventricularPulseWidthEntry = temp
self.vviAtrialPulseWidthValue.config(text="Current Value: " + vvi_ventricularPulseWidthEntry)
db.execute("UPDATE vvi SET vvi_ventricularPulseWidthEntry = ? WHERE (user = ?)", (vvi_ventricularPulseWidthEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#vviAtrialSensitivity
if(value == "vviAtrialSensitivity"):
temp = self.vviAtrialSensitivityEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
float(temp)
if (temp == '' or float(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(float(temp) < 0.25 or float(temp) > 10.0):
messagebox.showinfo("Error","The range is between 0.25 and 10.0")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
vvi_ventricularSensitivityEntry = temp
self.vviAtrialSensitivityValue.config(text="Current Value: " + vvi_ventricularSensitivityEntry)
db.execute("UPDATE vvi SET vvi_ventricularSensitivityEntry = ? WHERE (user = ?)", (vvi_ventricularSensitivityEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#vviARP
if(value == "vviARP"):
temp = self.vviARPEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(int(temp) < 150 or int(temp) > 500):
messagebox.showinfo("Error","The range is between 150 and 500")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
vvi_ARPEntry = temp
self.vviARPValue.config(text="Current Value: " + vvi_ARPEntry)
db.execute("UPDATE vvi SET vvi_ARPEntry = ? WHERE (user = ?)", (vvi_ARPEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#vviHysteresis
if(value == "vviHysteresis"):
temp = self.vviHysteresisEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
vvi_hysteresisEntry = temp
self.vviHysteresisValue.config(text="Current Value: " + vvi_hysteresisEntry)
db.execute("UPDATE vvi SET vvi_hysteresisEntry = ? WHERE (user = ?)", (vvi_hysteresisEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#vviRateSmoothing
if(value == "vviRateSmoothing"):
temp = self.vviRateSmoothingEntry.get()
#Try/access to sanitize user input and ask for confirmation if there are no errors
try:
int(temp)
if (temp == '' or int(temp)<0):
messagebox.showinfo("Error","Please enter a valid value")
pass
#Ensure value is in limited range
elif(int(temp) < 0 or int(temp) > 25):
messagebox.showinfo("Error","The range is between 0(off) and 25")
pass
#If everything is good update current value
else:
if messagebox.askyesno("Confirmation", "Replace current value?"):
messagebox.showinfo("Done", "Success")
vvi_rateSmoothingEntry = temp
self.vviRateSmoothingValue.config(text="Current Value: " + vvi_rateSmoothingEntry)
db.execute("UPDATE vvi SET vvi_rateSmoothingEntry = ? WHERE (user = ?)", (vvi_rateSmoothingEntry, currentuser))
db.commit()
except:
messagebox.showinfo("Error","Please enter a valid value")
pass
#Method used to log off user
def logOff(self):
if messagebox.askyesno("LogOff", "Do you want to log off?"):
self.master.destroy()
main()
#exit()
#Method to exit application
def on_exit(self):
if messagebox.askyesno("Exit", "Do you want to quit the application?"):
exit()
#Method for closing windows
def close_windows(self):
self.master.destroy()
exit()
#Main function that runs everything
def main():
#Run Tkinter
root = tk.Tk()
app = WelcomeFrame(root)
root.mainloop()
if __name__ == '__main__':
main() | true |
1abff19a7827a6f911bc981eb4fb97728751b218 | Python | A-Jacobson/FaceNet-Pytorch | /datasets.py | UTF-8 | 1,905 | 2.828125 | 3 | [] | no_license | import os
import random
from glob import glob
from PIL import Image
from torch.utils.data import Dataset
class TripletImageDataset(Dataset):
"""
Creates anchor, positive, negative triples from diretory of Image folders
"""
def __init__(self, root, transform=None):
self.name_to_id = dict((name, i)
for i, name in enumerate(sorted(os.listdir(root))))
self.id_to_name = dict((i, name)
for name, i in self.name_to_id.items())
self.images = glob(os.path.join(root, "*", "*"))
self.class_dirs = glob(os.path.join(root, "*"))
self.transform = transform
def create_triplets(self):
class_1, class_2 = random.sample(self.class_paths, 2)
images_1 = os.listdir(class_1)
image_2 = os.listdir(class_2)
return class_1, class_2, images_1, image_2
def __getitem__(self, idx):
anchor_path = random.choice(self.images)
anchor_class_dir, _ = os.path.split(anchor_path)
positive_image_paths = glob(os.path.join(anchor_class_dir, '*'))
positive_path = random.choice(positive_image_paths)
while True:
negative_class_dir = random.choice(self.class_dirs)
if negative_class_dir != anchor_class_dir:
break
negative_image_paths = glob(os.path.join(negative_class_dir, '*'))
negative_path = random.choice(negative_image_paths)
anchor = Image.open(anchor_path).convert('RGB')
positive = Image.open(positive_path).convert('RGB')
negative = Image.open(negative_path).convert('RGB')
if self.transform:
anchor = self.transform(anchor)
positive = self.transform(positive)
negative = self.transform(negative)
return anchor, positive, negative
def __len__(self):
return len(self.images)
| true |
0eabf157cc5b8aa71cad34be7ae0807e3ac6a5d7 | Python | crashish/stuff | /stakreport.py | UTF-8 | 577 | 2.78125 | 3 | [] | no_license | import requests
import bs4
hosts = ['192.168.1.104:1001', '192.168.1.90:1001']
res = {}
for host in hosts:
data = requests.get("http://"+host+"/h")
soup = bs4.BeautifulSoup(data.text, "html.parser")
res[host] = {}
for row in soup.findAll('tr'):
th = row.findAll('th')[0].text.strip()
if 'Thread' in th:
continue
tds = row.findAll('td')
tds = [float(td.text.strip()) for td in tds if len(td.text) > 0 ]
res[host][th] = tds
totals = [0,0,0]
for host in res:
for i,val in enumerate(res[host]['Totals:']):
totals[i] += val
print "Totals: {}".format(totals)
| true |
cb387a3b463d5b768cbcff13769f3adb886e6427 | Python | Snehagit6/G-Pythonautomation_softwares-Sanfoundry_programs | /Basic_Programs/reverseofno.py | UTF-8 | 171 | 4.03125 | 4 | [] | no_license | n = int(input("Enter the number of elements to be reversed:"))
rev=0
while n > 0:
dig = n % 10
rev = rev*10+dig
n = n//10
print("Reversed number : ", rev)
| true |
46f183d8b82110fa4ed292449d1864326570fb86 | Python | 215836017/LearningPython | /code/Test11.py | UTF-8 | 3,447 | 4.71875 | 5 | [] | no_license | print('函数式编程 --- 高阶函数 --- 内建函数:map/reduce')
'''
map/reduce
1. map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回
2. map()作为高阶函数,事实上它把运算规则抽象了,因此,我们不但可以计算简单的f(x)=x2次方,还可以计算任意复杂的函数
'''
# 比如我们有一个函数f(x)=x2次方,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()实现如下
def f(x):
return x * x
test_map = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print('test map:', list(test_map))
'''
1. reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,
其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
'''
#比方说对一个序列求和,就可以用reduce实现
from functools import reduce;
def add(x, y):
return x + y
def chengFa(x, y):
return x * y
print('test_reduce1: ', reduce(add, [1, 3, 5, 7, 9]))
print('test_reduce2: ', reduce(chengFa, [1, 3, 5, 7, 9]))
print('\n\n 函数式编程 --- 高阶函数 --- 内建函数:filter')
'''
1. Python内建的filter()函数用于过滤序列
2. 和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,
然后根据返回值是True还是False决定保留还是丢弃该元素
'''
# 在一个list中,删掉偶数,只保留奇数,可以这么写
def is_odd(n):
return n % 2 == 1
print('test_filter: ', list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])))
print('\n\n 函数式编程 --- 高阶函数 --- 内建函数:sorted')
'''
1. 排序也是在程序中经常用到的算法。无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小。如果是数字,我们可以直接比较,
但如果是字符串或者两个dict呢?直接比较数学上的大小是没有意义的,因此,比较的过程必须通过函数抽象出来
2. Python内置的sorted()函数就可以对list进行排序
3. 此外,sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序
'''
test_sorted1 = [1, 5, 6, 8, 2, 3, 4, 9, 7]
test_sorted2 = sorted(test_sorted1)
print('before orted: ', test_sorted1)
print('after orted: ', test_sorted2)
test_sorted3 = [3, 7, -1, -2, 9]
test_sorted4 = sorted(test_sorted3, key=abs)
print('before orted: ', test_sorted3)
print('after orted: ', test_sorted4) # 打印结果:after orted: [-1, -2, 3, 7, 9] 即按绝对值大小排序
test_sorted5 = ['bob', 'about', 'Zoo', 'Credit']
test_sorted6 = sorted(test_sorted5) # 默认情况下,对字符串排序,是按照ASCII的大小比较的, 由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面
print('before orted: ', test_sorted5)
print('after orted: ', test_sorted6)
test_sorted7 = sorted(test_sorted5, key=str.lower)
print('after orted: ', test_sorted7)
# 要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True
test_sorted8 = sorted(test_sorted5, key=str.lower, reverse=True)
print('after orted: ', test_sorted8) | true |
652e82ebb251213f3a9dd8eaf57223674452b704 | Python | prechelt/pyth | /tests/test_writelatex.py | UTF-8 | 1,517 | 2.8125 | 3 | [
"MIT"
] | permissive | """
unit tests of the latex writer
"""
from __future__ import absolute_import
import unittest
from pyth.plugins.latex.writer import LatexWriter
from pyth.plugins.python.reader import *
class TestWriteLatex(unittest.TestCase):
def test_basic(self):
"""
Try to create an empty latex document
"""
doc = PythonReader.read([])
latex = LatexWriter.write(doc).getvalue()
def test_paragraph(self):
"""
Try a single paragraph document
"""
doc = PythonReader.read(P[u"the text"])
latex = LatexWriter.write(doc).getvalue()
assert "the text" in latex
def test_bold(self):
doc = PythonReader.read([P[T(BOLD)[u"bold text"]]])
latex = LatexWriter.write(doc).getvalue()
assert r"\textbf{bold text}" in latex, latex
def test_italic(self):
doc = PythonReader.read([P[T(ITALIC)[u"italic text"]]])
latex = LatexWriter.write(doc).getvalue()
assert r"\emph{italic text}" in latex, latex
def test_metadata(self):
"""
assert that the document metadata are added into the latex file
"""
doc = PythonReader.read([])
doc["author"] = "The Author"
doc["subject"] = "The Subject"
doc["title"] = "The Title"
latex = LatexWriter.write(doc).getvalue()
assert "pdfauthor={The Author}" in latex, latex
assert "pdfsubject={The Subject}" in latex, latex
assert "pdftitle={The Title}" in latex, latex
| true |
2826677218722f622f19052d3cc59c8652db3eff | Python | ardacancglyn/Python | /17_List_Comprehension.py | UTF-8 | 592 | 4.375 | 4 | [] | no_license | #List Comprehension
#1-)
print("1-): ")
list1=[1,2,3,4,5,6,7,8,9,10]
list2=list()
for i in list1:
list2.append(i)
print(*list2)
#2-)1. SAME(Basic)
print("2-): ")
list3=list(range(1,21))
liste = []
for i in range(1000):
liste += [i]
#2-)2.SAME (Comprehension)
liste1 = [i for i in range(1000)]
#3-)1. SAME(Basic)
liste = []
for i in range(1000):
if i % 2 == 0:
liste += [i]
#3-)2. SAME(Comprehension)
liste = [i for i in range(1000) if i % 2 == 0]
| true |
0abd6ac1945bb90d421437be47a743e6f35f185b | Python | messerzen/Udacity_DataEngineer | /2_datamodeling/project1_datamodeling_with_postgres/etl.py | UTF-8 | 4,806 | 3.109375 | 3 | [] | no_license | import os
import glob
import psycopg2
import pandas as pd
from sql_queries import *
def process_song_file(cur, filepath):
"""
- Process the data stored in the song file, splitting the data in song and artist dataframe.
- Register each dataframe record in its respective tables in the database .
Parameters
----------
cur : cursor object
The database cursor object.
filepath : str
The filepath where the song_file is located.
"""
# open song file
df = pd.read_json(filepath, lines=True)
# insert song record
song_data = df[['song_id', 'title', 'artist_id', 'year', 'duration']]
cur.execute(song_table_insert, song_data.values[0])
# insert artist record
artist_data = df[['artist_id', 'artist_name',
'artist_location', 'artist_latitude',
'artist_longitude']]
cur.execute(artist_table_insert, artist_data.values[0])
def process_log_file(cur, filepath):
"""
- Process the data stored in the log file, splitting the data in time, user and songplay dataframe.
- Register each dataframe record in its respective database tables.
Parameters
----------
cur : cursor object
The database cursor object.
filepath : str
The filepath where the song_file is located.
"""
# open log file
df = pd.read_json(filepath, lines=True)
# filter by NextSong action
df = df[df['page']=='NextSong']
# convert timestamp column to datetime
t = pd.to_datetime(df['ts'], unit='ms')
# insert time data records
time_data = (t, t.dt.hour, t.dt.day, t.dt.week,
t.dt.month, t.dt.year, t.dt.weekday)
column_labels = ('start_time', 'hour', 'day',
'week', 'month', 'year', 'weekday')
time_df = pd.DataFrame({k:v for k,v in zip(column_labels, time_data)})
for i, row in time_df.iterrows():
cur.execute(time_table_insert, list(row))
# load user table
user_df = df[['userId', 'firstName', 'lastName', 'gender', 'level']]
# insert user records
for i, row in user_df.iterrows():
cur.execute(user_table_insert, row)
# insert songplay records
for index, row in df.iterrows():
# get songid and artistid from song and artist tables
cur.execute(song_select, (row.song, row.artist, row.length))
results = cur.fetchone()
if results:
songid, artistid = results
else:
songid, artistid = None, None
# insert songplay record
songplay_data = (pd.to_datetime(row.ts, unit='ms'), row.userId, songid, artistid,
row.sessionId, row.location, row.userAgent)
cur.execute(songplay_table_insert, songplay_data)
def process_data(cur, conn, filepath, func):
"""
- Navigates through each folder and stores all the json filepaths in a list.
- Iterates over each json file in the list and process the file according to the filetype: \
Applies process_song_file method for each song file.
Applies process_log_file method for each log file.
Parameters
----------
cur : cursor object
The database cursor object.
conn : connection object
The object that estabilishes the connection with database
filepath : str
The folder path where the *.json files are located.
func : method
The process method that will be applied to the files (process_log_files or process_song_files)
"""
# get all files matching extension from directory
all_files = []
for root, dirs, files in os.walk(filepath):
files = glob.glob(os.path.join(root,'*.json'))
for f in files :
all_files.append(os.path.abspath(f))
# get total number of files found
num_files = len(all_files)
print('{} files found in {}'.format(num_files, filepath))
# iterate over files and process
for i, datafile in enumerate(all_files, 1):
func(cur, datafile)
conn.commit()
print('{}/{} files processed.'.format(i, num_files))
def main():
"""
Establishes connection with the sparkify database and gets
cursor to it.
Process the *.json files in the song_data folder and stores the data in the database
Process the *.json files in the log_data folder folder and stores the data in the database
Finally, closes the connection.
"""
conn = psycopg2.connect("host=127.0.0.1 dbname=sparkifydb user=dataengineer password=udacity")
cur = conn.cursor()
process_data(cur, conn, filepath='./data/song_data', func=process_song_file)
process_data(cur, conn, filepath='./data/log_data', func=process_log_file)
conn.close()
if __name__ == "__main__":
main() | true |
f608b04f4c1fe001bdf632d38c514655e023ae54 | Python | gaurab123/DataQuest | /02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/05_WorkingWithMissingData/03_FindingTheMissingData_examples.py | UTF-8 | 498 | 3.6875 | 4 | [] | no_license | import pandas as pd
titanic_survival = pd.read_csv('titanic_survival.csv')
sex = titanic_survival["sex"]
sex_is_null = pd.isnull(sex)
# This loop show the sex element value with the corresponding isnull return value
# It illustrates the fact that a null value will return a true value
for index, item in enumerate(sex):
print('%s - %s' % (item, sex_is_null[index]))
# We can use this resultant series to select only the rows that have null values.
sex_null_true = sex[sex_is_null] | true |
350a0b385242283be21ecd93316e7c44939f4005 | Python | uttank/haksangbu | /sample_file.py | UTF-8 | 1,129 | 2.90625 | 3 | [] | no_license | import io
import os
# Imports the Google Cloud client library
from google.cloud import vision
# Instantiates a client
client = vision.ImageAnnotatorClient()
# The name of the image file to annotate
file_name = os.path.abspath('./data2.jpg')
result_file_name = os.path.abspath('./result.json')
# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
# Performs text detection on the image file
response = client.text_detection(image=image)
texts = response.text_annotations
print('Texts:')
with io.open(result_file_name,'w',encoding='utf-8') as f :
for text in texts:
f.write('\n"{}"'.format(text.description))
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in text.bounding_poly.vertices])
f.write('bounds: {}'.format(','.join(vertices)))
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message)) | true |
fd0a4a3111605e97fa21ac6c21ea240414013728 | Python | jsmojver/Backup_LoboPharm | /project/openpyxl/writer/tests/test_lxml.py | UTF-8 | 24,122 | 2.78125 | 3 | [] | no_license | from __future__ import absolute_import
# Copyright (c) 2010-2014 openpyxl
# stdlib
import datetime
import decimal
from io import BytesIO
# package
from openpyxl import Workbook
from lxml.etree import xmlfile, Element
# test imports
import pytest
from openpyxl.tests.helper import compare_xml
@pytest.fixture
def worksheet():
from openpyxl import Workbook
wb = Workbook()
return wb.active
@pytest.fixture
def out():
return BytesIO()
@pytest.fixture
def root_xml(out):
"""Root element for use when checking that nothing is written"""
with xmlfile(out) as xf:
xf.write(Element("test"))
return xf
@pytest.mark.parametrize("value, expected",
[
(9781231231230, """<c t="n" r="A1"><v>9781231231230</v></c>"""),
(decimal.Decimal('3.14'), """<c t="n" r="A1"><v>3.14</v></c>"""),
(1234567890, """<c t="n" r="A1"><v>1234567890</v></c>"""),
("=sum(1+1)", """<c r="A1"><f>sum(1+1)</f><v></v></c>"""),
(True, """<c t="b" r="A1"><v>1</v></c>"""),
("Hello", """<c t="s" r="A1"><v>0</v></c>"""),
("", """<c r="A1" t="s"></c>"""),
(None, """<c r="A1" t="s"></c>"""),
(datetime.date(2011, 12, 25), """<c r="A1" t="n" s="1"><v>40902</v></c>"""),
])
def test_write_cell(out, value, expected):
from .. lxml_worksheet import write_cell
wb = Workbook()
ws = wb.active
ws['A1'] = value
with xmlfile(out) as xf:
write_cell(xf, ws, ws['A1'], ["Hello"])
xml = out.getvalue()
diff = compare_xml(xml, expected)
assert diff is None, diff
@pytest.fixture
def write_rows():
from .. lxml_worksheet import write_rows
return write_rows
def test_write_sheetdata(out, worksheet, write_rows):
ws = worksheet
ws['A1'] = 10
with xmlfile(out) as xf:
write_rows(xf, ws, [])
xml = out.getvalue()
expected = """<sheetData><row r="1" spans="1:1"><c t="n" r="A1"><v>10</v></c></row></sheetData>"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_write_formula(out, worksheet, write_rows):
ws = worksheet
ws.cell('F1').value = 10
ws.cell('F2').value = 32
ws.cell('F3').value = '=F1+F2'
ws.cell('A4').value = '=A1+A2+A3'
ws.formula_attributes['A4'] = {'t': 'shared', 'ref': 'A4:C4', 'si': '0'}
ws.cell('B4').value = '='
ws.formula_attributes['B4'] = {'t': 'shared', 'si': '0'}
ws.cell('C4').value = '='
ws.formula_attributes['C4'] = {'t': 'shared', 'si': '0'}
with xmlfile(out) as xf:
write_rows(xf, ws, [])
xml = out.getvalue()
expected = """
<sheetData>
<row r="1" spans="1:6">
<c r="F1" t="n">
<v>10</v>
</c>
</row>
<row r="2" spans="1:6">
<c r="F2" t="n">
<v>32</v>
</c>
</row>
<row r="3" spans="1:6">
<c r="F3">
<f>F1+F2</f>
<v></v>
</c>
</row>
<row r="4" spans="1:6">
<c r="A4">
<f ref="A4:C4" si="0" t="shared">A1+A2+A3</f>
<v></v>
</c>
<c r="B4">
<f si="0" t="shared"></f>
<v></v>
</c>
<c r="C4">
<f si="0" t="shared"></f>
<v></v>
</c>
</row>
</sheetData>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_row_height(out, worksheet, write_rows):
ws = worksheet
ws.cell('F1').value = 10
ws.row_dimensions[ws.cell('F1').row].height = 30
with xmlfile(out) as xf:
write_rows(xf, ws, {})
xml = out.getvalue()
expected = """
<sheetData>
<row customHeight="1" ht="30" r="1" spans="1:6">
<c r="F1" t="n">
<v>10</v>
</c>
</row>
</sheetData>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
@pytest.fixture
def DummyWorksheet():
class DummyWorksheet:
def __init__(self):
self._styles = {}
self.column_dimensions = {}
return DummyWorksheet()
@pytest.fixture
def write_cols():
from .. lxml_worksheet import write_cols
return write_cols
@pytest.fixture
def ColumnDimension():
from openpyxl.worksheet.dimensions import ColumnDimension
return ColumnDimension
def test_no_cols(out, write_cols, DummyWorksheet, root_xml):
write_cols(root_xml, DummyWorksheet)
assert out.getvalue() == b"<test/>"
def test_col_widths(out, write_cols, ColumnDimension, DummyWorksheet):
ws = DummyWorksheet
ws.column_dimensions['A'] = ColumnDimension(width=4)
with xmlfile(out) as xf:
write_cols(xf, ws)
xml = out.getvalue()
expected = """<cols><col width="4" min="1" max="1" customWidth="1"></col></cols>"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_col_style(out, write_cols, ColumnDimension, DummyWorksheet):
ws = DummyWorksheet
ws.column_dimensions['A'] = ColumnDimension()
ws._styles['A'] = 1
with xmlfile(out) as xf:
write_cols(xf, ws)
xml = out.getvalue()
expected = """<cols><col max="1" min="1" style="1"></col></cols>"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_lots_cols(out, write_cols, ColumnDimension, DummyWorksheet):
ws = DummyWorksheet
from openpyxl.cell import get_column_letter
for i in range(1, 15):
label = get_column_letter(i)
ws._styles[label] = i
ws.column_dimensions[label] = ColumnDimension()
with xmlfile(out) as xf:
write_cols(xf, ws)
xml = out.getvalue()
expected = """<cols>
<col max="1" min="1" style="1"></col>
<col max="2" min="2" style="2"></col>
<col max="3" min="3" style="3"></col>
<col max="4" min="4" style="4"></col>
<col max="5" min="5" style="5"></col>
<col max="6" min="6" style="6"></col>
<col max="7" min="7" style="7"></col>
<col max="8" min="8" style="8"></col>
<col max="9" min="9" style="9"></col>
<col max="10" min="10" style="10"></col>
<col max="11" min="11" style="11"></col>
<col max="12" min="12" style="12"></col>
<col max="13" min="13" style="13"></col>
<col max="14" min="14" style="14"></col>
</cols>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
@pytest.fixture
def write_format():
from .. lxml_worksheet import write_format
return write_format
def test_sheet_format(out, write_format, ColumnDimension, DummyWorksheet):
with xmlfile(out) as xf:
write_format(xf, DummyWorksheet)
xml = out.getvalue()
expected = """<sheetFormatPr defaultRowHeight="15" baseColWidth="10"/>"""
diff = compare_xml(expected, xml)
assert diff is None, diff
def test_outline_format(out, write_format, ColumnDimension, DummyWorksheet):
worksheet = DummyWorksheet
worksheet.column_dimensions['A'] = ColumnDimension(outline_level=1)
with xmlfile(out) as xf:
write_format(xf, worksheet)
xml = out.getvalue()
expected = """<sheetFormatPr defaultRowHeight="15" baseColWidth="10" outlineLevelCol="1" />"""
diff = compare_xml(expected, xml)
assert diff is None, diff
def test_outline_cols(out, write_cols, ColumnDimension, DummyWorksheet):
worksheet = DummyWorksheet
worksheet.column_dimensions['A'] = ColumnDimension(outline_level=1)
with xmlfile(out) as xf:
write_cols(xf, worksheet)
xml = out.getvalue()
expected = """<cols><col max="1" min="1" outlineLevel="1"/></cols>"""
diff = compare_xml(expected, xml)
assert diff is None, diff
@pytest.fixture
def write_autofilter():
from .. lxml_worksheet import write_autofilter
return write_autofilter
def test_auto_filter(out, worksheet, write_autofilter):
ws = worksheet
ws.auto_filter.ref = 'A1:F1'
with xmlfile(out) as xf:
write_autofilter(xf, ws)
xml = out.getvalue()
expected = """<autoFilter ref="A1:F1"></autoFilter>"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_auto_filter_filter_column(out, worksheet, write_autofilter):
ws = worksheet
ws.auto_filter.ref = 'A1:F1'
ws.auto_filter.add_filter_column(0, ["0"], blank=True)
with xmlfile(out) as xf:
write_autofilter(xf, ws)
xml = out.getvalue()
expected = """
<autoFilter ref="A1:F1">
<filterColumn colId="0">
<filters blank="1">
<filter val="0"></filter>
</filters>
</filterColumn>
</autoFilter>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_auto_filter_sort_condition(out, worksheet, write_autofilter):
ws = worksheet
ws.cell('A1').value = 'header'
ws.cell('A2').value = 1
ws.cell('A3').value = 0
ws.auto_filter.ref = 'A2:A3'
ws.auto_filter.add_sort_condition('A2:A3', descending=True)
with xmlfile(out) as xf:
write_autofilter(xf, ws)
xml = out.getvalue()
expected = """
<autoFilter ref="A2:A3">
<sortState ref="A2:A3">
<sortCondtion descending="1" ref="A2:A3"></sortCondtion>
</sortState>
</autoFilter>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
@pytest.fixture
def write_sheetviews():
from .. lxml_worksheet import write_sheetviews
return write_sheetviews
def test_freeze_panes_horiz(out, worksheet, write_sheetviews):
ws = worksheet
ws.freeze_panes = 'A4'
with xmlfile(out) as xf:
write_sheetviews(xf, ws)
xml = out.getvalue()
expected = """
<sheetViews>
<sheetView workbookViewId="0">
<pane topLeftCell="A4" ySplit="3" state="frozen" activePane="bottomLeft"/>
<selection activeCell="A1" pane="bottomLeft" sqref="A1"/>
</sheetView>
</sheetViews>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_freeze_panes_vert(out, worksheet, write_sheetviews):
ws = worksheet
ws.freeze_panes = 'D1'
with xmlfile(out) as xf:
write_sheetviews(xf, ws)
xml = out.getvalue()
expected = """
<sheetViews>
<sheetView workbookViewId="0">
<pane xSplit="3" topLeftCell="D1" activePane="topRight" state="frozen"/>
<selection pane="topRight" activeCell="A1" sqref="A1"/>
</sheetView>
</sheetViews>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_freeze_panes_both(out, worksheet, write_sheetviews):
ws = worksheet
ws.freeze_panes = 'D4'
with xmlfile(out) as xf:
write_sheetviews(xf, ws)
xml = out.getvalue()
expected = """
<sheetViews>
<sheetView workbookViewId="0">
<pane xSplit="3" ySplit="3" topLeftCell="D4" activePane="bottomRight" state="frozen"/>
<selection pane="topRight"/>
<selection pane="bottomLeft"/>
<selection pane="bottomRight" activeCell="A1" sqref="A1"/>
</sheetView>
</sheetViews>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
@pytest.fixture
def write_worksheet():
from .. lxml_worksheet import write_worksheet
return write_worksheet
def test_merge(out, worksheet):
from .. lxml_worksheet import write_mergecells
ws = worksheet
ws.cell('A1').value = 'Cell A1'
ws.cell('B1').value = 'Cell B1'
ws.merge_cells('A1:B1')
with xmlfile(out) as xf:
write_mergecells(xf, ws)
xml = out.getvalue()
expected = """
<mergeCells count="1">
<mergeCell ref="A1:B1"/>
</mergeCells>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_no_merge(out, worksheet, root_xml):
from .. lxml_worksheet import write_mergecells
write_mergecells(root_xml, worksheet)
xml = out.getvalue()
expected = b"<test/>"
def test_header_footer(out, worksheet):
ws = worksheet
ws.header_footer.left_header.text = "Left Header Text"
ws.header_footer.center_header.text = "Center Header Text"
ws.header_footer.center_header.font_name = "Arial,Regular"
ws.header_footer.center_header.font_size = 6
ws.header_footer.center_header.font_color = "445566"
ws.header_footer.right_header.text = "Right Header Text"
ws.header_footer.right_header.font_name = "Arial,Bold"
ws.header_footer.right_header.font_size = 8
ws.header_footer.right_header.font_color = "112233"
ws.header_footer.left_footer.text = "Left Footer Text\nAnd &[Date] and &[Time]"
ws.header_footer.left_footer.font_name = "Times New Roman,Regular"
ws.header_footer.left_footer.font_size = 10
ws.header_footer.left_footer.font_color = "445566"
ws.header_footer.center_footer.text = "Center Footer Text &[Path]&[File] on &[Tab]"
ws.header_footer.center_footer.font_name = "Times New Roman,Bold"
ws.header_footer.center_footer.font_size = 12
ws.header_footer.center_footer.font_color = "778899"
ws.header_footer.right_footer.text = "Right Footer Text &[Page] of &[Pages]"
ws.header_footer.right_footer.font_name = "Times New Roman,Italic"
ws.header_footer.right_footer.font_size = 14
ws.header_footer.right_footer.font_color = "AABBCC"
from .. lxml_worksheet import write_header_footer
with xmlfile(out) as xf:
write_header_footer(xf, ws)
xml = out.getvalue()
expected = """
<headerFooter>
<oddHeader>&L&"Calibri,Regular"&K000000Left Header Text&C&"Arial,Regular"&6&K445566Center Header Text&R&"Arial,Bold"&8&K112233Right Header Text</oddHeader>
<oddFooter>&L&"Times New Roman,Regular"&10&K445566Left Footer Text_x000D_And &D and &T&C&"Times New Roman,Bold"&12&K778899Center Footer Text &Z&F on &A&R&"Times New Roman,Italic"&14&KAABBCCRight Footer Text &P of &N</oddFooter>
</headerFooter>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_no_header(out, worksheet, root_xml):
from .. lxml_worksheet import write_header_footer
write_header_footer(root_xml, worksheet)
assert out.getvalue() == b"<test/>"
def test_no_pagebreaks(out, worksheet, root_xml):
from .. lxml_worksheet import write_pagebreaks
write_pagebreaks(root_xml, worksheet)
assert out.getvalue() == b"<test/>"
def test_data_validation(out, worksheet):
from .. lxml_worksheet import write_datavalidation
from openpyxl.datavalidation import DataValidation, ValidationType
ws = worksheet
dv = DataValidation(ValidationType.LIST, formula1='"Dog,Cat,Fish"')
dv.add_cell(ws['A1'])
ws.add_data_validation(dv)
with xmlfile(out) as xf:
write_datavalidation(xf, worksheet)
xml = out.getvalue()
expected = """
<dataValidations count="1">
<dataValidation allowBlank="0" showErrorMessage="1" showInputMessage="1" sqref="A1" type="list">
<formula1>"Dog,Cat,Fish"</formula1>
<formula2>None</formula2>
</dataValidation>
</dataValidations>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_hyperlink(out, worksheet):
from .. lxml_worksheet import write_hyperlinks
ws = worksheet
ws.cell('A1').value = "test"
ws.cell('A1').hyperlink = "http://test.com"
with xmlfile(out) as xf:
write_hyperlinks(xf, ws)
xml = out.getvalue()
expected = """
<hyperlinks xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<hyperlink display="http://test.com" r:id="rId1" ref="A1"/>
</hyperlinks>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_no_hyperlink(out, worksheet, root_xml):
from .. lxml_worksheet import write_hyperlinks
write_hyperlinks(root_xml, worksheet)
assert out.getvalue() == b"<test/>"
def test_empty_worksheet(worksheet, write_worksheet):
xml = write_worksheet(worksheet, None)
expected = """
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetPr>
<outlinePr summaryBelow="1" summaryRight="1"/>
</sheetPr>
<dimension ref="A1:A1"/>
<sheetViews>
<sheetView workbookViewId="0">
<selection activeCell="A1" sqref="A1"/>
</sheetView>
</sheetViews>
<sheetFormatPr baseColWidth="10" defaultRowHeight="15"/>
<sheetData/>
<pageMargins bottom="1" footer="0.5" header="0.5" left="0.75" right="0.75" top="1"/>
</worksheet>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_printer_settings(worksheet, write_worksheet):
ws = worksheet
ws.page_setup.orientation = ws.ORIENTATION_LANDSCAPE
ws.page_setup.paperSize = ws.PAPERSIZE_TABLOID
ws.page_setup.fitToPage = True
ws.page_setup.fitToHeight = 0
ws.page_setup.fitToWidth = 1
ws.page_setup.horizontalCentered = True
ws.page_setup.verticalCentered = True
xml = write_worksheet(ws, None)
expected = """
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetPr>
<outlinePr summaryRight="1" summaryBelow="1"/>
<pageSetUpPr fitToPage="1"/>
</sheetPr>
<dimension ref="A1:A1"/>
<sheetViews>
<sheetView workbookViewId="0">
<selection sqref="A1" activeCell="A1"/>
</sheetView>
</sheetViews>
<sheetFormatPr baseColWidth="10" defaultRowHeight="15"/>
<sheetData/>
<printOptions horizontalCentered="1" verticalCentered="1"/>
<pageMargins left="0.75" right="0.75" top="1" bottom="1" header="0.5" footer="0.5"/>
<pageSetup orientation="landscape" paperSize="3" fitToHeight="0" fitToWidth="1"/>
</worksheet>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_page_margins(worksheet, write_worksheet):
ws = worksheet
ws.page_margins.left = 2.0
ws.page_margins.right = 2.0
ws.page_margins.top = 2.0
ws.page_margins.bottom = 2.0
ws.page_margins.header = 1.5
ws.page_margins.footer = 1.5
xml = write_worksheet(ws, None)
expected = """
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetPr>
<outlinePr summaryRight="1" summaryBelow="1"/>
</sheetPr>
<dimension ref="A1:A1"/>
<sheetViews>
<sheetView workbookViewId="0">
<selection sqref="A1" activeCell="A1"/>
</sheetView>
</sheetViews>
<sheetFormatPr baseColWidth="10" defaultRowHeight="15"/>
<sheetData/>
<pageMargins left="2" right="2" top="2" bottom="2" header="1.5" footer="1.5"/>
</worksheet>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
def test_vba(worksheet, write_worksheet):
ws = worksheet
ws.xml_source = """
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheetPr codeName="Sheet1"/>
<legacyDrawing r:id="rId2"/>
</worksheet>
"""
xml = write_worksheet(ws, None)
expected = """
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheetPr codeName="Sheet1">
<outlinePr summaryBelow="1" summaryRight="1"/>
</sheetPr>
<dimension ref="A1:A1"/>
<sheetViews>
<sheetView workbookViewId="0">
<selection activeCell="A1" sqref="A1"/>
</sheetView>
</sheetViews>
<sheetFormatPr baseColWidth="10" defaultRowHeight="15"/>
<sheetData/>
<pageMargins bottom="1" footer="0.5" header="0.5" left="0.75" right="0.75" top="1"/>
<legacyDrawing r:id="rId2"/>
</worksheet>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
@pytest.fixture
def worksheet_with_cf(worksheet):
from openpyxl.formatting import ConditionalFormatting
worksheet.conditional_formating = ConditionalFormatting()
return worksheet
@pytest.fixture
def write_conditional_formatting():
from .. lxml_worksheet import write_conditional_formatting
return write_conditional_formatting
def test_conditional_formatting_customRule(out, worksheet_with_cf, write_conditional_formatting):
from .. lxml_worksheet import write_conditional_formatting
ws = worksheet_with_cf
ws.conditional_formatting.add('C1:C10', {'type': 'expression', 'formula': ['ISBLANK(C1)'],
'stopIfTrue': '1', 'dxf': {}})
with xmlfile(out) as xf:
write_conditional_formatting(xf, ws)
xml = out.getvalue()
diff = compare_xml(xml, """
<conditionalFormatting sqref="C1:C10">
<cfRule type="expression" stopIfTrue="1" priority="1">
<formula>ISBLANK(C1)</formula>
</cfRule>
</conditionalFormatting>
""")
assert diff is None, diff
def test_conditional_font(out, worksheet_with_cf, write_conditional_formatting):
"""Test to verify font style written correctly."""
# Create cf rule
from openpyxl.styles import PatternFill, Font, Color
from openpyxl.formatting import CellIsRule
redFill = PatternFill(start_color=Color('FFEE1111'),
end_color=Color('FFEE1111'),
patternType='solid')
whiteFont = Font(color=Color("FFFFFFFF"))
ws = worksheet_with_cf
ws.conditional_formatting.add('A1:A3',
CellIsRule(operator='equal',
formula=['"Fail"'],
stopIfTrue=False,
font=whiteFont,
fill=redFill))
with xmlfile(out) as xf:
write_conditional_formatting(xf, ws)
xml = out.getvalue()
diff = compare_xml(xml, """
<conditionalFormatting sqref="A1:A3">
<cfRule operator="equal" priority="1" type="cellIs">
<formula>"Fail"</formula>
</cfRule>
</conditionalFormatting>
""")
assert diff is None, diff
def test_formula_rule(out, worksheet_with_cf, write_conditional_formatting):
from openpyxl.formatting import FormulaRule
ws = worksheet_with_cf
ws.conditional_formatting.add('C1:C10',
FormulaRule(
formula=['ISBLANK(C1)'],
stopIfTrue=True)
)
with xmlfile(out) as xf:
write_conditional_formatting(xf, ws)
xml = out.getvalue()
diff = compare_xml(xml, """
<conditionalFormatting sqref="C1:C10">
<cfRule type="expression" stopIfTrue="1" priority="1">
<formula>ISBLANK(C1)</formula>
</cfRule>
</conditionalFormatting>
""")
assert diff is None, diff
def test_protection(out, worksheet, write_worksheet):
ws = worksheet
ws.protection.enable()
xml = write_worksheet(ws, None)
expected = """
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetPr>
<outlinePr summaryBelow="1" summaryRight="1"/>
</sheetPr>
<dimension ref="A1:A1"/>
<sheetViews>
<sheetView workbookViewId="0">
<selection activeCell="A1" sqref="A1"/>
</sheetView>
</sheetViews>
<sheetFormatPr baseColWidth="10" defaultRowHeight="15"/>
<sheetData/>
<sheetProtection sheet="1" objects="0" selectLockedCells="0" selectUnlockedCells="0" scenarios="0" formatCells="1" formatColumns="1" formatRows="1" insertColumns="1" insertRows="1" insertHyperlinks="1" deleteColumns="1" deleteRows="1" sort="1" autoFilter="1" pivotTables="1"/>
<pageMargins bottom="1" footer="0.5" header="0.5" left="0.75" right="0.75" top="1"/>
</worksheet>
"""
diff = compare_xml(xml, expected)
assert diff is None, diff
| true |
79e66315e18f2a9e3cf3a9e050f21f637f06fe14 | Python | hirajanwin/LeetCode-5 | /1451. Rearrange Words in a Sentence/main.py | UTF-8 | 297 | 3.03125 | 3 | [
"MIT"
] | permissive | class Solution:
def arrangeWords(self, text: str) -> str:
text = text.lower().split()
res = []
for i, word in enumerate(text):
res.append((len(word), i, word))
res.sort()
p = " ".join([i[2] for i in res])
return p[0].upper() + p[1:]
| true |
67b347cde3d1d4a57176041fc3819ca93790edcc | Python | rspies/NWS_Python | /PRISM/PRISM_summary_table_monthly.py | UTF-8 | 4,663 | 2.671875 | 3 | [] | no_license | #_calculate_basin_nlcd_summary.py
#Ryan Spies
#ryan.spies@amec.com
#AMEC
#Description: creates summary table of PRISM data (converts mm to in)
#from .xls files output from ArcGIS Model Builder
#7/24/2014 -> modified to also run the script using .csv files (output from python arcpy tool)
#output single .csv
#import script modules
import os
#import xlrd # python module for exel file handling
import csv
import glob
#os.chdir("../..")
maindir = os.getcwd()
####################################################################
#USER INPUT SECTION
####################################################################
#ENTER RFC Region
RFC = 'WGRFC_2021'
fx_group = '' # leave blank if not processing by fx group
variables = ['ppt','tmean','tmax','tmin'] # use temperature: 'tmean','tmax','tmin' or precipitation: 'ppt'
resolution = '4km' # choices: '800m' or '4km' -> PRISM resolution
# if you only want to run specific basins -> list them below
# otherwise set it equal to empty list (basins_overwrite = [])
basins_overwrite = []
####################################################################
#END USER INPUT SECTION
####################################################################
for variable in variables:
print variable
#FOLDER PATH OF PRISM .xls/.csv DATA FILES
if fx_group != '':
csv_folderPath = maindir + '\\GIS\\' + RFC[:5] + os.sep + RFC + '\\PRISM\\Model_Builder_Output_' + variable + '_' + resolution + '_month\\' + fx_group + '\\'
else:
csv_folderPath = 'F:\\projects\\2021_twdb_wgrfc_calb\\data' + '\\PRISM\\Model_Builder_Output\\' + variable + '_' + resolution +'_month\\'
#csv_folderPath = maindir + '\\GIS\\' + RFC[:5] + os.sep + RFC + '\\PRISM\\Model_Builder_Output_' + variable + '_' + resolution + '_month\\'
#FOLDER PATH OF BASIN SUMMARY PRISM .xls DATA FILES (!Must be different than csv_FolderPath!)
output_folderPath = 'F:\\projects\\2021_twdb_wgrfc_calb\\data' + '\\PRISM\\Model_Builder_Output\\'
units = {'ppt':'inches','tmax':'degrees C','tmin':'degrees C','tmean':'degrees C'}
basin_files = glob.glob(csv_folderPath+'/*.csv') # list all basin .csv files in the above specified directory
if len(basins_overwrite) != 0:
basin_files = basins_overwrite # use the basins_overright variable to run only specified basins instead of all RFC basins
basins = []
for each in basin_files:
basename = os.path.basename(each)
if (basename.split('_'))[0] not in basins:
basins.append((basename.split('_'))[0].strip('\.'))
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
print 'Script is Running...'
#Define output file name
if fx_group != '':
out_file = open(output_folderPath + RFC[:5] + '_' + fx_group + '_' + RFC[-6:] + '_Monthly_PRISM_' + variable + '_' + resolution + '_Summary.csv', 'w')
else:
out_file = open(output_folderPath + RFC + '_Monthly_PRISM_' + variable + '_' + resolution + '_Summary.csv', 'w')
out_file.write('variable: ' + variable + ',' + 'units: ' + units[variable] + '\n')
out_file.write('Basin,'+'Jan,'+'Feb,'+'Mar,'+'Apr,'+'May,'+'Jun,'+'Jul,'+'Aug,'+'Sep,'+'Oct,'+'Nov,'+'Dec,'+'\n')
#loop through NLCD .xls files in folderPath
for basin in basins:
out_file.write(basin + ',')
for month in months:
print basin
basin_file = open(csv_folderPath + basin + '_prism_' + month + '.csv', 'rb')
csv_read = csv.reader(basin_file)
row_num = 0
if variable == 'ppt':
for row in csv_read:
if row_num == 1:
precip_in = float(row[2]) / 25.4 # convert mm to in
if RFC[:5] == 'APRFC':
precip_in = precip_in / 100 # AK PRISM units mm * 100
out_file.write(str("%.2f" % precip_in) + ',')
print month + ' -> ' + str("%.2f" % precip_in)
row_num += 1
else:
for row in csv_read:
if row_num == 1:
temp_in = float(row[2]) # no temperature conversion
if RFC[:5] == 'APRFC':
temp_in = temp_in / 100 # AK PRISM units C * 100
out_file.write(str("%.2f" % temp_in) + ',')
print month + ' -> ' + str("%.2f" % temp_in)
row_num += 1
out_file.write('\n')
print 'Finished!'
out_file.close()
| true |
fc5d84b0c5dde4ba5f3cc9ffe6a0f3f4cf5305dc | Python | busraerkoc/BookLibrary | /app/forms.py | UTF-8 | 475 | 2.578125 | 3 | [] | no_license | from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, SubmitField
class AddForm(FlaskForm):
title = StringField('Name of Book: ')
author = StringField('Name of Author: ')
publisher = StringField('Name of Publisher: ')
available = StringField('Note for Availability: ')
submit = SubmitField('Add Book')
class DelForm(FlaskForm):
id = IntegerField("Id Number of Book to Remove: ")
submit = SubmitField('Remove Book')
| true |
018b3b99179a6858c8486d58a5d44de1ee723954 | Python | RoachLok/MyCloudInstance | /database/external/yt_stack_data_db_dump.py | UTF-8 | 1,823 | 2.8125 | 3 | [] | no_license | import sqlite3
from nltk.tokenize import api
import yt_stack_query
#Lists from Youtube API
dates_yt = list(yt_stack_query.decode_yt()[0])
upvotes_yt = yt_stack_query.decode_yt()[1]
views_yt = yt_stack_query.decode_yt()[2]
#Lists from Stack Exchange API
dates_stack = list(yt_stack_query.decode_stack()[0])
upvotes_stack = yt_stack_query.decode_stack()[1]
views_stack = yt_stack_query.decode_stack()[2]
#Filtered tags
tags = yt_stack_query.get_tags()
#Concatenation of lists to insert into the DB
youtube_insert = [(date, upvote, view) for date,upvote,view in zip(dates_yt,upvotes_yt, views_yt)]
stack_insert = [(date, upvote, view) for date,upvote,view in zip(dates_stack,upvotes_stack, views_stack)]
tags_insert = [tuple([tag]) for tag in tags]
#Database generation
conn = sqlite3.connect('yt_stack.db')
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS youtube;')
cursor.execute('DROP TABLE IF EXISTS stack;')
cursor.execute('DROP TABLE IF EXISTS tag;')
cursor.execute("""CREATE TABLE youtube (
date VARCHAR(20) ,
upvotes INTEGER ,
views INTEGER
);""")
cursor.execute("""CREATE TABLE stack (
date VARCHAR(20) ,
upvotes INTEGER ,
views INTEGER
);""")
cursor.execute("""CREATE TABLE tag (
tags VARCHAR(20)
);""")
cursor.executemany('INSERT INTO youtube (date, upvotes, views) VALUES (?,?,?);',youtube_insert)
cursor.executemany('INSERT INTO stack (date, upvotes, views) VALUES (?,?,?);',stack_insert)
cursor.executemany('INSERT INTO tag (tags) VALUES (?);',tags_insert)
conn.commit()
print("\n Done, correctly generated stack exchange and youtube database.")
| true |
af9c19af1fd1c61ab130469613a7d1431db5abcf | Python | Aasthaengg/IBMdataset | /Python_codes/p02397/s255996488.py | UTF-8 | 124 | 3.015625 | 3 | [] | no_license | i=0
while 1:
i+=1
x,y=map(int, raw_input().split())
if x==0 and y==0:
break
print min(x,y),max(x,y) | true |
997a6c72f99c9b008dfdff862e6ce21912dc4c29 | Python | Apb58/Python-Projects | /range_check.py | UTF-8 | 4,363 | 3.375 | 3 | [] | no_license | #!/usr/bin/python3
## Intrarange checker:
## Adrian Bubie
## 12/03/18
## ------------
## This program takes 2 files of genomic positions as inputs, a reference and a query, and returns the positions
## in the query that fall within the positions of the reference. The reference file should be structured with
## 'chromosome:range_start-range_end' and should only contain one position range per line. The query file can contain
## either a list of ranges in the same style of the reference, such that any overalp in the ranges will return a positive
## result, or a list of single positions in the structure 'chromosome:gen_position'.
##
## The output can be specified as either an output of every query position with indication of whether they match a reference ## range ('all'), or just the list of query positions that overlap with the reference ('match')
##
## Execute the program: ./range_check.py -r [path/reference] -q [path/query] -o [path/output] -t [output_type]
import sys
import textwrap
import argparse as ap
import math
import json
def get_arguments():
parser = ap.ArgumentParser(prog='./range_check.py', formatter_class=ap.RawDescriptionHelpFormatter, description=textwrap.dedent('''\
IntraRange Checker
---------------------
Takes genomic postition queries and determines whether they fall within a series of user provided
reference positional ranges, both in sudo-BED style format (see /examples for details)
Returns to specified output file either a list of queries that fall into the reference ranges, or all queries with a positive or negative result indication.
'''))
parser.add_argument("-r", help="Reference file of genomic ranges. Must include absolute path the file. <str>", required=True, type=str)
parser.add_argument("-q", help="Query file of genomic positions (or ranges). Must include absolute path the file. <str>", required=True, type=str)
parser.add_argument("-o", help="Output file. Must include absolute path the file. <str>", required=True, type=str)
parser.add_argument("-t", help="Output file format; choice of 'all', which includes each query and result, or 'match' which only includes queries that overlapped with reference. <str>", required=True, type=str)
return parser.parse_args()
class genomic_ranges():
'''Genomic Range object: collection of reference genomic ranges that can be used to check queries.
object contains a chromosome, base pair start and base pair end.'''
def __init__(self, ref):
self.chr = str(ref.split(':')[0])
self.start = int(ref.split(':')[1].split('-')[0])
self.end = int(ref.strip('\n').split('-')[1])
def compile_ref_ranges(Reference):
ref_dict = []
ref = Reference.readline()
while ref:
if ref.startswith('chr') != True:
raise ValueError("Error: Reference file contains a malformed genomic range. Correct before continuing")
else:
ref_dict.append(genomic_ranges(ref))
ref = Reference.readline()
return set(ref_dict)
def overlap_check_single(ref_ranges,query):
match = False # Start by setting the match status to false
# Query parts:
qchr = str(query.split(':')[0])
qpos = int(query.split(':')[1])
if qchr.startswith('chr') != True:
raise ValueError("Error: Query file contains a malformed genomic range. Correct before continuing")
pot_mat_ref = [x for x in ref_ranges if x.chr == qchr]
mat_ref_abv = [x for x in pot_mat_ref if x.start <= qpos]
match_ref = [x for x in mat_ref_abv if x.end >= qpos]
if len(match_ref) > 0: #If there is at least one reference range returned, the query 'match' flag is flipped to true
match = True
return match
#TO DO
#def overlap_check_range(ref_ranges,query_range):
###################
## Main Function ##
###################
args = get_arguments()
Reference = open(args.r, 'r')
Query = open(args.q, 'r')
Output = open(args.o, 'w')
ret_type = args.t
if ret_type not in ['all','match']:
raise ValueError('Error: please select appropriate output format')
ref_ranges = compile_ref_ranges(Reference)
Qresults = dict()
qur = Query.readline()
while qur:
Qresults[qur.strip('\n')] = overlap_check_single(ref_ranges,qur)
qur = Query.readline()
if ret_type == 'all':
p = json.dumps(Qresults).replace(',','\n')
Output.write(p)
if ret_type == 'match':
subQres = [x for x in Qresults if Qresults[x] == True ]
Output.write('\n'.join(subQres))
Reference.close()
Query.close()
Output.close()
| true |
f153571d57a516a6850ddf451d17cf622c4bf063 | Python | saisai/python-3 | /beginner_scripts/functions.py | UTF-8 | 200 | 3.609375 | 4 | [] | no_license | #!/usr/bin/env python
def ifState():
a = 10;
if a > 10:
print "A is bigger than 10."
elif a < 10:
print "A is smaller than or equal to 10."
else :
print "A is not a number."
ifState()
| true |