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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
71132011a1040d91c4a6b2a78ccbd8c6caf989bb | Python | rohanghosh7/Hackerrank_Python_Solution | /Alphabet Rangoli.py | UTF-8 | 826 | 2.921875 | 3 | [] | no_license | def print_rangoli(s):
wid = 4*s - 3
for i in range(1,s+1):
for j in range(1, wid+1):
flag = 0
for k in range(1,s+1):
if (j<=2*s-1 and j is 2*s-2*i+2*k-1) or (j>2*s-1 and j is 2*s+2*i-2*k-1):
print(chr(97+s-k),end='')
flag = 1
if flag is 0:
print('-',end='')
print('')
for i in range(1,s):
for j in range(1, wid+1):
flag = 0
for k in range(1,s+1):
if (j<=2*s-1 and j is 2*i+2*k-1) or (j>2*s-1 and j is wid-2*i-2*(k-1)):
print(chr(97+s-k),end='')
flag = 1
if flag is 0:
print('-',end='')
print('')
if __name__ == '__main__':
n = int(input())
print_rangoli(n)
| true |
0486d17c2555fe3a7756066811bdc4f1b92cb623 | Python | alsignoriello/geometry | /data/3Dmesh/generate_poly.py | UTF-8 | 2,775 | 2.828125 | 3 | [] | no_license | #!/usr/bin/python
import sys
import numpy as np
from numpy.random import seed
from numpy import pi, sin , cos
from scipy.spatial import Delaunay
import operator
# random seed
seed(1292405)
# number of vertices
# Nv = int(sys.argv[1])
N = 10
# radius of polygon
r = float(sys.argv[1])
# allocate vertices
coords = []
# move to center
cx = 10
cy = 10
cz = 10
# pick random points on sphere
for i in range(0,N):
theta = (i * 2 * pi)/N
for j in range(0,N+1):
phi = (j*pi)/N
print theta, phi
# theta = np.random.uniform(0,2*pi)
# phi = np.random.uniform(0,pi)
x = cx + r * cos(theta) * sin(phi)
y = cy + r * sin(theta) * sin(phi)
z = cz + r * cos(phi)
# print x,y,z
if (x,y,z) not in coords:
coords.append((x,y,z))
coords = np.array(coords)
x = coords[:,0]
y = coords[:,1]
z = coords[:,2]
# triangulate
tt = Delaunay(coords)
ntetrahedrons = len(tt.simplices)
triangles = []
for i in range(0,ntetrahedrons):
i1 = tt.simplices[i,0]
i2 = tt.simplices[i,1]
i3 = tt.simplices[i,2]
i4 = tt.simplices[i,3]
triangles.append((i1,i2,i3))
triangles.append((i2,i3,i4))
triangles.append((i1,i3,i4))
triangles.append((i1,i2,i4))
# get all triangles on the surface
# i.e. find all triangles involved in one tetrahedron
counts = {}
for i1,i2,i3 in triangles:
# order 3 min -> max
i_sort = np.sort([i1,i2,i3])
tri = (i_sort[0],i_sort[1],i_sort[2])
if tri in counts:
counts[tri] += 1
else:
counts[tri] = 1
vertices = {}
f = open("triangles.txt","w")
ff = open("faces.txt","w")
vcount = 0
dists = []
A = np.zeros(3)
B = np.zeros(3)
C = np.zeros(3)
CC = np.array([cx,cy,cz])
for key,value in counts.iteritems():
if value == 1:
i1 = key[0]
i2 = key[1]
i3 = key[2]
Ax = x[key[0]]
Ay = y[key[0]]
Az = z[key[0]]
Bx = x[key[1]]
By = y[key[1]]
Bz = z[key[1]]
Cx = x[key[2]]
Cy = y[key[2]]
Cz = z[key[2]]
f.write("%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n"%
(Ax,Ay,Az,Bx,By,Bz,Cx,Cy,Cz))
if (Ax,Ay,Az) in vertices:
i1 = vertices[(Ax,Ay,Az)]
else:
i1 = vcount
vertices[(Ax,Ay,Az)] = i1
vcount += 1
if (Bx,By,Bz) in vertices:
i2 = vertices[(Bx,By,Bz)]
else:
i2 = vcount
vertices[(Bx,By,Bz)] = i2
vcount += 1
if (Cx,Cy,Cz) in vertices:
i3 = vertices[(Cx,Cy,Cz)]
else:
i3 = vcount
vertices[(Cx,Cy,Cz)] = i3
vcount += 1
# check vertex order
A[:] = Ax,Ay,Az
B[:] = Bx,By,Bz
C[:] = Cx,Cy,Cz
N = np.cross((B - A),(C - A))
w = np.dot(N,A-CC)
if w < 0:
ff.write("%d\t%d\t%d\n"%(i1,i2,i3))
else:
ff.write("%d\t%d\t%d\n"%(i3,i2,i1))
f.close()
ff.close()
fv = open("vertices.txt","w")
sorted_v = sorted(vertices.items(), key=operator.itemgetter(1))
for key,value in sorted_v:
x = key[0]
y = key[1]
z = key[2]
fv.write("%f\t%f\t%f\n"%(x,y,z))
fv.close()
| true |
f9564a68b2731fa04be686856a3a3fe49e0798e1 | Python | amantaya/Image-Processing-Python | /image-processing/04-drawing-bitwise/DrawPractice.py | UTF-8 | 548 | 2.9375 | 3 | [] | no_license | """
* Program to practice with skimage drawing methods.
"""
import random
import numpy as np
import skimage
from skimage.viewer import ImageViewer
# create the black canvas
image = np.zeros(shape=(600, 800, 3), dtype="uint8")
viewer = ImageViewer(image)
viewer.show()
# mask = np.ones(shape=image.shape[0:2], dtype="bool")
# WRITE YOUR CODE TO DRAW ON THE IMAGE HERE
rr1, cc1 = skimage.draw.circle(300, 400, radius=100)
image[rr1, cc1] = [128, 25, 128]
# display the results
# Display constructed mask
viewer = ImageViewer(image)
viewer.show() | true |
cea636a57e8c66a4c68dbe7e113a929539e24c3e | Python | javierlopeza/IIC2233-2015-2 | /Tareas/T07/MainWindow.py | UTF-8 | 22,848 | 2.71875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from PyQt4 import QtGui, uic
import dropbox
import dropbox.files
import threading
import os
import time
ventana = uic.loadUiType("main.ui")
class MainWindow(ventana[0], ventana[1]):
def __init__(self, dbx):
super().__init__()
self.setupUi(self)
self.dbx = dbx
user_info = self.dbx.users_get_current_account()
self.username = user_info.name.display_name
self.EstadoLabel.setText("Usuario Conectado: {}".format(self.username))
icono = QtGui.QIcon(QtGui.QPixmap('assets/logo.png'))
self.setWindowIcon(icono)
self.LogoLabel.setPixmap(QtGui.QPixmap('assets/logo.png'))
self.LogoLabel.setScaledContents(True)
# Se actualiza arbol de archivos.
self.actualizar = True
self.crear_thread(self.update_files_tree, (self.ArbolArchivos, self.ArbolArchivos2), "thread_actualizar_arbol")
# Mostrar historial button
self.VerHistorialButton.clicked.connect(self.mostrar_historial)
# Actualizar Button
self.ActualizarButton.clicked.connect(self.actualizar_pressed)
# Descargar Button y Thread Descargas
self.DescargarArchivoButton.clicked.connect(self.descargar_pressed)
self.thread_descarga_archivo = threading.Thread()
# Subir Button y Thread Subidas
self.SubirArchivoButton.clicked.connect(self.subir_pressed)
self.thread_subir_archivo = threading.Thread()
# Crear carpeta button y thread
self.CrearCarpetaButton.clicked.connect(self.crear_carpeta_pressed)
self.thread_crear_carpeta = threading.Thread()
# Descargar carpeta button
self.DescargarCarpetaButton.clicked.connect(self.descargar_carpeta_pressed)
# Renombrar button
self.RenombrarButton.clicked.connect(self.renombrar_pressed)
self.thread_renombrar = threading.Thread()
# Mover button
self.MoverButton.clicked.connect(self.mover_pressed)
self.thread_mover = threading.Thread()
# Aceptar Button
self.AceptarButton.clicked.connect(self.aceptar_pressed)
self.thread_aceptar = threading.Thread()
# Cancelar button
self.CancelarButton.clicked.connect(self.habilitar)
# Arbol 2 label item changed
self.ArbolArchivos2.itemClicked.connect(self.update_pathlabel)
def crear_thread(self, funcion, argumentos, nombre):
t = threading.Thread(name=nombre, target=funcion, args=argumentos)
t.setDaemon(True)
t.start()
setattr(self, nombre, t)
def update_files_tree(self, parent1, parent2, folder=''):
if self.actualizar:
for entry in self.dbx.files_list_folder(folder).entries:
# print(entry.name)
if isinstance(entry, dropbox.files.FolderMetadata):
new_carpeta1 = QtGui.QTreeWidgetItem(parent1)
new_carpeta1.setText(0, entry.name)
new_carpeta2 = QtGui.QTreeWidgetItem(parent2)
new_carpeta2.setText(0, entry.name)
self.update_files_tree(new_carpeta1, new_carpeta2, entry.path_lower)
else:
new_file1 = QtGui.QTreeWidgetItem(parent1)
new_file1.setText(0, entry.name)
new_file2 = QtGui.QTreeWidgetItem(parent2)
new_file2.setText(0, entry.name)
def mostrar_historial(self):
archivo_seleccionado = self.ArbolArchivos.currentItem()
item = archivo_seleccionado
if archivo_seleccionado:
path = []
while item is not None:
path.append(str(item.text(0)))
item = item.parent()
path = '/' + '/'.join(reversed(path))
path_llegada, nombre = os.path.split(path)
if nombre.count(".") == 0 or nombre.count(".") > 1:
es_carpeta = True
else:
es_carpeta = False
if not es_carpeta:
self.crear_thread(self.historial_archivo, (path, nombre), "thread_historial")
elif es_carpeta:
self.crear_thread(self.historial_carpeta, (path, nombre), "thread_historial")
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe seleccionar un archivo.", QtGui.QMessageBox.Ok)
def historial_archivo(self, path_archivo, nombre_archivo):
try:
revisiones = self.dbx.files_list_revisions(path_archivo, limit=99)
num_rows = self.HistorialTable.rowCount()
# Se limpia la HistorialTable.
for r in range(num_rows):
self.HistorialTable.removeRow(0)
# Se muestra el nombre archivo del que se obtuvo el historial.
self.HistorialLabel.setText("Historial de Modificaciones del Archivo: {}".
format(nombre_archivo))
# Se agregan las revisiones obtenidas a la HistorialTable.
for rev in revisiones.entries:
n_row = self.HistorialTable.rowCount()
self.HistorialTable.insertRow(n_row)
self.HistorialTable.setVerticalHeaderItem(n_row, QtGui.QTableWidgetItem(rev.name))
fecha = "-".join(reversed(str(rev.client_modified).split(" ")[0].split("-")))
hora = str(rev.client_modified).split(" ")[1]
size = rev.size
self.HistorialTable.setItem(n_row, 0, QtGui.QTableWidgetItem(str(fecha)))
self.HistorialTable.setItem(n_row, 1, QtGui.QTableWidgetItem(str(hora)))
self.HistorialTable.setItem(n_row, 2, QtGui.QTableWidgetItem(str(size)))
except:
QtGui.QMessageBox.critical(None, 'ERROR', "Vuelva a intentarlo.", QtGui.QMessageBox.Ok)
def historial_carpeta(self, path_carpeta, nombre_carpeta):
try:
# Se limpia la HistorialTable.
num_rows = self.HistorialTable.rowCount()
for r in range(num_rows):
self.HistorialTable.removeRow(0)
# Se muestra el nombre de la carpeta del que se obtuvo el historial.
self.HistorialLabel.setText("Historial de Modificaciones de la Carpeta: {}".
format(nombre_carpeta))
for entry in self.dbx.files_list_folder(path_carpeta).entries:
try:
revisiones = self.dbx.files_list_revisions(entry.path_lower, limit=99)
except:
continue
# Se agregan las revisiones obtenidas a la HistorialTable.
for rev in revisiones.entries:
n_row = self.HistorialTable.rowCount()
self.HistorialTable.insertRow(n_row)
self.HistorialTable.setVerticalHeaderItem(n_row, QtGui.QTableWidgetItem(rev.name))
fecha = "-".join(reversed(str(rev.client_modified).split(" ")[0].split("-")))
hora = str(rev.client_modified).split(" ")[1]
size = rev.size
self.HistorialTable.setItem(n_row, 0, QtGui.QTableWidgetItem(str(fecha)))
self.HistorialTable.setItem(n_row, 1, QtGui.QTableWidgetItem(str(hora)))
self.HistorialTable.setItem(n_row, 2, QtGui.QTableWidgetItem(str(size)))
except:
QtGui.QMessageBox.critical(None, 'ERROR', "Vuelva a intentarlo.", QtGui.QMessageBox.Ok)
def actualizar_pressed(self):
self.actualizar_method()
def actualizar_method(self):
try:
self.actualizar = False
while self.thread_actualizar_arbol.isAlive():
time.sleep(0.05)
self.actualizar = True
self.ArbolArchivos.clear()
self.ArbolArchivos2.clear()
self.crear_thread(self.update_files_tree, (self.ArbolArchivos, self.ArbolArchivos2),
"thread_actualizar_arbol")
except:
pass
def descargar_pressed(self):
if not self.thread_descarga_archivo.isAlive():
archivo_seleccionado = self.ArbolArchivos.currentItem()
if archivo_seleccionado:
nombre_archivo = archivo_seleccionado.text(0)
if nombre_archivo.count(".") > 0:
item = archivo_seleccionado
path = []
while item is not None:
path.append(str(item.text(0)))
item = item.parent()
path_archivo = '/' + '/'.join(reversed(path))
path_destino_descarga = QtGui.QFileDialog.getExistingDirectory(self)
if path_destino_descarga:
path_destino_descarga = os.path.join(path_destino_descarga, nombre_archivo)
self.crear_thread(self.descargar_archivo,
(path_destino_descarga, path_archivo),
"thread_descarga_archivo")
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe seleccionar un archivo.",
QtGui.QMessageBox.Ok)
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe seleccionar un archivo.",
QtGui.QMessageBox.Ok)
else:
QtGui.QMessageBox.critical(None,
'ERROR',
"Actualmente se esta descargando "
"un archivo, por favor espere.",
QtGui.QMessageBox.Ok)
def descargar_archivo(self, path_destino_descarga, path_archivo):
try:
self.dbx.files_download_to_file(path_destino_descarga, path_archivo, rev=None)
except:
pass
def descargar_carpeta_pressed(self):
if not self.thread_descarga_archivo.isAlive():
carpeta_seleccionada = self.ArbolArchivos.currentItem()
if carpeta_seleccionada:
nombre_carpeta = carpeta_seleccionada.text(0)
if nombre_carpeta.count(".") == 0 or nombre_carpeta.count(".") > 1:
item = carpeta_seleccionada
path = []
while item is not None:
path.append(str(item.text(0)))
item = item.parent()
path_carpeta = '/' + '/'.join(reversed(path))
path_destino_descarga = QtGui.QFileDialog.getExistingDirectory(self)
if path_destino_descarga:
path_destino_descarga = os.path.join(path_destino_descarga, nombre_carpeta)
self.crear_thread(self.descargar_carpeta,
(path_destino_descarga, path_carpeta, nombre_carpeta),
"thread_descarga_archivo")
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe seleccionar una carpeta.",
QtGui.QMessageBox.Ok)
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe seleccionar una carpeta.",
QtGui.QMessageBox.Ok)
else:
QtGui.QMessageBox.critical(None,
'ERROR',
"Actualmente se esta descargando "
"un archivo, por favor espere.",
QtGui.QMessageBox.Ok)
def descargar_carpeta(self, path_destino_descarga, path_carpeta_dbx, nombre_carpeta):
if not os.path.exists(path_destino_descarga):
self.crear_thread(self.bajar_contenido,
(path_destino_descarga, path_carpeta_dbx),
"thread_descarga_archivo")
def bajar_contenido(self, path_destino_pc, path_carpeta_dbx):
try:
os.makedirs(path_destino_pc)
for entry in self.dbx.files_list_folder(path_carpeta_dbx).entries:
if isinstance(entry, dropbox.files.FolderMetadata):
self.bajar_contenido(os.path.join(path_destino_pc, entry.name), entry.path_lower)
else:
self.dbx.files_download_to_file(os.path.join(path_destino_pc, entry.name),
entry.path_lower,
rev=None)
except Exception as err:
print(err)
def subir_pressed(self):
if not self.thread_subir_archivo.isAlive():
dir_seleccionado = self.ArbolArchivos.currentItem()
if dir_seleccionado:
item = dir_seleccionado
path = []
while item is not None:
path.append(str(item.text(0)))
item = item.parent()
path.reverse()
path = path[:-1]
path_dir = '/' + '/'.join(path)
path_origen_subida = QtGui.QFileDialog.getOpenFileName(self)
if path_origen_subida:
nombre_archivo = os.path.split(path_origen_subida)[1]
path_subida = path_dir + '/' + nombre_archivo
path_subida = path_subida.replace("//", "/")
self.crear_thread(self.subir_archivo,
(path_origen_subida, path_subida),
"thread_subir_archivo")
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe seleccionar un directorio.",
QtGui.QMessageBox.Ok)
else:
QtGui.QMessageBox.critical(None,
'ERROR',
"Actualmente esta subiendo un archivo, por favor espere.",
QtGui.QMessageBox.Ok)
def subir_archivo(self, path_origen_subida, path_subida):
try:
with open(path_origen_subida, 'rb') as archivo:
self.dbx.files_upload(archivo, path_subida)
self.actualizar_method()
except:
pass
def crear_carpeta_pressed(self):
if not self.thread_crear_carpeta.isAlive():
ubicacion_seleccionada = self.ArbolArchivos.currentItem()
if ubicacion_seleccionada:
nombre_carpeta = self.NombreCarpetaLineEdit.text()
if nombre_carpeta:
item = ubicacion_seleccionada
path = []
while item is not None:
path.append(str(item.text(0)))
item = item.parent()
path.reverse()
path = path[:-1]
path_creacion = '/' + '/'.join(path) + '/' + nombre_carpeta
path_creacion = path_creacion.replace("//", "/")
self.crear_thread(self.crear_carpeta,
(path_creacion,),
"thread_crear_carpeta")
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe ingresar un nombre para la carpeta nueva.",
QtGui.QMessageBox.Ok)
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe seleccionar una ubicacion de creacion.",
QtGui.QMessageBox.Ok)
else:
QtGui.QMessageBox.critical(None,
'ERROR',
"Actualmente se esta creando una carpeta, por favor espere.",
QtGui.QMessageBox.Ok)
def crear_carpeta(self, path_creacion):
try:
self.dbx.files_create_folder(path_creacion)
self.actualizar_method()
except:
pass
def renombrar_pressed(self):
if not self.thread_renombrar.isAlive():
archivo_seleccionado = self.ArbolArchivos.currentItem()
if archivo_seleccionado:
nombre_archivo = archivo_seleccionado.text(0)
if nombre_archivo.count(".") > 0:
extension = os.path.splitext(nombre_archivo)[1]
item = archivo_seleccionado
path = []
while item is not None:
path.append(str(item.text(0)))
item = item.parent()
path_archivo = '/' + '/'.join(reversed(path))
nuevo_nombre = self.NuevoNombreLineEdit.text()
if nuevo_nombre:
nuevo_nombre += extension
self.crear_thread(self.renombrar,
(path_archivo, nuevo_nombre),
"thread_renombrar")
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe ingresar un nuevo nombre.",
QtGui.QMessageBox.Ok)
else:
item = archivo_seleccionado
path = []
while item is not None:
path.append(str(item.text(0)))
item = item.parent()
path_archivo = '/' + '/'.join(reversed(path))
nuevo_nombre = self.NuevoNombreLineEdit.text()
if nuevo_nombre:
self.crear_thread(self.renombrar,
(path_archivo, nuevo_nombre),
"thread_renombrar")
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe ingresar un nuevo nombre.",
QtGui.QMessageBox.Ok)
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe seleccionar un archivo o carpeta.",
QtGui.QMessageBox.Ok)
else:
QtGui.QMessageBox.critical(None,
'ERROR',
"Actualmente se esta renombrando "
"un archivo o carpeta, por favor espere.",
QtGui.QMessageBox.Ok)
def renombrar(self, path_original, nuevo_nombre):
try:
path_llegada = os.path.split(path_original)[0]
nuevo_path = path_llegada + "/" + nuevo_nombre
self.dbx.files_move(path_original, nuevo_path)
self.actualizar_method()
except Exception as err:
print(err)
def mover_pressed(self):
if not self.thread_mover.isAlive():
archivo_seleccionado = self.ArbolArchivos.currentItem()
if archivo_seleccionado:
self.deshabilitar()
else:
QtGui.QMessageBox.critical(None, 'ERROR', "Debe seleccionar un archivo o carpeta.",
QtGui.QMessageBox.Ok)
else:
QtGui.QMessageBox.critical(None,
'ERROR',
"Actualmente se esta moviendo "
"un archivo o carpeta, por favor espere.",
QtGui.QMessageBox.Ok)
def aceptar_pressed(self):
archivo_seleccionado = self.ArbolArchivos.currentItem()
item = archivo_seleccionado
path = []
while item is not None:
path.append(str(item.text(0)))
item = item.parent()
path_origen = '/' + '/'.join(reversed(path))
path_destino = self.DestinoLabel.text().split(": ")[1]
if path_destino:
self.crear_thread(self.mover,
(path_origen, path_destino),
"thread_mover")
def mover(self, path_origen, path_destino):
try:
self.dbx.files_move(path_origen, path_destino)
self.habilitar()
self.actualizar_method()
except:
self.habilitar()
def deshabilitar(self):
self.DestinoLabel.setText("Destino Archivo A Mover: ")
self.ArbolArchivos.setEnabled(False)
self.ActualizarButton.setEnabled(False)
self.VerHistorialButton.setEnabled(False)
self.DescargarArchivoButton.setEnabled(False)
self.DescargarCarpetaButton.setEnabled(False)
self.SubirArchivoButton.setEnabled(False)
self.MoverButton.setEnabled(False)
self.MoverButton.setEnabled(False)
self.CrearCarpetaButton.setEnabled(False)
self.RenombrarButton.setEnabled(False)
self.NombreCarpetaLineEdit.setEnabled(False)
self.NuevoNombreLineEdit.setEnabled(False)
self.HistorialTable.setEnabled(False)
self.ArbolArchivos2.setEnabled(True)
self.CancelarButton.setEnabled(True)
def habilitar(self):
self.DestinoLabel.setText("Destino Archivo A Mover: ")
self.ArbolArchivos.setEnabled(True)
self.ActualizarButton.setEnabled(True)
self.VerHistorialButton.setEnabled(True)
self.DescargarArchivoButton.setEnabled(True)
self.DescargarCarpetaButton.setEnabled(True)
self.SubirArchivoButton.setEnabled(True)
self.MoverButton.setEnabled(True)
self.MoverButton.setEnabled(True)
self.CrearCarpetaButton.setEnabled(True)
self.RenombrarButton.setEnabled(True)
self.NombreCarpetaLineEdit.setEnabled(True)
self.NuevoNombreLineEdit.setEnabled(True)
self.HistorialTable.setEnabled(True)
self.ArbolArchivos2.setEnabled(False)
self.AceptarButton.setEnabled(False)
self.CancelarButton.setEnabled(False)
def update_pathlabel(self):
self.AceptarButton.setEnabled(True)
nombre_archivo = self.ArbolArchivos.currentItem().text(0)
item = self.ArbolArchivos2.currentItem()
path = []
while item is not None:
path.append(str(item.text(0)))
item = item.parent()
path.reverse()
path = path[:-1]
path_item = '/' + '/'.join(path) + '/' + nombre_archivo
path_item = path_item.replace('//', '/')
self.DestinoLabel.setText("Destino Archivo A Mover: {}".format(path_item))
| true |
2f24a9f7016a19ab44f81e29ec2fa2c7293d9204 | Python | Asara/bangbot3 | /bangbot/plugins/cc.py | UTF-8 | 3,259 | 2.59375 | 3 | [
"WTFPL"
] | permissive | # -*- coding: utf-8 -*-
from irc3.plugins.command import command
import irc3
import json
import os
import requests
ccfolder = 'extra/ccfolder/'
if not os.path.exists(ccfolder):
os.makedirs(ccfolder)
@irc3.plugin
class Plugin(object):
def __init__(self, bot):
self.bot = bot
@command(permission=None, options_first=True)
def setmycc(self, mask, target, args):
"""Set your favorite crypto currencies for !cc @
%%setmycc <currencies>...
"""
ccfile = ccfolder + target + '_' + mask.nick
currencies = args['<currencies>']
try:
with open(ccfile, 'w') as f:
for currency in currencies:
f.write("{}\n".format(currency.upper()))
yield 'Your cryptocurrency favorites saved'
except:
yield 'Could not save your preferences. Please contact the administrator'
@command(permission=None, options_first=True)
def cc(self, mask, target, args):
"""Get the price of the specified cryptocurrency, or @ for your favorites, which is set with !setmycc.
%%cc <requestedCryptoCur>
"""
currency_name = str(args['<requestedCryptoCur>'])
if currency_name != '@':
currency_name = currency_name.upper()
try:
d = requests.get(
'https://min-api.cryptocompare.com/data/pricemultifull?fsyms=' +
currency_name +
'&tsyms=USD'
).json()['DISPLAY'][currency_name]['USD']
yield(
currency_name +
':' +
d['PRICE'] +
'. Market cap:' +
d['MKTCAP'] +
'. 24 Hour low:' +
d['LOW24HOUR'] +
'. 24 hour high:' +
d['HIGH24HOUR']
)
except:
yield('Currency not found')
else:
ccfile = ccfolder + target + '_' + mask.nick
try:
with open(ccfile, 'r') as f:
currencies = f.read().splitlines()
for currency in currencies:
try:
d = requests.get(
'https://min-api.cryptocompare.com/data/pricemultifull?fsyms=' +
currency +
'&tsyms=USD'
).json()['DISPLAY'][currency]['USD']
yield(
currency +
':' +
d['PRICE'] +
'. Market cap:' +
d['MKTCAP'] +
'. 24 Hour low:' +
d['LOW24HOUR'] +
'. 24 hour high:' +
d['HIGH24HOUR']
)
except:
yield('Currency not found')
except:
yield('Try saving your favorites first with !setmycc')
| true |
c91275bd35d62df78618f105ff7c7d27e02a1801 | Python | styinx/ACBIB | /ACBIB.py | UTF-8 | 6,518 | 2.640625 | 3 | [] | no_license | # Assetto Corsa Basic Information Board (ACBIB)
import ac
import math
try:
import app.acbib as acbib
import app.gui as gui
except:
ac.console("error importing gui")
# global settings
APP_WIDTH = 600
APP_HEIGHT = 170
invalid_lap = False
ratio = 1
font_huge = 70
font_big = 40
font_medium = 20
font_small = 15
def acMain(ac_version):
global app
global lap_count, lap_current, lap_last, lap_best, lap_delta, lap_diff
global car_speed, car_gear, car_rpm, car_pos, car_fuel, car_prev, car_next
global car_tyre_1, car_tyre_2, car_tyre_3, car_tyre_4
try:
app = gui.App("ACBIB", "", APP_WIDTH, APP_HEIGHT, gui.Color(0, 0, 0, 0.8))
app.setRenderCallback(glRender)
grid = gui.Grid(app, 5, 5)
#ac.console("{}{}".format(self.pos[0], self.pos[1]))
lap_count = gui.Label(None, app)
car_pos = gui.Label(None, app)
car_fuel = gui.Label(None, app)
lap_best = gui.Label(None, app)
lap_last = gui.Label(None, app)
lap_current = gui.Label(None, app)
car_prev = gui.Label(None, app, "", gui.Color(1, 0, 0, 1))
lap_diff = gui.DiffBar(None, app, True)
car_next = gui.Label(None, app, "", gui.Color(0, 1, 0, 1))
car_speed = gui.Label(None, app)
car_gear = gui.Label(None, app)
car_rpm = gui.Label(None, app)
car_tyre_1 = gui.Label(None, app)
car_tyre_2 = gui.Label(None, app)
car_tyre_3 = gui.Label(None, app)
car_tyre_4 = gui.Label(None, app)
grid.add(lap_count, 0, 0)
grid.add(car_pos, 0, 1)
grid.add(car_fuel, 0, 2)
grid.add(lap_best, 1, 0)
grid.add(lap_last, 1, 1)
grid.add(lap_current, 1, 2)
grid.add(car_prev, 0, 4)
grid.add(lap_diff, 2, 3)
grid.add(car_next, 4, 4)
grid.add(car_speed, 2, 0)
grid.add(car_gear, 2, 1)
grid.add(car_rpm, 2, 2)
grid.add(car_tyre_1, 3, 0, 1, 2)
grid.add(car_tyre_2, 4, 0, 1, 2)
grid.add(car_tyre_3, 3, 2, 1, 2)
grid.add(car_tyre_4, 4, 2, 1, 2)
except TypeError:
ac.console(" ACBIB: Error while initializing.")
return "ACBIB"
def acUpdate(deltaT):
global app
global lap_current, lap_last, lap_best, lap_count, lap_delta, lap_diff
global car_speed, car_gear, car_rpm, car_pos, car_fuel, car_prev, car_next
global car_tyre_1, car_tyre_2, car_tyre_3, car_tyre_4
app.update()
lap_count.setText("Lap: {}/{}".format(acbib.ACLAP.getLap(0), acbib.ACLAP.getLaps()))
car_pos.setText("Pos: {}/{}".format(acbib.ACCAR.getPosition(0), acbib.ACSESSION.getCarsCount()))
car_fuel.setText("Fuel: {:3.0f} l".format(acbib.ACCAR.getFuel()))
lap_current.setText("CUR: {}".format(acbib.ACLAP.getCurrentLap(0)))
lap_last.setText("LST: {}".format(acbib.ACLAP.getLastLap(0)))
lap_best.setText("BST: {}".format(acbib.ACLAP.getBestLap(0)))
car_prev.setText("{}".format(acbib.ACCAR.getPrevCarDiffTime(True)))
car_next.setText("{}".format(acbib.ACCAR.getNextCarDiffTime(True)))
car_speed.setText("{:3.0f} km/h".format(acbib.ACCAR.getSpeed(0)))
car_gear.setText("{}".format(acbib.ACCAR.getGear(0)))
car_rpm.setText("{:4.0f} rpm".format(acbib.ACCAR.getRPM(0)))
car_tyre_1.setText("{:3.1f}°C\n{:3.1f} psi\n{:3.1f}%".format(acbib.ACCAR.getTyreTemp(0, "c"),
acbib.ACCAR.getTyrePressure(0),
acbib.ACCAR.getTyreWear(0)))
car_tyre_2.setText("{:3.1f}°C\n{:3.1f} psi\n{:3.1f}%".format(acbib.ACCAR.getTyreTemp(1, "c"),
acbib.ACCAR.getTyrePressure(1),
acbib.ACCAR.getTyreWear(1)))
car_tyre_3.setText("{:3.1f}°C\n{:3.1f} psi\n{:3.1f}%".format(acbib.ACCAR.getTyreTemp(2, "c"),
acbib.ACCAR.getTyrePressure(2),
acbib.ACCAR.getTyreWear(2)))
car_tyre_4.setText("{:3.1f}°C\n{:3.1f} psi\n{:3.1f}%".format(acbib.ACCAR.getTyreTemp(3, "c"),
acbib.ACCAR.getTyrePressure(3),
acbib.ACCAR.getTyreWear(3)))
def glRender(deltaT):
global app
global lap_diff
app.render()
lap_diff.render()
# shifting
rpm_max = acbib.ACCAR.getRPMMax()
rpm = acbib.ACCAR.getRPM()
progress = rpm / rpm_max
offset = rpm_max * 0.8 / rpm_max
shift_min = 0.9
shift_max = 0.95
cube_len = int(APP_WIDTH / 40)
# shift steering wheel lights
if progress > offset:
for i in range(min(10, int((progress - offset) / (1 - offset) * 10))):
if i < 2:
gui.GL.rect(i * int(APP_WIDTH / 10) + (cube_len / 2), -cube_len, int(APP_WIDTH / 10) - cube_len,
cube_len, gui.Color(0, 0.9, 0, 1))
elif i < 7:
gui.GL.rect(i * int(APP_WIDTH / 10) + (cube_len / 2), -cube_len, int(APP_WIDTH / 10) - cube_len,
cube_len, gui.Color(1, 1, 0, 1))
else:
gui.GL.rect(i * int(APP_WIDTH / 10) + (cube_len / 2), -cube_len, int(APP_WIDTH / 10) - cube_len,
cube_len, gui.Color(0, 0.2, 0.9, 1))
# shift progress background
gui.GL.rect(0, APP_HEIGHT, APP_WIDTH, 6, gui.Color(0.6, 0.6, 0.6, 1))
# shift progress indicator
if acbib.ACCAR.getRPM() < acbib.ACCAR.getRPMMax() * shift_min:
gui.GL.rect(0, APP_HEIGHT, progress * APP_WIDTH, 6, gui.Color(0, 0.9, 0, 1.0))
elif acbib.ACCAR.getRPMMax() * shift_min <= acbib.ACCAR.getRPM() <= acbib.ACCAR.getRPMMax() * shift_max:
gui.GL.rect(0, APP_HEIGHT, progress * APP_WIDTH, 6, gui.Color(0.9, 0.9, 0, 1.0))
gui.GL.rect(-10, 0, 10, APP_HEIGHT + 6, gui.Color(0.9, 0.9, 0, 1.0))
gui.GL.rect(APP_WIDTH, 0, 10, APP_HEIGHT + 6, gui.Color(0.9, 0.9, 0, 1.0))
elif acbib.ACCAR.getRPM() > acbib.ACCAR.getRPMMax() * shift_max:
gui.GL.rect(0, APP_HEIGHT, progress * APP_WIDTH, 6, gui.Color(0.9, 0, 0, 1.0))
# track progress
track_progress = acbib.ACCAR.getLocation()
if track_progress > 0:
gui.GL.rect(0, APP_HEIGHT + 6, track_progress * APP_WIDTH, 6, gui.Color(0, 0.5, 0.9, 1))
def acShutdown():
l = 1
| true |
714c28ac76b6d2c8885b8aad7177a9c5fcae19ea | Python | Papiertieger23/HypixelIO | /hypixelio/models/recent_games/recent_game_info.py | UTF-8 | 779 | 2.828125 | 3 | [
"MIT"
] | permissive | from hypixelio.utils.time import unix_time_to_datetime
class RecentGameInfo:
def __init__(self, game: dict) -> None:
"""
Parameters
----------
game: dict
The game's JSON data received from the Hypixel API.
"""
self.DATE = unix_time_to_datetime(game["date"])
self.END_DATETIME = unix_time_to_datetime(game["ended"])
self.GAME_TYPE = game["gameType"]
self.MODE = game.get("mode")
self.MAP = game["map"]
def __hash__(self) -> int:
return hash((self.DATE, self.MAP))
def __str__(self) -> str:
return self.GAME_TYPE
def __repr__(self) -> str:
return f'<{self.__class__.__name__} game_type="{self.GAME_TYPE}" mode="{self.MODE}" map="{self.MAP}">'
| true |
ac80e6eabaa5a3db1805ce698497f46f1ed2908b | Python | lwillmeth/AnalysisofAlgorithms | /Implementation2/seqAlign.py | UTF-8 | 4,828 | 2.90625 | 3 | [] | no_license | <<<<<<< HEAD
import sys, re, time
=======
#!/usr/bin/python
'''
CS 325 - Implementation 2
Sequence alignment via dynamic programming
Kyle Prouty, Levi Willmeth, Andrew Morrill
Winter 2017
'''
import sys, re
>>>>>>> 0404bc8bdd747e9a9d205a4781cff61271b9bce3
DEBUGGING = False
costFile = 'imp2cost.txt'
seqFile = 'imp2input.txt'
outFile = 'imp2output.txt'
def readInputFile(cFile):
''' Read the input strings in from a file '''
# Overwrite output file, if it exists
open(outFile, 'w+').close()
with open(cFile, 'r') as file:
# Solve each line in the file.
for line in file:
a, b = line.split(',')
align('-'+a, '-'+b[:-1])
def readCostFile(cFile):
''' Read the cost array into a dictionary of key:value pairs'''
costs = {}
with open(cFile, 'r') as file:
chars = ''
for f in file:
f = f.strip('\n').split(',')
if f[0] is '*':
# Read in available chars but skip the leading *
chars = f
for k in f[1:]:
costs[k] = {}
else:
# Treat this line as costs for the far left char
for i, c in enumerate(f):
costs[f[0]][chars[i]] = c
return costs, chars[1:]
<<<<<<< HEAD
#@profile
=======
# @profile
>>>>>>> 0404bc8bdd747e9a9d205a4781cff61271b9bce3
def align(topWord, sideWord):
def printArr(arr):
''' Display the array as it would appear on paper '''
# Print the header
print ' #',
for x in topWord:
# Pad each column to 2 spaces to fix large inputs
print "{:>2}".format(x),
print ''
# Print each line
for y in xrange(lenSide):
for x in xrange(lenTop):
if x is 0:
print "{:>2}".format(sideWord[y]),
print "{:>2}".format(arr[x][y]),
print ''
def printCosts(arr):
''' Display the costs as an unsorted array '''
# Print the header
print ' #',
for a in costs:
# Pad each column to 2 spaces to fix large inputs
print "{:>2}".format(a),
print ''
# Print each line
for a in costs:
print "{:>2}".format(a),
for b in costs:
print "{:>2}".format(costs[a][b]),
print ''
def getCost(a, b):
''' Returns cost to convert from one letter to another '''
return int(costs[a][b])
def walkHome():
''' Walk back to the beginning, creating the changed strings '''
tW, sW = '', ''
x, y = lenTop-1, lenSide-1
while x > 0 or y > 0:
if DEBUGGING: print x, y, B[x][y]
if B[x][y] == '-':
sW = '-'+sW
tW = topWord[x]+tW
x -= 1
elif B[x][y] == '|':
sW = sideWord[y]+sW
tW = '-'+tW
y -= 1
else:
sW = sideWord[y]+sW
tW = topWord[x]+tW
x -= 1
y -= 1
return tW, sW
# Save word sizes for later
lenTop = len(topWord)
lenSide = len(sideWord)
# Set up the (mostly empty) array
A = [[0]*lenSide for y in xrange(lenTop)]
B = [[0]*lenSide for y in xrange(lenTop)]
# C = [[0 for x in xrange(lenSide)] for y in xrange(lenTop)]
# D = [[0 for x in xrange(lenSide)] for y in xrange(lenTop)]
for i in xrange(1,lenTop):
A[i][0] = A[i-1][0] + getCost('-', topWord[i])
B[i][0] = '-'
for i in xrange(1, lenSide):
A[0][i] = A[0][i-1] + getCost('-', sideWord[i])
B[0][i] = '|'
for x in xrange(1,lenTop):
for y in xrange(1,lenSide):
t, s = topWord[x], sideWord[y]
A[x][y], B[x][y] = min(
(A[x-1][y] + getCost('-', t), '-'), # insert - into top word
(A[x][y-1] + getCost(s, '-'), '|'), # insert - into side word
(A[x-1][y-1] + getCost(t, s), '\\') # align characters
)
# Walk backwards through the array to find the two strings
t, s = walkHome()
if DEBUGGING:
print "Calculating the alignment cost between:"
print topWord
print sideWord
print '=== Cost Array ==='
printCosts(costs)
print 'The resulting array:'
printArr(A)
print '=== Path Home ==='
printArr(B)
print '=== Resulting Strings ==='
# Append this result to the output file, or print it to screen
with open(outFile, 'a') as out:
out.write('{},{}:{}\n'.format(t, s, A[lenTop-1][lenSide-1]))
start = time.time()
# Read in the costs from file
costs, chars = readCostFile(costFile)
readInputFile(seqFile)
end = time.time()
print(end-start) | true |
083882968c34470366c400d8f118a6c21a8810ac | Python | Mastah95/IOIOIO | /tests.py | UTF-8 | 2,514 | 3.296875 | 3 | [
"MIT"
] | permissive | import unittest
from itertools import product
import numpy as np
from main import get_neighbours, get_next_move
class TestGetNeighbours(unittest.TestCase):
def test_finds_neighbourhood(self):
matrix_shape = (10, 20)
position = (5, 7)
ys = (-1, 0, 1)
xs = (-1, 0, 1)
offsets = set(product(ys, xs)) - {(0, 0)}
expected = ((position[0] + y, position[1] + x) for (y, x) in offsets)
actual = get_neighbours(position, matrix_shape)
self.assertSetEqual(set(expected), set(actual))
def test_finds_edge_neighbourhood(self):
matrix_shape = (7, 10)
position = (5, 9)
h, w = matrix_shape
matrix_positions = set(product(range(h), range(w)))
actual = set(get_neighbours(position, matrix_shape))
self.assertTrue(actual.issubset(matrix_positions))
self.assertEqual(len(actual), 5)
def test_finds_corner_neighbourhood(self):
matrix_shape = (7, 10)
position = (6, 9)
h, w = matrix_shape
matrix_positions = set(product(range(h), range(w)))
actual = set(get_neighbours(position, matrix_shape))
self.assertTrue(actual.issubset(matrix_positions))
self.assertEqual(len(actual), 3)
def test_returns_empty_result_out_of_range(self):
matrix_shape = (7, 10)
position = (777, 999)
actual = set(get_neighbours(position, matrix_shape))
self.assertEqual(len(actual), 0)
class TestGetNextMove(unittest.TestCase):
def test_is_valid_move(self):
position = (5, 6)
shape = (8, 10)
pheromones = np.random.rand(*shape)
variances = np.random.randint(0, 100, shape)
alpha = 1.0
beta = 1.0
ys = (-1, 0, 1)
xs = (-1, 0, 1)
offsets = set(product(ys, xs)) - {(0, 0)}
valid_moves = set((position[0] + y, position[1] + x)
for (y, x) in offsets)
for _ in range(20):
move = get_next_move(position, pheromones, variances, alpha, beta)
self.assertTrue(move in valid_moves)
def test_handles_zero_variances(self):
"""Check that results are provided if input variances are all zeros."""
position = (5, 6)
shape = (8, 10)
pheromones = np.zeros(shape)
variances = np.zeros_like(pheromones)
alpha = 1.0
beta = 1.0
move = get_next_move(position, pheromones, variances, alpha, beta)
self.assertIsNotNone(move)
| true |
43b5ca76c86d6c805b253a8e6ff8799a5ac80c8a | Python | DmitriChe/pydev_hw5 | /file_manager.py | UTF-8 | 5,480 | 3.171875 | 3 | [] | no_license | import os
import sys
import shutil
import json
from account import account
from victorina import victorina
def make_directory(folder_name):
if not os.path.exists(folder_name):
os.mkdir(folder_name)
return 'Папка успешно создана'
else:
return 'Папка с таким именем уже существует - придумайте другое имя!'
def delete_file_dir(f_name):
if os.path.exists(f_name):
shutil.rmtree(f_name, ignore_errors=True)
if os.path.exists(f_name):
return 'Файл НЕ удален!'
else:
return 'Файл(папка) успешно удален!'
else:
return 'Такого объекта не сущестует!'
def copy_file_dir():
path_from = input('Введите название исходного файла(папки) для копирования: ')
if os.path.exists(path_from):
path_to = input('Введите новое название для копии файла(папки): ')
if path_from == path_to:
print('Имена исходного и конечного объектов должны быть разными! Попробуйте снова.')
else:
if os.path.exists(path_to):
print('Объект с таким именем уже существует. Введите другое имя для копии.')
else:
if os.path.isfile(path_from):
shutil.copy(path_from, path_to)
if os.path.exists(path_to):
print('Объект успешно скопирован')
else:
print('Что-то пошло не так с этим копированием...')
else:
shutil.copytree(path_from, path_to)
if os.path.exists(path_to):
print('Объект успешно скопирован')
else:
print('Что-то пошло не так с этим копированием...')
else:
print('Исходного объекта не существует, введите другое имя!')
def change_dir(dir_path):
if os.path.exists(dir_path):
os.chdir(dir_path)
return f'Вы перешли в деректорию: {os.getcwd()}'
else:
return 'Нет такой директории! Попробуйте еще раз.'
def save_dirlist():
dirlist_data = {
'files': [],
'dirs': [],
}
dir_list = os.listdir(os.getcwd())
for item in dir_list:
if os.path.isfile(item):
dirlist_data['files'].append(item)
else:
dirlist_data['dirs'].append(item)
with open('dir_list', 'w', encoding='utf-8') as f:
f.write(json.dumps(dirlist_data))
with open('dir_list', 'r', encoding='utf-8') as f:
# f.read(json.dumps(dirlist_data))
if json.load(f) == dirlist_data:
return 'Содержимое директории успешно записано в файл dir_list'
else:
return 'Ошибка сохранения данных директории в файл'
if __name__ == '__main__':
while True:
print('\n1. создать папку')
print('2. удалить (файл/папку)')
print('3. копировать (файл/папку)')
print('4. просмотр содержимого рабочей директории')
print('5. посмотреть только папки')
print('6. посмотреть только файлы')
print('7. просмотр информации об операционной системе')
print('8. создатель программы')
print('9. играть в викторину')
print('10. мой банковский счет')
print('11. смена рабочей директории')
print('12. сохранить содержимое рабочей директории в файл')
print('0. выход')
choice = input('Выберите пункт меню: ')
if choice == '1':
print(make_directory(input('Введите имя папки: ')))
elif choice == '2':
print(delete_file_dir(input('Введите имя папки(файла) для удаления: ')))
elif choice == '3':
copy_file_dir()
elif choice == '4':
print(os.listdir())
elif choice == '5':
print([x for x in os.listdir() if not os.path.isfile(x)])
elif choice == '6':
print([x for x in os.listdir() if os.path.isfile(x)])
elif choice == '7':
print(sys.platform)
elif choice == '8':
print('*** Build by Human Intelligence of DmitryChe! ***')
elif choice == '9':
victorina()
elif choice == '10':
account()
elif choice == '11':
print(change_dir(input('Введите путь к новой рабочей директори: ')))
elif choice == '12':
print(save_dirlist())
elif choice == '0':
break
else:
print('\nНеверный пункт меню\n')
| true |
108ae3585a1d247f1f13b955c20b302c0bfae751 | Python | shikixyx/AtCoder | /Enterprise/HHKB/2020/2020_C.py | UTF-8 | 383 | 2.875 | 3 | [] | no_license | import sys
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(input())
P = list(map(int, input().split()))
NUM_LIST = [False] * 200100
ANS = []
idx = 0
for p in P:
NUM_LIST[p] = True
while NUM_LIST[idx]:
idx += 1
ANS.append(idx)
print("\n".join(map(str, ANS)))
| true |
75a222c9a7ae088f568e4ab061e9bf180818d850 | Python | mmr12/DeepBlueSea | /models/baseline_model.py | UTF-8 | 2,936 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | from base.base_model import BaseModel
import tensorflow as tf
from models.utils_model import *
class BaselineModel(BaseModel):
def __init__(self, config):
super(BaselineModel, self).__init__(config)
self.build_model()
self.init_saver()
def build_model(self):
self.is_training = tf.placeholder(tf.bool)
self.x = tf.placeholder(tf.float32, shape=[None, 60, 60, self.config.num_channels])
self.y = tf.placeholder(tf.int64, shape=[None])
# network architecture
layer_conv1 = create_convolutional_layer(input=self.x,
num_input_channels=self.config.num_channels,
conv_filter_size=self.config.filter_size_conv1,
num_filters=self.config.num_filters_conv1)
layer_conv2 = create_convolutional_layer(input=layer_conv1,
num_input_channels=self.config.num_filters_conv1,
conv_filter_size=self.config.filter_size_conv2,
num_filters=self.config.num_filters_conv2)
layer_conv3 = create_convolutional_layer(input=layer_conv2,
num_input_channels=self.config.num_filters_conv2,
conv_filter_size=self.config.filter_size_conv3,
num_filters=self.config.num_filters_conv3)
layer_flat = create_flatten_layer(layer_conv3)
layer_fc1 = create_fc_layer(input=layer_flat,
num_inputs=layer_flat.get_shape()[1:4].num_elements(),
num_outputs=self.config.fc_layer_size,
use_relu=True)
layer_fc2 = create_fc_layer(input=layer_fc1,
num_inputs=self.config.fc_layer_size,
num_outputs=2,
use_relu=False)
with tf.name_scope("loss"):
self.cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.y, logits=layer_fc2))
self.train_step = tf.train.AdamOptimizer(self.config.learning_rate).minimize(self.cross_entropy,
global_step=self.global_step_tensor)
self.pred = tf.argmax(layer_fc2, 1)
correct_prediction = tf.equal(self.pred, self.y)
self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
def init_saver(self):
# here you initialize the tensorflow saver that will be used in saving the checkpoints.
self.saver = tf.train.Saver(max_to_keep=self.config.max_to_keep) | true |
62efcb7778366aee68a870bcf2e69e47e60ecd65 | Python | KunHCS/flaskbank | /flaskbank/backend/model.py | UTF-8 | 1,784 | 2.671875 | 3 | [] | no_license | """
Database initialization
"""
from . import mongo
import pymongo
import random
import luhn
from functools import wraps
jti_blacklist = set()
clients = mongo.db.clients
clients.create_index([('username', pymongo.ASCENDING)], unique=True)
clients.create_index([('accounts.account_number', pymongo.ASCENDING)],
unique=True)
uniqueID_db = mongo.db.unique_counter
uniqueID_db.create_index([('id', pymongo.ASCENDING)], unique=True)
try:
uniqueID_db.insert_one({
'id': 'account_number',
'count': 10000
})
except pymongo.errors.DuplicateKeyError as e:
pass
def unique_bank_account(f):
@wraps(f)
def wrapper(*args):
for i in range(5):
bank_num = f(*args)
result = clients.find_one({'accounts.account_number': bank_num})
if not result:
return bank_num
raise Exception('No unique bank number found')
return wrapper
@unique_bank_account
def get_account_num(acc_type):
"""
Get the next unique id for specific key
:param acc_type: (string) key to access
:return: (number) unique ID
"""
checking_prefix = '2'
saving_prefix = '3'
credit_prefix = '4'
new_id = uniqueID_db.find_one_and_update(
{'id': 'account_number'},
{'$inc': {'count': 1}}
)
temp = list(str(new_id['count']))
temp.extend(list(str(random.randrange(100, 1000))))
suffix = ''.join(random.sample(temp, k=len(temp)))
if acc_type == 'checking':
return luhn.append(checking_prefix + suffix)
elif acc_type == 'saving':
return luhn.append(saving_prefix + suffix)
elif acc_type == 'credit':
return luhn.append(credit_prefix + suffix)
else:
raise Exception('No account type specified')
| true |
34ed287f6298bf26914143ace069d489026c96d4 | Python | InevitableShot/JSP2020 | /lista7/zad3.py | UTF-8 | 755 | 3.8125 | 4 | [] | no_license | import time
from random import randint
t1 = [randint(0, 20) for i in range(0, 100)]
t2 = [randint(0, 20) for i in range(0, 200)]
t3 = [randint(0, 20) for i in range(0, 300)]
def bubble_sort(tab):
n = len(tab)
while n > 1:
for i in range(0, n-1):
if tab[i] > tab[i+1]:
tab[i], tab[i+1] = tab[i+1], tab[i]
n -= 1
return tab
def check(tab):
t_start = time.process_time()
bubble_sort(tab)
t_stop = time.process_time()
print(
f'Czas wykonania sortowania dla tablicy {len(tab)} elementowej wynosi: {t_stop-t_start: .9f}s')
def main():
check(t1)
check(t2)
check(t3)
# Nie ma szans pokazania czasu wykonywania sie tego sortowania dla tak małych tablic
main()
| true |
1388b2361f9d0e2cafd2b7ac5f96c6f1807e213b | Python | nikhilranjan7/open-cv | /video_loading.py | UTF-8 | 507 | 2.515625 | 3 | [] | no_license | import cv2
import numpy as np
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc('m','p','4','v')
out = cv2.VideoWriter('output.m4v', fourcc, 20.0, (640,480))
while True:
ret, frame = cap.read()
frame = cv2.resize(frame, (640,480))
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
out.write(frame)
cv2.imshow('frame', frame)
cv2.imshow('gray', gray)
if cv2.waitKey(1) & 0xFF == ord('q'): # Need only 8 bits
break
cap.release()
out.release()
cv2.destroyAllWindows()
| true |
b0b798837b1e86e672d97e563006ca9ce9533b1d | Python | cam-hart/Thermal-Resistance-of-a-heatsink | /heatsink_thermal_resistance.py | UTF-8 | 4,272 | 2.765625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 3 15:19:54 2021
@author: camer
"""
import pandas as pd
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
"""
num_fins=N(10,12,14,16,18)
base_thickness=x(10mm)
base_width=w (46.9mm)
gap_thickness=b
fin_thickness=t(1.5mm)
fin_height=H(30mm)
fin_length=L (60mm)
metal_thermal_conductivity=Km (180 W/mk)
fluid_thermal_conductivity=Kf (2.624kW/m*K)
dynamic_viscocity=Vd (1.846*(10**-5))
kinematic_viscosity=Vk (1.586*(10**-5))
freestream_velocity=v_f
Specific_heat_capacity=Cp (1.0049kJ/kg*K)
Q=air flow(m^3/min)
fluid density (1.777kg/m^3)
"""
fan_curve=pd.read_excel('Copy of FanCurveData.xlsx',index_col=None,usecols='A,B')
air_flow=np.array(fan_curve['Air Flow [m^3/minute]'].tolist())
pressure=np.array(fan_curve['Static Pressure [mm-H2O]'].tolist())
#importing excel data, making arrays for graph
plt.scatter(pressure,air_flow)
def volume_flow_fP(x,a,b,c,d,e,f):
return (a*(x**5))+(b*(x**4))+(c*(x**3))+(d*(x**2))+(e*x)+f
#making a linear function for volume flow rate as a function of pressure, originally
#did the other way around but realised needs to be flipped
coefficients,other=curve_fit(volume_flow_fP,pressure,air_flow)
a,b,c,d,e,f=coefficients
x=np.arange(pressure[len(pressure)-1],pressure[0],0.001)
plt.plot(x,volume_flow_fP(x,a,b,c,d,e,f))
plt.ylabel("Air flow rate (m^3/s)")
plt.xlabel("Pressure drop (mm(H2O)")
plt.show()
#plotting function to see how accurate it is. Tried function in form a**b, but didn't work. Left order of
#function at 5 because it fits pretty well
class Rsink:
def __init__(self,N,Q):
self.N=N
self.Q=Q
self.x=0.01
self.w=0.047
self.t=0.0015
self.H=0.03
self.L=0.06
self.Km=180
self.Kf=2624
self.density=1.777
self.Vd=1.846*(10**-5)
self.Vk=1.586*(10**-5)
self.Cp=1.0049
self.b=(self.w-(self.N*self.t))/(self.N-1)
self.v_f=(self.Q*60)/0.041*0.012
self.mu=1-((self.N*self.t)/self.w)
self.Kc=0.42*(1-(self.mu**2))
self.Ke=(1-(self.mu**2))**2
self.v_ch=self.v_f*(1+(self.t/self.b))
self.Rech=(self.v_ch*self.L)/self.Vk
self.l=self.L/(2*self.b*self.Rech)
self.prandtl_number=(self.Cp*self.Vd)/self.Kf
self.Reb=(self.b*self.v_ch)/self.Vk
self.nusselt_number=(((self.Reb*self.prandtl_number*0.5)**-3)+((0.664*math.sqrt(self.Reb*(self.prandtl_number**1/3)*(1+(3.65/math.sqrt(self.Reb)))))**-3))**(-1/3)
self.h=(self.Kf*self.nusselt_number)/self.b
self.fRech=24-(32.527*(self.b/self.H))+(46.721*((self.b/self.h)**2))
self.Fapp=((((3.44/math.sqrt(self.l))**2)+(self.fRech**2))**0.5)/self.Rech
self.P_drop_pa=(((self.Fapp*self.N*((2*self.H*self.L)+(self.b*self.L)))/(self.H*self.w))+self.Kc+self.Ke)*0.5*self.density*(self.v_ch**2)
self.P_drop_mmh20=self.P_drop_pa/9.80665
self.P=2*(self.t+self.L)
self.Ac=self.t*self.L
self.m=math.sqrt((self.h*self.P)/(self.Km*self.Ac))
self.R_fin=1/math.sqrt(self.h*self.P*self.Km*self.Ac)*math.tanh(self.m*self.H)
self.R_sink=1/(self.N/self.R_fin)+(self.h*self.N*self.b*self.L)
#making a class to contain all Rsink data. Starting with the variables, the constants @300K,
#then coding the equations, ensuring theyre in the right order.
self.Q2=volume_flow_fP(self.P_drop_mmh20, a, b, c, d, e, f)
Q=0.1
N=int(input("Enter number of fins:"))
Previous=0
while True:
Q=Rsink(N,Q).Q2
Q=Rsink(N,Q).Q2
if Q==Previous:
break
Previous=Q
#finding operating point using a while loop until volume flow rate converges, ie equal to last
#for N=10 and N=18, it oscillates between two very close points (less than 1*10^-15), so changed it to return Q when
#its equal to the second previous, by repeating line
print("R-Sink for "+str(N)+" fins is: "+str(Rsink(N,Q).R_sink)+" (K/W)")
#printing R-sink using operating point
with open("R_sink_f(N).txt", "a") as file:
file.write(str(N)+" "+str(Rsink(N,Q).R_sink)+'\n')
#adds result to file
| true |
284a3b0b50776c6c309870352a681114f6382025 | Python | kekeFu/Python2020 | /test_2_file/file_advance_2.py | UTF-8 | 1,530 | 3.421875 | 3 | [] | no_license | """
文件或文件夹操作:
1.rename(), 重命名
2.remove(), 删除
文件夹操作:
1.mkdir(),创建文件夹
2.rmdir(),删除文件夹
3.getcwd(),获取当前文件夹路径
4.chdir(目录),改变默认目录, 并定位到指定目录
4.listdir(目录),获取目录列表
总结:批量处理文件命名容易出错,最好不要缺省参数
"""
import os
# os.rename('test1.txt', 't.txt')
# os.remove('test2.txt')
# os.mkdir('a')
# os.rmdir('a')
# print(os.getcwd())
# os.chdir('a')
# os.mkdir('b')
# print(os.listdir('a'))
# os.rename('a', 'aa')
"""
测试案例,批处理重命名文件
获取最初文件名,确定字符串要插入最初文件名的位置,
创建新文件名,重命名
"""
path = r'D:\Users\ASUS\PycharmProjects\test_2_beifen'
fifle_list = os.listdir(path)
print(fifle_list)
for i in fifle_list:
old_name = i
new_name = 'py_' + i
print('旧文件名:%-20s,新文件名:%-20s' % (old_name, new_name))
# os.rename(i, new_name)
"""
恢复: 修改seting(interpret),
修改文件夹名字(运行一下会产生一个新的.idea文件,并且报错)
在有venv(虚拟环境)的情况下,非常容易出错!
"""
# path = r'D:\Users\ASUS\PycharmProjects\test_2_beifen'
# fifle_list = os.listdir(path)
# print(fifle_list)
# for i in fifle_list:
# old_name = i
# num = len('py_')
# new_name = i[num:]
# print('旧文件名:%-20s,新文件名:%-20s' % (old_name, new_name))
# os.rename(i, new_name)
| true |
a5505ea2a9af2b80bea582064568a27ed41c11a2 | Python | adrianmikol/2020-11-21-python | /funkcje/zadanie3.py | UTF-8 | 964 | 3.90625 | 4 | [] | no_license | """
Napisać funkcję obliczającą całkowity wstępu grupy osób do kina, wg zasady:
jeden bilet kosztuje 20
przy zakupie co najmniej 10 biletów bilet kosztuje 13
Przy co najmniej 150 osobach koszt jest stały i wynosi 1600.00 za całość.
"""
def koszt_biletow_grupy(liczba_osob, cennik):
return ( cennik['cena_sali'] if liczba_osob >= cennik['min_sala']
else liczba_osob * ( cennik["cena_grupowa"] if liczba_osob >= cennik["min_grupa"]
else cennik["cena_zwykla"] ) )
grupy_testowe = [ 1, 2, 5, 7, 9, 13, 20, 50, 140, 160 ]
c1 = {
"cena_zwykla" : 20,
"cena_grupowa" : 13,
"min_grupa" : 10,
"cena_sali" : 1600,
"min_sala" : 150
}
c2 = {
"cena_zwykla": 19,
"cena_grupowa": 14,
"min_grupa": 12,
"cena_sali": 1600,
"min_sala": 150
}
for g in grupy_testowe:
koszt = koszt_biletow_grupy(g, c1)
koszt2 = koszt_biletow_grupy(g, c2)
print(f"osób: {g} koszt: {koszt} koszt2: {koszt2}")
| true |
3a3cc0e3ad636c0e20f3844b2e8b4ee4ef37ab55 | Python | saileshnankani/QHacks2019 | /Models.py | UTF-8 | 5,200 | 3.3125 | 3 | [] | no_license | import collections
from Events import Event
from _datetime import datetime
EPSILON = 0.005
class Calendar:
def __init__(self):
self.week1 = Week()
self.week2 = Week()
self.week3 = Week()
self.week4 = Week()
self.week5 = Week()
class Week:
def __init_(self):
self.Monday = Day("Monday")
self.Tuesday = Day("Tuesday")
self.Wednesday = Day("Wednesday")
self.Thursday = Day("Thursday")
self.Friday = Day("Friday")
self.Saturday = Day("Saturday")
self.Sunday = Day("Sunday")
self.test = "test"
class Day:
def __init__(self, day):
self.day = day
self.time_slots = {1.0: [], 13.0: [], 1.5: [], 13.5: [], 2.0: [], 14.0: [], 2.5: [], 14.5: [],
3.0: [], 15.0: [], 3.5: [], 15.5: [], 4.0: [], 16.0: [], 4.5: [], 16.5: [],
5.0: [], 17.0: [], 5.5: [], 17.5: [], 6.0: [], 18.0: [], 6.5: [], 18.5: [],
7.0: [], 19.0: [], 7.5: [], 19.5: [], 8.0: [], 20.0: [], 8.5: [], 20.5: [],
9.0: [], 21.0: [], 9.5: [], 21.5: [], 10.0: [], 22.0: [], 10.5: [], 22.5: [],
11.0: [], 23.0: [], 11.5: [], 23.5: [], 12.0: [], 0.0: [], 12.5: [], 0.5: []}
#self.time_slots = {'1:00': [], '13:00': [], '1:30': [], '13:30': [], '2:00': [], '14:00': [], '2:30': [], '14:30': [],
# '3:00': [], '15:00': [], '3:30': [], '15:30': [], '4:00': [], '16:00': [], '4:30': [], '16:30': [],
# '5:00': [], '17:00': [], '5:30': [], '17:30': [], '6:00': [], '18:00': [], '6:30': [], '18:30': [],
# '7:00': [], '19:00': [], '7:30': [], '19:30': [], '8:00': [], '20:00': [], '8:30': [], '20:30': [],
# '9:00': [], '21:00': [], '9:30': [], '21:30': [], '10:00': [], '22:00': [], '10:30': [], '22:30': [],
# '11:00': [], '23:00': [], '11:30': [], '23:30': [], '12:00': [], '00:00': [], '12:30': [], '00:30': []}
# input: time of day
# returns list of items (event types) that are most to least frequent during that time; removes duplicates
def commonEvents (self, time):
timeArray = self.time_slots[time]
counts = collections.Counter(timeArray)
sortedEvents = []
for k in sorted(counts, key=counts.__getitem__, reverse=True):
sortedEvents.extend([k for _ in range(counts[k])])
sortedEvents_new = []
for item in sortedEvents:
if item not in sortedEvents_new:
sortedEvents_new.append(item)
return sortedEvents_new
# input: event type
# output: returns list of time lists that are most common for the event type
def commonTime (self, eventType):
bestTimes = []
for timeList in self.time_slots :
if eventType == (self.time_slots[timeList][0]):
if timeList not in bestTimes: bestTimes.append(timeList)
return bestTimes
# input: duration of event, and list of optimal times
# output: returns list of times that cover the duration of event
def timeBlock (self, duration, bestTimes):
goodTimes = []
timeUnits = duration / 30
i = 0
while (i < 48) : #loops through all times
a = 0
while (a < timeUnits and a < len(bestTimes)) :
if i == bestTimes[a]:
goodTimes.append(i)
a = a + 1
i = i + 0.5
return goodTimes
calendar = Calendar()
firstMeeting = Event("Meeting", datetime(2019, 1, 4, 15, 30), 30)
secondHomework = Event("Homework", datetime(2019, 1, 6, 12, 00), 60)
thirdHomework = Event("Homework", datetime(2019, 1, 8, 15, 30), 30)
fourthHomework = Event("Homework", datetime(2019, 1, 11, 15, 20), 30)
fifthHomework = Event("Homework", datetime(2019, 1, 13, 12, 00), 60)
sixthHomework = Event("Homework", datetime(2019, 1, 15, 15, 30), 30)
monday = Day('Monday')
tuesday = Day('Tuesday')
wednesday = Day('Wednesday')
thursday = Day('Thursday')
friday = Day('Friday')
saturday = Day('Saturday')
sunday = Day("Sunday")
monday.time_slots = {1.0: ["Meeting", "Studying", "Homework", "Meeting","Homework", "Homework"], 13.5: ["Studying", "Studying", "Stuyding", "Projects", "Errands"]}
tuesday.time_slots = {12.0: ["Meeting", "Errands", "Errands", "Errands", "Errands", "Meeting"], 13.5: ["TestPrep", "TestPrep", "TestPrep", "Projects", "Errands"]}
wednesday.time_slots = {1.0: ["Meeting", "Meeting", "Meeting", "Meeting","Homework", "Homework"], 13.5: ["Studying", "Studying", "Stuyding", "Projects", "Errands"]}
thursday.time_slots = {1.0: ["Meeting", "Studying", "Homework", "Meeting","Homework", "Homework"], 13.5: ["Studying", "Studying", "Stuyding", "Projects", "Errands"]}
friday.time_slots = {1.0: ["Meeting", "Studying", "Homework", "Meeting","Homework", "Homework"], 13.5: ["Studying", "Studying", "Stuyding", "Projects", "Errands"]}
days = [monday,tuesday,wednesday,thursday,friday]
for daysingular in days:
print(daysingular.timeBlock(firstMeeting.duration, daysingular.commonTime("Meeting")))
| true |
527cf37406555f96733ce06c78131c09831d87f2 | Python | daniyaniazi/OpenCV | /8.Basic_image_operations.py | UTF-8 | 743 | 3 | 3 | [] | no_license | import cv2
img= cv2.imread("images/FACE.jpeg")
print(img.shape)#tuple od no of rows ,cols,channels
print(img.size)#return total no of pixels is accessed
print(img.dtype)#return image datatype
b,g,r=cv2.split(img)
img= cv2.merge((b,g,r))
cv2.imshow("image",img)
# Resizing an image
imgResized=cv2.resize(img,(300,200))
#roi= region of interest
#area of an image you want to work with
# Cropping img[height,width]
area=img[123:240, 188:280]
print(area.shape)
img[5:122, 302:394]=area
# img[200:317, 200:292]=area
# img[:117, :92]=area
# paste=img[200:317, 200:292]
#dimesions should be excact
paste=img[5:122, 302:394]
print(paste.shape)
cv2.imshow("Resized image",imgResized)
cv2.imshow("image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
| true |
2b4ff4889f1031edf20440e85fb72454ab0fcdbb | Python | tokaevaAA/msu_python_spring2021 | /dz/dz3Contest/dz2_F.py | UTF-8 | 480 | 3.671875 | 4 | [] | no_license | def expand_seq(n, openb, closeb, s):
if (openb + closeb < 2 * n):
if openb < n:
Str = s + "("
yield from expand_seq(n, openb + 1, closeb, Str)
if closeb < openb:
Str = s + ")"
yield from expand_seq(n, openb, closeb + 1, Str)
else:
yield s
def brackets(n):
s = ""
yield from expand_seq(n, 0, 0, s)
if __name__ == "__main__":
n = int(input())
for i in brackets(n):
print(i)
| true |
9b7e50f7c72cb17a609f8b5a1399a28de4806265 | Python | pyrusx/learningpython | /dictionarypractice.py | UTF-8 | 306 | 3.21875 | 3 | [] | no_license |
def dicttest():
mydict = {}
mydict['hi'] = 2
mydict['bye'] = 50
'''
mydict hi -> 2
'''
mydict['hi'] = mydict['hi'] + 1
print(mydict)
'''
mydict {
"a" : 3
"b" : 1
}
JavaScript Object Notation
abaaaaaaa
'''
| true |
f40b9cbd28afd5428232fdef810dd402320c9400 | Python | sideroff/python-exercises | /01_basic/exercise_020.py | UTF-8 | 119 | 3.5 | 4 | [
"MIT"
] | permissive | def copies_of_string(string, number_of_copies):
return string * number_of_copies
print(copies_of_string("asd", 6)) | true |
a87b4d7a5656151f0ffb634c56eddd54ec642f5d | Python | kelvin-lu/ballet_ames_sim_lower_threshold | /ballet_ames_sim_lower_threshold/features/contrib/user_06/feature_37.py | UTF-8 | 262 | 2.625 | 3 | [] | no_license | from ballet import Feature
import ballet.eng
def calc_age(ser):
return 2018 - ser
input = "Yr Sold"
transformer = ballet.eng.SimpleFunctionTransformer(calc_age)
name = "Years since sold"
feature = Feature(input=input, transformer=transformer, name=name)
| true |
c93dc563ea1949b6da100813fc21b5da41154c7b | Python | kth496/Algorithm-study | /leetcode/BinaryTreeLevelOrderTraversal2.py | UTF-8 | 514 | 2.9375 | 3 | [] | no_license | class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
ret = []
q = deque()
q.append((root, 1))
if not root: return ret
while q:
cur, depth = q.popleft()
if not cur: continue
if len(ret) < depth:
level = []
ret.insert(0, level)
ret[-depth].append(cur.val)
q.append((cur.left, depth + 1))
q.append((cur.right, depth + 1))
return ret
| true |
204d8bef02e93c3d3a9902dddfe76d68c570ec8b | Python | tpltnt/tektronix222 | /tests/features/steps.py | UTF-8 | 1,793 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | from lettuce import *
import sys
sys.path.append('../../tektronix222/')
from tek222 import Tek222
@step(u'Given there is a working serial port')
def given_there_is_no_file_named(step):
assert True, 'yay!'
@step(u'When the object is initialized')
def when_the_object_is_initialized(step):
world.scope = Tek222('/dev/ttyU0')
assert 'Tek222' in str(world.scope.__class__), "object initialized %s" % world.scope.__class__
@step(u'Then it should open the given serial port')
def then_it_should_open_the_given_serial_port(step):
currentport = world.scope.portstr
assert '/dev/' in currentport, "first port taken %s" % currentport
@step(u'Given there is an initialized object')
def given_there_is_an_initialized_object(step):
assert 'Tek222' in str(world.scope.__class__), "object initialized %s" % world.scope.__class__
@step(u'When the oscilloscope is disconnected')
def when_the_oscilloscope_is_disconnected(step):
assert world.scope.disconnect, 'scope connection closed'
@step(u'Then the serial port should be closed')
def then_the_serial_port_should_be_closed(step):
# read should fail
assert None == world.scope.portstr , 'portstring after disconnect %s' % world.scope.portstr
@step(u'When the oscilloscope is unplugged')
def when_the_oscilloscope_is_unplugged(step):
assert False, 'This step must be implemented'
@step(u'Then an exception should be raised')
def then_an_exception_should_be_raised(step):
assert False, 'This step must be implemented'
@step(u'When the ID is queried')
def when_the_id_is_queried(step):
#world.idstring = world.scope.get_id()
assert False, 'trying to query ID'
@step(u'Then the ID should be returned')
def then_the_id_should_be_returned(step):
assert 'ID TEK-222' in world.idstring, 'ID string is %s' % world.idstring
| true |
fd6a9d8dc73897844d03068ed21e0b87194aa7a1 | Python | yhshin0/python_ruby | /06. Input_Output/python2.py | UTF-8 | 344 | 3.703125 | 4 | [] | no_license | in_str = input("아이디를 입력해주세요.\n")
# input()을 통해 들어오는 값의 형태는 str이므로 11과 일치하지 않음. 대신 "11"을 사용해야 함.
real_egoing = "11"
real_k8805 = "ab"
if real_egoing == in_str:
print("Hello!, egoing")
elif real_k8805 == in_str:
print("Hello!, k8805")
else:
print("Who are you?")
| true |
6ae5a2db7e973957213a2c9b89ca49dfa3633287 | Python | laomu/py_1709 | /1.Django_cursor/days05_总结/mysite/mytemp/views.py | UTF-8 | 995 | 2.59375 | 3 | [] | no_license | from django.shortcuts import render
from . import models
# Create your views here.
def index(request):
# 1. 传递第一种数据:简单的变量赋值
message = "欢迎访问本系统"
# 2. 传递
user = models.User(id=1, name="jerry")
# 3. 传递一个列表
msg_list = ["雪琪", "瓶儿", "小环"]
# 4. 传递一个字典
msg_dict = {"name": "拓跋晔", "age": 120}
# 2.1. 程序结构 if结构
login_user = "admin"
# 2.2. 程序结构 for结构
user1 = models.User(id=1, name="jerry")
user2 = models.User(id=2, name="tom")
user3 = models.User(id=3, name="shuke")
user4 = models.User(id=4, name="beita")
user5 = models.User(id=5, name="yuehao")
ulist = [user1, user2, user3, user4, user5]
#ulist = []
return render(request, "mytemp/index.html", {"user": user, "msg": message, "mlist": msg_list, "mdict": msg_dict, \
"luser": login_user, "ulist": ulist}) | true |
a548148bcff0a64c5f3cb93cffd3ba2a3232e25e | Python | ClaudeHuang/GitLearn | /python/mymodule_demo.py | UTF-8 | 145 | 2.546875 | 3 | [] | no_license | import mymodule
# 导入自制模块
mymodule.say_hi()
# 用.来访问模块中的成员(数据)
print('version', mymodule.__version__) | true |
fb2941c67ad9c917b8baf4acf5358f745d466916 | Python | rishirajsinghjhelumi/Coding-Templates | /SPOJ/7683.py | UTF-8 | 92 | 3.203125 | 3 | [] | no_license | t=input()
while t:
t-=1
x=raw_input().split()
print pow(int(x[0]),int(x[1],3),int(x[2]))
| true |
6c402152f987a8ed44d7a665cf9c39a20609782c | Python | Python-study-f/Algorithm-study_1H | /Algorithm_2021/April_2021/210425/1915_Largest_Square/1915_210422_ohzz.py | UTF-8 | 488 | 3.015625 | 3 | [] | no_license | # 가장 큰 정사각형 1915
n, m = map(int, input().split())
board = [list(map(int, list(input()))) for _ in range(n)]
dp = [[0] * m for _ in range(n)]
maxValue = 0
for i in range(n):
for j in range(m):
if board[i][j] == 1:
tmp = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])
dp[i][j] = tmp + 1
if maxValue < dp[i][j]:
maxValue = dp[i][j]
print(maxValue * maxValue)
# 42서울 마지막 과제랑 비슷했음.
| true |
25001ffe10b19ee5aefd67a95f730973b0461eca | Python | Mropat/Project-MTLS | /all_scripts/python/Sequence/BLOSUM/confusion_seq.py | UTF-8 | 4,117 | 2.5625 | 3 | [] | no_license | import pickle
import numpy as np
from sklearn.model_selection import cross_validate
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import recall_score
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
import matplotlib.pyplot as plt
def get_sets(filename):
prot_id = []
sequence = []
structure = []
padding = "0"*offset
with open(filename, "r") as fh:
line = fh.readline()
while line:
if line.startswith(">"):
prot_id.append(line.strip())
sequence.append(padding + fh.readline().strip() + padding)
structure.append(fh.readline().strip())
elif line.startswith("\n"):
fh.readline()
line = fh.readline()
return prot_id, sequence, structure
def train_set():
protid, sequence, structure = get_sets("datasets/3sstride_full.txt")
seq_vec = []
struct_vec = []
for i, protid in enumerate(protid[:split]):
if protid in redset:
continue
struct = structure[i]
seq = sequence[i]
for f in struct:
struct_vec.append(ord(f))
for res in range(offset, len(seq)-offset):
seq_windows = seq[res-offset: res+offset+1]
seq_vec.append(seq_windows)
x_vec = []
for window in seq_vec:
encoded_window = []
for r in window:
r = encdict[r]
encoded_window.extend(r)
x_vec.append(encoded_window)
y_vec = np.array(struct_vec)
x_vec = np.asarray(x_vec)
return x_vec, y_vec
def val_set():
protid, sequence, structure = get_sets("datasets/3sstride_full.txt")
xval_seq_vec = []
xval_struct_vec = []
for i, protid in enumerate(protid[split:]):
if protid in redset:
continue
xval_struct = structure[i+split]
xval_seq = sequence[i+split]
for f in xval_struct:
xval_struct_vec.append(ord(f))
for res in range(offset, len(xval_seq)-offset):
seq_windows = xval_seq[res-offset: res+offset+1]
xval_seq_vec.append(seq_windows)
xval_x_vec = []
for window in xval_seq_vec:
encoded_window = []
for r in window:
r = encdict[r]
encoded_window.extend(r)
xval_x_vec.append(encoded_window)
xval_y_vec = np.array(xval_struct_vec)
xval_x_vec = np.asarray(xval_x_vec)
return xval_x_vec, xval_y_vec
def train_validate_model():
x_vec, y_vec = train_set()
xval_x_vec, xval_y_vec = val_set()
clf = LinearSVC()
clf.fit(x_vec, y_vec)
meanacc = clf.score(xval_x_vec, xval_y_vec)
print("Mean accuracy: " + str(meanacc))
predicted = clf.predict(xval_x_vec)
target_names = ["Coil", "Helix", "Sheet"]
print(target_names)
print(classification_report(xval_y_vec, predicted, target_names=target_names))
cm = confusion_matrix(xval_y_vec, predicted)
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
plt.imshow(cm, cmap="Purples", interpolation='none')
plt.title("Random Forest BLOSUM " + "score: " +
str(meanacc*100)[:4]+"%")
plt.xticks(np.arange(0, 3), target_names)
plt.yticks(np.arange(0, 3), target_names)
plt.ylabel('True')
plt.xlabel('Predicted')
for i in range(3):
for j in range(3):
plt.text(i, j, str(cm[i, j].round(decimals=2) * 100)[:4]+"%",
horizontalalignment="center", color="white" if cm[i, j] > 0.5 else "black")
plt.show()
if __name__ == "__main__":
window = 21
offset = window//2
encdict = pickle.load(
open("all_scripts/python/Sequence/zero_ohedict.sav", "rb+"))
redset = pickle.load(open("all_scripts/python/red_set.sav", "rb+"))
split = 250
train_validate_model()
| true |
68d2738f3217743851219bbf79edc759299811c6 | Python | Dhivya-Ra/star | /sectwenty.py | UTF-8 | 215 | 3.1875 | 3 | [] | no_license | s=input("")
for i in s:
if ord(i)>=120 or ord(i)==121 or ord(i)==122:
b=chr(96+3-(122-ord(i)))
elif ord(i)==88 or ord(i)==89 or ord(i)==90:
b=chr(64+3-(90-ord(i)))
else:
b= chr(ord(i) + 3)
print(b,end="")
| true |
35b72b9974befd6347049668a099a9d061f4f1a1 | Python | MichaelSluydts/schnetpack | /custom/triplets/Samplers.py | UTF-8 | 5,220 | 2.84375 | 3 | [
"MIT"
] | permissive | from torch.utils.data.sampler import Sampler, RandomSampler
import itertools
import numpy as np
from torch.utils.data.sampler import BatchSampler
import random
import pdb
class SequentialNRepeatSampler(Sampler):
r"""Samples elements sequentially, always in the same order.
Arguments:
data_source (Dataset): dataset to sample from
"""
def __init__(self, data_source, N_repeats = 1):
self.data_source = data_source
self.N_repeats = N_repeats
def __iter__(self):
return iter(itertools.chain.from_iterable(itertools.repeat(x, self.N_repeats) for x in range(len(self.data_source))))
def __len__(self):
return len(self.data_source)*self.N_repeats
class RandomSequentialNRepeatSampler(Sampler):
r"""Samples elements sequentially, always in the same order.
Arguments:
data_source (Dataset): dataset to sample from
"""
def __init__(self, data_source, N_repeats = 1):
self.data_source = data_source
self.N_repeats = N_repeats
def __iter__(self):
iterator = list(itertools.chain.from_iterable(itertools.repeat(x, self.N_repeats) for x in range(len(self.data_source))))
random.shuffle(iterator)
return iter(iterator)
def __len__(self):
return len(self.data_source)*self.N_repeats
class RandomSampler_own(RandomSampler):
r"""Samples elements randomly. If without replacement, then sample from a shuffled dataset.
If with replacement, then user can specify ``num_samples`` to draw.
Arguments:
data_source (Dataset): dataset to sample from
num_samples (int): number of samples to draw, default=len(dataset)
replacement (bool): samples are drawn with replacement if ``True``, default=False
"""
def __len__(self):
return self.num_samples
class BalancedBatchSampler(BatchSampler):
"""
BatchSampler - from a MNIST-like dataset, samples n_classes and within these classes samples n_samples.
Returns batches of size n_classes * n_samples
"""
def __init__(self, dataset, n_classes, n_samples, train):
self.labels = np.array([s[1] for s in dataset.samples])
self.train = train
self.labels_set = list(set(self.labels))
self.label_to_indices = {label: np.where(self.labels == label)[0]
for label in self.labels_set}
for l in self.labels_set:
np.random.shuffle(self.label_to_indices[l])
self.used_label_indices_count = {label: 0 for label in self.labels_set}
self.count = 0
self.n_classes = n_classes
self.n_samples = n_samples
self.dataset = dataset
self.batch_size = self.n_samples * self.n_classes
def __iter__(self):
self.count = 0
while self.count + self.batch_size <= len(self.dataset):
classes = np.random.choice(self.labels_set, self.n_classes, replace=False)
indices = []
for class_ in classes:
indices.extend(self.label_to_indices[class_][
self.used_label_indices_count[class_]:self.used_label_indices_count[
class_] + self.n_samples])
self.used_label_indices_count[class_] += self.n_samples
if self.used_label_indices_count[class_] + self.n_samples > len(self.label_to_indices[class_]):
np.random.shuffle(self.label_to_indices[class_])
self.used_label_indices_count[class_] = 0
yield indices
self.count += self.n_classes * self.n_samples
def __len__(self):
return len(self.dataset) // self.batch_size
class BalancedBatchSamplerReplace(BatchSampler):
"""
BatchSampler - from a MNIST-like dataset, samples n_classes and within these classes samples n_samples.
Returns batches of size n_classes * n_samples
"""
def __init__(self, dataset, n_classes, n_samples, N_repeats = 100):
self.labels = np.array([s["_idx"] for s in dataset.samples])
self.labels_set = list(set(self.labels))
self.label_to_indices = {label: np.where(self.labels == label)[0]
for label in self.labels_set}
for l in self.labels_set:
np.random.shuffle(self.label_to_indices[l])
self.used_label_indices_count = {label: 0 for label in self.labels_set}
self.count = 0
self.n_classes = n_classes
self.n_samples = n_samples
self.dataset = dataset
self.batch_size = self.n_samples * self.n_classes
self.N_repeats = N_repeats
def __iter__(self):
self.count = 0
while self.count + self.batch_size <= len(self.dataset)*self.N_repeats:
classes = np.random.choice(self.labels_set, self.n_classes, replace=False)
indices = []
for class_ in classes:
indices.extend([self.label_to_indices[class_]]*self.n_samples)
yield indices
self.count += self.n_classes * self.n_samples
def __len__(self):
return len(self.dataset)*self.N_repeats//self.batch_size | true |
175dd4b9f20fd329dcf3429083a362b94d777d51 | Python | zeeke/gitlab-build-hooks | /trello_commit_to_card.py | UTF-8 | 2,933 | 2.734375 | 3 | [] | no_license | #! /usr/bin/env python
import gitlab
import configargparse
import re
from trello import TrelloClient
from trello.card import Card
def search_for_card_numbers(message):
return re.findall('#(\d+)', message)
def create_link_message(commit):
return "{} committed {}:\n{}".format(commit.author_name, commit.short_id, commit.message)
def create_gitlab_commit_url(project, commit):
return "{}/commit/{}".format(project.web_url, commit.id)
class IntegrationEngine:
def __init__(self, gitlab_client, trello_client):
self.gitlab = gitlab_client
self.trello_client = trello_client
def commit_link_to_trello_cards(self, opts):
commit = self.gitlab.project_commits.get(opts.gitlab_commit_id, project_id=opts.gitlab_project_id)
project = self.gitlab.projects.get(opts.gitlab_project_id)
for card_number in search_for_card_numbers(commit.message):
card = self.get_card_by_board_and_number(opts.trello_board_id, card_number)
self.attach_link_to_card(card, create_gitlab_commit_url(project, commit), create_link_message(commit))
def attach_link_to_card(self, card, url, message):
card.attach(name=message, url=url)
def get_card_by_board_and_number(self, board_id, card_number):
board = self.trello_client.get_board(board_id)
json_obj = board.client.fetch_json(
'/boards/' + board.id + '/cards/' + card_number,
)
return Card.from_json(board, json_obj)
class Options:
def __init__(self):
self.trello_token = None
self.trello_api_key = None
self.trello_board_id = None
self.gitlab_token = None
self.gitlab_commit_id = None
self.gitlab_project_id = None
def make_gitlab(self):
return gitlab.Gitlab('https://gitlab.com', self.gitlab_token)
def make_trello(self):
return TrelloClient(
api_key=self.trello_api_key,
# api_secret=self.trello_secret,
token=self.trello_token,
# token_secret='your-oauth-token-secret'
)
if __name__ == "__main__":
parser = configargparse.ArgParser(description='Add a comment to the trello card specified in the commit message.')
parser.add('--trello-api-key', env_var='TRELLO_API_KEY', required=True)
parser.add('--trello-token', env_var='TRELLO_TOKEN', required=True, help='a valid aythorization token for trello')
parser.add('--trello-board-id', env_var='TRELLO_BOARD_ID', required=True, help='a trello board id')
parser.add('--gitlab-token', env_var='GITLAB_TOKEN', required=True)
parser.add('--gitlab-commit-id', env_var='CI_BUILD_REF', required=True)
parser.add('--gitlab-project-id', env_var='CI_PROJECT_ID', required=True)
options = Options()
parser.parse_args(namespace=options)
IntegrationEngine(options.make_gitlab(), options.make_trello()).commit_link_to_trello_cards(options)
| true |
847ea7dd9a9ee89e34c51f294da25802464358a0 | Python | crvernon/mosartwmpy | /mosartwmpy/utilities/inherit_docs.py | UTF-8 | 646 | 3.140625 | 3 | [
"CC0-1.0"
] | permissive | import types
def inherit_docs(cls: object) -> object:
"""A class decorator to automatically inherit docstrings from parents.
Args:
cls (object): The class that needs docstrings
Returns:
object: The class with docstrings inherited from parents
"""
for name, func in vars(cls).items():
if isinstance(func, types.FunctionType) and not func.__doc__:
for parent in cls.__bases__:
parfunc = getattr(parent, name, None)
if parfunc and getattr(parfunc, '__doc__', None):
func.__doc__ = parfunc.__doc__
break
return cls | true |
91f3e228e5e580c7f4ce3e7f69de0af84ac95a01 | Python | digitic/CV-Thesis-Celeste | /FinalEdges.py | UTF-8 | 1,170 | 2.71875 | 3 | [] | no_license | import numpy
import cv2
#Determine source video
cap = cv2.VideoCapture("CelesteVideos/Level1.mp4")
frame_width = int(cap.get(3) / 2)
frame_height = int(cap.get(4) / 2)
#Output file creation
out = cv2.VideoWriter('CelesteVideos/edgeDetection.mp4',cv2.VideoWriter_fourcc('M','P','4','V'), 30, (frame_width,frame_height), False)
while(cap.isOpened()):
#ret is a boolean of if a frame was successfully captured
ret, frame = cap.read()
#frameTaken = (frameTaken + 1) % FRAMEGAP
if (ret): #and frameTaken == 0:
frame = cv2.pyrDown(frame)
#Edge detection test
edges = cv2.Canny(frame, 200, 450)
"""
width = int(edges.shape[1] * scale_percent / 100)
height = int(edges.shape[0] * scale_percent / 100)
dim = (width, height)
# resize image
resized_edges = cv2.resize(edges, dim, interpolation = cv2.INTER_AREA)
"""
out.write(edges)
#cv2.imshow('Canny edge detection', edges)
#Break if capture ends.
else:
break
#Break if q is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows() | true |
0d4f086384f16c6614d4e9e6bfecbbb4766c1d75 | Python | verovanie/Student-database-management | /backEnd_studentDatabase.py | UTF-8 | 2,594 | 2.859375 | 3 | [] | no_license | import sqlite3
def connection():
try:
conn=sqlite3.connect("student.db")
except:
print("cannot connect to the database")
return conn
def studentData() :
con = connection()
con = sqlite3.connect("student.db")
cur = con.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS student(
ID TEXT PRIMARY KEY ,
Firstname TEXT ,
Surname TEXT ,
DoB TEXT ,
Gender TEXT ,
Branch TEXT ,
Father TEXT ,
Address TEXT ,
Mobile INTEGER)''')
con.commit()
con.close()
def addStudentRec(ID , Firstname , Surname , DoB, Branch , Gender ,Father ,Address ,Mobile) :
con = connection()
con = sqlite3.connect("student.db")
cur =con.cursor()
cur.execute("INSERT INTO student VALUES(?,?,?,?,?,?,?,?,?)",(ID , Firstname , Surname , DoB, Branch , Gender ,Father ,Address ,int(Mobile)))
con.commit()
con.close()
def viewData() :
con = connection()
con = sqlite3.connect("student.db")
cur =con.cursor()
cur.execute("SELECT * FROM student ")
row = cur.fetchall()
con.close()
return row
def deleteRec(ID) :
con = connection()
con = sqlite3.connect("student.db")
cur =con.cursor()
cur.execute("DELETE FROM student WHERE id = ? " , (ID))
con.commit()
con.close()
def searchData(ID = "" , Firstname = "" , Surname = "" , DoB = "" , Branch = "" ,\
Gender = "" , Father ="" ,Address = "" ,Mobile = "" ) :
con = connection()
con = sqlite3.connect("student.db")
cur = con.cursor()
cur.execute("SELECT * FROM student WHERE ID = ? , Firstname = ? , \
Surname = ? , DoB = ? ,Branch = ? , Gender = ? ,Father = ? , Address = ? ,Mobile = ? ",\
(ID , Firstname , Surname , DoB, Branch , Gender ,Father ,Address ,Mobile))
row = cur.fetchall()
con.close()
return row
def updateData(ID , Firstname = "" , Surname = "" , DoB = "" , Branch = "",\
Gender = "" , Father ="" ,Address = "" ,Mobile = "" ) :
con = connection()
con = sqlite3.connect("student.db")
cur = con.cursor()
cur.execute("UPDATE student WHERE ID = ? , Firstname = ? , \
Surname = ? , DoB = ? ,Branch = ? , Gender = ? ,Father = ? ,\
Address = ? ,Mobile = ? " , ( Firstname , Surname , DoB, Branch ,\
Gender ,Father ,Address ,Mobile ,ID))
con.close()
studentData()
| true |
0f3526c8835d7d19bcac3068b5ee805b90f5eaf3 | Python | hao6699/sort_python | /连续子数组最大和.py | UTF-8 | 285 | 3.109375 | 3 | [] | no_license | def FindGreatestSumOfSubArray(self, array):
# write code here
totalsum = array[0]
max_sum = array[0]
for i in range(1,len(array)):
totalsum = max(totalsum+array[i],array[i])
max_sum = max(totalsum,max_sum)
return max_sum
| true |
902747a9848890dafe6270314cf040e7aa4ba21b | Python | namanpujari/microstate_correlation | /utils.py | UTF-8 | 7,517 | 3.4375 | 3 | [] | no_license | """Some utility functions for microstate hydrogen bond analysis.
"""
from __future__ import print_function
# Globals
import sys
import time
from functools import wraps
GROTTHUSS = ["GLU", "ASP", "SER", "THR", "HIS", "TYR", "ASN", "GLN", "HOH", "PAA", "PDD"]
# Cofactors in the heme group
# The function below returns a boolean value based on whether a given residue is within
# the GROTTHUSS list defined above. It is very easy to see how this works. The 'residue in
# GROTTHUS' statement basically checks if the arg of the function is within the list and returns
# a True/False value.
def is_grotthuss(residue):
return residue in GROTTHUSS
# Functions
def function_timer(function):
# wraps is a wrapper decorator provided by functools that basically makes the wrapped
# function the wrapper. In the interest of clarity, the @wraps(function) statement basically
# does this: once function_timer is used as a decorator, like @function_timer before the declaration
# of a function, calling function() and executing print(function.__name__) will actually
# return the name of the function, not the name of the wrapper in the function_timer decorator, which
# is 'function_timer'.
@wraps(function)
# Wrapper with the name 'function_timer'
def function_timer(*args, **kwargs):
# Use the python 'time' module to obtain the time right before the function
# is executed.
t0 = time.time()
# Execute function and provide result to a variable that is named 'result'
result = function(*args, **kwargs)
# Obtain the time right after the execution of the function. This can be used
# to calculate the total time
t1 = time.time()
# Prints the name of the function executed, and the total time taken
print("Total time running %s: %2.2f seconds" %
(function.__name__, t1 - t0))
return result
# Returns an unexecuted instance of the function as an object. This is callable
return function_timer
# Can be repeatedly called to print the progress of a routine. It prints to the terminal repeatedly
# and removes the previous bar from the terminal in the same process, and makes an aesthetic loading
# screen look.
def print_progress_bar (count, total):
"""
Create and update progress bar during a loop.
Parameters
----------
iteration : int
The number of current iteration, used to calculate current progress.
total : int
Total number of iterations
Notes
-----
Based on:
http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console
"""
# length of the bar is defined to be 60, and is essentially just the PHYSICAL
# length of the loading bar.
bar_len = 60
# Length of the blackened (filled in) segment of the bar is mathematically calculated
# to be count/total * 60, so that the cap is 60, the physical length of the bar.
filled_len = int(round(bar_len * count / float(total)))
# The percent progress rounded to 1 decimal place
percents = round(100.0 * count / float(total), 1)
# \u2588 is a a filled in black bar (may also be white depending on terminal color)
# The line below creates the bar, and used * to print a certain str multiple times. For example
# "naman" * 3 is >> namannamannaman
bar = "o" * filled_len + '-' * (bar_len - filled_len)
sys.stdout.write('Progress |%s| %s%3s Done\r' % (bar, percents, '%'))
sys.stdout.flush()
if count == total:
print()
# Depending on the substate given, generates clusters of residues.
def generate_cluster_dictionary(sub_state):
"""
Generate a dictionary containing key clusters and corresponding residues
for a given sub_state.
Parameters
----------
sub_state : string
Specifify
"""
# Lists of residues in each cluster
clust_dict = {
"BNC" : ['CUBK9500', 'HE3K9300'],
"PLS" : ['PDDK9102', 'PAAK9301', 'PDDK9302', 'TYRA0175',
'ASPA0407', 'HISA0411', 'ASPB0229', 'ASPA0412', 'THRA0337', 'GLUB0254',
'SERB0218', 'PAAK9101', 'ARGA0052', 'TYRA0414', 'SERA0497', 'SERA0498'],
"EXT" : ['HISA0093', 'SERA0156', 'THRA0187', 'SERA0168', 'THRA0100',
'TYRB0262', 'SERA0186', 'GLUA0182', 'ASPA0188', 'ASPA0485', 'GLUA0488'],
"GLU" : ["GLUA0286"],
"EXT_EXP" : ['HISA0093', 'GLUA0182', 'ASPA0188', 'ASPA0485', 'GLUA0488'],
"EXT_INT" : ['SERA0168', 'THRA0100']
}
# Only works if substate defined is either f1, f2 or f4.
if sub_state not in ["f1", "f2", "f4"]:
sys.exit("Only f1, f2 and f4 substates are currently supported.")
# If substate is valid, and is either f1 or f4, then simply returns the dictionary above.
if sub_state == "f1" or sub_state == "f4":
return clust_dict
# However, if the substate is f3, then it will return a modified version of the dictionary
# above.
else:
# using the .keys() method for dictionaries, converts the keys of the cluster dictionary
# into a list. Then iterates across those keys, accessing the data in each residue
# cluster.
for k in list(clust_dict.keys()):
# Initiate updated_cluster_residue list
updated_cluster_residues = []
# res is a variable that holds each item in the value of each key in the dictonary.
# Since each value is a list, then res is simply each, individual item in the list
for res in clust_dict[k]:
# For the given cluster, if the given reside has an "A" as its fourth character,
# then obtain the residue number and subtract 11. Append that modified residue
# number in front of "04d", and then append that segment after the first three
# characters in the original residue name. Add that value to the updated_cluster_residue
# list.
if res[3] == "A":
resnum = int(res[4:])
modified_resnum = resnum - 11
str_resnum = "%04d" % (modified_resnum)
modified_res = res[0:4] + str_resnum
updated_cluster_residues.append(modified_res)
else:
# If the 4th character is not "A", then append the original residue name
# to the list.
updated_cluster_residues.append(res)
# Update the new list under the original key.
clust_dict[k] = updated_cluster_residues
return clust_dict
def generate_path_pdb(conformers, source_pdb, prefix= "path"):
"""generate a pdb file from path data
Parameters
----------
conformers : TYPE
Description
source_pdb : TYPE
Description
prefix : str, optional
Description
"""
with open(source_pdb, 'r') as pdb:
pdb_lines = pdb.readlines()
with open(prefix + ".pdb", "w") as f:
for conf in conformers:
for l in pdb_lines:
if l.split()[3] == conf[0:3]:
#print l.split()[3], l.split()[4]
#print conf[0:3], conf[5:]
if l.split()[4] == conf[5:] or l.split()[4] == conf[5:11] + "000":
#print l.split()[3], l.split()[4]
#print conf[0:3], conf[5:]
f.write(l) | true |
f509c4ebf1553d9e8311ada8c34e1550a5df2ccf | Python | Mkrolick/MachineLearningExploration | /DeepLearningBook/Chapter 1/simple_net.py | UTF-8 | 1,388 | 2.8125 | 3 | [] | no_license | import tensorflow as tf
from tensorflow import keras
# Network and training
epochs = 200
batch_size = 128
verbose = 1
nb_classes = 10 # number of outputs = number of digits
n_hidden = 128
validation_split = 0.2 # how much train is reserved for validation
mnist = tf.keras.datasets.mnist
(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
#print(len(X_train[0][0][0]))
X_train = X_train.reshape((60000, 784))
X_train = X_train.astype('float32')
X_test = X_test.reshape((10000, 784))
X_test = X_test.astype('float32')
X_train, X_test = X_train / 255.0, X_test / 255.0
Y_train = keras.utils.to_categorical(Y_train, nb_classes)
Y_test = keras.utils.to_categorical(Y_test, nb_classes)
model = keras.models.Sequential()
model.add(keras.layers.Dense(128, input_shape=(784,), name="Dense1", activation='relu'))
model.add(keras.layers.Dropout(0.3))
model.add(keras.layers.Dense(128, name="Dense2", activation='relu'))
model.add(keras.layers.Dropout(0.3))
model.add(keras.layers.Dense(10, name="Dense3", activation='softmax'))
model.summary()
model.compile(optimizer = 'SGD', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, verbose=verbose, validation_split=validation_split)
test_loss, test_accuracy = model.evaluate(X_test, Y_test)
print(f"test accuracy: {test_accuracy}, test loss: {test_loss}")
| true |
e5d8950624a0a0a57e7ba5783ce7a8f685a8404e | Python | vaishak-github/python-progs | /Employee_record_management_system/search_record.py | UTF-8 | 710 | 3.96875 | 4 | [] | no_license | def search(lst, eid, choice):
if choice == 1:
for i in lst:
if i['emp_id'] == eid:
print("The details for employee with id:",eid, "\n Id:", i['emp_id'], "|| Name:", i['emp_name'],
"|| Email:", i['emp_email'], "|| DOB:", i['emp_dob'])
return i
if choice == 2:
a = 1
# print("The records matching ", eid, "are:\n ", a, ")")
result = [print("The details for employee with Name:",eid,"\n Id:", i['emp_id'], "|| Name:", i['emp_name'],
"|| Email:", i['emp_email'], "|| DOB:", i['emp_dob'])
for i in lst if i['emp_name'].startswith(eid)]
return result
| true |
ee25317037c1b95554ae59e47a915d46a16fbe42 | Python | ankurdave/graphframes | /python/graphframes/tests.py | UTF-8 | 2,793 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
if sys.version_info[:2] <= (2, 6):
try:
import unittest2 as unittest
except ImportError:
sys.stderr.write('Please install unittest2 to test with Python 2.6 or earlier')
sys.exit(1)
else:
import unittest
from pyspark import SparkContext
from pyspark.sql import DataFrame, SQLContext
from .graphframe import GraphFrame
class GraphFrameTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.sc = SparkContext('local[4]', cls.__name__)
cls.sql = SQLContext(cls.sc)
@classmethod
def tearDownClass(cls):
cls.sc.stop()
cls.sc = None
cls.sql = None
class GraphFrameTest(GraphFrameTestCase):
def setUp(self):
super(GraphFrameTest, self).setUp()
localVertices = [(1,"A"), (2,"B"), (3, "C")]
localEdges = [(1,2,"love"), (2,1,"hate"), (2,3,"follow")]
v = self.sql.createDataFrame(localVertices, ["id", "name"])
e = self.sql.createDataFrame(localEdges, ["src", "dst", "action"])
self.g = GraphFrame(v, e)
def test_construction(self):
g = self.g
vertexIDs = map(lambda x: x[0], g.vertices.select("id").collect())
assert sorted(vertexIDs) == [1, 2, 3]
edgeActions = map(lambda x: x[0], g.edges.select("action").collect())
assert sorted(edgeActions) == ["follow", "hate", "love"]
def test_motif_finding(self):
g = self.g
motifs = g.find("(a)-[e]->(b)")
assert motifs.count() == 3
self.assertSetEqual(set(motifs.columns), {"a", "e", "b"})
def test_bfs(self):
g = self.g
paths = g.bfs("name='A'", "name='C'")
self.assertEqual(paths.count(), 1)
self.assertEqual(paths.select("v1.name").head()[0], "B")
paths2 = g.bfs("name='A'", "name='C'", edgeFilter="action!='follow'")
self.assertEqual(paths2.count(), 0)
paths3 = g.bfs("name='A'", "name='C'", maxPathLength=1)
self.assertEqual(paths3.count(), 0)
| true |
054759bb301e5177b0dc1956a568413060535a7b | Python | DonaldWhyte/notes-parallel-scientific-computing | /CourseworkWorksheets/coursework2/task3/compute_efficiency.py | UTF-8 | 1,263 | 2.890625 | 3 | [] | no_license | import sys
def efficiency(serialTime, parallelTime, numProcesses):
return serialTime / (numProcesses * parallelTime)
if __name__ == "__main__":
# Parse command line arguments
if len(sys.argv) < 3:
sys.exit("Usage: python {0} <inputRuntimeFile> <outputEfficiencyFile>".format(sys.argv[0]))
inputRuntimeFile = sys.argv[1]
outputEfficiencyFile = sys.argv[2]
# Load input file
runtimes = []
with open(inputRuntimeFile, "r") as f:
for line in f.readlines():
fields = line.split()
runtimes.append( (int(fields[0]), float(fields[1])) )
# Find serial execution time
serialTime = None
for rt in runtimes:
if rt[0] == 1:
serialTime = rt[1]
if not serialTime:
sys.exit("Serial execution time not found in data file")
# Compute efficiencies
efficiencies = []
for rt in runtimes:
efficiencies.append( (rt[0], efficiency(serialTime, rt[1], rt[0])) )
# Write speedups to a file
with open(outputEfficiencyFile, "w") as f:
for ef in efficiencies[:-1]: # to prevent extra empty line being written
f.write("{0} {1}\n".format(*ef))
f.write("{0} {1}".format(efficiencies[-1][0], efficiencies[-1][1]))
| true |
b0640c6d477c374d80ad08f032962a0dc052d0cd | Python | fanshi118/NYC_Restaurant_Health_Score_Prediction | /scripts/311_parser.py | UTF-8 | 1,510 | 2.84375 | 3 | [] | no_license | __author__ = 'Shi Fan'
import pandas as pd, numpy as np
if __name__=='__main__':
# dataset can be downloaded from here
# https://data.cityofnewyork.us/Social-Services/311-Service-Requests-from-2010-to-Present/erm2-nwe9
# set filter: "Agency is DOHMH" and "Location Type contains Restaurant"
# click "Export" and "Download as CSV"
df = pd.read_csv('../input/311_DOHMH_Restaurant.csv')
# cleaning data
df = df[df['Incident Zip']!='NY']
df['Incident Zip'] = df['Incident Zip'].astype(float)
df = df.dropna(subset=['Incident Zip'])
df['Incident Zip'] = df['Incident Zip'].astype(int)
df = df[(df['Incident Zip']>10000) & (df['Incident Zip']<20000)]
# feature engineering
comp_types = ['Total Complaints','Food Establishment', 'Food Poisoning', 'Smoking']
cols = ['num_complaints','num_food_est','num_food_poi','num_smoking']
df_311 = pd.DataFrame(index=df.groupby('Incident Zip').mean().index)
# start parsing
for i in range(len(comp_types)):
if comp_types[i]=='Total Complaints':
df_311[cols[i]] = df.groupby('Incident Zip').count()['Unique Key'].values
else:
df_temp = df[df['Complaint Type']==comp_types[i]].groupby('Incident Zip').aggregate(len)['Unique Key'].reset_index().set_index('Incident Zip')
df_311 = df_311.merge(df_temp, how='left', left_index=True, right_index=True, sort=True).rename(columns={'Unique Key':cols[i]})
del df_311.index.name
df_311.fillna(0, inplace=True)
# finish parsing, write the dataframe to csv
df_311.to_csv('../output/311_parsing_result.csv') | true |
6bc3f9a86dc87725252ff971d212b76dd6a46e92 | Python | GreatStephen/MyLeetcodeSolutions | /Remove All Adjacent Duplicates In String/stack.py | UTF-8 | 275 | 3.109375 | 3 | [] | no_license | class Solution:
def removeDuplicates(self, S: str) -> str:
# 甚至比2pointer还慢
deq = collections.deque()
for i,v in enumerate(S):
if len(deq)>0 and deq[-1]==v: deq.pop()
else: deq.append(v)
return ''.join(deq) | true |
1979d73a9a323a74e1e6f1fd858cb0738afa9ace | Python | marvjaramillo/ulima-intro210-clases | /s062-grupal/menu.py | UTF-8 | 520 | 3.171875 | 3 | [] | no_license | OPCION_COTIZAR = 1
OPCION_PARTICIPAR = 2
OPCION_DETENER = 3
OPCION_CREDITOS = 4
lista_opciones = [ "Cotizar envio",
"Participar por un premio",
"Detener aplicacion",
"Creditos"
]
def mostrar_menu():
print("*" * 20)
print("*" * 20)
for i in range(len(lista_opciones)):
print((i + 1), ". ", lista_opciones[i])
print("*" * 20)
def obtener_opcion():
opcion = int(input("Seleccione una opcion: "))
return opcion
| true |
0a0e1a2e67497d30a0d7301aa6c98db663feb58a | Python | perrozzi/cmg-cmssw | /FWCore/Services/bin/profilereader.py | UTF-8 | 4,001 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env python
"""module to read profiling information generated by the SimpleProfiling Service
"""
import os
class FunctionInfo(object):
"""Holds the profiling information about one function
"""
def __init__(self,attrList):
self.address =attrList[0]
self.name =os.popen("c++filt "+attrList[-1]).read().strip()
self.leafCount = int(attrList[1])
self.countOfFunctPlusChildWithRecursion = int(attrList[2])
self.countOfFunctPlusChild = int(attrList[3])
self.fractionInFunctionOnly = float(attrList[4])
self.fractionInPath = float(attrList[5])
self.__callerTemp = dict()
self.__calleeTemp = dict()
def addCaller(self,caller,weight):
#print caller.name, weight
self.__callerTemp.setdefault(caller.address,[0,caller])[0]+=weight
def addCallee(self,callee,weight):
self.__calleeTemp.setdefault(callee.address,[0,callee])[0]+=weight
def normalize(self):
self.callerList = list()
self.calleeList = list()
for caller in self.__callerTemp.keys():
(count,_caller) = self.__callerTemp[caller]
self.callerList.append((float(count)/self.countOfFunctPlusChildWithRecursion,_caller))
for callee in self.__calleeTemp.keys():
(count,_callee) = self.__calleeTemp[callee]
self.calleeList.append((float(count)/self.countOfFunctPlusChildWithRecursion,_callee))
self.callerList.sort()
self.callerList.reverse()
self.calleeList.sort()
self.calleeList.reverse()
class Path(object):
def __init__(self,attrList):
self.count = int(attrList[0])
self.functionIds = [int(x) for x in attrList[1:] if x != '\n']
class ProfileData(object):
def __init__(self,filesToUseInfo,feedBackStream=None):
#try to determine the filePrefix from the value given
# since caller may have given us just one of the files
# instead of the prefix to the files
(dir,base) = os.path.split(filesToUseInfo)
uniqueID = base.split('_')[1]
filePrefix = os.path.join(dir,"profdata_"+uniqueID+"_")
if feedBackStream:
feedBackStream.write('reading file: '+filePrefix+'names')
nameFile = file(filePrefix+'names','r')
self.idToFunctionInfo = dict()
self.functionNameToId = dict()
feedbackIndex = 0
for line in nameFile:
if feedBackStream and (0 == feedbackIndex % 100):
feedBackStream.write('.')
feedbackIndex +=1
infoList = line.split('\t')
self.idToFunctionInfo.setdefault( int(infoList[0]), FunctionInfo(infoList[1:]))
self.functionNameToId.setdefault(self.idToFunctionInfo[int(infoList[0])].name, int(infoList[0]))
if feedBackStream:
feedBackStream.write('\nreading file: '+filePrefix+'paths')
pathFile = file(filePrefix+'paths','r')
self.paths = list()
feedbackIndex = 0
for line in pathFile:
if feedBackStream and (0 == feedbackIndex % 100):
feedBackStream.write('.')
feedbackIndex +=1
line.strip()
path = Path( line.split(' ')[1:])
self.paths.append(path)
caller = None
for funcId in path.functionIds:
func = self.idToFunctionInfo[funcId]
if caller:
func.addCaller(caller,path.count)
caller.addCallee(func,path.count)
caller = func
feedbackIndex = 0
if feedBackStream:
feedBackStream.write('\nprocessing data:')
for x in self.idToFunctionInfo.items():
if feedBackStream and (0 == feedbackIndex % 100):
feedBackStream.write('.')
feedbackIndex +=1
x[1].normalize()
if __name__ == '__main__':
import sys
profile = ProfileData(sys.argv[1])
print profile.idToFunctionInfo
| true |
bc4f2cb71599ee23c84c3b22602ac30dd62e64f3 | Python | Bandydan/Python_scripts | /factor.py | UTF-8 | 355 | 3.625 | 4 | [] | no_license | #!/usr/bin/python2.7
def factorial(x):
y = 1
n = x
if x > 1:
while x - y > 0:
n = n * (x - y)
y +=1
return n
elif x == 0 or x == 1:
n = 1
return n
def factor(x):
if x == 0 or x == 1:
return 1
result = x
counter = x
while counter > 1:
result *= counter - 1
counter -= 1
return result
print factor(12)
print factorial(12)
| true |
02b4fb21388f7f8ce2f8977f82492dbf00c152cf | Python | mattsains/powermonitor | /GPIOInterface/powermonitor.py | UTF-8 | 3,945 | 2.90625 | 3 | [] | no_license | import spidev
import ctypes
import time
class PowerMonitor:
def __init__(self):
self.spidev = spidev.SpiDev()
self.spidev.open(0, 1)
def _send_data(self, command, receive_bytes, *data):
"""Internal wrapper function used to format the command byte"""
commandbyte = 0b10100010 | (command << 2)
checksum = (((command >> 2) & 1) ^
((command >> 1) & 1) ^
((command >> 0) & 1))
commandbyte += checksum
response = []
for packet in [commandbyte] + list(data) + receive_bytes * [0]:
time.sleep(0.01)
response += self.spidev.xfer([packet])
response = response[len(data) + 1:]
if receive_bytes == 1:
return response[0]
else:
return response
def handshake(self):
"""Performs a handshake with the microcontroller. It is recommended to do this make sure the microcontroller is
actually there. Returns a map with keys 'HIGH_CURRENT', 'OVER_CURRENT' and 'NO_VOLTAGE', or false if no valid
response was received"""
response = self._send_data(0b000, 1)
if response & 1 << 7 and not response & 1:
return {
"HIGH_CURRENT": bool(response & (1 << 1)),
"OVER_CURRENT": bool(response & (1 << 2)),
"NO_VOLTAGE": bool(response & (1 << 3))
}
else:
return False
def read_raw(self):
"""Returns two numbers representing the raw measurements from the current and voltage sensor"""
response = self._send_data(0b001, 4)
return {
"CURRENT": response[0] << 8 | response[1],
"VOLTAGE": response[2] << 8 | response[3]
}
def read_watts(self):
"""Returns the watts being used right now"""
response = self._send_data(0b010, 2)
return ctypes.c_int16(response[0] << 8 | response[1]).value
def read_power_factor(self):
"""Returns the measured power factor of the device (between -1 and 1)"""
return self._send_data(0b011, 1) - 128
def read_calibration(self):
"""Returns a map containing the calibration paramaters. See specification for details
If something goes wrong, will throw an exception"""
response = self._send_data(0b100, 9)
sum = 0
for byte in response[:-1]:
sum += byte
if sum & 0xFF != response[-1]:
raise Exception("IO Error", "The calibration parameter checksum was incorrect")
return {
"FILTER_STRENGTH": response[0],
"SIGNAL_OFFSET": (response[1] << 8) | response[2],
"CURRENT_SCALE": (response[3] << 8) | response[4],
"VOLTAGE_SCALE": (response[5] << 8) | response[6],
"VOLTAGE_PHASE_DELAY": response[7]
}
def write_calibration(self, filter_strength, signal_offset, current_scale, voltage_scale, voltage_phase_delay):
"""Writes calibration parameters to the microcontroller"""
signal_offset_high=signal_offset>>8
signal_offset_low=signal_offset&0xFF
current_scale_high=current_scale>>8
current_scale_low=current_scale&0xFF
voltage_scale_high=voltage_scale>>8
voltage_scale_low=voltage_scale&0xFF
sum = (filter_strength + signal_offset_high + signal_offset_low + current_scale_high + current_scale_low + voltage_scale_high + voltage_scale_low + voltage_phase_delay) % 256
response = self._send_data(0b101, 1, filter_strength, signal_offset_high, signal_offset_low, current_scale_high, current_scale_low, voltage_scale_high, voltage_scale_low, voltage_phase_delay, sum)
if response != 0b10101010:
raise Exception("IO Error",
"Did not receive calibration write confirmation from the microcontroller - did it actually "
"write?")
| true |
ad1dbd21a8cb809c3858cc368a3d333d943f8f21 | Python | eletromagcomp/projeto3 | /projeto3_plus.py | UTF-8 | 9,421 | 2.734375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 20:03:28 2019
@author: hiro
"""
import numpy as np
import matplotlib.pyplot as plt
import time
import math
from celluloid import Camera
from scipy.optimize import newton
from mpl_toolkits.axes_grid1 import make_axes_locatable
#%% HIROCOISAS###########################################
#%% VARIÁVEIS
def n_malha():
return 100
def amplitude():
return 10
def v_max(): #Entre 0 e 1
return 0.1
def time_step():
return 1
def frequencia():
return v_max()/amplitude()
def periodo():
return 2*np.pi/frequencia()
#%% FUNÇÃO DA POSIÇÃO DA CASA
def charge_position(t_ret):
x = 0.5
y = 0
z = amplitude()*np.cos(t_ret*frequencia())
xyz_charge = np.array((x, y, z))
return xyz_charge
#%% FUNÇÃO DA VELOCIDADE DA CARGA
def charge_velocity(t_ret):
v_x = 0
v_y = 0
v_z = -v_max() * np.sin(t_ret*frequencia())
v_charge = np.array((v_x, v_y, v_z))
return v_charge
#%% FUNÇÃO DA ACELERAÇÃO DA CARGA
def charge_acceleration(t_ret):
a_x = 0
a_y = 0
a_z = -(v_max()**2)/amplitude() * np.cos(t_ret*frequencia())
a_charge = np.array((a_x, a_y, a_z))
return a_charge
#%% CAMPO ELETRICO
def electric_field(t_ret, xyz):
xyz_charge = charge_position(t_ret)
R = xyz - xyz_charge
R_norm = np.linalg.norm(R)
R_hat = R/R_norm
v_charge = charge_velocity(t_ret)
v_charge_norm = np.linalg.norm(v_charge)
a_charge = charge_acceleration(t_ret)
u = R_hat - v_charge
electric = R_norm/(np.dot(R, u))**3 * ((1 - v_charge_norm**2)*u + np.cross(R, np.cross(u, a_charge)))
return electric
#%% SIMULAÇÃO
def simulation(t):
def t_retarded(t_ret,*args):
x,y,z = xyz
dist = np.sqrt(((x - 0.5)**2 + y**2 + (z - amplitude()*np.cos(frequencia()*t_ret))**2))
return dist - (t - t_ret)
def t_retarded_prime(t_ret, *args):
x,y,z = xyz
dist = np.sqrt(((x - 0.5)**2 + y**2 + (z - amplitude()*np.cos(frequencia()*t_ret))**2))
return (v_max()*np.sin(t_ret*frequencia())*(z - amplitude()*np.cos(t_ret*frequencia())))/dist + 1
x = np.arange(-n_malha()/2, n_malha()/2)
y = 0
z = np.arange(-n_malha()/2, n_malha()/2)
electric_x = np.zeros((n_malha(), n_malha()))
electric_y = np.zeros((n_malha(), n_malha()))
electric_z = np.zeros((n_malha(), n_malha()))
guess = 1
for i in range(n_malha()):
for j in range(n_malha()):
xyz = np.array((x[i], y, z[j]))
t_ret = newton(t_retarded, guess, fprime=t_retarded_prime, args=(xyz, t), tol=10**(-3), maxiter = 100)
guess = t_ret
electric_x[i, j], electric_y[i, j], electric_z[i, j] = electric_field(t_ret, xyz)
electric_xyz = np.array([electric_x, electric_y, electric_z])
return electric_xyz
#%% PLOT
def plot(electric_x,electric_z):
x = np.arange(-n_malha()/2, n_malha()/2)
z = np.arange(-n_malha()/2, n_malha()/2)
X, Z = np.meshgrid(x, z)
x_charge, y_charge, z_charge = charge_position(t)
#Carga
ax_stream.plot(x_charge, z_charge, 'bo')
ax_quiver.plot(x_charge, z_charge, 'bo')
ax_both.plot(x_charge, z_charge, 'bo')
ax_radiation.plot(x_charge+ n_malha()/2 + 0.5, z_charge + n_malha()/2 , 'bo')
#Streamplot
ax_stream.streamplot(z, x, np.transpose(electric_x), np.transpose(electric_z), color = 'black', arrowstyle='-', density = 1.5)
ax_both.streamplot(z, x, np.transpose(electric_x), np.transpose(electric_z), color = 'black', arrowstyle='-', density = 1.5)
#Quiver
U = electric_z
V = electric_x
U = U / np.sqrt(U**2 + V**2);
V = V / np.sqrt(U**2 + V**2);
ax_quiver.quiver(Z, X, V, U, pivot='mid', color='r', units='inches')
ax_both.quiver(Z, X, V, U, pivot='mid', color='r', units='inches')
#Radiação
x_charge, y_charge, z_charge = charge_position(t)
Rz = Z - z_charge
Rx = X - x_charge
radiation = np.abs(Rz*electric_z + Rx*electric_x)
im = ax_radiation.pcolor(radiation.transpose(), cmap=plt.cm.inferno, vmin=0, vmax=1)
divider = make_axes_locatable(ax_radiation)
cax = divider.append_axes('right', size='5%', pad=0.05)
figure_radiation.colorbar(im, cax=cax)
ax_stream.set_aspect('equal')
ax_quiver.set_aspect('equal')
ax_both.set_aspect('equal')
camera_stream.snap()
camera_quiver.snap()
camera_both.snap()
camera_radiation.snap()
#%% CÁLCULOS
#Criar as figuras para os plots
figure_stream, ax_stream = plt.subplots()
figure_stream.set_size_inches((7,7))
camera_stream = Camera(figure_stream)
figure_quiver, ax_quiver = plt.subplots()
figure_quiver.set_size_inches((7,7))
camera_quiver = Camera(figure_quiver)
figure_both, ax_both = plt.subplots()
figure_both.set_size_inches((7,7))
camera_both = Camera(figure_both)
figure_radiation, ax_radiation = plt.subplots()
figure_radiation.set_size_inches((7,7))
camera_radiation = Camera(figure_radiation)
#%% KIRBYCOISAS #############################################
#cria malha de dimensao 201 por 201
def malha():
m = np.zeros((201,201,2), dtype= 'int')
for i in range(201):
for j in range(201):
m[i][j] = np.array([i-100,j-100])
return m
#chute inicial para o tempo retardado
def chute0():
return 0.0
def tolerancia():
return 0.001
#fazemos unidades com q=c=1.
#amplitude do movimento
def amplitude():
return 10.0
#frequencia angular
def omega():
return 0.01
#PS: para termos sempre v<c devemos ter omega*amplitude < c=1
#posicao da carga em funcao do tempo
def pos_carga(t):
b = amplitude()
w = omega()
x=0.0
z = b*np.cos(w*t)
r = np.array([x,z])
return r
#velocidade da carga
def vel_carga(t):
b = amplitude()
w = omega()
vx = 0.0
vz = -b*w*np.sin(w*t)
v = np.array([vx,vz])
return v
#calcula a funcao f(t_ret) da qual queremos as raizes
def f(r,t,t_ret):
dist = np.sqrt( np.sum((r-pos_carga(t_ret))**2 ) )
fun = t - t_ret - dist
return fun
#calcula a derivada da funcao f(t_ret) da qual queremos as raizes
def df(r,t,t_ret):
dist = np.sqrt( np.sum((r-pos_carga(t_ret))**2 ) )
dfun = np.sum( (r-pos_carga(t_ret))*vel_carga(t_ret) )/dist - 1
return dfun
#calcula o tempo retardado para um dado ponto (x,z,t)
def tempo_retardado(r,t, chute):
tol = tolerancia()
efe = f(r,t,chute)
while efe > tol:
chute = chute - f(r,t,chute)/df(r,t,chute)
efe = f(r,t,chute)
return chute
#calcula o campo eletrico para um dado instante de tempo
def campo_eletrico(t):
ponto = malha()
campo = np.zeros((201,201,2), dtype= 'float')
w = omega()
chute = chute0() #chute inicial para t_ret
for i in range(101,200):
for j in range(0,200):
t_ret = tempo_retardado(ponto[i][j], t, chute)
r = ponto[i][j]
dR = r - pos_carga(t_ret) #separacao no tempo retardado
dist = np.sum(dR**2) #distancia ao tempo retardado
v = vel_carga(t_ret) #velocidade no tempo retardado
a = -w**2*(r-dR) #aceleracao no tempo retardado
u = dR/dist - v
#calcula o campo por aquela formula dado o tempo retardado. Eu uso alguma peculiaridades do nosso sistema (movimento unidimensional no eixo z "[1]" pra otimizar umas contas, abrindo umas componentes explicitamente)
campo[i][j] = ( (1-v[1]**2)*u*dist + np.array([dR[1],-dR[0]])*a[1]*r[0] )/np.sum(dR*u)**3
#espelha o campo no eixo x
campo[200-i][j][0] = -campo[i][j][0]
campo[200-i][j][1] = campo[i][j][1]
return campo
#%% RODA O CAMPO DO HIRO
#Definição do intervalo de tempo que vamos considerar, rodando pra um período é suficiente
t_interval = np.arange(0, 2*periodo(), periodo()/30)
start = time.time()
#Rodando para os diferentes intervalos de tempo
for t in t_interval:
electric_xyz = simulation(t)
electric_x, electric_y, electric_z = electric_xyz
plot(electric_x, electric_z)
print('t = ' + str(t) + ' de ' + str(t_interval[-1]))
end = time.time()
tempo = end - start
print(tempo)
#%% RODA O CAMPO DO KIRBY
pi = math.pi
tempo = np.linspace(0.0,4*pi/omega(),60) #cria a sequencia temporal onde sao calculados os campos varrendo 3 periodos
k=0
for t in tempo:
k=k+1
print(k,t)
field = campo_eletrico(t)
electric_x = np.transpose(field[:,:,0])
electric_z = np.transpose(field[:,:,1])
plot(electric_x,electric_z)
#%%
#Cria o gif
animation_stream = camera_stream.animate()
animation_quiver = camera_quiver.animate()
animation_both = camera_both.animate()
animation_radiation = camera_radiation.animate()
animation_stream.save('n' + str(n_malha()) + '_a' + str(amplitude()) + '_v' + str(v_max()) + '_stream.gif' , writer = 'imagemagick')
animation_quiver.save('n' + str(n_malha()) + '_a' + str(amplitude()) + '_v' + str(v_max()) + '_quiver.gif', writer = 'imagemagick')
animation_both.save('n' + str(n_malha()) + '_a' + str(amplitude()) + '_v' + str(v_max()) + '_both.gif' , writer = 'imagemagick')
animation_radiation.save('n' + str(n_malha()) + '_a' + str(amplitude()) + '_v' + str(v_max()) + '_radiation.gif' , writer = 'imagemagick')
| true |
350cffbe67c00486ab930e46dd42d5a133187fb4 | Python | cchaas-uwaterloo/UW-SDIC_distributed_data_aggregation | /Applications/OCT14_LMS_analysis.py | UTF-8 | 2,809 | 2.546875 | 3 | [] | no_license | from Downloaders import readLMSData
from Operations import calculateRMS
from Util import segmentList
import os
# Get data file path
# Local data files
'''
target_file_path = os.path.dirname(__file__)
dir_index = target_file_path.rfind('/')
target_file_path = target_file_path[:dir_index]
# Config_
target_file_path = target_file_path + '/Data/APM_OCT14_2020escalator1.txt'
'''
# Other data files
target_file_path = 'C:/Users/camer/Desktop/Fall 2020 URI/oct_7_site/Data/APM_OCT14_2020_GATE120_SPEED1.txt'
print(target_file_path)
# Config_
print("Reading Input1 data")
raw_data_list_Input1 = readLMSData(target_file_path, 'Input1')[0]
print("Reading Input2 data")
raw_data_list_Input2 = readLMSData(target_file_path, 'Input2')[0]
# Get the RMS value for the entire run
run_rms_Input1 = calculateRMS(raw_data_list_Input1)
run_rms_Input2 = calculateRMS(raw_data_list_Input2)
# segment the run into 10 second intervals and get rms values for each interval
sample_rate_Hz = 40960
segment_length = 10
print("segmenting Input1 data:")
segments_Input1 = segmentList(raw_data_list_Input1, (sample_rate_Hz*segment_length))
print("segmenting Input2 data:")
segments_Input2 = segmentList(raw_data_list_Input2, (sample_rate_Hz*segment_length))
segments_Input1_rms = []
segments_Input2_rms = []
for segment in segments_Input1:
segment_rms = calculateRMS(segment)
segments_Input1_rms.append(segment_rms)
for segment in segments_Input2:
segment_rms = calculateRMS(segment)
segments_Input2_rms.append(segment_rms)
# write to console
print('-------------------------------------------')
print('SUMMARY')
print('Overall run indicators:')
print('Input1:')
print('RMS: ', run_rms_Input1.value)
print('Input2:')
print('RMS:', run_rms_Input2.value)
print(' ')
print('Segmented run indicators:')
print('Input1:')
print('RMS:')
for value in segments_Input1_rms:
print(value.value)
print('Input2:')
print('RMS:')
for value in segments_Input2_rms:
print(value.value)
# write to file
# Config_
file_name_ = 'OCT14_2020escalator1_analysis.txt'
cur_path = os.path.dirname(__file__)
file_path = os.path.relpath(('..\\Data\\' + file_name_), cur_path)
file = open(file_path, 'x')
file.write('-------------------------------------------\n')
file.write('SUMMARY\n')
file.write('Overall run indicators:\n')
file.write('Input1:\n')
file.write('RMS: ' + str(run_rms_Input1.value) + '\n')
file.write('Input2:\n')
file.write('RMS:' + str(run_rms_Input2.value) + '\n')
file.write('\n')
file.write('Segmented run indicators: (' + str(segment_length) + 's) \n')
file.write('Input1:\n')
file.write('RMS:\n')
for value in segments_Input1_rms:
file.write(str(value.value) + '\n')
file.write('Input2:\n')
file.write('RMS:\n')
for value in segments_Input2_rms:
file.write(str(value.value) + '\n')
file.close()
| true |
d4fccf043ca14933d80d6617a73bab0996f78939 | Python | gemst1/Blog | /TensorBoard/arbitrary_image.py | UTF-8 | 1,245 | 2.671875 | 3 | [] | no_license | from datetime import datetime
import io
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot']
logdir = './logs/image/train_data/' + datetime.now().strftime("%Y%m%d-%H%M%S")
file_writer = tf.summary.create_file_writer(logdir)
def plot_to_image(figure):
# convert the matplotlib figure to png image
buf = io.BytesIO()
plt.savefig(buf, format='png')
plt.close(figure)
buf.seek(0)
image = tf.image.decode_png(buf.getvalue(), channels=4)
# add bath dimension
image = tf.expand_dims(image, 0)
return image
def image_grid():
figure = plt.figure(figsize=(10, 10))
for i in range(25):
plt.subplot(5, 5, i+1, title=class_names[train_labels[i]])
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
return figure
figure = image_grid()
with file_writer.as_default():
tf.summary.image("Training data", plot_to_image(figure), step=0)
| true |
be8025afb910a1bafed34a3c776d6555d35078d1 | Python | l2radamanthys/TxtMerge | /textmerge.py | UTF-8 | 5,300 | 3.015625 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import Tkinter as tk
import ttk
from tkFileDialog import askopenfilenames, asksaveasfilename
import tkMessageBox
import os
import random
from merge import MergeProcess
class MainFrame(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack()
self.files = []
btn_select_files = tk.Button(self, text="Agregar Archivos", command=self.add_files, pady=10)
btn_select_files.grid(row=0, column=1, pady=5)
self.file_list = tk.Listbox(self, width=30)
self.file_list.grid(row=1, column=0, rowspan=4, columnspan=2, padx=5)
btn_up = tk.Button(self, text="Subir", command=self.move_up, width=8, pady=10)
btn_up.grid(row=1, column=2, padx=5)
btn_down = tk.Button(self, text="Bajar", command=self.move_down, width=8, pady=10)
btn_down.grid(row=2, column=2)
btn_delete = tk.Button(self, text="Quitar", command=self.delete_item, width=8, pady=10)
btn_delete.grid(row=3, column=2)
btn_clear = tk.Button(self, text="Limpiar", command=self.clear_list, width=8, pady=10)
btn_clear.grid(row=4, column=2)
btn_merge = tk.Button(self, text="Unir Archivos", command=self.merge_files, pady=10)
btn_merge.grid(row=5, column=1, pady=5)
def add_files(self):
"""
Agregar Archivos
"""
files = askopenfilenames(multiple=True)
if os.name == 'nt':
#es windows por alguna razon no convierte el string en una tupla
#por lo que hay que hacerlo a mano una referencia del problema
# http://bugs.python.org/issue5712
files = self.master.tk.splitlist(files)
for _file in files:
fname = _file.split('/')[-1]
row = [fname, _file]
if 1:#row in self.files: #no se permiten archivos duplicados
self.files.append(row)
self.file_list.insert(tk.END, fname)
def delete_item(self):
"""
Quita el item seleccionado
"""
try:
pos = int(self.file_list.curselection()[0])
self.files.pop(pos)
#fname = self.file_list.get(pos)
self.file_list.delete(pos, pos)
print pos,fname
except:
pass
def move_up(self):
"""
Sube una posicion el item seleccionado
"""
pos = int(self.file_list.curselection()[0])
if pos != 0:
fname = self.file_list.get(pos)
self.file_list.delete(pos)
self.file_list.insert(pos-1, fname)
self.file_list.selection_set(pos-1)
aux = self.files[pos]
self.files[pos] = self.files[pos-1]
self.files[pos-1] = aux
def move_down(self):
"""
Deciende una posicion el item seleccionado
"""
pos = int(self.file_list.curselection()[0])
if pos != self.file_list.size()-1:
fname = self.file_list.get(pos)
self.file_list.delete(pos)
self.file_list.insert(pos+1, fname)
self.file_list.selection_set(pos+1)
aux = self.files[pos]
self.files[pos] = self.files[pos+1]
self.files[pos+1] = aux
def clear_list(self):
"""
Limpiar Listado de archivos
"""
self.file_list.delete(0, tk.END)
self.files = []
def merge_files(self):
"""
Seleccionar destion y llamar al processo de union de archivos
"""
if 1:#len(self.files) > 0:
_output = asksaveasfilename()
if _output == "":
_output = "salida.txt"
main = tk.Toplevel(self.master)
_files = []
for _file in self.files:
_files.append(_file[1])
_output = open(_output, 'w')
progress = MergeProgress(root=main, files=_files, output=_output)
class MergeProgress(tk.Frame):
"""
Ventana de Progreso de copiado
"""
def __init__(self, root, files=[], output='salida.txt'):
tk.Frame.__init__(self, master=root)
self.files = files
self.output = output
self.size = len(self.files)
self.pack()
lbl = tk.Label(self, text="Uniendo Archivos..")
lbl.grid(row=0, pady=10, padx=10, sticky=tk.W)
self.gauge = ttk.Progressbar(self, orient=tk.HORIZONTAL, length=300, maximum=self.size)
self.gauge.grid(row=1, padx=10)
separator = ttk.Separator(self)
separator.grid(row=2, pady=10)
#iniciar union
self.merge = MergeProcess(self.files, self.output, self.gauge)
self.merge.start()
self.get_merge_status()
def get_merge_status(self):
"""
Unir
"""
if self.merge.is_run:
self.master.after(100, self.get_merge_status)
else:
self.gauge.stop()
self.output.close()
tkMessageBox.showinfo('Informacion', 'Finalizo el Copiado')
self.master.destroy()
if __name__ == "__main__":
main = tk.Tk()
main.title('Text Merge')
app = MainFrame(main)
main.mainloop()
| true |
b43bc5d49b850d9c3f543212953d45dc1b72f7c8 | Python | jlyang1990/LeetCode | /800. Climbing Stairs II.py | UTF-8 | 912 | 2.96875 | 3 | [] | no_license | # n stairs, exactly k steps, every step: 1, 2 or 3 stairs
# O(nk) time, O(n) space
def climbStairs(n, k):
if n < 3:
count = [1]*n
else:
count = [1]*3+[0]*(n-3)
for i in range(k-1):
for j in range(n-1, -1, -1):
if j == 0:
count[j] = 0
elif j == 1:
count[j] = count[j-1]
elif j == 2:
count[j] = count[j-1] + count[j-2]
else:
count[j] = count[j-1] + count[j-2] + count[j-3]
return count[n-1]
# n stairs, at most k steps, every step: 1, 2 or 3 stairs
# O(nk) time, O(n) space
def climbStairs(n, k):
if n < 3:
count = [1]*n
else:
count = [1]*3+[0]*(n-3)
count_total = count[n-1]
for i in range(k-1):
for j in range(n-1, -1, -1):
if j == 0:
count[j] = 0
elif j == 1:
count[j] = count[j-1]
elif j == 2:
count[j] = count[j-1] + count[j-2]
else:
count[j] = count[j-1] + count[j-2] + count[j-3]
count_total += count[n-1]
return count_total | true |
05a1e28e30e02063ce1eff81ae954f4be76a6814 | Python | ArtsenMachin/audithon.task20 | /models/models.py | UTF-8 | 9,956 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | import psycopg2
import json
from pydantic import BaseModel, ValidationError
from typing import List, Optional
conn = psycopg2.connect(database="audithon", user="postgres",
password="4432", host="26.173.145.160", port="5434")
cursor = conn.cursor()
class json_serializable(BaseModel):
type = "FeatureCollection"
features = [{}]
def add_features(self, name, value, id):
self.features[id][name] = value
def add_new_features_item(self):
self.features.append({})
#
# Шаблонные функции на получение данных из БД
# ----------------------------------------------------------------------------------
#
def get_data(query):
cursor.execute(query)
results = cursor.fetchall()
return results
def jsonify(some_tuple):
results = json.dumps(some_tuple, ensure_ascii=False,
separators=(',', ': '))
return results
#
# ----------------------------------------------------------------------------------
#
def map_baloon_data():
baloon_data = get_data(
"""select
co.object_id,
co.reestr_number_cval,
co.cultural_object_name_cval,
cast(((coordinates_cval->>'coordinates')::jsonb ->> 0)::varchar as varchar(100)) coordinates_cval,
case when co.image_jsonval is not null then co.image_jsonval ->> 'url'
else 'https://cdn.discordapp.com/attachments/824553156905533491/825070117393793044/08cd6ad2398e2cc415bed2c5acd76b33.png' end image,
cc.culture_cathegory_shortname_cval,
cc.color_cval,
os.state_name_cval,
row_number () over () rn,
cast(((coordinates_cval->>'coordinates')::jsonb ->> 1)::varchar as varchar(100)) coordinates_cval2
from dev.cultural_object_hist co
left join dev.culture_cathegory_hist cc
on cc.culture_cathegory_id = co.culture_cathegory_id_nval
left join dev.object_state_hist os
on os.state_id = co.state_id_nval
left join dev.object_type_hist ot
on ot.object_type_id = co.object_type_id_nval
left join dev.region_hist rh
on rh.region_id = co.region_id_nval
left join dev.unesco_affiliation_hist ua
on ua.unesco_affiliation_id = co.unesco_affiliation_id_nval
where co.coordinates_cval is not null"""
)
baloon_inf = json_serializable()
object_id = 0
for okn_object in baloon_data:
object_id_default = okn_object[0]
coordinates = [float(okn_object[9]), float(okn_object[3])]
balloon_content_header = okn_object[2] + \
"<br><span class='description'>" + okn_object[1] + "</span>"
balloon_content_body = "<img src=" + \
okn_object[4] + \
" width='200'><br/> <b>Значение:</b>" + okn_object[5]
balloon_content_footer = "Состояние культурного объекта: <br/>" + \
okn_object[7]
hint_content = "Значение: "+okn_object[5]
icon_caption = okn_object[2]
color = okn_object[6]
baloon_inf.add_features("type", "Feature", object_id)
baloon_inf.add_features("id", object_id_default, object_id)
baloon_inf.add_features(
"geometry", {"type": "Point", "coordinates": coordinates}, object_id)
baloon_inf.add_features("properties", {
"balloonContentHeader": balloon_content_header,
"balloonContentBody": balloon_content_body,
"balloonContentFooter": balloon_content_footer,
"hintContent": hint_content,
"iconCaption": icon_caption}, object_id)
baloon_inf.add_features("options", {"preset": color}, object_id)
object_id += 1
baloon_inf.add_new_features_item()
del baloon_inf.features[-1]
return(jsonify(baloon_inf.dict()))
def regions_get():
return jsonify(get_data(
"select * from test.region_hist rh "
"order by rh.region_id"
))
def region_and_cult_value(region, value, state):
if region == 'all':
regions = 0
else:
regions = int(region)
return get_data(
"select "
"cc.culture_cathegory_name_cval, "
"rh.region_name_cval, "
"coalesce(count(c.object_id), 0) cath_name_count, "
"os.state_name_cval "
'from dev.cultural_object_hist c '
"full join dev.map_region_cathegory mrc "
"on mrc.culture_cathegory_id = c.culture_cathegory_id_nval "
"and mrc.region_id = c.region_id_nval "
"and mrc.state_id = c.state_id_nval "
"right join dev.culture_cathegory_hist cc "
"on cc.culture_cathegory_id = mrc.culture_cathegory_id "
"right join dev.region_hist rh "
"on mrc.region_id = rh.region_id "
"right join dev.object_state_hist os "
"on os.state_id = mrc.state_id "
"where (%i = 0 or mrc.region_id = %i) "
"and (cc.system_name_cval = '%s' or '%s' = 'all') "
"and (os.system_name_cval = '%s' or '%s' = 'all') "
"group by os.state_name_cval, cc.culture_cathegory_name_cval, rh.region_name_cval "
"order by rh.region_name_cval, cc.culture_cathegory_name_cval "
% (regions, regions, value, value, state, state)
)
def diagrams(regions, cult_value, state):
# все регионы, все значение, 1 состояние
if (regions == 'all' and cult_value == 'all' and state != 'all'):
cul_value = region_and_cult_value('all', 'all', state)
json_inf = json_serializable()
object_id = 0
for i in range(0, len(cul_value), 4):
json_inf.add_features("category", cul_value[i][1], object_id)
json_inf.add_features("first", cul_value[i+3][2], object_id)
json_inf.add_features("second", cul_value[i+1][2], object_id)
json_inf.add_features("third", cul_value[i+2][2], object_id)
json_inf.add_features("fourth", cul_value[i][2], object_id)
json_inf.add_new_features_item()
object_id += 1
del json_inf.features[-1]
return(jsonify(json_inf.features))
# 1 регион, все значения, 1 состояние
elif (regions != 'all' and cult_value == 'all' and state != 'all'):
cul_value = region_and_cult_value(regions, 'all', state)
json_inf = json_serializable()
json_inf.add_features("category", cul_value[0][1], 0)
json_inf.add_features("first", cul_value[3][2], 0)
json_inf.add_features("second", cul_value[1][2], 0)
json_inf.add_features("third", cul_value[2][2], 0)
json_inf.add_features("fourth", cul_value[0][2], 0)
return(jsonify(json_inf.features))
# 1 регион, 1 значение, 1 состояние
elif (regions != 'all' and cult_value != 'all' and state != 'all'):
cul_value = region_and_cult_value(regions, cult_value, state)
return(str(cul_value[0][2]))
# 1 регион, все значения, все состояния
elif (regions != 'all' and cult_value == 'all' and state == 'all'):
cul_value = region_and_cult_value(regions, 'all', 'all')
json_inf = json_serializable()
object_id = 0
for i in range(0, len(cul_value), 4):
json_inf.add_features("category", cul_value[i][1], 0)
json_inf.add_features("first", cul_value[i+2][2], 0)
json_inf.add_features("second", cul_value[i+1][2], 0)
json_inf.add_features("third", cul_value[i+3][2], 0)
json_inf.add_features("fourth", cul_value[i][2], 0)
json_inf.add_new_features_item()
object_id += 1
del json_inf.features[-1]
return(jsonify(json_inf.features))
# все регионы, 1 значение, все состояния
elif (regions == 'all' and cult_value != 'all' and state == 'all'):
cul_value = region_and_cult_value('all', cult_value, 'all')
json_inf = json_serializable()
object_id = 0
for i in range(0, len(cul_value), 4):
json_inf.add_features("category", cul_value[i][1], 0)
json_inf.add_features("first", cul_value[i+2][2], 0)
json_inf.add_features("second", cul_value[i+1][2], 0)
json_inf.add_features("third", cul_value[i+3][2], 0)
json_inf.add_features("fourth", cul_value[i][2], 0)
json_inf.add_new_features_item()
object_id += 1
del json_inf.features[-1]
return(jsonify(json_inf.features))
# все регионы, 1 значение, 1 состояние
elif (regions == 'all' and cult_value != 'all' and state != 'all'):
return 4
# все регионы, все значения, все состояния
elif (regions == 'all' and cult_value == 'all' and state == 'all'):
cul_value = region_and_cult_value('all', 'all', state)
json_inf = json_serializable()
object_id = 0
for i in range(0, len(cul_value), 4):
json_inf.add_features("category", cul_value[i][1], object_id)
json_inf.add_features("first", cul_value[i+3][2], object_id)
json_inf.add_features("second", cul_value[i+1][2], object_id)
json_inf.add_features("third", cul_value[i+2][2], object_id)
json_inf.add_features("fourth", cul_value[i][2], object_id)
json_inf.add_new_features_item()
object_id += 1
del json_inf.features[-1]
return(jsonify(json_inf.features))
# 1 регион, 1 значение, все состояния
else:
return 1
def add_new(name, typeo, importance, adress, coordinate, comment, data):
cursor.execute("insert into dev.user_form_new_okn(object_name_cval, object_type_id_nval, culture_cathegory_id_nval, full_address_cval, coordinates_cval, comment_cval, image_path_cval) "
" values('%s',%i,%i,'%s','%s','%s','%s')" %(name, int(typeo), int(importance), adress,
coordinate, comment, data)
)
conn.commit() | true |
16c6139b84bb24b74258b86d80ba17feb98f80b1 | Python | kkujawinski/git-pre-push-hook | /tests/mock_repo/test_file.py | UTF-8 | 108 | 3.46875 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | def add(x , y):
return x+ y
def substract(x, y):
return x - 1
def multiply(x, y):
return x*y
| true |
4f2b1dbf80cc66a7119ed201a0bb8392f3d317fe | Python | mluker/azure-dns-to-terraform | /tfdnsgen.py | UTF-8 | 2,850 | 2.96875 | 3 | [] | no_license | #!/usr/bin/env python3
import argparse
import csv
import json
parser = argparse.ArgumentParser(description='Terraform Code Generator')
parser.add_argument('--rg', action="store", dest='rg', required=True, help='resource group name')
parser.add_argument('--zone', action="store", dest='zone', required=True, help='name of the DNS zone')
parser.add_argument('--tffile', action="store", dest='tffile', required=True, help='output file to write the generated code')
parser.add_argument('--csvfile', action="store", dest='csvfile', required=True, help='input file to read from')
args = parser.parse_args()
def csv_file_to_tf_code(file, zone, rg):
json_string = csv_file_to_json(file)
records = json.loads(json_string)
tf_code = ""
for record in records:
if record["Type"] == "CNAME":
tf_code += parse_cname(record, zone, rg) + '\n'
elif record["Type"] == "A":
tf_code += parse_arecord(record, zone, rg) + '\n'
return tf_code
def csv_file_to_json(file, pretty = False):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
field = reader.fieldnames
for row in reader:
csv_rows.extend([{field[i]:row[field[i]] for i in range(len(field))}])
return json.dumps(csv_rows, sort_keys=False, indent=4, separators=(',', ': ')) if pretty else json.dumps(csv_rows)
def write_json_file(data, json_file, pretty = True):
with open(json_file, "w") as f:
f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': ')) if pretty else json.dumps(data))
def write_file(data, file):
with open(file, "w") as f:
f.write(data)
def generate_terraform_name(zone, name):
return name.replace(".", "_").replace("-", "_") + "_" + zone.replace(".", "_")
def parse_cname(record, zone, rg):
r = 'resource "azurerm_dns_cname_record" "%s" {\n' % generate_terraform_name(zone, record['Name'])
r += ' zone_name = "%s"\n' % zone
r += ' resource_group_name = "%s"\n' % rg
r += ' ttl = "%s"\n' % record['TTL']
r += ' record = "%s"\n' % record['Value']
r += ' provider = azurerm.prod\n'
r += '}\n'
return r
def parse_arecord(record, zone, rg):
r = 'resource "azurerm_dns_a_record" "%s" {\n' % generate_terraform_name(zone, record['Name'])
r += ' zone_name = "%s"\n' % zone
r += ' resource_group_name = "%s"\n' % rg
r += ' ttl = "%s"\n' % record['TTL']
r += ' records = ["%s"]\n' % record['Value']
r += ' provider = azurerm.prod\n'
r += '}\n'
return r
def main():
csv_file = args.csvfile
tf_file = args.tffile
zone = args.zone
rg = args.rg
tf_code = csv_file_to_tf_code(csv_file, zone, rg)
print(csv_file_to_json(csv_file, True))
print(tf_code)
write_file(tf_code, tf_file)
if __name__ == "__main__":
main()
| true |
863404ab835692810310b5bfb9c424c665582ad5 | Python | ashishkashinath/Grad_School_Courses | /CS461_ECE422/MP References/mnwrhsn/CS461_UIUC_FA17-master/mp1/sol_1.1.2.2.py | UTF-8 | 570 | 2.875 | 3 | [] | no_license | import sys
from Crypto.Cipher import AES
ciphertext_file = sys.argv[1]
key_file = sys.argv[2]
iv_file = sys.argv[3]
output_file = sys.argv[4]
with open(ciphertext_file) as f:
ciphertext = f.read().strip().decode('hex')
f.close()
with open(key_file) as f:
key = f.read().strip().decode('hex')
f.close()
with open(iv_file) as f:
IV = f.read().strip().decode('hex')
f.close()
cipher = AES.new(key, AES.MODE_CBC, IV)
plaintext = cipher.decrypt(ciphertext)
print plaintext
with open(output_file, 'w') as f:
f.write(plaintext)
f.close()
| true |
5d92a5a4edd7ce7c0a0821c0addd6a8fd61e5c28 | Python | martimunicoy/peleffy-benchmarks | /peleffybenchmarktools/dihedrals/dihedralhandler.py | UTF-8 | 5,425 | 2.765625 | 3 | [
"MIT"
] | permissive | """
This module contains classes and functions to handle dihedral benchmarks.
"""
class DihedralBenchmark(object):
"""
It defines a certain dihedral and allows to run several benchmarks
on it.
"""
def __init__(self, dihedral_atom_indexes, molecule):
"""
It initializes a DihedralBenchmark object.
Parameters
----------
dihedral_atom_indexes : tuple[int]
The indexes of atoms involved in the dihedral
molecule : an peleffy.topology.Molecule
The peleffy's Molecule object
"""
# Hide peleffy output
from peleffy.utils import Logger
logger = Logger()
logger.set_level('WARNING')
molecule.assert_parameterized()
self._atom_indexes = dihedral_atom_indexes
self._molecule = molecule
self._forcefield = molecule.forcefield
def generate_dihedral_conformers(self, resolution):
"""
Given a resolution, it generates all the possible conformers
that come out when rotating the dihedral's rotatable bond.
Parameters
----------
resolution : float
The resolution, in degrees, that is applied when rotating
the dihedral rotatable bond. Default is 30 degrees
Returns
-------
rdkit_mol : an rdkit.Chem.rdchem.Mol object
The RDKit's Molecule object with the conformers that were
generated
"""
from copy import deepcopy
from rdkit.Chem import rdMolTransforms
rdkit_mol = deepcopy(self.molecule.rdkit_molecule)
conformer = rdkit_mol.GetConformer()
for angle in range(0, 360, resolution):
rdMolTransforms.SetDihedralDeg(conformer, *self.atom_indexes,
angle)
rdkit_mol.AddConformer(conformer, assignId=True)
# Remove initial conformer (which is repeated)
rdkit_mol.RemoveConformer(conformer.GetId())
return rdkit_mol
def save_dihedral_conformers(self, resolution=30):
"""
It saves the dihedral conformers that are obtained when
rotating the dihedral's rotatable bond with a certain resolution.
Parameters
----------
resolution : float
The resolution, in degrees, that is applied when rotating
the dihedral rotatable bond. Default is 30 degrees
"""
mol_with_conformers = self.generate_dihedral_conformers(resolution)
from rdkit import Chem
# Write structures
w = Chem.SDWriter('conformers.sdf')
for i, conf in enumerate(mol_with_conformers.GetConformers()):
tm = Chem.Mol(mol_with_conformers, False, conf.GetId())
w.write(tm)
w.close()
def display_dihedral(self):
"""
It displays the dihedral that is being tracked
"""
from rdkit import Chem
from copy import deepcopy
try:
from IPython.display import display
from IPython.display import SVG
except ImportError:
raise Exception('Jupyter notebook not found')
rdk_mol = deepcopy(self.molecule.rdkit_molecule)
Chem.rdDepictor.Compute2DCoords(rdk_mol)
d = Chem.Draw.rdMolDraw2D.MolDraw2DSVG(250, 250)
Chem.Draw.rdMolDraw2D.PrepareAndDrawMolecule(
d, rdk_mol, highlightAtoms=self.atom_indexes)
d.FinishDrawing()
display(SVG(d.GetDrawingText()))
def get_dihedral_parameters(self):
"""
It returns the parameters of the dihedral that is being tracked,
according to the OpenFF toolkit.
Returns
-------
parameters : dict
The dictionary with the parameters
"""
from openforcefield.topology import Topology
from openforcefield.typing.engines.smirnoff import ForceField
topology = Topology.from_molecules([self.molecule.off_molecule])
ff = ForceField(self.forcefield + '.offxml')
all_parameters = ff.label_molecules(topology)[0]
parameters = dict(all_parameters['ProperTorsions'])[self.atom_indexes]
return parameters
@property
def atom_indexes(self):
"""
The indexes of atoms involved in the dihedral.
Returns
-------
atom_indexes : tuple[int]
The tuple of atom indexes
"""
return self._atom_indexes
@property
def molecule(self):
"""
The molecule the dihedral belongs to.
Returns
-------
molecule : an peleffy.topology.Molecule
The peleffy's Molecule object
"""
return self._molecule
@property
def forcefield(self):
"""
The forcefield employed to parameterize the molecule.
Returns
-------
forcefield : an openforcefield.typing.engines.smirnoff.ForceField
object
The forcefield employed to parameterize this Molecule object
"""
return self._forcefield
@property
def rotatable_bond(self):
"""
It returns the atom indexes in the dihedral that belong to the
rotatable bond.
Returns
-------
rot_bond : tuple[int]
The tuple of atom indexes
"""
return tuple(list(self.atom_indexes)[1:3])
| true |
135b5828023b8c29aa739f9d2cdc2c69fe5e4b40 | Python | facloud/python-algorithms | /algos/perf/__init__.py | UTF-8 | 719 | 3.25 | 3 | [] | no_license | import time
import matplotlib.pyplot as plt
class PerformanceTestResult(object):
def __init__(self, validation_outcome, duration):
self.validation_outcome = validation_outcome
self.duration = duration
def run_performance_test(p, size):
random_input = p.get_random_input(size)
start_time = time.time()
res = p.run(random_input)
end_time = time.time()
return PerformanceTestResult(
p.validate_result(random_input, res), end_time-start_time
)
def draw_line_chart(p, sizes):
values = []
for s in sizes:
res = run_performance_test(p, s)
values.append(res.duration)
plt.plot(sizes, values)
plt.axes().set_xscale('log')
plt.show()
| true |
becb5547281e82c25376cffa803649396e836e4f | Python | Nitta-K-git/pybind_samples | /out/numpy_mod_test.py | UTF-8 | 362 | 3.1875 | 3 | [
"MIT"
] | permissive | import numpy_mod as tes
import numpy as np
a = np.array([1,3,5,6]).reshape(2,2) # 今回の関数は2次元のみ限定
print(a)
tes.print_array(a) # numpyデータをprint
b = tes.modify_array(a,3) # ブロードキャスト処理
print(a)
print(b)
tes.modify_array_inplace(a,4) # ブロードキャスト処理で引数自体を書き換え
print(a)
| true |
633cc0c703b14a13b3eca6fda02826982b684547 | Python | silvermund/keras-study | /keras/keras10_validation2.py | UTF-8 | 959 | 3.34375 | 3 | [] | no_license | from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt
#1. 데이터
x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13])
y = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13])
## 잘라서 만들어라!!!
x_train = x[:8] # 훈련, 공부하는 거
y_train = y[:8]
x_test = x[8:11]
y_test = y[8:11]
x_val = x[11:]
y_val = y[11:]
#2. 모델 구성
model = Sequential()
model.add(Dense(5, input_dim=1))
model.add(Dense(4))
model.add(Dense(3))
model.add(Dense(2))
model.add(Dense(1))
#3. 컴파일, 훈련
model.compile(loss='mse', optimizer='adam')
model.fit(x_train, y_train, epochs=1000, batch_size=1, validation_data=(x_val, y_val))
#4. 평가, 예측
loss = model.evaluate(x_test, y_test)
print('loss : ', loss)
result = model.predict([11])
print('11의 예측값 : ', result)
# y_predict = model.predict(x)
# plt.scatter(x,y)
# plt.plot(x,y_predict, color='red')
# plt.show()
| true |
ab0867a4a11938628213ad39cda6bdd2f9887572 | Python | badrequest400/qa-management_system | /manager_test.py | UTF-8 | 2,643 | 3 | 3 | [] | no_license | import unittest
from manager import *
from item import *
from subscriber import *
class ManagerTest(unittest.TestCase):
def setUp(self):
self.a = Item('Hundred Years of Solitude', 'Gabriel Marquez', 'BF123')
self.b = Item('The Neuromancer', 'William Gibson', 'BF124')
self.c = Item('Going Postal', 'Terry Pratchett', 'BF125')
self.manager = Manager([self.a, self.b], [])
self.d = Subscriber('John Smith', 'john.smith@gmail.com', '8 Crescent Rd', self.manager)
self.manager.__borrowed = []
def test_add_get_subscribers(self):
self.assertEqual(self.manager.addSubscriber('John Smith'), 'Can only add type Subscriber')
self.assertEqual(self.manager.getSubscribers(), [self.d])
self.assertNotEqual(self.manager.getSubscribers(), ['a', 'b'])
def test_add_get_item(self):
self.assertEqual(self.manager.addItem('a String'), 'Can only add type Item')
self.manager.addItem(self.c)
self.assertEqual(self.manager.getItems(), [self.a, self.b, self.c])
def test_borrow_item(self):
self.manager.addItem(self.c)
self.assertEqual(self.manager.getItems(), [self.a, self.b, self.c])
self.assertEqual(self.manager.borrowItem('BF125', 'John Smith'), 'Item borrowed')
self.assertEqual(self.manager.getItems(), [self.a, self.b])
self.assertEqual(self.manager.getBorrowed(), [self.c])
self.assertEqual(self.manager.borrowItem('HF987', 'Jane Smith'), 'Item ID was not found in database')
def test_item_return(self):
self.manager.addItem(self.c)
self.manager.borrowItem('BF125', 'John Smith')
self.assertEqual(self.manager.getItems(), [self.a, self.b])
self.assertEqual(self.manager.getBorrowed(), [self.c])
self.assertEqual(self.manager.returnItem('BF125'), 'Item returned')
self.assertEqual(self.manager.getItems(), [self.a, self.b, self.c])
self.assertEqual(self.manager.getBorrowed(), [])
self.assertEqual(self.manager.returnItem('HF987'), 'Item ID was not found in database')
def test_message_overdue(self):
self.assertEqual(self.manager.messageOverDue(self.d), 'Message sent and confirmed')
def test_check_duedates(self):
self.manager.addItem(self.c)
self.manager.borrowItem('BF125', 'John Smith')
# SET BORROWED DATE BACK FROM CURRENT TIME SO IT WILL BE DUE FOR TEST CASE
for i in self.manager.getBorrowed():
if i.getId() == 'BF125':
i.setBorrowedDate(datetime(2015, 6, 12, 0, 0, 0, 0))
self.assertEqual(self.manager.checkDueDates()[0].getId(), 'BF125')
if __name__ == '__main__':
unittest.main()
| true |
df51389b142e0c372be452924c05b34814ef3bc2 | Python | liyimpc/pytool | /base/stack.py | UTF-8 | 167 | 3.53125 | 4 | [] | no_license | '''
栈:
先进后出,用数组模拟操作
'''
stack = []
# 压入数据
stack.append("A")
stack.append("B")
stack.append("C")
# 取出数据
stack.pop()
| true |
3c83590019b959559ea8c865826713a107c13966 | Python | marsXyr/ERL | /core/neuro_evolutionary.py | UTF-8 | 8,159 | 2.5625 | 3 | [
"MIT"
] | permissive | import random
import numpy as np
import fastrand, math
# Neuroevolution SSNE
class SSNE:
def __init__(self, args):
self.current_gen = 0
self.args = args
self.population_size = self.args.pop_size
self.num_elitists = int(self.args.elite_fraction * args.pop_size)
if self.num_elitists < 1: self.num_elitists = 1
self.rl_policy = None
self.selection_stats = {'elite': 0, 'selected': 0, 'discarded': 0, 'total': 0.0000001}
def selection_tournament(self, index_rank, num_offsprings, tournament_size):
total_choices = len(index_rank)
offsprings = []
for i in range(num_offsprings):
winner = np.min(np.random.randint(total_choices, size=tournament_size))
offsprings.append(index_rank[winner])
offsprings = list(set(offsprings)) # Find unique offsprings
if len(offsprings) % 2 != 0: # Number of offsprings should be even
offsprings.append(offsprings[fastrand.pcg32bounded(len(offsprings))])
return offsprings
def list_argsort(self, seq):
return sorted(range(len(seq)), key=seq.__getitem__)
def regularize_weight(self, weight, mag):
if weight > mag: weight = mag
if weight < -mag: weight = -mag
return weight
def crossover_inplace(self, gene1, gene2):
for param1, param2 in zip(gene1.parameters(), gene2.parameters()):
# References to the variable tensors
W1 = param1.data
W2 = param2.data
if len(W1.shape) == 2: # Weights no bias
num_variables = W1.shape[0]
# Crossover opertation [Indexed by row]
num_cross_overs = fastrand.pcg32bounded(num_variables * 2) # Lower bounded on full swaps
for i in range(num_cross_overs):
receiver_choice = random.random() # Choose which gene to receive the perturbation
if receiver_choice < 0.5:
ind_cr = fastrand.pcg32bounded(W1.shape[0]) #
W1[ind_cr, :] = W2[ind_cr, :]
else:
ind_cr = fastrand.pcg32bounded(W1.shape[0]) #
W2[ind_cr, :] = W1[ind_cr, :]
elif len(W1.shape) == 1: # Bias
num_variables = W1.shape[0]
# Crossover opertation [Indexed by row]
num_cross_overs = fastrand.pcg32bounded(num_variables) # Lower bounded on full swaps
for i in range(num_cross_overs):
receiver_choice = random.random() # Choose which gene to receive the perturbation
if receiver_choice < 0.5:
ind_cr = fastrand.pcg32bounded(W1.shape[0]) #
W1[ind_cr] = W2[ind_cr]
else:
ind_cr = fastrand.pcg32bounded(W1.shape[0]) #
W2[ind_cr] = W1[ind_cr]
def mutate_inplace(self, gene):
mut_strength = 0.1
num_mutation_frac = 0.1
super_mut_strength = 10
super_mut_prob = 0.05
reset_prob = super_mut_prob + 0.05
num_params = len(list(gene.parameters()))
ssne_probabilities = np.random.uniform(0, 1, num_params) * 2
model_params = gene.state_dict()
for i, key in enumerate(model_params): # Mutate each param
if key == 'lnorm1.gamma' or key == 'lnorm1.beta' or key == 'lnorm2.gamma' or key == 'lnorm2.beta' or key == 'lnorm3.gamma' or key == 'lnorm3.beta': continue
# References to the variable keys
W = model_params[key]
if len(W.shape) == 2: # Weights, no bias
num_weights = W.shape[0] * W.shape[1]
ssne_prob = ssne_probabilities[i]
if random.random() < ssne_prob:
num_mutations = fastrand.pcg32bounded(int(math.ceil(num_mutation_frac * num_weights))) # Number of mutation instances
for _ in range(num_mutations):
ind_dim1 = fastrand.pcg32bounded(W.shape[0])
ind_dim2 = fastrand.pcg32bounded(W.shape[-1])
random_num = random.random()
if random_num < super_mut_prob: # Super Mutation probability
W[ind_dim1, ind_dim2] += random.gauss(0, super_mut_strength * W[ind_dim1, ind_dim2])
elif random_num < reset_prob: # Reset probability
W[ind_dim1, ind_dim2] = random.gauss(0, 1)
else: # mutauion even normal
W[ind_dim1, ind_dim2] += random.gauss(0, mut_strength * W[ind_dim1, ind_dim2])
# Regularization hard limit
W[ind_dim1, ind_dim2] = self.regularize_weight(W[ind_dim1, ind_dim2], 1000000)
def clone(self, master, replacee): # Replace the replacee individual with master
for target_param, source_param in zip(replacee.parameters(), master.parameters()):
target_param.data.copy_(source_param.data)
def reset_genome(self, gene):
for param in (gene.parameters()):
param.data.copy_(param.data)
def epoch(self, pop, fitness_evals):
# Entire epoch is handled with indices; Index rank nets by fitness evaluation (0 is the best after reversing)
index_rank = self.list_argsort(fitness_evals); index_rank.reverse() # fitness值从大到小
elitist_index = index_rank[:self.num_elitists] # Elitist indexes safeguard
# Selection step
offsprings = self.selection_tournament(index_rank, num_offsprings=len(index_rank) - self.num_elitists,
tournament_size=3) # 随机选k个个体竞争产生下一代。
# Figure out unselected candidates
unselects = []; new_elitists = []
for i in range(self.population_size):
if i in offsprings or i in elitist_index:
continue
else:
unselects.append(i)
random.shuffle(unselects) # 将序列的元素随机排序
# COMPUTE RL_SELECTION RATE
if self.rl_policy != None: # RL Transfer happened
self.selection_stats['total'] += 1.0
if self.rl_policy in elitist_index: self.selection_stats['elite'] += 1.0
elif self.rl_policy in offsprings: self.selection_stats['selected'] += 1.0
elif self.rl_policy in unselects: self.selection_stats['discarded'] += 1.0
self.rl_policy = None
# Elitism step, assigning elite candidates to some unselects
for i in elitist_index:
try: replacee = unselects.pop(0)
except: replacee = offsprings.pop(0)
new_elitists.append(replacee)
self.clone(master=pop[i], replacee=pop[replacee])
# Crossover for unselected genes with 100 percent probability
if len(unselects) % 2 != 0: # Number of unselects left should be even
unselects.append(unselects[fastrand.pcg32bounded(len(unselects))])
for i, j in zip(unselects[0::2], unselects[1::2]):
off_i = random.choice(new_elitists)
off_j = random.choice(offsprings)
self.clone(master=pop[off_i], replacee=pop[i])
self.clone(master=pop[off_j], replacee=pop[j])
self.crossover_inplace(pop[i], pop[j])
# Crossover for selected offsprings
for i, j in zip(offsprings[0::2], offsprings[1::2]):
if random.random() < self.args.crossover_prob: self.crossover_inplace(pop[i], pop[j])
# Mutate all genes in the population except the new elitists
for i in range(self.population_size):
if i not in new_elitists: # Spare the new elitists
if random.random() < self.args.mutation_prob: self.mutate_inplace(pop[i])
return new_elitists[0]
#Functions
def unsqueeze(array, axis=1):
if axis == 0: return np.reshape(array, (1, len(array)))
elif axis == 1: return np.reshape(array, (len(array), 1))
| true |
31506051faff870369638d07d1465e3bc5024c44 | Python | puneet-10/POI-in-Enron-Company | /poi_id.py | UTF-8 | 6,654 | 2.75 | 3 | [] | no_license | #!/usr/bin/python
import sys
import matplotlib.pyplot as plt
import pickle
from sklearn import preprocessing
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
sys.path.append("../tools/")
from sklearn.metrics import accuracy_score
from feature_format import featureFormat, targetFeatureSplit
from tester import dump_classifier_and_data
### Task 1: Select what features you'll use.
### features_list is a list of strings, each of which is a feature name.
### The first feature must be "poi".
features_list = ["poi", "fraction_from_poi_email", "fraction_to_poi_email", 'shared_receipt_with_poi']
### Load the dictionary containing the dataset
with open("final_project_dataset.pkl", "rb") as data_file:
data_dict = pickle.load(data_file)
features = ["salary", "bonus"]
#print(data_dict.values())
#print(data_dict.keys())
data_dict.pop('TOTAL',0)
salary=[]
bonus=[]
for key in data_dict:
if data_dict[key]['salary']!='NaN':
if int(data_dict[key]['salary'])>600000:
salary.append(key) #people who having salary more than 600000
if data_dict[key]['bonus']!='NaN':
if int(data_dict[key]['bonus'])>4000000:
bonus.append(key) #peopl having bonus more than 4000000
#print(bonus)
#print(salary)
for outlier in bonus:
data_dict.pop(outlier)
for i in a:
try:
data_dict.pop(i)
except:
continue
#removing outlier
#or point in data_dict:
# salary = point[0]
# bonus = point[1]
# plt.scatter( salary, bonus )
#plt.xlabel("salary")
#plt.ylabel("bonus")
#plt.show()
my_dataset = data_dict
#print(data_dict['BUY RICHARD B'])
data=featureFormat(data_dict,features)
#print(data)
### Task 2: Remove outliers
outliers=[]
for key in data_dict:
if data_dict[key]['salary']=='NaN':
continue
outliers.append((key,int(data_dict[key]['salary'])))
o=(sorted(outliers,key=lambda x:x[1],reverse=True)[:4])
#print(o)
### Task 3: Create new features
### Store to my_dataset for easy export below.
def dict_to_list(key,normalizer):
lists=[]
for i in data_dict:
if data_dict[i][key]=="NaN" or data_dict[i][normalizer]=="NaN":
lists.append(0.)
elif data_dict[i][key]>=0:
lists.append(float(data_dict[i][key])/float(data_dict[i][normalizer]))
return lists
fraction_from_poi_email=dict_to_list("from_poi_to_this_person","to_messages")
fraction_to_poi_email=dict_to_list("from_this_person_to_poi","from_messages")
#getting the fraction of emails send by or to person of intrests to all other peoples
count=0
from_poi=[]
to_poi=[]
for i in data_dict:
data_dict[i]["fraction_from_poi_email"]=fraction_from_poi_email[count]
data_dict[i]["fraction_to_poi_email"]=fraction_to_poi_email[count]
count +=1
for s in data_dict:
if float(data_dict[s]["fraction_from_poi_email"])>0.15:
from_poi.append(s)
if float(data_dict[s]["fraction_to_poi_email"])>0.8:
to_poi.append(s)
#print(from_poi,to_poi)
#creating lists for finding poi by this features
for w in from_poi:
try:
data_dict.pop(w)
except:
continue
for q in to_poi:
try:
data_dict.pop(q)
except:
continue
#removing the outlier
#for t in data_dict:
# try:
# print(data_dict[t]["fraction_from_poi_email"])
# except:
# continue
### Extract features and labels from dataset for local testing
data = featureFormat(my_dataset, features_list, sort_keys = True)
for point in data:
from_poi = point[1]
to_poi = point[2]
plt.scatter( from_poi, to_poi )
if point[0] == 1:
plt.scatter(from_poi, to_poi, color="r", marker="*")
plt.xlabel("fraction of emails this person gets from poi")
plt.show()
labels, features = targetFeatureSplit(data)
### Task 4: Try a varity of classifiers
### Please name your classifier clf for easy export below.
### Note that if you want to do PCA or other multi-stage operations,
### you'll need to use Pipelines. For more info:
### http://scikit-learn.org/stable/modules/pipeline.html
# Provided to give you a starting point. Try a variety of classifiers.
### Task 5: Tune your classifier to achieve better than .3 precision and recall
### using our testing script. Check the tester.py script in the final project
### folder for details on the evaluation method, especially the test_classifier
### function. Because of the small size of the dataset, the script uses
### stratified shuffle split cross validation. For more info:
### http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html
# Example starting point. Try investigating other evaluation techniques!
from sklearn.cross_validation import train_test_split
features_train, features_test, labels_train, labels_test =train_test_split(features, labels, test_size=0.3, random_state=42)
from sklearn.cross_validation import KFold
kf=KFold(len(labels),3)
for train,test in kf:
features_train= [features[ii] for ii in train]
features_test= [features[ii] for ii in test]
labels_train=[labels[ii] for ii in train]
labels_test=[labels[ii] for ii in test]
#from sklearn.naive_bayes import GaussianNB
#clf = GaussianNB()
#clf.fit(features_train, labels_train)
#pred = clf.predict(features_test)
#accuracy = accuracy_score(pred,labels_test)
#print(accuracy)
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
clf.fit(features_train,labels_train)
score = clf.score(features_test,labels_test)
print( 'accuracy before tuning ', score)
importances = clf.feature_importances_
import numpy as np
indices = np.argsort(importances)[::-1]
#print ('Feature Ranking:')
#for i in range(16):
# print ("{} feature {} ({})".format(i+1,features_list[i+1],importances[indices[i]]))
clf = DecisionTreeClassifier(min_samples_split=8)
clf = clf.fit(features_train,labels_train)
pred= clf.predict(features_test)
acc=accuracy_score(labels_test, pred)
print( "accuracy after tuning = ", acc)
print ('precision = ', precision_score(labels_test,pred))
print( 'recall = ', recall_score(labels_test,pred))
## Task 6: Dump your classifier, dataset, and features_list so anyone can
### check your results. You do not need to change anything below, but make sure
### that the version of poi_id.py that you submit can be run on its own and
### generates the necessary .pkl files for validating your results.
dump_classifier_and_data(clf, my_dataset, features_list)
pickle.dump(clf, open("my_classifier.pkl", "w") )
pickle.dump(data_dict, open("my_dataset.pkl", "w") )
pickle.dump(features_list, open("my_feature_list.pkl", "w") )
| true |
f24041261a1cb59fdff06f83964282df7464103f | Python | manishita-dey/Image_Color_Palette_Generator | /main.py | UTF-8 | 1,885 | 2.84375 | 3 | [] | no_license | from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
import os
import numpy as np
import matplotlib as plt
from PIL import Image
UPLOAD_FOLDER = 'static/uploads/'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
@app.route("/")
def home():
return render_template('home_page.html')
@app.route("/image", methods = ['POST'])
def upload_image():
image = request.files['filename']
# image_file_name = secure_filename(image.filename)
image.save(os.path.join(app.config['UPLOAD_FOLDER'], image.filename))
# Converting the image received in numpy array
img = Image.open(image)
img = np.array(img)
# Flatting the numpy array to obtain all unique colors as rows and RGB pixels as columns
# Also obtaining the frequency of each unique color occuring in the image
all_color_palette_arr, occcurCount = np.unique(img.reshape(-1, img.shape[2]), axis=0, return_counts=True)
# Zipping both the above arrays
list_of_colors_and_occurence = zip(all_color_palette_arr, occcurCount)
# Converting the zip into list
zipped = list(list_of_colors_and_occurence)
# Sorting the above obtained list in descending order of occurence frequency
res = sorted(zipped, key = lambda x: x[1], reverse=True)
# splicing the final obtained list to obtain top 10 most common occuring color in image
final_top_10 = res[:10]
color_list = []
# converting to hexcode
for color in final_top_10:
hexcode = '#%02x%02x%02x' % (color[0][0],color[0][1], color[0][2])
color_list.append(hexcode)
return render_template('image_details.html', filename = image.filename, color_palette = color_list)
if __name__ == '__main__':
app.run(debug=True)
| true |
54d07a77c063fb813934e254a7a2f11f223f048b | Python | DorotaOrzeszek/ProjectEuler | /Euler23.py | UTF-8 | 783 | 3.28125 | 3 | [] | no_license | import math
def divsum(n):
dssum = -n
sq = math.sqrt(n)
if math.floor(sq) == sq:
dssum += sq
end = int(sq)
else:
end = int(sq)+1
for i in range(1,end):
if n % i == 0:
dssum += i
dssum += n/i
return dssum
def nrtype(n):
if n == divsum(n):
return 'p' # n is perfect'
elif n > divsum(n):
return 'd' # n is deficient'
else:
return 'a' # n is abundant
maxnr = 28123
abundants = set()
for i in range(1,maxnr+1):
if i < divsum(i):
abundants.add(i)
sums = []
for a in range(1,maxnr+1):
for b in abundants:
if b > a:
break
if (a-b) in abundants:
sums.append(a)
break
notsums = range(1,maxnr+1)
for el in sums:
notsums.remove(el)
answer = 0
for number in notsums:
answer += number
print answer
| true |
8e5a48d144bb93515dad1cf9f7ab5e387a75b77c | Python | deepakag5/Data-Structure-Algorithm-Analysis | /leetcode/puzzle_roman_to_int.py | UTF-8 | 1,213 | 3.953125 | 4 | [] | no_license | # Time complexity : O(1)
# As there is a finite set of roman numerals, the maximum number possible number can be 3999,
# which in roman numerals is MMMCMXCIX. As such the time complexity is O(1)
# If roman numerals had an arbitrary number of symbols, then the time complexity would be proportional
# to the length of the input, i.e. O(n). This is assuming that looking up the value of each symbol is O(1)
# Space complexity : O(1)O(1).
# Because only a constant number of single-value variables are used, the space complexity is O(1)
def romanToInt(s):
values_dict = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
total = 0
i = 0
while i < len(s):
if i + 1 < len(s) and values_dict[s[i]] < values_dict[s[i + 1]]:
# If the symbols are out of numeric order.
# We subtract the value of i+1 and i to get their total value
total += values_dict[s[i + 1]] - values_dict[s[i]]
# jump two places as we are considering
# both i and i+1 here
i += 2
else:
total += values_dict[s[i]]
i += 1
return total
| true |
ae28dd19e7e0aa414dd9c4f5654fd17bcaf885aa | Python | rahdirs11/CodeForces | /python/translation.py | UTF-8 | 84 | 2.84375 | 3 | [] | no_license | s, t = input(), input()
print('YES' if ''.join(list(reversed(s))) == t else 'NO')
| true |
43c2801153ffeb6cc3259963b10d6df58c40e97a | Python | diop/kebetu | /random_dictionary_words.py | UTF-8 | 578 | 3.546875 | 4 | [
"MIT"
] | permissive | import sys
import random
def get_dictionary_words():
with open('snippet.txt', 'r') as f:
dictionary_words = f.read().split(' ')
return dictionary_words
def create_random_sentence(dictionary, num_words):
for _ in range(num_words):
random_sentence = ' '.join(random.sample(dictionary, num_words)) + '.'
return random_sentence
def main():
num_words = int(sys.argv[1])
dictionary = get_dictionary_words()
print('words -->', dictionary)
print(create_random_sentence(dictionary, num_words))
if __name__ == '__main__':
main() | true |
761e91951e003ed882a2728ff7ff40c2e15c130d | Python | rhys-newbury/EmbodiedFlowMaps | /data_processing_scripts/process_fac_file.py | UTF-8 | 531 | 2.875 | 3 | [] | no_license | import collections
d = collections.defaultdict(int)
def process_fac(fac):
for index, line in enumerate(open(fac)):
if index == 0:
continue
data = list(map(lambda x : x.strip(), line.split(",")))
time = float(data[4][0] + "." + data[4][1:])
total = time * float(data[3])
d[data[1]] += total
print(d)
output = '\n'.join(map(lambda i : (str(i[0]) + "," + str(i[1])), d.items()))
file = open("capacities.csv", 'w')
file.write(output)
file.close() | true |
7e526503c016d36f0041a71e978a34916302c0ac | Python | abbindustrigymnasium/python-kompendium-ABBjaceng | /Kompendium/Kapitel 2 Öviningsuppgifter/2.3.py | UTF-8 | 198 | 3.125 | 3 | [] | no_license | A="Dator>> "
print(A +"Hej!\n" + A +"Vad heter du i förnamn?")
B=str(input("Du>> " ))
print(A + "Vad heter du i efternamn?")
C=str(input("Du>> "))
print(A+ "Trevligt att träffas "+ B +" " + C+"!") | true |
58b1dff1ec407d600e43fb93cd7d833faa0fcf9b | Python | fatihmete/dfviewer | /dfviewer/__init__.py | UTF-8 | 5,794 | 2.703125 | 3 | [
"MIT"
] | permissive | import sys
import numpy as np
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton,\
QLineEdit, QTableWidget, QTableWidgetItem,\
QLabel, QHBoxLayout, QVBoxLayout,\
QHeaderView, QComboBox, QCheckBox, QStatusBar
from PyQt5.QtCore import pyqtSlot
def v(data, showRows = 100):
app = QApplication(sys.argv)
ex = App(data, showRows)
#sys.exit()
app.exec_()
class App(QWidget):
def __init__(self, data, showRows):
super().__init__()
self.data = data
self.showRows = showRows
self.initUI()
def initUI(self):
self.setWindowTitle('DataFrame Viewer')
self.showMaximized()
self.activePage = 0
self.sortIndex = 0
self.sortAscending = False
#Buttons
self.prevButton = QPushButton("< Prev",self)
self.nextButton = QPushButton("Next >",self)
self.lastButton = QPushButton("Last >>",self)
self.firstButton = QPushButton("<< First",self)
self.nextButton.clicked.connect(self.nextPage)
self.prevButton.clicked.connect(self.prevPage)
self.lastButton.clicked.connect(self.lastPage)
self.firstButton.clicked.connect(self.firstPage)
#Search
self.searchBox = QLineEdit(self)
self.searchBox.setPlaceholderText('Search in selected column...')
self.searchBox.returnPressed.connect(self.loadDataFrame)
self.searchComboBox = QComboBox()
for col_name in list(self.data.columns):
self.searchComboBox.addItem(col_name)
self.searchComboBox.currentIndexChanged.connect(self.loadDataFrame)
self.searchQueryCheckBox = QCheckBox("Search Query")
self.searchQueryCheckBox.stateChanged.connect(self.loadDataFrame)
#Table widget
self.tableWidget = QTableWidget()
self.tableWidget.horizontalHeader().sectionDoubleClicked.connect(self.changeSortCriteria)
#Status bar
self.statusBar = QStatusBar()
#Layout
self.Vlayout = QHBoxLayout()
self.layout = QVBoxLayout()
self.Vlayout.addWidget(self.searchBox)
self.Vlayout.addWidget(self.searchComboBox)
self.Vlayout.addWidget(self.searchQueryCheckBox)
self.Vlayout.addWidget(self.prevButton)
self.Vlayout.addWidget(self.nextButton)
self.Vlayout.addWidget(self.firstButton)
self.Vlayout.addWidget(self.lastButton)
self.layout.addLayout(self.Vlayout)
self.layout.addWidget(self.tableWidget)
self.layout.addWidget(self.statusBar)
self.setLayout(self.layout)
self.loadDataFrame()
self.show()
@pyqtSlot()
def nextPage(self):
if self.activePage != self.maxPageNumber:
self.activePage +=1
self.loadDataFrame()
def prevPage(self):
if self.activePage != 0:
self.activePage -=1
self.loadDataFrame()
def lastPage(self):
self.activePage = self.maxPageNumber
self.loadDataFrame()
def firstPage(self):
self.activePage = 0
self.loadDataFrame()
def changeSortCriteria(self,i):
if i == self.sortIndex:
if self.sortAscending == True:
self.sortAscending = False
else:
self.sortAscending = True
self.sortIndex = i
self.loadDataFrame()
def loadDataFrame(self):
try:
df = self.data
if len(self.searchBox.text())>=1:
if self.searchQueryCheckBox.isChecked():
#Query mode
df = df.query(self.searchBox.text())
#We print query to log
print("Search Query: {}".format(self.searchBox.text() ) )
else:
df = df[df[self.searchComboBox.currentText()].astype(str).str.contains(self.searchBox.text())]
self.rowsCount = df.shape[0]
self.colsCount = df.shape[1]
self.maxPageNumber = int(np.ceil(self.rowsCount / self.showRows)) - 1
#to fix wrong page bug in search mode
if self.activePage > self.maxPageNumber:
self.activePage = 0
self.statusBar.showMessage("Page {}/{}, Rows: {} - {}, Total Results : {}"\
.format(self.activePage,\
self.maxPageNumber,\
(self.activePage*self.showRows),\
(self.activePage*self.showRows+self.showRows),\
self.rowsCount))
df = df.reset_index()\
.sort_values(self.data.columns[self.sortIndex], ascending=self.sortAscending)\
.iloc[(self.activePage*self.showRows):(self.activePage*self.showRows+self.showRows)]
self.tableWidget.setRowCount(0)
self.tableWidget.setColumnCount(0)
self.tableWidget.setColumnCount(self.colsCount)
self.tableWidget.setHorizontalHeaderLabels(list(self.data.columns))
self.tableWidget.setRowCount(df.shape[0])
i=0
for index,row in df.iterrows():
for col in range(self.colsCount):
w_item = QTableWidgetItem(str(row[col+1]))
self.tableWidget.setItem(i, col, w_item)
i+=1
except Exception as e:
print("An error occured. {}".format(e))
| true |
58115a78f8519254d110c761bac3d1351a6c09aa | Python | vensder/py_hw_2016 | /hw3_db.py | UTF-8 | 3,238 | 3.90625 | 4 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 2016_python.py
#
# Student Dmitry Makarov <vensder@gmail.com>
from time import sleep
'''
2. Сохранить объект в файл можно так:
»> import pickle
»> data = {
... 'a': [1, 2.0, 3, 4+6j],
... 'b': ("character string", b"byte string"),
... 'c': {None, True, False}
... }
»>
»> with open('data.pickle', 'wb') as f:
... pickle.dump(data, f)
Тогда так его можно прочитать:
»> with open('data.pickle', 'rb') as f:
... data_new = pickle.load(f)
Сделайте простую базу данных.
При первом запуске программы она создает файл pickle с данными.
При последующих открывает этот файл и выводит на экран содержимое
3.* Реализовать поиск/фильтрацию в базе данных - то есть вывод по условию.
'''
# Горизонтальная линия
hor = lambda i: '-' * i
data = {
'кот': {'ловит мышей','умеет мяукать'},
'кит': {'живет в океане','ест планктон'},
'студент': {'ходит на лекции'},
'профессор': {'ходит на лекции'},
}
import pickle
# Пробуем открыть файл с данными. Если его нет, создаем файл с данными.
# Если он есть, но не читается, пишем, что плохой формат.
data_new = ''
try:
with open('data.p','rb') as f:
try:
data_new = pickle.load(f)
except:
print('Bad format of file. Remove it?')
remove = input('yes/no?')
if remove == 'yes':
import os
os.remove('data.p')
if data_new:
print(data_new)
except FileNotFoundError:
with open('data.p','wb') as f:
pickle.dump(data,f)
# Поиск по ключу
print('Хотите узнать, что делают:')
for i in data.keys():
print(i)
print('?')
print('Введите кого-нибудь:')
data_object = input()
sleep(1)
# Выдача информации об объекте по ключу
if data_object in data.keys():
print(data_object + ':')
print(data.get(data_object))
else:
print('про ' + data_object + ' ничего не знаем')
sleep(1)
print(hor(24))
# Поиск по значению
print('\nЗнаете, кто: ')
for i in data.values():
print(i)
print('?')
sleep(1)
print('Введите вопрос, например:')
print('Кто ест планктон?')
question = input()
sleep(1)
#Кто ходит на лекции?
found = False
'''
for subj, actions in data.items():
for action in actions:
if action in question:
print(subj)
found = True
'''
for subj in data.keys():
for action in data.get(subj):
if action in question:
print(subj)
found = True
if not found:
print('Извините, но мы не знаем, ' + question.lower())
| true |
2889d05a1c970fd5fc5293cc677bbda1a80e17b5 | Python | EduardoSaverin/Sentiment-Analysis | /word_cloud.py | UTF-8 | 496 | 2.984375 | 3 | [] | no_license | from wordcloud import WordCloud
import matplotlib.pyplot as plt
def show_wordcloud(data, title = None):
wordcloud = WordCloud(
background_color = 'white',
max_words = 200,
max_font_size = 40,
scale = 3,
random_state = 42
).generate(str(data))
fig = plt.figure(1, figsize = (20, 20))
plt.axis('off')
if title:
fig.suptitle(title, fontsize = 20)
fig.subplots_adjust(top = 2.3)
plt.imshow(wordcloud)
plt.show() | true |
e21989be0fda30b95836c52df553e30c0c59939d | Python | nipunaw/Lotus | /src/lotusFloating.py | UTF-8 | 8,309 | 2.625 | 3 | [
"MIT"
] | permissive | # CIS 4930
########### Contributors ###########
# Nipuna Weerapperuma
# Hannah Williams
# David Jaworski
# Carlos Morales-Diaz
# Spencer Bass
########### PyQT5 imports ###########
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
class FloatingWidget(QtWidgets.QWidget):
def __init__(self, child, parent, x=0, y=0, resize_child = False, padding = 6):
super().__init__(parent=parent)
self.child_widget = child
self.child_widget.setParent(self)
# self.child_widget.setFocusPolicy(QtCore.Qt.ClickFocus)
# self.child_widget.clearFocus()
# self.setFocusPolicy(QtCore.Qt.ClickFocus)
# self.setFocus()
self.position_x = self.pos().x()
self.position_y = self.pos().y()
self.setMinimumWidth(self.child_widget.width()+padding)
self.setMinimumHeight(self.child_widget.height()+padding)
self.setGeometry(x, y, self.child_widget.width()+padding, self.child_widget.height()+padding)
self.setAttribute(QtCore.Qt.WA_StyledBackground, True)
self.child_widget.move(3, 3)
self.child_widget.setStyleSheet('border-width: 0px 0px 0px 0px;')
self.setStyleSheet('background-color: white; border:1px solid black;')
self.resize_child = resize_child
self.move_only = False
self.left_side = False
self.right_side = False
self.top_side = False
self.bottom_side = False
self.to_delete = False
self.is_heading = False
## Right-click options
self.menu = QtWidgets.QMenu(self)
placeAction = QtWidgets.QAction("Place", self)
deleteAction = QtWidgets.QAction('Delete', self)
deleteAction.triggered.connect(self.deleteWidget) # lambda state, x = self : self.parent().floatingWidgetDelete(x)
placeAction.triggered.connect(lambda state, x = self : self.parent().floatingWidgetPlace(x))
self.menu.addAction(placeAction)
self.menu.addAction(deleteAction)
## Cursor
self.setMouseTracking(True)
self.child_widget.setMouseTracking(True)
self.curr_cursor_shape = QtGui.QCursor().shape()
self.cursor = QtGui.QCursor()
self.installEventFilter(self)
def deleteWidget(self):
self.to_delete = True
self.parent().floatingWidgetDelete(self)
def leaveEvent(self, event):
self.cursor.setShape(self.curr_cursor_shape)
def mousePressEvent(self, event: QtGui.QMouseEvent) -> None:
if event.button() == Qt.LeftButton:
if event.pos().x() < 10:
self.left_side = True
if event.pos().y() < 10:
self.top_side = True
if self.width() - event.pos().x() < 10:
self.right_side = True
if self.height() - event.pos().y() < 10:
self.bottom_side = True
if not (self.left_side or self.top_side or self.right_side or self.bottom_side):
self.move_only = True
self.start_size = QtCore.QPoint(self.width(), self.height())
self.start_geometry = QtCore.QPoint(self.geometry().x(), self.geometry().y())
self.start_mouse_position = event.globalPos()
if event.button() == Qt.RightButton:
self.menu.popup(QtGui.QCursor.pos())
def mouseMoveEvent(self, event: QtGui.QMouseEvent) -> None:
#print(('Mouse coords: ( %d : %d )' % (event.x(), event.y())))
self.curr_cursor_shape = QtGui.QCursor().shape() ## Setting cursor
if event.pos().x() < 10 and event.pos().y() < 10:
self.cursor.setShape(Qt.SizeFDiagCursor)
elif self.width() - event.pos().x() < 10 and event.pos().y() < 10:
self.cursor.setShape(Qt.SizeBDiagCursor)
elif self.width() - event.pos().x() < 10 and self.height() - event.pos().y() < 10:
self.cursor.setShape(Qt.SizeFDiagCursor)
elif event.pos().x() < 10 and self.height() - event.pos().y() < 10:
self.cursor.setShape(Qt.SizeBDiagCursor)
elif event.pos().x() < 10:
self.cursor.setShape(Qt.SizeHorCursor)
elif event.pos().y() < 10:
self.cursor.setShape(Qt.SizeVerCursor)
elif self.width() - event.pos().x() < 10:
self.cursor.setShape(Qt.SizeHorCursor)
elif self.height() - event.pos().y() < 10:
self.cursor.setShape(Qt.SizeVerCursor)
else:
self.cursor.setShape(Qt.ArrowCursor)
self.setCursor(self.cursor)
if self.move_only:
self.move(event.globalPos() - self.start_mouse_position + self.start_geometry)
elif self.left_side and self.top_side: # upper left corner
resize_point = self.start_mouse_position - event.globalPos() + self.start_size
self.resize(resize_point.x(), resize_point.y())
if self.width() == self.minimumWidth() and self.height() == self.minimumHeight(): # additional check necessary
pass
elif self.width() == self.minimumWidth():
self.move(self.geometry().x(), event.globalY() - self.start_mouse_position.y() + self.start_geometry.y())
elif self.height() == self.minimumHeight():
self.move(event.globalX() - self.start_mouse_position.x() + self.start_geometry.x(), self.geometry().y())
else:
self.move(event.globalPos() - self.start_mouse_position + self.start_geometry)
elif self.right_side and self.top_side: # upper right corner
resize_point = self.start_mouse_position - event.globalPos() + self.start_size
resize_point_inverted = event.globalPos() - self.start_mouse_position + self.start_size
self.resize(resize_point_inverted.x(), resize_point.y())
if self.height() != self.minimumHeight(): # additional check necessary
self.move(self.start_geometry.x(), event.globalY() - self.start_mouse_position.y() + self.start_geometry.y())
elif self.left_side and self.bottom_side: # lower left corner
resize_point = self.start_mouse_position - event.globalPos() + self.start_size
resize_point_inverted = event.globalPos() - self.start_mouse_position + self.start_size
self.resize(resize_point.x(), resize_point_inverted.y())
if self.width() != self.minimumWidth(): # additional check necessary
self.move(event.globalX() - self.start_mouse_position.x() + self.start_geometry.x(), self.start_geometry.y())
elif self.right_side and self.bottom_side: # lower right corner
resize_point_inverted = event.globalPos() - self.start_mouse_position + self.start_size
self.resize(resize_point_inverted.x(), resize_point_inverted.y())
elif self.left_side: # left side
resize_point = self.start_mouse_position - event.globalPos() + self.start_size
self.resize(resize_point.x(), self.start_size.y())
if self.width() != self.minimumWidth(): # additional check necessary
self.move(event.globalX() - self.start_mouse_position.x() + self.start_geometry.x(), self.start_geometry.y())
elif self.right_side: # right side
resize_point_inverted = event.globalPos() - self.start_mouse_position + self.start_size
self.resize(resize_point_inverted.x(), self.start_size.y())
elif self.top_side: # top side
resize_point = self.start_mouse_position - event.globalPos() + self.start_size
self.resize(self.start_size.x(), resize_point.y())
if self.height() != self.minimumHeight(): # additional check necessary
self.move(self.start_geometry.x(), event.globalY() - self.start_mouse_position.y() + self.start_geometry.y())
elif self.bottom_side: # bottom side
resize_point_inverted = event.globalPos() - self.start_mouse_position + self.start_size
self.resize(self.start_size.x(), resize_point_inverted.y())
if self.resize_child:
self.child_widget.resize(self.width() - 6, self.height() - 6)
def mouseReleaseEvent(self, event: QtGui.QMouseEvent) -> None:
self.move_only = False
self.left_side = False
self.right_side = False
self.top_side = False
self.bottom_side = False
| true |
e55d4c968193eeacf1ced0e94416b6ae271f7614 | Python | limyer/NetworkTermProject | /참고 예제/RSPClient테스트용.py | UTF-8 | 403 | 2.84375 | 3 | [] | no_license | from socket import *
import threading
ADDR=('192.168.200.172',12000)
clientSocket=socket(AF_INET,SOCK_STREAM)
clientSocket.connect(ADDR)
def clientThread():
print(clientSocket.recv(2048).decode())
t=threading.Thread(target=clientThread)
t.daemon=True
t.start()
sentence='a'
while sentence!='.':
sentence=input("Input : ")
clientSocket.send(sentence.encode())
clientSocket.close() | true |
642a23fb360dab305050ebe5a99272f1726a4c5f | Python | xzhu2/BIA660 | /Team Sports/FinalProject/RestServiceHandler.py | UTF-8 | 5,045 | 2.53125 | 3 | [] | no_license | """
BIA 660
Final Project A sport statistic analysis website
Author: Han Yan
"""
import cherrypy
import simplejson
from MongoDBHandler import *
###
### Classes
###
class RESTResource(object):
"""
Base class for providing a RESTful interface to a resource.
Support http request:
handle_GET
handle_PUT
handle_POST
handle_DELETE
"""
@cherrypy.expose
def default(self, *vpath, **params):
method = getattr(self, "handle_" + cherrypy.request.method, None)
if not method:
methods = [x.replace("handle_", "")
for x in dir(self) if x.startswith("handle_")]
cherrypy.response.headers["Allow"] = ",".join(methods)
raise cherrypy.HTTPError(405, "Method not implemented.")
return method(*vpath, **params);
class BasketballResource(RESTResource):
"""Class of basketball resoure handler"""
def __shotChartRequest(self, db, params):
"""Handler for shot chart query request"""
year = int(params['year'])
return db.getShotmap('final_Shot_Map', params['team'], year)
def __teamStatusRequest(self, db, params):
"""Handler for team status query request"""
year = int(params['year'])
team = params['team']
attribute = params['attribute']
order = int(params['order'])
return db.queryTeamStatus("Regular_Team_Stats", team, attribute, order, year)
def __finalStatusRequest(self, db, params):
"""Handler for final status query request"""
year = params['year']
team = params['team']
attr = params['attribute']
print year, team, attr
return db.querySF('final_Stats', year, team, attr, '517e7b8d4c59662ed245edbf')
def __misStatusRequest(self, db, params):
"""Handler for miscellaneous stats query request"""
year = int(params['year'])
team = params['team']
attribute = params['attribute']
order = int(params['order'])
return db.queryTeamStatus("Regular_Mis_Stats", team, attribute, order, year)
def __topTeamRequest(self, db, params):
"""Handler for top ten query request"""
year = int(params['year'])
attr = params['attribute']
order = int(params['order'])
ret = db.getTopTeam('Regular_Team_Stats', attr, year, order)
for item in ret:
if item['_id'] == "League Average":
ret.remove(item)
return ret
def __finalTotalRequest(self, db, params):
team = params['team']
return db.queryFinalAverageTotal('final_Stats', team, '517e7b8d4c59662ed245edbf')
def __finalEachStatus(self, db, params):
attr = params['attribute']
return db.queryFinalEachStatByYear(attr)
def __finalQuarter(self, db, params):
attr = params['quarter']
return db.queryFinalQuarterScore('final_Stats', int(attr), '517e7b8d4c59662ed245edbf')
def handle_GET(self, *vpath, **params):
"""Get method handler
Arguments:
vpath -- request url path list.
params -- request arguments directory.
Return:
result of the http get request.
"""
cherrypy.response.headers['Origin'] = 'http://api.bia660finalproject.com'
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
requestPath = vpath[0]
db = NBADBClient('localhost', 27017, 'NBAdata')
if requestPath == 'shotmap':
retJson = self.__shotChartRequest(db, params)
elif requestPath == 'regularstatus':
retJson = self.__teamStatusRequest(db, params)
elif requestPath == 'misstatus':
retJson = self.__misStatusRequest(db, params)
elif requestPath == 'finalstatus':
retJson = self.__finalStatusRequest(db, params)
elif requestPath == 'reqularTopTen':
retJson = self.__topTeamRequest(db, params)
elif requestPath == 'finalTotals':
retJson = self.__finalTotalRequest(db, params)
elif requestPath == 'finalEachStatus':
retJson = self.__finalEachStatus(db, params)
elif requestPath == 'finalQuarter':
retJson = self.__finalQuarter(db, params)
return simplejson.dumps(retJson)
class FootballResource(RESTResource):
"""Class of basketball resoure handler"""
def handle_GET(self, *vpath, **params):
"""Get method handler
Arguments:
vpath -- request url path list.
params -- request arguments directory.
Return:
result of the http get request.
"""
cherrypy.response.headers['Origin'] = 'http://api.bia660finalproject.com'
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
requestPath = vpath[0]
if requestPath == 'premierleague':
db = premierLeagueDBClient('localhost', 27017, 'PremierLeaguedata')
chartName = params['chartName']
retJson = db.getDataByName('DataCollection', chartName)
try:
year = params['year']
except KeyError:
try:
year = params['season']
except KeyError:
return simplejson.dumps(retJson)
return simplejson.dumps(retJson[year])
class RestServer(object):
"""Class of restfull server that will be published by cherrypy"""
basketball = BasketballResource()
football = FootballResource()
@cherrypy.expose
def index(self):
return "This is a rest ful service server."
"""cherrypy server config file"""
conf = {
'global': {
'server.socket_host': '0.0.0.0',
'server.socket_port': 9999,
}
}
cherrypy.quickstart(RestServer(), '/', conf)
| true |
befb0995df41d043ee6118f0ecb2709475a7354f | Python | Arnab-Banerjee-Kolkata/SudokuGame | /Sudoku.py | UTF-8 | 19,228 | 3 | 3 | [] | no_license | from random import randint
from tkinter import *
import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
import time
import random
numbers = [1,2,3,4,5,6,7,8,9]
n=9
m=3
def search(c=0):
"Recursively search for a solution starting at position c."
i, j = divmod(c, n)
i0, j0 = i - i % m, j - j % m # Origin of mxm block
numbers = list(range(1, n + 1))
random.shuffle(numbers)
for x in numbers:
if (x not in board[i] # row
and all(row[j] != x for row in board) # column
and all(x not in row[j0:j0+m] # block
for row in board[i0:i])):
board[i][j] = x
if c + 1 >= n**2 or search(c + 1):
return board
else:
# No number is valid in this cell: backtrack and try again.
board[i][j] = None
return None
return search()
EASY=45
MEDIUM=32
HARD=25
class Box: #Contains all characteristics and properties of a single box of the grid
def __init__(self):
self.isValue=False #Stores is cell has value or is empty
self.value='' #Stores value of cell
self.isInitialValue=False #Stores if value in the cell is given in question(True) or input by user(False)
self.bckgrnd="white"
def Create_puzzle(difficulty):
global grid
grid=[[Box() for i in range(9)] for j in range(9)]
global board
board=[[None for a in range(9)] for a in range(9)]
search()
diff=0
if(difficulty=="easy"):
diff=EASY
elif(difficulty=="medium"):
diff=MEDIUM
else:
diff=HARD
rows=[0 for i in range(9)]
cols=[0 for i in range(9)]
for i in range(diff):
while True:
x=randint(0,8)
y=randint(0,8)
chk=0
if(i==diff-1):
for j in range(9):
if(rows[j]==0 or cols[j]==0):
chk=1
break
if(grid[x][y].isValue==False):
grid[x][y].value=board[x][y]
grid[x][y].isValue=True
grid[x][y].isInitialValue=True
rows[x]=cols[y]=1
break
if(chk==1):
break
if(chk==1):
Create_puzzle(difficulty)
class chkBoard(tk.Frame):
def __init__(self, parent):
# use black background so it "peeks through" to
# form grid lines
tk.Frame.__init__(self, parent, background="black")
self._widgets = []
for row in range(9):
current_row = []
for column in range(9):
if(grid[row][column].isInitialValue==True and grid[row][column].bckgrnd=="red"):
label = tk.Label(self, text=grid[row][column].value,borderwidth=5, height=3, width=6, font=20,background=grid[row][column].bckgrnd, relief="raised")
elif(grid[row][column].isInitialValue==True):
label = tk.Label(self, text=grid[row][column].value,borderwidth=5, height=3, width=6, font=20,background="skyblue", relief="raised")
else:
label = tk.Label(self, text=grid[row][column].value,borderwidth=5, height=3, width=6, font=20,background=grid[row][column].bckgrnd)
# data=label.get("%d")
if(column%3==2 and row%3==2):
label.grid(row=row, column=column, sticky="nsew", padx=(1,5), pady=(1,5))
current_row.append(label)
elif(column%3==2):
label.grid(row=row, column=column, sticky="nsew", padx=(1,5), pady=1)
current_row.append(label)
elif(row%3==2):
label.grid(row=row, column=column, sticky="nsew", padx=1, pady=(1,5))
current_row.append(label)
else:
label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
current_row.append(label)
class hintBoard(tk.Frame):
def __init__(self, parent):
# use black background so it "peeks through" to
# form grid lines
tk.Frame.__init__(self, parent, background="black")
self._widgets = []
for row in range(9):
current_row = []
for column in range(9):
if(grid[row][column].isInitialValue==True):
label = tk.Label(self, text=grid[row][column].value,borderwidth=5, height=3, width=6, font=20,background="skyblue", relief="raised")
else:
label = tk.Label(self, text=grid[row][column].value,borderwidth=5, height=3, width=6, font=20,background=grid[row][column].bckgrnd)
if(column%3==2 and row%3==2):
label.grid(row=row, column=column, sticky="nsew", padx=(1,5), pady=(1,5))
current_row.append(label)
elif(column%3==2):
label.grid(row=row, column=column, sticky="nsew", padx=(1,5), pady=1)
current_row.append(label)
elif(row%3==2):
label.grid(row=row, column=column, sticky="nsew", padx=1, pady=(1,5))
current_row.append(label)
else:
label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
current_row.append(label)
class ResetDialog(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, background="white")
written=Frame(dia)
written.pack(side="top")
label=tk.Label(written, text="Do you want to clear all entered values?", borderwidth=1, height=5, width=40, font=20, background="white", foreground="red")
label.grid(row=0,column=0)
clck=Frame(dia)
clck.pack(side="bottom")
yb=tk.Button(clck, text="YES", width=20)
yb.grid(row=5, column=1)
yb.config(command=Reset)
nb=tk.Button(clck, text="NO", width=20)
nb.grid(row=5, column=15)
nb.config(command=dia.destroy)
dia.minsize(50,100)
def showResetDialog():
global dia
dia=tk.Tk()
dia.title("RESET DIALOG BOX")
ResetDialog(dia).pack(side="top", fill="x")
dia.mainloop()
class NewGameDialog(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, background="white")
written=Frame(dia2)
written.pack(side="top")
label=tk.Label(written, text="Do you want to start a new game?", borderwidth=1, height=5, width=40, font=20, background="white", foreground="red")
label.grid(row=0,column=0)
clck=Frame(dia2)
clck.pack(side="bottom")
yb=tk.Button(clck, text="YES", width=20)
yb.grid(row=5, column=1)
yb.config(command=NewGame)
nb=tk.Button(clck, text="NO", width=20)
nb.grid(row=5, column=15)
nb.config(command=dia2.destroy)
dia2.minsize(50,100)
def showNewGameDialog():
global dia2
dia2=tk.Tk()
dia2.title("NEW GAME DIALOG BOX")
NewGameDialog(dia2).pack(side="top", fill="x")
dia2.mainloop()
class DevelopersWindow(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, background="white")
#img=PhotoImage(file="background.jpg")
label1=tk.Label(self, text="TEAM: Bengal Institute Of Technology, Kolkata", borderwidth=1, height=5, width=80, font="Verdana 13 bold", background="white", foreground="black", anchor='w')
label1.grid(row=0,column=0)
label6=tk.Label(self, text="DATE: December, 2017", borderwidth=1, height=3, width=80, font="verdana 13 bold", background="white", foreground="black",anchor='w')
label6.grid(row=1,column=0)
label2=tk.Label(self, text="LEAD PROGRAMMER: ARNAB BANERJEE", borderwidth=1, height=5, width=80, font="verdana 13 bold", background="white", foreground="black", anchor='w')
label2.grid(row=2,column=0)
label3=tk.Label(self, text="ASSISTANT DEVELOPERS: RUPSA DE", borderwidth=1, height=2, width=80, font="verdana 13 bold", background="white", foreground="black", anchor='w')
label3.grid(row=3,column=0)
label4=tk.Label(self, text=" SAIKAT KARFA", borderwidth=1, height=2, width=80, font="verdana 13 bold", background="white", foreground="black", anchor='w')
label4.grid(row=4,column=0)
label5=tk.Label(self, text=" DEBAPRATIM CHAKRABORTY", borderwidth=1, height=2, width=80, font="verdana 13 bold", background="white", foreground="black", anchor='w')
label5.grid(row=5,column=0)
developers.minsize(100,100)
def showDevelopers():
global developers
developers=tk.Tk()
developers.title("DEVELOPERS")
DevelopersWindow(developers).pack(side="top", fill="x")
developers.mainloop()
class makeGrid(tk.Frame):
def __init__(self, parent):
# use black background so it "peeks through" to
# form grid lines
tk.Frame.__init__(self, parent, background="black")
self._widgets = []
for row in range(9):
current_row = []
for column in range(9):
if(grid[row][column].isInitialValue==True):
label = tk.Label(self, text=grid[row][column].value,borderwidth=5, height=3, width=6, font=20,background="skyblue", relief="raised")
else:
vcmd = (self.register(self.isLegal),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W',row,column)
label = tk.Entry(self, text=grid[row][column].value,borderwidth=0, width=10, font=70,background=grid[row][column].bckgrnd,
cursor="hand1",justify='center',validate="key", validatecommand=vcmd)
# data=label.get("%d")
if(column%3==2 and row%3==2):
label.grid(row=row, column=column, sticky="nsew", padx=(1,5), pady=(1,5))
current_row.append(label)
elif(column%3==2):
label.grid(row=row, column=column, sticky="nsew", padx=(1,5), pady=1)
current_row.append(label)
elif(row%3==2):
label.grid(row=row, column=column, sticky="nsew", padx=1, pady=(1,5))
current_row.append(label)
else:
label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
current_row.append(label)
self._widgets.append(current_row)
chkbutton=tk.Button(self,text="CHECK",width=20, height=2)
chkbutton.grid(row=0,column=9)
chkbutton.config(command=makeGrid.check)
clr=tk.Button(self,text="RESET",width=20, height=2)
clr.grid(row=1,column=9)
clr.config(command=showResetDialog)
hn=tk.Button(self, text="HINT",width=20, height=2)
hn.grid(row=2,column=9)
hn.config(command=makeGrid.ShowHint)
sub=tk.Button(self,text="SUBMIT",width=20, height=2)
sub.grid(row=3, column=9)
sub.config(command=Submit)
newg=tk.Button(self,text="NEW GAME",width=20, height=2)
newg.grid(row=4, column=9)
newg.config(command=showNewGameDialog)
dev=tk.Button(self, text="DEVELOPERS", width=20, height=2)
dev.grid(row=5, column=9)
dev.config(command=showDevelopers)
for column in range(9):
self.grid_columnconfigure(column, weight=1)
def isLegal(self, d, i, P, s, S, v, V, W,row,column):
if(int(i)>0):
self.bell()
return False
if(len(P)==0):
grid[int(row)][int(column)].value=''
grid[int(row)][int(column)].isValue=False
return True
for char in S:
if(char.isdigit()==False):
self.bell()
return False
inval=int(S)
if(inval<1 or inval>9):
self.bell()
return False
else:
grid[int(row)][int(column)].value=inval
grid[int(row)][int(column)].isValue=True
return True
def check():
chk1=0
for i in range(9):
for j in range(9):
if(grid[i][j].isInitialValue):
continue
val=grid[i][j].value
for k in range(9):
if(grid[i][k].value==val and val!='' and k!=j):
grid[i][j].bckgrnd="red"
grid[i][k].bckgrnd="red"
chk1=1
if(grid[k][j].value==val and val!='' and k!=i):
grid[k][j].bckgrnd="red"
grid[i][j].bckgrnd="red"
chk1=1
startx=i-(i%3)
starty=j-(j%3)
for k in range(startx,startx+3):
for m in range(starty, starty+3):
if(grid[k][m].value==val and val!='' and (k!=i and m!=j)):
grid[k][m].bckgrnd="red"
grid[i][j].bckgrnd="red"
chk1=1
break
if(chk1==1):
root2=tk.Tk()
root2.title("SUDOKU-CHECK(3 SEC)")
chkBoard(root2).pack(side="top", fill="x")
root2.after(3000,root2.destroy)
#time.sleep(5)
for i in range(9):
for j in range(9):
grid[i][j].bckgrnd="white"
def ShowHint():
chk1=0
for i in range(9):
for j in range(9):
if(grid[i][j].value!=board[i][j] and grid[i][j].isValue==True):
grid[i][j].bckgrnd="orange"
if(grid[i][j].isValue==False):
grid[i][j].value=board[i][j]
grid[i][j].bckgrnd="lightgreen"
root2=tk.Tk()
root2.title("SUDOKU-HINT(5 SEC)")
hintBoard(root2).pack(side="top", fill="x")
root2.after(5000,root2.destroy)
#time.sleep(5)
for i in range(9):
for j in range(9):
grid[i][j].bckgrnd="white"
if(grid[i][j].isValue==False):
grid[i][j].value=''
def Reset():
dia.destroy()
for i in range(9):
for j in range(9):
if(grid[i][j].isInitialValue==False):
grid[i][j].value=''
grid[i][j].isValue=False
#print("Operation Complete.")
root.destroy()
set()
def set():
global root
root=tk.Tk()
root.title("SUDOKU")
makeGrid(root).pack(side="top", fill="x")
root.mainloop()
def winner(chk1):
canvas_width = 500
canvas_height =500
master = tk.Tk()
master.title("RESULT")
MARGIN=20
SIDE=50
w = Canvas(master,
width=canvas_width,
height=canvas_height)
w.pack()
st=''
tg=''
if(chk1==0):
st="RIGHT ANSWER!"
tg="AC"
x0=y0=MARGIN+SIDE*2
x1=y1=MARGIN+SIDE*7
w.create_oval(x0,y0,x1,y1,
tags="victory", fill="light green", outline="black")
x = y = MARGIN + 4 * SIDE + SIDE / 2
w.create_text(x, y,
text=st, tags=tg,
fill="black", font=("Arial", 32))
else:
st="WRONG ANSWER!"
tg="WA"
x0=y0=MARGIN+SIDE*2
x1=y1=MARGIN+SIDE*7
w.create_oval(x0,y0,x1,y1,
tags="victory", fill="dark orange", outline="red")
x = y = MARGIN + 4 * SIDE + SIDE / 2
w.create_text(x, y,
text=st, tags=tg,
fill="red", font=("Arial", 32))
#root2=tk.Tk()
mainloop()
def NewGame():
dia2.destroy()
root.destroy()
for i in range(9):
for j in range(9):
grid[i][j].value=''
grid[i][j].isValue=False
grid[i][j].isInitialValue=False
grid[i][j].bckgrnd="white"
global root3
root3=tk.Tk()
root3.title("SELECT DIFFICULTY")
es=tk.Button(root3,text="EASY",width=15)
es.grid(row=0, column=3)
es.config(command=setEasy)
mid=tk.Button(root3,text="MEDIUM",width=15)
mid.grid(row=0, column=6)
mid.config(command=setMid)
hr=tk.Button(root3,text="HARD",width=15)
hr.grid(row=0, column=9)
hr.config(command=setHard)
root3.mainloop()
def Submit():
chk1=0
chk2=0
for i in range(9):
for j in range(9):
if(grid[i][j].isInitialValue):
continue
if(grid[i][j].isValue==False):
chk2=1
val=grid[i][j].value
for k in range(9):
if(grid[i][k].value==val and val!='' and k!=j):
chk1=1
if(grid[k][j].value==val and val!='' and k!=i):
chk1=1
startx=i-(i%3)
starty=j-(j%3)
for k in range(startx,startx+3):
for m in range(starty, starty+3):
if(grid[k][m].value==val and val!='' and (k!=i and m!=j)):
chk1=1
break
if(chk2==1):
break
if(chk2==0 and chk1==0):
winner(chk1)
else:
winner(1)
def setEasy():
root3.destroy()
Create_puzzle("easy")
global root
root=tk.Tk()
root.title("SUDOKU")
makeGrid(root).pack(side="top", fill="x")
root.mainloop()
def setMid():
root3.destroy()
Create_puzzle("medium")
global root
root=tk.Tk()
root.title("SUDOKU")
makeGrid(root).pack(side="top", fill="x")
root.mainloop()
def setHard():
root3.destroy()
Create_puzzle("hard")
global root
root=tk.Tk()
root.title("SUDOKU")
makeGrid(root).pack(side="top", fill="x")
root.mainloop()
#just a checker method
def main():
global root3
root3=tk.Tk()
root3.title("SELECT DIFFICULTY")
es=tk.Button(root3,text="EASY",width=15)
es.grid(row=0, column=3)
es.config(command=setEasy)
mid=tk.Button(root3,text="MEDIUM",width=15)
mid.grid(row=0, column=6)
mid.config(command=setMid)
hr=tk.Button(root3,text="HARD",width=15)
hr.grid(row=0, column=9)
hr.config(command=setHard)
root3.mainloop()
if(__name__=="__main__"):
main()
| true |
027816e7cdab9736fa6da5219666a5c1b929f94d | Python | hwans21/python | /Day04/module_basic02.py | UTF-8 | 528 | 4.09375 | 4 | [] | no_license | # 모듈 내에 존재하는 변수, 함수, 클래스를 직접 임포트하는 방법
from math import factorial,gcd
print(factorial(6))
print(factorial(5))
print(gcd(12,18))
# 임포트할 모듈을 별칭을 지정해서 사용하기
import statistics as st
li = [34,55,12,33,55,66,99]
print('평균:', st.mean(li))
print('분산:',st.variance(li))
print('표준편차:',st.stdev(li))
# 위에서 알려드린 두 가지 개념을 합쳐서도 사용이 가능합니다.
from math import factorial as fac
print(fac(10))
| true |
75a0044bd940082fd4ae4a7a3fd6569429039cc4 | Python | adamatan/bin-devils | /scripts/comment/comment.py | UTF-8 | 1,695 | 3.3125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
import sys
import argparse
############################### Parse arguments ################################
parser = argparse.ArgumentParser(description='Generates fixed-width comments.')
parser.add_argument('-d', '--debug', help="Debug mode", action='store_true')
languages = parser.add_mutually_exclusive_group()
languages.add_argument('-j', '--java', help="/* Use Java notation */", action='store_true')
languages.add_argument('-x', '--xml', help="<!-- Use XML notation -->", action='store_true')
parser.add_argument('message', type=str, nargs='?',
default='Use -h for help!',
help='Message to be displayed (e.g, "fuggedaboudit")')
parser.add_argument('width', type=int, default=80, nargs='?',
help='Total line width (hashes + message)')
args = parser.parse_args()
if args.debug:
print args
############################# Exit on width error ##############################
if len(args.message)>args.width:
sys.stderr.write('Warning: "%s": length is %d, wider than %d\n' % (args.message,
len(args.message), args.width))
############################## Calculate # width ###############################
filler_width = (args.width-len(args.message)-2)/2
if args.java:
filler = "*"*(filler_width-1)
filler_start = '/'+filler
filler_end = filler+'/'
elif args.xml:
filler = " "*(filler_width-3)
filler_start = "<!--"+filler[:-1]
filler_end = filler+"-->"
else:
filler_start=filler_end= "#"*max(1, filler_width)
if len(args.message)%2==1:
filler_end = filler_end[0]+filler_end
################################# Print result #################################
print filler_start+" %s "%args.message+filler_end
| true |
48e9dcc6735115d196b87d25fe9d788124a98900 | Python | copperstick6/alexa-git | /alexa-skill.py | UTF-8 | 1,677 | 2.59375 | 3 | [] | no_license | import logging
from random import randint
from flask import Flask, render_template, request, redirect
from flask_ask import Ask, statement, question, session, request
import urllib2
import json
import gitFeed
import techcrunch
import qod
app = Flask(__name__)
log = logging.getLogger()
ask = Ask(app, "/")
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
newsList = []
numNews = len(newsList)
@ask.launch
def welcome():
return question(render_template('welcome'))
@ask.intent('gitIntent')
def getGit():
a = gitFeed.gitEvents()
answer = a.getEvents()
numAnswer = a.getCount()
finalStatement = "You have " + str(numAnswer) + " new events. " + str(answer)
return statement(finalStatement)
@ask.intent('techCrunchIntent')
def getTechCrunch():
a = techcrunch.techNews()
a.getNews()
news = a.getList()
count = a.getCount()
finalStatement = ""
for i in range(0, count):
finalStatement += "Article Number " + str(i + 1) + ". " + news[i][0].encode('utf-8') + " "
finalStatement += " Select one of " + str(count) + " choice to hear a description of the article"
return question(finalStatement)
@ask.intent('inspirationIntent')
def getQuote():
a = qod.QOD()
return statement(a.getQuote())
@ask.intent('techCrunchChoiceIntent', convert={'number': int})
def getNews(number):
a = techCrunch.techNews()
a.getNews()
news = a.getList()
numNews = a.getCount()
if number > numNews:
return statement("Invalid choice. Choose again.")
return statement(news[number][1].encode('utf-8') + ". More to be continued on the article.")
if __name__ == '__main__':
app.run(debug=True)
| true |
482202ce235025c58c315b5748997838ae3777bb | Python | Lagom92/algorithm | /0405/subset.py | UTF-8 | 748 | 2.90625 | 3 | [] | no_license | def f(n, N, K):
global cnt
if n == N:
s = 0
for i in range(N):
if b[i] == 1:
s += a[i]
if s == K:
cnt += 1
for i in range(N):
if b[i] == 1:
print(a[i], end=" ")
print()
return
else:
b[n] = 0
f(n+1, N, K)
b[n] = 1
f(n+1, N, K)
# T = int(input())
T = 1
for tc in range(1, T+1):
# N, K = map(int, input().split())
# a = list(map(int, input().split()))
N, K = 4, 3
a = [1, 2, 1, 2]
b = [0]*N # 원소의 포함여부를 나타내는 배열
cnt = 0
f(0, N, K)
print('#{} {}'.format(tc, cnt))
# 1 2
# 2 1
# 1 2
# 1 2
# 1 4 | true |
19222eb90c4c9b2f34ed7847a241c49bc76a74ca | Python | VadymLinyvyi/ST_Falcon_Courses | /Lections/Lection 13/services/guest_service.py | UTF-8 | 938 | 3.078125 | 3 | [] | no_license | from colorama import Fore
from models.guests import Guest
from helpers.input_helper import get_string, get_age
from helpers.output_helper import pretty_print
class Guest_service():
def search_guest(self):
name = get_string("Please, enter guest name: ")
guest = Guest.objects().filter(name__icontains=name)
columns = ('Name', 'Age', 'Is_card')
pretty_print(guest, columns)
return guest
def guest_list(self):
print("Guest List")
guests = Guest.objects()
columns = ('Name', 'Age', 'Is_card')
pretty_print(guests, columns)
def add_guest(self):
min_age = Guest.age.min_value
name = get_string("Please, enter you name: ")
age = get_age("Please, enter you age: ", min_age=min_age)
guest = Guest(name=name, age=age)
guest.save()
print(Fore.GREEN, "Guest added", Fore.RESET)
return guest
| true |
4bfb9ba5ceb445faa8a9287f2072042b86f00f0d | Python | chancejiang/tiddlyweb | /test/test_tiddlers_fields.py | UTF-8 | 3,492 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | """
Test extended fields on tiddlers.
Some tiddlers have additional fields what we don't
know about ahead of time, but we'd like to handle.
Most straightforward things to do here seems to be
to do what TiddlyWiki does: have a fields field.
"""
import simplejson
from tiddlyweb.config import config
from tiddlyweb.serializer import Serializer
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.model.bag import Bag
from fixtures import reset_textstore, _teststore
def setup_module(module):
reset_textstore()
module.store = _teststore()
def test_tiddler_has_fields():
tiddler = Tiddler('feebles')
assert hasattr(tiddler, 'fields')
def test_tiddler_fields_dict():
tiddler = Tiddler('feebles')
assert type(tiddler.fields) == dict
def test_tiddler_fields_contains_stuff():
tiddler = Tiddler('feebles')
tiddler.fields = {u'this':u'is cool', u'so':u'is that'}
assert tiddler.fields['this'] == 'is cool'
assert tiddler.fields['so'] == 'is that'
def test_tiddler_fields_are_stored():
bag = Bag('bag0')
store.put(bag)
tiddler = Tiddler('feebles', bag='bag0')
tiddler.fields = {u'field1': u'value1', u'field2': u'value2'}
store.put(tiddler)
tiddler_second = Tiddler('feebles', bag='bag0')
tiddler_second = store.get(tiddler_second)
assert tiddler_second.fields['field1'] == 'value1'
assert tiddler_second.fields['field2'] == 'value2'
def test_tiddler_fields_ignore_server():
bag = Bag('bag0')
store.put(bag)
tiddler = Tiddler('server\nimpostor', bag='bag0')
tiddler.tags = [u'foo\nbar']
tiddler.fields = {u'field1': u'value1\nafterlinefeed', u'server.host': u'value1', u'server.type': u'value2'}
store.put(tiddler)
tiddler_second = Tiddler('server\nimpostor', bag='bag0')
tiddler_second = store.get(tiddler_second)
assert tiddler_second.fields['field1'] == 'value1\nafterlinefeed'
assert 'server.host' not in tiddler_second.fields.keys()
assert 'server.type' not in tiddler_second.fields.keys()
# these following rely on the previous
def test_tiddler_fields_as_text():
tiddler = Tiddler('feebles', bag='bag0')
tiddler = store.get(tiddler)
serializer = Serializer('text')
serializer.object = tiddler
text_of_tiddler = serializer.to_string()
assert 'field1: value1\n' in text_of_tiddler
assert 'field2: value2\n' in text_of_tiddler
def test_tiddler_fields_as_json():
tiddler = Tiddler('feebles', bag='bag0')
tiddler = store.get(tiddler)
serializer = Serializer('json')
serializer.object = tiddler
json_string = serializer.to_string()
tiddler_info = simplejson.loads(json_string)
assert tiddler_info['fields']['field1'] == 'value1'
assert tiddler_info['fields']['field2'] == 'value2'
assert tiddler_info['bag'] == 'bag0'
tiddler = Tiddler('new feebles', bag='bag0')
serializer.object = tiddler
serializer.from_string(json_string)
assert tiddler.fields['field1'] == 'value1'
assert tiddler.fields['field2'] == 'value2'
assert tiddler.bag == 'bag0'
def test_tiddler_fields_as_html():
tiddler = Tiddler('feebles', bag='bag0')
tiddler = store.get(tiddler)
serializer = Serializer('html')
serializer.object = tiddler
wiki_string = serializer.to_string()
assert 'field1="value1"' in wiki_string
assert 'field2="value2"' in wiki_string
assert 'title="feebles"' in wiki_string
#def test_fields_in_tiddler_put():
#def test_fields_in_tiddler_get():
| true |
df97738fd132ecfbdbfea5198b388b517bcacb41 | Python | JamieStarrCompany/yelp_challenge | /Legacy/app/routes.py | UTF-8 | 1,247 | 2.578125 | 3 | [] | no_license | from flask import render_template, flash, redirect, url_for
from app import app
from app.forms import SearchForm
import graph
name = ''
address = ''
rating = 0
review_count = 0
def get_stats(rest_name, rest_address, stars, rest_review_count):
global name
global address
global rating
global review_count
name = rest_name
address = rest_address
rating = stars
review_count = rest_review_count
@app.route('/')
@app.route('/index')
def index():
return render_template('base.html')
@app.route('/display_restaurants')
def display_stats():
print(name)
print(address)
print(rating)
print(review_count)
return render_template('display_template.html', name=name, address=address, rating=rating, review_count=review_count)
@app.route('/find_restaurants', methods=['GET', 'POST'])
def find_restaurants():
form = SearchForm()
if form.validate_on_submit():
flash('City to search in {}'.format(form.city.data))
flash('Cuisine {}'.format(form.cuisine.data))
flash('Day {}'.format(form.day.data))
flash('Time {}'.format(form.time.data))
graph.get_input(form.city.data, form.cuisine.data, form.day.data, form.time.data)
return redirect(url_for('display_stats'))
return render_template('search_template.html', form=form)
| true |
9fda65ad618f4786fc00a0660fbe62666a941881 | Python | sangkeerthana70/Python-playground | /functionsPython/parmsInFunction.py | UTF-8 | 111 | 2.734375 | 3 | [] | no_license | def my_function(fname):
print(fname + " Smith")
my_function("Earl")
my_function("Toby")
my_function("Linda") | true |
9d66260bfeb09f661977a5b927152b4e49667f6b | Python | zhangyue0503/python | /ex/benbanfaxuepy/py1.py | UTF-8 | 100 | 3.21875 | 3 | [] | no_license | # -*- coding=utf-8 -*-
# %r功能
x = "There are %d types of people." % 10
print "I said: %r." % x
| true |
71e240df20c5cbd09e4daa8380381ca587d3355f | Python | bakerks/Szabos-fractional-wave-eqaution | /2D Code/Szabo2D.py | UTF-8 | 6,673 | 3.171875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# coding: utf-8
# Approximates the solution to Szabos fractional wave equation using schemes with and without correction terms within the approximation of the fractional derivatives, corresponding schemes are seen in Eqs 3.9 and 3.8 respectively. This notebook contains 2 examples, one with a smooth solution (used to make Fig 3) and the other nonsmooth.
# Run the support that contains start up packages and weights codes:
# In[1]:
#For .py:
#exec(open("supportCorrections.py").read())
#For .ipynb:
get_ipython().run_line_magic('run', 'supportCorrections.ipynb')
# Set Parameters
# In[2]:
dx = 0.125 #space meshsize
dt = dx/10 #time step size
tend = 2 #end time
N = int(tend/dt) #number of time steps
dt = tend/N
gamma = 0.7 #order of fractional derivative
a0 = 1
#constant in front of FD
#A=0 #set =0 to remove fd
A = -a0*(4/math.pi)*math.gamma(-gamma-1)*math.gamma(gamma+2)*cos((gamma+1)*(math.pi/2))
B=1 #B=0 to remove corrections
p=2 #p=1 for BDF1, p=2 for BDF2 within CQ
#Controls extra terms required for higher order derivatives
if gamma<0:
X = 0
else:
X = 1-B
cgam = ceil(gamma)
# Set up the problem with the exact solution:
# In[3]:
#Example 1: Smooth case
c1 = 24
c2 = 12
def exact_time(tn):
return sin(c1*tn) + cos(c2*tn)
def dexact_time(tn):
return c1*cos(c1*tn) - c2*sin(c2*tn)
def ddexact_time(tn):
return -c1**2*sin(c1*tn) - c2**2*cos(c2*tn)
#Example 2: Non-Smooth case
#def exact_time(tn):
# return 1+ tn + tn**2 - 2*tn**(2+cgam-gamma)/(math.gamma(2-gamma)*(3-gamma)*(2-gamma))
#def dexact_time(tn):
# return 1+ 2*tn - 2*(2+cgam-gamma)*tn**(1+cgam-gamma)/(math.gamma(2-gamma)*(3-gamma)*(2-gamma))
#def ddexact_time(tn):
# return 2 - 2*(2+cgam -gamma)*(1+cgam-gamma)*tn**(cgam-gamma)/(math.gamma(2-gamma)*(3-gamma)*(2-gamma))
#Full term
def exact(tn):
return exact_time(tn)*sin(math.pi * x)*sin(math.pi * y)
def dexact(tn):
return dexact_time(tn)*sin(math.pi * x)*sin(math.pi * y)
# Generate mesh and finite element materials
# In[4]:
geo = SplineGeometry()
geo.AddRectangle( (-1, -1), (1, 1), bcs = ("bottom", "right", "top", "left"))
mesh = Mesh( geo.GenerateMesh(maxh=dx))
fes = H1(mesh, order=1, dirichlet="bottom|right|left|top")
u = fes.TrialFunction()
v = fes.TestFunction()
#generate stiffness and mass matrices
a=BilinearForm(fes,symmetric=False)
a+=SymbolicBFI(grad(u)*grad(v))
a.Assemble()
m=BilinearForm(fes,symmetric=False)
m+=SymbolicBFI(u*v)
m.Assemble()
# Define the function f, which forces u to be an exact solution
# In[5]:
def f_time(t):
if ceil(gamma) == 0:
ans= ddexact_time(t) + (2*(math.pi)**2)*(exact_time(t)) + A*simple_fint(t,dexact_time,ceil(gamma)-gamma)
else:
ans= ddexact_time(t) + (2*(math.pi)**2)*(exact_time(t)) + A*simple_fint(t,ddexact_time,ceil(gamma)-gamma)
return float(ans)
f_space_exact = sin(math.pi * x) *sin(math.pi *y)
f_space = LinearForm(fes)
f_space += SymbolicLFI(f_space_exact*v)
f_space.Assemble()
# Define initial conditions
# In[6]:
un1=GridFunction(fes) #u0 / u_{n-1}
un1.Set(exact_time(0)*sin(math.pi*x)*sin(math.pi*y))
un=GridFunction(fes) #u1 / u_n
un.Set((exact_time(0)+dt*dexact_time(0)+0.5*dt**2 *ddexact_time(0))*sin(math.pi*x)*sin(math.pi*y))
Draw(un,mesh,"u")
V0=GridFunction(fes) #v0
V0.Set(dexact_time(0)*sin(math.pi*x)*sin(math.pi*y))
V1=GridFunction(fes) #v1 placeholder
V1.Set(0*x*y)
V1 = V1.vec
# Gather weights for CQ
# In[7]:
stored_weights = weights(N,tend,p-1, lambda s: s**gamma)
w0 = float(stored_weights[0])
# Invert the matrices that scale $u_{n+1}$
# In[8]:
#make matrix that will be inverted in the first step only - to help calculate v1
mstar_initial=m.mat.CreateMatrix()
mstar_initial.AsVector().data=(1 + ((A * dt * w0)/2) + (A * B * (dt * corr_weights1(1,gamma))/2) )* m.mat.AsVector()
invmstar_initial=mstar_initial.Inverse(freedofs=fes.FreeDofs())
#make matrix that will be inverted during every other time step
mstar=m.mat.CreateMatrix()
mstar.AsVector().data=(1 + ((A * dt * w0)/2)) * m.mat.AsVector()
invmstar=mstar.Inverse(freedofs=fes.FreeDofs())
# Create stores for $u$s and $v$s
# In[9]:
#store u0 and u1 as numpy arrays with a vector of zeros as a placeholder for u2
u_storage = np.array([un1.vec.FV().NumPy()[:], un.vec.FV().NumPy()[:], np.zeros(len(un1.vec))])
#create a storage space for v's
v_storage = np.zeros((N,len(V0.vec)))
v_storage[0,:] = V0.vec.FV().NumPy()[:]
# Create a vector to store the new solution
# In[10]:
res = un.vec.CreateVector()
# Initiate error
# In[11]:
error = 0
# Do the time stepping
# In[12]:
for n in range(1,N):
#so we can calulate the first step differently to get V1
if n==1:
D=0
else:
D=1
#compute the approximation of the fractional derivative
CQ = np.zeros(len(un.vec))
for k in range (0, n):
CQ +=stored_weights[n-k] * (v_storage[k] - X*v_storage[0])
#make this useable - via temporary vector
temp = un.vec.CreateVector()
temp.FV().NumPy()[:] = CQ
#run scheme
res.data = dt * dt * f_time(n*dt) * f_space.vec
res.data += 2 * m.mat * un.vec
res.data -= m.mat * un1.vec
res.data -= dt * dt * a.mat * un.vec
res.data -= A * dt**2 * m.mat * temp
res.data += A * 0.5 * dt * w0 * m.mat * un1.vec
res.data += A * dt**2 * X *w0* m.mat * V0.vec
res.data -= A * B * dt**2 * corr_weights0(n,gamma) * m.mat * V0.vec
res.data -= A * B * D * dt**2 * corr_weights1(n,gamma) * m.mat * V1
res.data += A * B * (1-D) * dt * 0.5 * corr_weights1(1,gamma) * m.mat * un1.vec
#redefine u_n and u_{n-1}
un1.vec.data = un.vec
if n==1:
un.vec.data = invmstar_initial * res
else:
un.vec.data = invmstar * res
#add new data into u_storage
if n==1:
u_storage[2] = un.vec.FV().NumPy()[:]
else:
u_storage[0] = u_storage[1]
u_storage[1] = u_storage[2]
u_storage[2] = un.vec.FV().NumPy()[:]
#calculate new v
v_new = np.array([(u_storage[-1] - u_storage[-3])/(2*dt)])
#for the first step replace the v1 placeholder with v1
if n==1:
temp2 = un.vec.CreateVector()
temp2.FV().NumPy()[:] = v_new
V1 = temp2
#add this to the v array
v_storage[n,:] = v_new
Redraw(blocking=True)
#error calculation
error = max(error,sqrt (Integrate ( (un-exact((n+1)*dt))*(un-exact((n+1)*dt)), mesh)))
# Print error
# In[13]:
print("Max l2 error:" , error)
print ("End L2 error:", sqrt (Integrate ( (un-exact((n+1)*dt))*(un-exact((n+1)*dt)), mesh)))
# In[ ]:
| true |
b80f582d8e454a067456c63c451100f7b508ccb7 | Python | luftbuefel/microbitFlappyBird | /microbitFlappyBird.py | UTF-8 | 2,754 | 3.609375 | 4 | [
"MIT"
] | permissive | from microbit import *
from random import *
import music
class Wall:
column = -1
hole = -1
birdRow = 2
BIRD_COLUMN = 1
birdCanMove = True
birdBrightness = 9
score = 0
WALL_MOVE_TIMER = 800
WALL_BRIGHTNESS = 3
EMPTY_ROW = "00000"
wallMoveTimer = WALL_MOVE_TIMER
walls = []
wallsUpdated = True
gamePlaying = True
def moveUp():
global birdRow
if birdRow > 0:
birdRow -= 1
updateDisplay()
return
def moveDown():
global birdRow
if birdRow < 4:
birdRow += 1
updateDisplay()
return
def addAWall():
global walls
newWall = Wall()
newWall.column = 5
newWall.hole = randint(0, 4)
walls.append(newWall)
return
#this function controls the data for positioning the walls but not displaying
def moveWalls():
global score
for wall in walls:
wall.column -= 1
#when a wall is in the first column, it is time to add a new one
if(wall.column==BIRD_COLUMN and wall.hole!=birdRow):
gameOver()
return
if(wall.column == 0):
addAWall()
#add a point to the score and play a score sound
score += 1
music.play(music.BA_DING)
if(wall.column < 0):
#delete the wall from the list
del walls[0]
updateDisplay()
return
def updateDisplay():
screenContents = ""
#move the bird up and down
for row in range(0, 5):
nextRow = EMPTY_ROW
for wall in walls:
wallColumn = wall.column
hole = wall.hole
if(row!=hole):
nextRow = nextRow[:wallColumn]+str(WALL_BRIGHTNESS)+nextRow[wallColumn:]
if(row != 4):
nextRow += ":"
#draw the bird
if(birdRow == row):
nextRow = nextRow[:BIRD_COLUMN]+str(birdBrightness)+nextRow[BIRD_COLUMN+1:]
#go through and add the walls
screenContents += nextRow
display.show(Image(screenContents))
return
def gameOver():
global gamePlaying
gamePlaying = False
display.show(Image.SKULL)
sleep(1000)
display.scroll("Score: "+str(score), delay=100,loop=True)
return
#add an initial wall
addAWall();
#Update each frame
while gamePlaying:
if button_a.is_pressed() and birdCanMove is True:
birdCanMove = False
moveUp()
elif button_b.is_pressed() and birdCanMove is True:
birdCanMove = False
moveDown()
if not button_a.is_pressed() and not button_b.is_pressed():
birdCanMove = True
#decrement the wall timer
wallMoveTimer -= 1
#check if walls need to be moved
if(wallMoveTimer==0):
moveWalls()
wallMoveTimer = WALL_MOVE_TIMER
| true |
791378dc9bdf5295774f708d03a89eb4f2ddcf23 | Python | zdyxry/LeetCode | /array/1450_number_of_students_doing_homework_at_a_given_time/1450_number_of_students_doing_homework_at_a_given_time.py | UTF-8 | 327 | 3.015625 | 3 | [] | no_license | from typing import List
class Solution:
def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
return sum(a<=queryTime<=b for a,b in zip(startTime,endTime))
startTime = [1,2,3]
endTime = [3,2,7]
queryTime = 4
res = Solution().busyStudent(startTime, endTime, queryTime)
print(res) | true |
1b487f1eaf15f1129f7b6a301066a335e4b06431 | Python | 1noll1/lt2212-v19-a4 | /gendata.py | UTF-8 | 3,831 | 3.0625 | 3 | [] | no_license | import os, sys, glob, argparse, numpy as np, pandas as pd, subprocess, re
from nltk import word_tokenize
from nltk.corpus import stopwords
import numpy as np
from sklearn.model_selection import train_test_split
'''I removed metavars from R and P because I saw no use of them
and they were causing conflict
'''
#Part 1: Preprocessing
def retrieving_data(filename, language_name):
'''to do:
- percentage of set to be used training/test
- further tokenisation
- truncation
Args:
filename: .txt file of source/target language data
language_name: string
Output:
language_text: list: tokenized data without stopwords
'''
language_text = []
stop_words = stopwords.words(language_name)
with open(filename, encoding ='UTF-8') as f:
position = 0 # to keep track of reading position
if args.startline:
print('Starting at line {}.'.format(args.startline))
for i in range(args.startline): # start at line "startline"
position += 1
line = f.readline()
for line in f:
position += 1
line = word_tokenize(line) # tolower?
language_text.append(line)
if position == args.endline:
break
return language_text
print('Length of English lines: {}'.format(len(english_lines)))
print('Length of French lines: {}'.format(len(french_lines)))
def truncate_me(text1, text2):
'''Zip languages together --Lin
this returns a list of tuples that is the french/english line
i have truncated it, i don't know if you think there is a better way to output
this bit? --Rob
'''
twin_lines = []
for i in range(len(text1)):
lens = [len(text1[i]), len(text2[i])]
print(lens)
twin_lines.append((text1[i][:min(lens)],text2[i][:min(lens)]))
#print(len(twin_lines[i][0]), len(twin_lines[i][1])) #testing that it worked
return twin_lines
def gengrams(text):
trigrams = ngrams(text, 3, pad_left=True, pad_right=False, left_pad_symbol='<s>')
return trigrams
def split_data(data, T):
'''To split our test and training. We could also do this manually if you prefer.
Let's figure out what the data is supposed to look like first ;)
Args:
data: arrays
T: desired size of test data in fractions (e.g. 0.1, 0.4...)
Output:
arrays
'''
X_train, X_test, y_train, y_test = train_test_split(data, test_size=T) #should we shuffle? yes/no
return X_train, X_test, y_train, y_test
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Convert text to features")
parser.add_argument("-S", "--start", metavar="S", dest="startline", type=int,
default=0,
help="What line of the input data file to start from. Default is 0, the first line.")
parser.add_argument("-E", "--end", metavar="E", dest="endline",
type=int, default=100,
help="What line of the input data file to end on. Default is None, whatever the last line is.")
parser.add_argument("-T", "--test", metavar="T", dest="test_range",
type=int, default=20, help="What percentage of the set will be test")
parser.add_argument("-R", "--random", dest="random", action="store_true", default=False, help="Specify whether to get random training/test")
parser.add_argument("-P", "--preprocessing", dest="prepro", action="store_true", default=False,
help="specifies whether or not to use preprocessing")
args = parser.parse_args()
english_lines = retrieving_data('english_slice.txt', 'english')
french_lines = retrieving_data('french_slice.txt', 'french')
truncate_me(english_lines,french_lines) | true |
18e78699db3f708744c0c052b27631b8f59a378b | Python | firgaty/jfp-2019 | /main.py | UTF-8 | 3,901 | 3.015625 | 3 | [] | no_license | #!/usr/bin/python3
import random
# top line is 0
board = [[0] * 7 for _ in range(100)]
base = 0
L = 6
C = 7
# debug
def pboard():
for i in range(L):
for j in range(C):
print(board[base + L - i - 1][j], end=' ')
print()
# clean line if full
def is_tetris():
for e in board[base]:
if e == 0:
return False
return True
def clean():
global base
if is_tetris():
base += 1
return True
return False
# 0 == nothing
# otherwise == player
def play(c, p):
#print("base", base)
for i in range(L):
#print(base + L - i - 1)
if board[base + L - i - 1][c] != 0:
assert (i != 0)
board[base + L - i][c] = p
return base + L - i
board[base][c] = p
return base
# find adjacent seq
def find_seq_aux(p, dx, dy):
seqs = []
for i in range(base, base + L):
for j in range(7):
s = []
for k in range(4):
x = j + k * dx
y = i + k * dy
if (x > 0 and x < C
and y < base + 7 and y >= base
and board[y][x] == p):
s.append((x, y))
else:
break
if k > 0:
seqs.append(s)
return seqs
def find_seq(p):
seqs = find_seq_aux(p, 1, 0) # horiziontals
seqs.extend(find_seq_aux(p, 0, 1)) # verticals
seqs.extend(find_seq_aux(p, 1, 1)) # diags
seqs.extend(find_seq_aux(p, -1, 1)) # anti diags
seqs.sort(key=lambda x: len(x))
return seqs
def find_seq_max(p, length, dx, dy):
for i in range(base, base + L):
for j in range(C):
s = []
for k in range(4):
x = j + k * dx
y = i + k * dy
if (x < C and x >= 0
and y < base + L and y >= base
and board[y][x] == p):
s.append((x, y))
else:
break
if len(s) >= 4:
return True
return False
# sum length of sequences
def eval_score(p):
return sum(map(lambda x: len(x) ** 3, find_seq(p)))
def is_win(p):
return find_seq_max(p, 4, 1, 0) or \
find_seq_max(p, 4, 0, 1) or \
find_seq_max(p, 4, 1, 1) or \
find_seq_max(p, 4, -1, 1) # anti
# STRATS
# 1 me
# -1 opp
def stockfish(max_depth, depth, p):
global base
s = eval_score(depth % 2 + 1)
scores = [s] * 7
if depth == 0:
return s
for c in range(7):
if board[base + L - 1][c] != 0:
scores[c] = -1000000000
continue
i = play(c, 1 if p == 1 else 2)
cleaned = clean()
if is_win(depth % 2 + 1):
scores[c] = 100000000000 * p
else:
scores[c] = stockfish(max_depth, depth - 1, p * (-1))
board[i][c] = 0
if cleaned:
base -= 1
if depth == max_depth:
return scores
return sum(scores) / (2 * len(scores))
def move_stockfish():
n = 4
p = 1
scores = stockfish(n, n, p)
#print(scores)
c, m = 0, scores[0]
for i in range(1, 7):
if scores[i] > m:
c, m = i, scores[i]
return c
def move_random():
pos = []
for i in range(C):
if board[base + L - 1][i] == 0:
pos.append(i)
return random.choice(pos)
# CHANGE STRAT
strat = move_stockfish
# main loop
while True:
# opponent play
move = move_random()
if move >= 0:
play(move, 2)
if is_win(2):
print("Perdu")
break
clean()
pboard()
print("--")
#print("seq player 2")
# print(find_seq(2))
# we play
move = strat()
play(move, 1)
clean()
if is_win(1):
print("Gagne")
break
pboard()
print("--")
| true |
b73ccc7c890f58090810be24b8ab0cad4e7b77d1 | Python | mbromberek/Python_One_Liners | /ch05_regex/08_get_monetary_nbr.py | UTF-8 | 641 | 3.6875 | 4 | [] | no_license | ## dependencies
import re
## Data
report = '''
If you invested $1 in the year 1801, you would have $18087791.41 today.
This is a 7.967% return on investment.
But if you invested only $0.25 in 1801, you would end up with $4521947.8525.
'''
## My try
result = re.findall('(\$[0-9]+(\.[0-9]*)*)', report)
print(result)
# [('$1', ''), ('$18087791.41', '.41'), ('$0.25', '.25'), ('$4521947.85', '.85')]
## One-liner
dollars = [x[0] for x in re.findall('(\$[0-9]+(\.[0-9]*)?)', report)]
'''
? in this example means zero or one instance of group in front of it
'''
## Result
print(dollars)
# ['$1', '$18087791.41', '$0.25', '$4521947.8525']
| true |
9f69919ec07ab9df48efb4e4c3d78ab65ad54bd4 | Python | cb285/SeniorProject | /amazon/lambda/home_lambda_handler.py | UTF-8 | 11,199 | 2.71875 | 3 | [] | no_license | from requests import *
import string
from word2number import w2n
USER = "clayton"
PASSWORD = "clayton"
SERVER_URL = "https://" + USER + ":" + PASSWORD + "@192.195.228.50:58000"
VERIFY_SSL = False
SERVER_TIMEOUT = 5
# create translator for removing punctuation
translator=str.maketrans('','',string.punctuation)
def remove_punct(s):
return s.translate(translator).lower()
def parse_name_to_level(name_to_level):
split_str = name_to_level.split(" to ")
if(len(split_str) != 2):
if(len(split_str) == 1):
if(":" in name_to_level):
split_str = split_str[0].split(":")
hour = int(split_str[0].split(" ")[-1])
minute = int(split_str[1])
level = hour + 1
name_to_parse = split_str[0][:-2] + str(60 - minute)
device_name = parse_name(name_to_parse)
return device_name, level
else:
name_turn = split_str[0]
split_str = name_turn.split(" ")
if(split_str[-1] in ["on", "off", "dim", "dimmed"]):
device_name = parse_name(name_turn[:-len(split_str[-1])])
level = parse_level(split_str[-1])
return device_name, level
return "", -1
device_name = parse_name(split_str[0])
level = parse_level(split_str[1])
return device_name, level
def parse_level(s):
s = remove_punct(s)
# on
if(s == "on"):
return 100
# dim or dimmed
elif(s in ["dim", "dimmed"]):
return 50
# off
elif(s == "off"):
return 0
try:
# number or number words
number = w2n.word_to_num(s)
except ValueError:
return -1
return number
def parse_name(s):
# remove punctuation
s = remove_punct(s)
# split by spaces
words = s.split(" ")
was_num = False
# combine words to underscore separated string
device_name = ""
for word in words:
if(word != " "):
if(word in ["a", "b", "c", "d", "e", "f"]):
device_name = device_name + str(word)
was_num = True
continue
try:
# check if number or number words
number = w2n.word_to_num(word)
except ValueError:
if(was_num):
device_name = device_name + "_" + word + "_"
else:
device_name = device_name + word + "_"
was_num = False
continue
device_name = device_name + str(number)
was_num = True
# remove extra "_"
while(device_name[-1] == "_"):
device_name = device_name[:-1]
# return
return device_name
def lambda_handler(event, context):
if('request' in event):
if('intent' in event['request']):
if('name' in event['request']['intent']):
intent = event['request']['intent']
intent_name = intent['name']
# get slots (if any)
try:
slots = intent["slots"]
except KeyError:
pass
if(intent_name == "test"):
name_to_level = slots["name_to_level"]["value"]
device_name, level = parse_name_to_level(name_to_level)
if(level == -1):
return build_response("sorry, I couldn't catch the device name or level. please try again.")
return build_response("device name is " + device_name + " and level is " + str(level))
# discover_devices intent
elif(intent_name == "discover_devices"):
cmd = "discover_devices"
payload = {"cmd":cmd}
stat = server_request(payload)
if(stat):
return build_response("okay, trying to discover new devices")
else:
return build_response("sorry, something went wrong. please try again")
elif(intent_name == "list_devices"):
cmd = "list_devices"
payload = {"cmd":cmd}
s = server_request(payload)
if(not s):
return build_response("sorry, something went wrong. please try again.")
if(s == "none"):
return build_response("there are currently zero devices in the database.")
device_list = s.split(",")
device_list_str = ""
# combine in string
for device_name in device_list:
device_list_str = device_list_str + device_name + ", "
# remove extra ", "
device_list_str = device_list_str[:-2]
if(len(device_list) == 1):
return build_response("there is currently one device in the database: " + device_list_str)
return build_response("there are currently " + str(len(device_list)) + " devices in the database: " + device_list_str)
# set_device_level intent
elif(intent_name == "set_device_level"):
if("value" in slots["name_to_level"]):
device_name, level = parse_name_to_level(slots["name_to_level"]["value"])
if(level == -1):
return build_response("sorry, I couldn't catch the device name or level. please try again.")
cmd = "set_device_level"
payload = {"cmd":cmd, 'name':device_name, 'level':level}
stat = server_request(payload)
if(stat):
return build_response("okay, I set " + device_name.replace("_", " ") + " to " + str(level) + ".")
else:
return build_response("sorry, I couldn't do that. check that the device is turned on and in the database.")
else:
return build_response("sorry, I couldn't understand that. here's an example: set light to 30.")
# get_device_level intent
elif(intent_name == "get_device_level"):
if("value" in slots["name"]):
cmd = "get_device_level"
device_name = parse_name(slots["name"]["value"])
payload = {"cmd":cmd, 'name':device_name}
level = server_request(payload)
if(level != -1):
if(level == 100):
return build_response("your device called " + device_name + " is on")
elif(level == 0):
return build_response("your device called " + device_name + " is off")
else:
return build_response("your device called " + device_name + " is set to " + str(level))
else:
return build_response("sorry, I couldn't reach that device. please check that it is turned on and in the database.")
else:
return build_response("sorry, I couldn't understand that. here's an example: is the light on?")
elif(intent_name == "set_temperature"):
if("value" in slots["temperature"]):
cmd = "set_temperature"
temp = int(slots["temperature"]["value"])
payload = {"cmd":cmd, 'temp':temp}
stat = server_request(payload)
if(stat):
return build_response("okay, I set the temperature to " + str(temperature))
else:
return build_response("sorry, something went wrong when I tried to set the temperature. check the server log for details.")
elif(intent_name == "change_device_name"):
if("old_to_new" in slots):
split_str = slots["old_to_new"]["value"].split(" to ")
if(len(split_str) != 2):
return build_response("sorry, I couldn't get the name or new name. please try again.")
old_name = parse_name(split_str[0])
new_name = parse_name(split_str[1])
payload = {'cmd':'change_device_name', 'name':old_name, 'new_name':new_name}
stat = server_request(payload)
if(stat):
return build_response("okay, I changed " + device_name + " to " + new_device_name + ".")
else:
return build_response("sorry, I couldn't do that. make sure there is a device in the database called " + device_name + ".")
elif(intent_name == "remove_device"):
if("name" in slots):
device_name = parse_name(slots["name"]["value"])
payload = {'cmd':'remove_device', 'name':device_name}
stat = server_request(payload)
if(stat):
return build_response("okay, I removed " + device_name + " from the database.")
else:
return build_response("sorry, I couldn't do that. make sure there is a device in the database called " + device_name + ".")
else:
return build_response("sorry, I couldn't understand that. here's an example: set the temperature to 70 degrees")
return build_response("sorry, I couldn't understand that. please try again. here's an example: set my light to 84.")
def build_response(resp_str):
return {
"version": "1.0",
"sessionAttributes": {},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": resp_str
},
"shouldEndSession": True
}
}
def server_request(payload):
r = get(SERVER_URL, params=payload, verify=False, timeout=SERVER_TIMEOUT)
response = r.text
if(response.isdigit()):
return (int(response))
else:
if(response == "ok"):
return True
elif(response == "failed"):
return False
else:
return response
| true |
a2fee87eafeea66b849cf090b14756ea98592287 | Python | macalinao/market-maker | /exchange.py | UTF-8 | 2,441 | 3.125 | 3 | [
"MIT"
] | permissive | import uuid
def parse_message(message):
if message['type'] == 'book':
return Book(message)
return message
class Order(object):
def __init__(self, security, direction, quantity, price=None):
self.order_id = str(uuid.uuid4())
self.security = security
self.direction = direction
self.quantity = quantity
self.price = price
def is_limit(self):
return self.price is not None
class Book(object):
def __init__(self, data):
self.timestamp = data['timestamp']
self.book = data['book']
def min_ask(self, security):
asks = self.book[security]['asks']
if not asks:
return None
return min([price for price, _ in asks])
def max_bid(self, security):
bids = self.book[security]['bids']
if not bids:
return None
return max([pq[0] for pq in bids])
def spread(self, security):
"""Calculates the spread of a security."""
min_ask = self.min_ask(security)
max_bid = self.max_bid(security)
if min_ask is None or max_bid is None:
return None
return min_ask - max_bid
class Exchange(object):
def __init__(self, client):
self.client = client
self.orders = {}
# Subscribers to different message types
self.subscribers = {}
client.on_message(self._handle_message)
self.on('book', self._handle_book)
def place_order(self, security, direction, amount, price=None):
order = Order(security, direction, amount, price)
self.orders[order.order_id] = order
# Place order using exchange client
if order.is_limit():
self.client.limit(order.order_id, order.security, order.direction, order.price, order.quantity)
else:
self.client.market(order.order_id, order.security, order.direction, order.quantity)
def on(self, message_type, cb):
if not message_type in self.subscribers:
self.subscribers[message_type] = []
self.subscribers[message_type].append(cb)
def _handle_message(self, message):
"""Handles incoming messages."""
t = message['type']
if not t in self.subscribers:
return
subs = self.subscribers[t]
for sub in subs:
sub(parse_message(message))
def _handle_book(self, book):
self.book = book
| true |
b5c009434801ddf2d3aee58febf972b8b5d8432b | Python | repakyky/egoroff_OOP | /venv/oop22_polymorphism.py | UTF-8 | 1,798 | 4.0625 | 4 | [] | no_license |
# Полиморфизм
# Короче это такой принцип написания кода.
# Для трёх разных классов мы написали методы подсчёта площади, которые при этом работают по-разному
# (Для прямоугольника, квадрата и круга)
# При этом названия методов одинаковые - вместо:
# - get_rectangle_area;
# - get_square_area;
# - get_circle_area;
# Везде используется get_area,
# что позволяет в соседнем файле oop22_polymorphism_example.py использовать цикл for без дополнительных условий
#
# Аналогично если мы умножаем число на число, получаем произведение:
# 5 * 3 >>> 15
# А если число на строку:
# 5 * 'a' >>> 'aaaaa'
# Хотя в обоих случаях используется один и тот же оператор '*', функционал различается
# в зависимости от того, к объектам какого класса он применяется
class Rectangle:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return f'Rectangle {self.a} x {self.b}'
def get_area(self):
return self.a * self.b
class Square:
def __init__(self, a):
self.a = a
def __str__(self):
return f'Square {self.a} x {self.a}'
def get_area(self):
return self.a ** 2
class Circle:
def __init__(self, r):
self.r = r
def __str__(self):
return f'Circle rad = {self.r}'
def get_area(self):
return 3.14 * self.r ** 2 | true |
98fe8a5007f5266b2faabd1e778f0416488b5528 | Python | thinker3/py_learn | /codeeval/products_and_order.py | UTF-8 | 445 | 3.125 | 3 | [] | no_license | from sys import argv
import itertools
digits = {
'0': '0',
'1': '1',
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
}
def order(one):
one = [digits[i] for i in one]
for p in itertools.product(*one):
yield ''.join(p)
f = open(argv[1], 'r')
for one in f:
one = one.strip()
if one:
print(','.join(order(one)))
f.close()
| true |