seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
34564583000 | import logging
import os
from datetime import date
from pathlib import Path
from ._version import get_versions
from .watchdog import Watchdog
# Environment variables and if they are required
ENVIRONMENT_VARS = {
"TZ": False,
"INFLUXDB_HOST": False,
"INFLUXDB_PORT": False,
"INFLUXDB_DATABASE": False,
"INFLUXDB_USER": False,
"INFLUXDB_PASSWORD": False,
"OPERATION_MODE": False,
"SSH_LOG_PATH": False,
"LOG_LEVEL": False,
}
__version__ = get_versions()["version"]
def _real_main():
# Setup logging
_logging_setup(copyright=True)
# Unset empty variables
_unset_empty_env(ENVIRONMENT_VARS)
# Check if required variables are present
_check_vars_exist(ENVIRONMENT_VARS)
# Select if working as a TCP socket (for rsyslog) or as a log watchdog (default)
OPERATION_MODE = os.getenv("OPERATION_MODE")
if not OPERATION_MODE:
logging.warning('OPERATION_MODE variable is not set. Defaulting to "watchdog"')
OPERATION_MODE = "watchdog"
elif OPERATION_MODE.casefold() not in ("socket", "watchdog"):
err = f'OPERATION_MODE={OPERATION_MODE} is not recognised and this cannot continue"'
logging.error(err)
raise EnvironmentError(err)
else:
logging.info(f"Using OPERATION_MODE={OPERATION_MODE}")
# Bootstrap intrusion-monitor from OPERATION_MODE
_bootstrap(OPERATION_MODE)
def _bootstrap(operation_mode):
"""Initialises intrusion-monitor in either `watchdog` or `socket` operation modes."""
if operation_mode == "watchdog":
log_path = Path(os.getenv("SSH_LOG_PATH", "/watchdog/log/auth.log"))
# Check if file exists and can be read
if not log_path.exists():
err = f"No file was not found and this can't continue. Log path provided is: {log_path.absolute()}"
logging.critical(err)
return FileNotFoundError(err)
elif not os.access(log_path, os.R_OK):
err = f'The file cant be opened. Running: "sudo chmod o+r <Log file>" might solve this issue.'
logging.critical(err)
raise PermissionError(err)
else:
logging.info(f"Log file found at: {log_path.absolute()}")
with open(log_path, "r") as f:
lines = f.readlines()
logging.debug(
"Here are the last 5 lines of the log file:\n\t{}".format(
"\t".join(lines[-5:])
)
)
# Everything seems okay, starting watchdog
watchdog = Watchdog(log_path)
logging.debug(f"So far so good, starting log Watchdog...")
watchdog.start()
elif operation_mode == "socket":
logging.critical(
f"This feature is not yet implemented and this can't continue. OPERATION_MODE is {operation_mode}"
)
raise NotImplementedError(
f"The OPERATION_MODE={operation_mode} is not yet implemented."
)
# server.start()
else:
logging.critical(
f"A critical problem occurred while trying to bootstrap from OPERATION_MODE and this can't continue. "
f"OPERATION_MODE is {operation_mode}"
)
raise EnvironmentError(
"A critical problem occurred while trying to bootstrap from OPERATION_MODE and this can't continue. "
)
def _unset_empty_env(vars):
"""Unset empty environment variables."""
for v in vars:
var = os.getenv(v, None)
if not var and var is not None and len(var) == 0:
del os.environ[v]
logging.warning(
f"Environment variable {v} is set but is empty. Unsetted..."
)
def _logging_setup(copyright=True, version=True):
log_level = os.getenv("LOG_LEVEL", "info")
if log_level.casefold() == "debug":
log_level = logging.DEBUG
elif log_level.casefold() == "info":
log_level = logging.INFO
else:
# Default
log_level = logging.INFO
logging.basicConfig(
format="%(asctime)s [%(levelname)s]: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=log_level,
)
# Print copyright
if copyright:
logging.info(f"Copyright {date.today().year} Afonso Costa")
logging.info('Licensed under the Apache License, Version 2.0 (the "License");')
# Print version
if version:
logging.info("Version: {}".format(get_versions()["version"]))
logging.info(
"Intrusion Monitor: An SSH log watchdog, which exports failed login attempts to an InfluxDB timeseries database."
)
def _check_vars_exist(vars):
"""Checks if the required variables exist."""
vars_missing = []
for v in [v for v in vars if vars[v]]:
var = os.getenv(v, None)
if not var:
logging.error(f"Environment variable {v} is not set and its mandatory!")
vars_missing.append(v)
if vars_missing:
logging.critical(
"Some mandatory environment variables are not set and this can't continue. Env variables missing: {}".format(
", ".join(vars_missing)
)
)
raise EnvironmentError(
"Some mandatory environment variables are not set. Env variables missing: {}".format(
", ".join(vars_missing)
)
)
def main():
try:
_real_main()
except KeyboardInterrupt:
logging.error("ERROR: Interrupted by user")
raise
except:
logging.critical(
"Fatal error occurred and intrusion-monitor cannot continue..."
)
raise
| afonsoc12/intrusion-monitor | intrusion_monitor/__init__.py | __init__.py | py | 5,669 | python | en | code | 2 | github-code | 36 |
10351048342 |
class Vertex: #reprezentuje vrchol v grafu
def __init__(self, id, name):
self.id = id #numerický identifikátor vrcholu (int)
self.name = name #jméno vrcholu (String)
self.minDistance = float('inf') #deafaultne infinity
self.previousVertex = None
self.edges = []
class Edge: #reprezenetuje hranu v grafu
def __init__(self, source, target, weight):
self.source = source
self.target = target
self.weight = weight
class Dijkstra:
def __init__(self):
self.vertexes = [] # this is an object
def sortArray (self, stackv):
sorted = False # We haven't started sorting yet
while not sorted:
sorted = True # Assume the list is now sorted
for element in range(0, len(stackv)):
try:
if stackv[element].minDistance > stackv[element + 1].minDistance:
sorted = False # We found two elements in the wrong order
hold = stackv[element + 1]
stackv[element + 1] = stackv[element]
stackv[element] = hold
except IndexError:
break
def computePath(self, sourceId):
stackv = []
done = []
for each in self.vertexes:
if each.id == sourceId:
each.minDistance = 0
stackv.append(each)
else:
stackv.append(each)
self.sortArray(stackv)
while len(stackv) != 0:
rootVertex = stackv.pop(0)
for e in rootVertex.edges:
target = self.getVId(e.target)
distance = rootVertex.minDistance + e.weight
if target.minDistance > distance:
target.minDistance = distance
target.previousVertex = rootVertex
done.append(target)
self.sortArray(stackv)
for each in self.vertexes:
print("MinDistance to " + each.name + " is " + str(each.minDistance))
def getVId(self, vertexId):
for rootVertex in self.vertexes:
if (rootVertex.id == vertexId):
return rootVertex
def getShortestPathTo(self, targetId):
shortestPath = []
return shortestPath #vrati nejkratsi cestu
def createGraph(self, vertexes, edgesToVertexes):
self.vertexes = vertexes
for e in edgesToVertexes: # e stands for edge
for each in self.vertexes:
if each.id == e.source:
each.edges.append(e)
def resetDijkstra(self):
for v in self.vertexes:
v.minDistance = float('inf')
v.previousVertex = None
def getVertexes(self):
return self.vertexes
dijkstra = Dijkstra()
list_of_vertexes = [Vertex(0, "Redville"), Vertex(1, "Blueville"), Vertex(2, "Greenville"), Vertex(3, "Orangeville"), Vertex(4, "Purpleville")]
list_of_edges = [Edge(0, 1, 9), Edge(0, 2, 1), Edge(0, 3, 4), Edge(1, 0, 5), Edge(1, 2, 3), Edge(1, 4, 3), Edge(2, 0, 3), Edge(2, 1, 3), Edge(3, 0, 7), Edge(3, 4, 1), Edge(4, 1, 8), Edge(4, 3, 8)]
dijkstra.createGraph(list_of_vertexes, list_of_edges)
dijkstra.computePath(1)
dijkstra.resetDijkstra() | Hajneken/Python-excercises- | HW9_Dijkstra.py | HW9_Dijkstra.py | py | 3,440 | python | en | code | 0 | github-code | 36 |
7086566402 | from django.shortcuts import render,redirect
from adm.models import *
def ViewInicio(request):
listJogos = Jogo.objects.select_related('Vencedora','Perdedora').all()
context = {
"listJogos":listJogos,
}
return render(request,"inicio.html",context)
def ViewCadastro(request):
if request.method == "POST":
listPessoas = request.POST.getlist('Jogador[]', None)
x=0
objJogo = Jogo()
for pessoa in listPessoas:
objPessoa = Pessoa()
objPessoa.Nome = pessoa
objPessoa.save()
if (x%2) == 0:
objEquipe = Equipe()
objPessoaAux = objPessoa
objEquipe.Nome = objPessoa
objEquipe.save()
objEquipe.Pessoas.add(objPessoa)
else:
objEquipe.Nome = str(objPessoa) + ' e ' + str(objPessoaAux)
objEquipe.save()
objEquipe.Pessoas.add(objPessoa)
objJogo.Nome += objEquipe.Nome
objJogo.save()
objJogo.Equipes.add(objEquipe)
x+=1
return redirect("InicioJogo", objJogo.id)
context = {
"Nome_pagina": "Cadastrar Jogo"
}
return render(request,"cadastro.html", context )
def ViewInicioJogo(request,idJogo):
objJogo = Jogo.objects.select_related('Vencedora','Perdedora').get(pk=idJogo)
listEquipes = objJogo.Equipes.all()
if request.method == "POST":
try:
ObjPartida = Partida.objects.select_related('Vencedora','Perdedora','Jogo').get(Jogo=objJogo,Fim=False)
except:
ObjPartida = Partida()
ObjPartida.Jogo = objJogo
ObjPartida.save()
listRodada=[]
for index, PtsCanastra in enumerate(request.POST.getlist('PtsCanastra[]')):
obj = {
"PtsCanastra": PtsCanastra,
"QtdCartas" :request.POST.getlist("QtdCartas[]", None)[index],
"QtdRed" : request.POST.getlist("QtdRed[]", None)[index],
"QtdBlack" : request.POST.getlist("QtdBlack[]", None)[index],
"Morto" : request.POST.getlist("Morto[]", None)[index],
}
listRodada.append(obj)
EquipeSelecionada=0
MaiorPontuacao = 0
for rodada in listRodada:
ObjRodada = Rodada()
ObjRodada.Partida = ObjPartida
ObjRodada.Equipe = listEquipes[EquipeSelecionada]
ObjRodada.PontosCanastra = rodada["PtsCanastra"]
ObjRodada.QtdCartas = rodada["QtdCartas"]
ObjRodada.QtdRed = rodada["QtdRed"]
ObjRodada.QtdBlack = rodada["QtdBlack"]
ObjRodada.Morto = rodada["Morto"]
ObjRodada.TotalPontos = 0
if int(ObjRodada.PontosCanastra) < 100:
ObjRodada.TotalPontos = (((int(ObjRodada.PontosCanastra) + (int(ObjRodada.QtdCartas)*10)) - (100*int(ObjRodada.QtdRed))) - (int(ObjRodada.QtdBlack)*100))
else:
ObjRodada.TotalPontos = (((int(ObjRodada.PontosCanastra) + (int(ObjRodada.QtdCartas)*10)) + (100*int(ObjRodada.QtdRed))) - (int(ObjRodada.QtdBlack)*100))
print("confere morto")
print(ObjRodada.Morto)
if ObjRodada.Morto == 'False':
print(f" A equipe {ObjRodada.Equipe} não pegou o morto")
ObjRodada.TotalPontos -= 100
ObjRodada.save()
try:
listRodadas = Rodada.objects.select_related('Equipe','Partida').filter(Partida=ObjPartida,Equipe=listEquipes[EquipeSelecionada])
totalpontos = 0
for rodada in listRodadas:
totalpontos += rodada.TotalPontos
if totalpontos >= 3000:
if MaiorPontuacao == 0:
MaiorPontuacao = totalpontos
if MaiorPontuacao <= totalpontos:
ObjPartida.Vencedora = listEquipes[EquipeSelecionada]
ObjPartida.Fim = True
for eq in listEquipes:
if eq != listEquipes[EquipeSelecionada]:
ObjPartida.Perdedora = eq
ObjPartida.save()
except:
listRodadas = []
EquipeSelecionada+=1
#contabilizar quem ganhou mais partidas.
ListPartida = Partida.objects.select_related('Vencedora','Perdedora','Jogo').filter(Jogo=objJogo)
listEquipe1 = []
listEquipe2 = []
print("estou aqui")
for partida in ListPartida:
if partida.Vencedora:
if partida.Vencedora == listEquipes[0]:
listEquipe1.append(partida)
else:
listEquipe2.append(partida)
if len(listEquipe1)>len(listEquipe2):
print(f'{listEquipes[0]} vencedora')
objJogo.Vencedora = listEquipes[0]
objJogo.Perdedora = listEquipes[1]
elif len(listEquipe2)>len(listEquipe1):
print(f'{listEquipes[1]} vencedora')
objJogo.Vencedora = listEquipes[1]
objJogo.Perdedora = listEquipes[0]
else:
print("empate")
objJogo.Vencedora = None
objJogo.Perdedora = None
objJogo.save()
return redirect("Resultado" , objJogo.id)
context = {
"objJogo":objJogo,
"listEquipes":listEquipes,
}
return render(request,"inicio_jogo.html",context)
def ViewResultado(request,idJogo):
objJogo = Jogo.objects.select_related('Vencedora','Perdedora').get(pk=idJogo)
try:
ListPartidas = Partida.objects.select_related('Vencedora','Perdedora','Jogo').filter(Jogo=objJogo)
ListPartidasRodadas = []
for Objpartida in ListPartidas:
listRodadas = Rodada.objects.select_related('Equipe','Partida').filter(Partida=Objpartida)
obj = {
"ObjPartida" : Objpartida,
"QtdRodadas" : len(listRodadas)
}
ListPartidasRodadas.append(obj)
except Partida.DoesNotExist:
ListPartidasRodadas = []
context = {
"objJogo":objJogo,
'ListPartidasRodadas': ListPartidasRodadas
}
return render(request,"resultados.html",context)
def ViewInfo(request,idPartida,idJogo):
objJogo = Jogo.objects.select_related('Vencedora','Perdedora').get(pk=idJogo)
ObjPartida = Partida.objects.select_related('Vencedora','Perdedora','Jogo').get(pk=idPartida)
try:
ListRodada = Rodada.objects.select_related('Equipe','Partida').filter(Partida=ObjPartida)
except:
ListRodada = []
context = {
"ObjPartida":ObjPartida,
"ListRodada":ListRodada,
"objJogo":objJogo,
}
return render(request,"mais_informacoes.html",context)
| michel110299/Administrador_tranca | adm/views.py | views.py | py | 7,068 | python | pt | code | 0 | github-code | 36 |
74752046504 | from lxml import etree
import unittest
from unittest.mock import MagicMock, patch
from lib.parsers.parseOCLC import readFromClassify, loadEditions, extractAndAppendEditions
from lib.dataModel import WorkRecord
from lib.outputManager import OutputManager
class TestOCLCParse(unittest.TestCase):
@patch.object(OutputManager, 'checkRecentQueries', return_value=False)
def test_classify_read(self, mockCheck):
mockXML = MagicMock()
work = etree.Element(
'work',
title='Test Work',
editions='1',
holdings='1',
eholdings='1',
owi='1111111',
)
start = etree.Element('start')
start.text = '0'
work.text = '0000000000'
mockXML.find.side_effect = [work, start]
mockXML.findall.return_value = []
resWork, resCount, oclcID = readFromClassify(mockXML, 'testUUID')
self.assertIsInstance(resWork, WorkRecord)
self.assertEqual(resCount, 1)
self.assertEqual(oclcID, '0000000000')
mockCheck.assert_called_once_with('lookup/owi/1111111/0')
@patch('lib.parsers.parseOCLC.parseEdition', return_value=True)
def test_loadEditions(self, mockParse):
testEditions = [i for i in range(16)]
outEds = loadEditions(testEditions)
self.assertEqual(len(outEds), 16)
@patch('lib.parsers.parseOCLC.loadEditions')
def test_extractEditions(self, mockLoad):
mockXML = MagicMock()
mockXML.findall.return_value = ['ed1', 'ed2', 'ed3']
mockWork = MagicMock()
mockWork.instances = []
mockLoad.return_value = [1, 2, 3]
extractAndAppendEditions(mockWork, mockXML)
self.assertEqual(mockWork.instances, [1, 2, 3])
mockLoad.assert_called_once_with(['ed1', 'ed2', 'ed3'])
| NYPL/sfr-ingest-pipeline | lambda/sfr-oclc-classify/tests/test_parseOCLC.py | test_parseOCLC.py | py | 1,821 | python | en | code | 1 | github-code | 36 |
34124762528 | """
this program is a simulation of the inner planets of our solar system (namely the sun, Mercury,
Venus, Earth and Mars). The planets are objects of the class Planet which enables this class (solarSystemAnimation)
to animate them. The information of the planets can be found in the file PropertiesPlanets.
"""
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
from PlanetClass import Planet
class SolarSystemAnimation(object):
""" this class creates an animation using any planets found in the file PropertiesPlanets.
It then creates a simulation using these planets. There are several plots to display different things
such as the total energy of the system, or their orbit. """
def __init__(self):
# these two lists will contain the planets and their patches respectively
self.listPlanets = []
self.listPatches = []
# this gets the information from the file
self.getInfoFile()
# this is some parameters for the simulation, try to keep the timeStep small for more accuracy
self.interval = 0
self.nframes = 9999999999
self.timeStep = 70000
# this list contains the total energy for each iteration
self.listTotalEnergy = []
def getInfoFile(self):
""" this method gets all the information in the file about the planets """
self.f = open("PropertiesPlanets.txt", "r")
# first we ignore the first paragraph where we explain what the file is for.
line = self.f.readline()
while line is not "\n":
line = self.f.readline()
# this gets the information about the planets
self.getInformationPlanets()
self.f.close()
def getInformationPlanets(self):
""" This method gets all the information about the planets from the file. It also
adds a satellite with custrom parameters (but not from the file). """
line = self.f.readline()
while line is not "\n":
try:
planetName = line[:line.index("\n")]
planetMass = self.getNumber()
planetInitPosx = self.getNumber()
planetInitPosy = self.getNumber()
planetInitPos = np.array([planetInitPosx, planetInitPosy])
planetInitVelx = self.getNumber()
planetInitVely = self.getNumber()
planetInitVel = np.array([planetInitVelx, planetInitVely])
planetRadius = self.getNumber()
planetColour = self.getString()
except:
print("There was a problem while getting information from the file.")
quit()
planet = Planet(planetName, planetMass, planetInitPos, planetInitVel, planetRadius, planetColour)
self.listPlanets.append(planet)
self.listPatches.append(planet.patch)
line = self.f.readline()
# we also include a satellite that we implement here
satName = "Satellite"
satMass = 500000
satInitPos = np.array([1.5e+11+100, 0])
satInitVelx = 11500
satInitVely = -800
satInitVel = np.array([satInitVelx, satInitVely+29748.485675745])
satRadius = 928e+6
satColour = "#000000"
Satellite = Planet(satName, satMass, satInitPos, satInitVel, satRadius, satColour)
self.listPlanets.append(Satellite)
self.listPatches.append(Satellite.patch)
def getNumber(self):
""" This is a helper method that reads a line from the file and removes
everythin before the : as that is simply the name of the variable in the file.
it returns the value as a float. """
line = self.f.readline()
# here we convert the line into a float where we remove the characters begore the colon
number = float(line[line.index(':')+1:])
return number
def getString(self):
""" This is a helper method that reads a line from the file and removes
everythin before the : as that is simply the name of the variable in the file.
it returns the value as a string."""
line = self.f.readline()
string = line[line.index(':')+1:line.index('\n')]
return string
def calculateTotalEnergy(self):
""" this method calculates the total energy of the system by adding
the kinetic and potential energies together. """
self.potEnergy = Planet.calculatePotentialEnergy(self.listPlanets)
self.sumKineticEnergy = Planet.calculateTotalKineticEnergy(self.listPlanets)
self.totalEnergy = self.sumKineticEnergy + self.potEnergy
def updateTotalEnergyPlot(self):
""" this method updates the plot of the total energy. """
# y values of the graph
self.calculateTotalEnergy()
self.listTotalEnergy.append(self.totalEnergy)
# updates the plot
self.totalEnergyPlot.clear()
self.totalEnergyPlot.title.set_text("Total Energy of system over time")
self.totalEnergyPlot.plot(self.listTotalEnergy)
def printTotalEnergyToFile(self, i):
""" this method prints the total energy of the system every nth iteration. """
# reduce the frequency at which the info is written to the file
n = 50
if (i % n == 0):
self.f = open("TotalEnergy.txt", "a+")
self.f.write("Total energy of system: " + str(self.totalEnergy) + "\n")
self.f.close()
def checkDistanceSatMars(self, i):
""" This method checks whether the satelite is close to Mars. if so, it prints the time of the
journey in the legend of the plot "traces orbit". """
for planet in self.listPlanets:
if planet.name == "Satellite":
if (planet.checkDistMars(i, self.timeStep, self.listPlanets)):
for i in range(len(self.textLegendOrbit)):
if self.textLegendOrbit[i] == planet.name:
self.textLegendOrbit[i] = planet.name + " time to Mars: " + str(round(planet.distanceToMars, 7))
self.tracesOrbitPlot.legend(self.tracesOrbitPlot.lines[1:], self.textLegendOrbit, loc='lower left', bbox_to_anchor=(0.0, -0.6))
def checkOrbitPlanets(self, i):
""" This method checks if the planet has gone around then sun. If so it displays
the time it took for that planet to go around the sun in the legend of the plot "traces orbit". """
for planet in self.listPlanets:
if (planet.name != "Sun"):
if (planet.checkOrbitalPeriod(i, self.timeStep, self.listPlanets)):
for i in range(len(self.textLegendOrbit)):
if self.textLegendOrbit[i] == planet.name:
self.textLegendOrbit[i] = planet.name + " orbit: " + str(round(planet.orbitalPeriod, 7))
self.tracesOrbitPlot.legend(self.tracesOrbitPlot.lines[1:], self.textLegendOrbit, loc='lower left', bbox_to_anchor=(0.0, -0.6))
def updateDisplays(self, i):
""" this method updates the figures on the animation and everything related to
the animation. """
self.updateTotalEnergyPlot()
self.printTotalEnergyToFile(i)
# this plots the trace of the orbit for each planet
self.tracesOrbitPlot.lines = []
for planet in self.listPlanets:
planet.trail = self.tracesOrbitPlot.plot(planet.positionsx, planet.positionsy, color=planet.colour, linewidth=0.5)
self.checkDistanceSatMars(i)
self.checkOrbitPlanets(i)
self.fig.canvas.draw()
def stepForwardSimulation(self):
""" this method will make a step forward in the animation by appliying one step in
the Beeman scheme. """
# we first move the planets to their positions
for i in range(len(self.listPatches)):
self.listPatches[i].center = self.listPlanets[i].pos
# * then we calculate the postitions of te planets for the next iteration
for planet in self.listPlanets:
planet.calculatePOS(self.timeStep)
# * then we calculate the new acceleration of the planets according to their new position
for planet in self.listPlanets:
planet.calculateACC(self.listPlanets)
# * then we can calculate the velocity of each planet for the next iteration
for planet in self.listPlanets:
planet.calculateVEL(self.timeStep)
# * finally we update the values of acceleration for each planet
for planet in self.listPlanets:
planet.updateACC()
def animate(self, i):
""" This function is the one that is executed every time a frame is redrawn
so it calls the method to move the planets and the method that update the plots. """
self.updateDisplays(i)
self.stepForwardSimulation()
return self.listPatches
def initAnim(self):
""" This method is executed before the animation start, so it adds the patches
of the planets to the axes. """
for patch in self.listPatches:
self.simulationPlot.add_patch(patch)
return self.listPatches
def run(self):
""" This method launches the animation, it is called outside the class to start the
animation. """
# we first create the plot and axes
self.fig = plt.figure(figsize=(7, 7))
self.simulationPlot = plt.subplot(2,2,1)
self.tracesOrbitPlot = plt.subplot(2,2,2)
self.totalEnergyPlot = plt.subplot(2,2,3)
# set up the axes for simulationPlot
self.simulationPlot.axis('scaled')
self.simulationPlot.title.set_text("Simulation of planets")
maxOrbitalR = 0
for planet in self.listPlanets:
if planet.pos[0] > maxOrbitalR:
maxOrbitalR = planet.pos[0]
scaleUp = 1.1 * maxOrbitalR
self.simulationPlot.set_xlim(-scaleUp, scaleUp)
self.simulationPlot.set_ylim(-scaleUp, scaleUp)
# set up the axes for tracesOrbitPlot
self.tracesOrbitPlot.axis('scaled')
self.tracesOrbitPlot.title.set_text("Traces of planets in orbit")
self.tracesOrbitPlot.set_xlim(-scaleUp, scaleUp)
self.tracesOrbitPlot.set_ylim(-scaleUp, scaleUp)
for planet in self.listPlanets:
planet.trail = self.tracesOrbitPlot.plot(planet.positionsx, planet.positionsy, color=planet.colour, linewidth=0.5, label='orbit of ' + planet.name)
self.textLegendOrbit = []
for planet in self.listPlanets:
if planet.name != "Sun":
self.textLegendOrbit.append(planet.name)
self.tracesOrbitPlot.legend(self.tracesOrbitPlot.lines[1:], self.textLegendOrbit, loc='lower left', bbox_to_anchor=(0.0, -0.6))
# create the animator
FuncAnimation(self.fig, self.animate, init_func = self.initAnim, frames = self.nframes, repeat = False, interval = self.interval, blit = True)
# show the plot
plt.show()
def main():
anim = SolarSystemAnimation()
anim.run()
main() | Platiniom64/OrbitalMotionSimulation | OrbitalMotion.py | OrbitalMotion.py | py | 11,622 | python | en | code | 0 | github-code | 36 |
40983404414 | """new fileds are added user
Revision ID: 7758fd2f291e
Revises: 5444eea98e3f
Create Date: 2019-05-03 01:12:53.120773
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7758fd2f291e'
down_revision = '5444eea98e3f'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('user', sa.Column('country', sa.String(), nullable=True))
op.add_column('user', sa.Column('gender', sa.String(), nullable=True))
op.add_column('user', sa.Column('relationship_status', sa.String(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('user', 'relationship_status')
op.drop_column('user', 'gender')
op.drop_column('user', 'country')
# ### end Alembic commands ###
| ShashwatMishra/Mini-Facebook | Mini Facebook/migrations/versions/7758fd2f291e_new_fileds_are_added_user.py | 7758fd2f291e_new_fileds_are_added_user.py | py | 911 | python | en | code | 1 | github-code | 36 |
40057143195 | #!/usr/bin/env python3
import scapy.all as scapy
import argparse
from datetime import datetime
import sys
def ip():
parse = argparse.ArgumentParser()
parse.add_argument("-ip", dest="ip", help="Needs IP range /24")
parse.add_argument("-i", dest="interface", help='Needs interface')
parse.add_argument("-t", dest="time", help="Number of packets sent")
options= parse.parse_args()
if not options.ip:
parse.error('>> Needs ip address. Use -h for further details.')
elif not options.interface:
parse.error('>> Needs interface. Use -h for further details')
else:
return options
def scan(ip,interface,timer=5):
client_list=[]
while timer >0:
arp_request = scapy.ARP(pdst = ip)
broadcast= scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
ans = scapy.srp(arp_request_broadcast, timeout=1,iface=interface, verbose=False)[0]
for i in ans:
client_dic={'IP':i[1].psrc, 'MAC':i[1].hwsrc}
if client_dic not in client_list:
client_list.append(client_dic)
timer = timer -1
return client_list
def output(results_list):
print('','-'*100,'\n',"\t IP \t\t\tMac address",'\n','-'*100)
for i in results_list:
print('\t',i['IP'] + "\t\t" + i['MAC'])
options = ip()
print('\nScanning please wait:\n ')
start=datetime.now()
try:
if options.time:
scan_results=scan(options.ip, options.interface,int(options.time))
else:
scan_results=scan(options.ip, options.interface)
output(scan_results)
except KeyboardInterrupt:
print('User requested shut down:')
sys.exit()
stop=datetime.now()
duration= stop-start
print('-'*100,'\nScan Complete\n')
print('Scan duration: %s'%(duration))
| WMDA/ctf | tools/python_scripts/network_scanner.py | network_scanner.py | py | 1,853 | python | en | code | 1 | github-code | 36 |
24678905467 | class Poker:
from Trump import Trump as trump
def is_int(n):
try:
int(n)
return True
except ValueError:
return False
def error_check(s):
if len(s) > 5:
message = "ハンドは5枚です。"
elif len(s) != len(set(s)):
message = "選択したカードが重複しています。"
else:
for i in s:
if len(i) != 1:
message = "カンマ区切りで入力してください。"
break
int_check = Poker.is_int(i)
if int_check == False:
message = "0~4の数字で入力してください。"
break
else:
if int(i) >= 5:
message = "0~4の数字で入力してください。"
break
else:
message = None
return message
def hand_check(hand):
hand_num = sorted([Poker.trump().change(i[1]) for i in hand])
hand_suit = [i[0] for i in hand]
double_num = list(set(hand_num))
point_num = []
if len(set(hand_suit)) == 1:
point = 5 #フラッシュ
point_num = sorted(hand_num, reverse = True)
if len(double_num) == 5 and hand_num[0] + 4 == hand_num[4]:
point = 8 #ストレートフラッシュ
point_num = [hand_num[4]]
if hand_num[4] == 13:
point = 9 #ロイヤルストレートフラッシュ
elif len(double_num) == 5 and hand_num[0] + 4 == hand_num[4]:
point = 4 #ストレート
point_num.append(hand_num[4])
else:
if len(double_num) == 2:
if 2 <= hand_num.count(double_num[0]) <= 3:
point = 6 #フルハウス
if hand_num.count(double_num[0]) == 3:
point_num = sorted(double_num)
else:
point_num = sorted(double_num, reverse = True)
else:
point = 7 #フォーカード
point_num.append(hand_num[1])
elif len(double_num) == 3:
if hand_num.count(double_num[0]) == 2 or hand_num.count(double_num[1]) == 2:
point = 2 #ツーペア
point_num.append(hand_num[1]); point_num.append(hand_num[3])
point_num.sort(reverse = True)
else:
point = 3 #スリーカード
point_num.append(hand_num[2])
elif len(double_num) == 4:
point = 1 #ワンペア
point_num = [num for num in double_num if hand_num.count(num) > 1]
else:
point = 0 #ノーペア
return point, point_num
def stfla_check(hand):
hand_suit = [x[0] for x in hand]
set_hand_suit = list(set(hand_suit))
hand_num = [Poker.trump().change(i[1]) for i in hand]
sort_hand_num = sorted(hand_num)
flag = False
index = None
if len(set(hand_num)) == 5:
if len(set_hand_suit) == 2:
if hand_suit.count(set_hand_suit[0]) == 4 or hand_suit.count(set_hand_suit[1]) == 4:
flag = True
if hand_suit.count(set_hand_suit[0]) == 4:
suit = set_hand_suit[0]
else:
suit = set_hand_suit[1]
for i, s in enumerate(hand):
if s[0] != suit:
index = i
break
else:
if sort_hand_num[3] - sort_hand_num[0] <= 4 or sort_hand_num[4] - sort_hand_num[1] <= 4:
flag = True
if sort_hand_num[4] - sort_hand_num[1] <= 4:
num = sort_hand_num[0]
else:
num = sort_hand_num[4]
index = hand_num.index(num)
return flag, index
def point_to_hand(point):
hand_list = ["ノーペア", "ワンペア", "ツーペア", "スリーカード", "ストレート", "フラッシュ",
"フルハウス", "フォーカード", "ストレートフラッシュ", "ロイヤルストレートフラッシュ"]
return hand_list[point]
def calc_div(bet_money, point):
ratio_list = [1, 1, 2, 3, 4, 5, 7, 20, 50, 100]
div = bet_money * ratio_list[point]
return div
def judge(player, dealer):
player_point, player_num = player[0], player[1]
dealer_point, dealer_num = dealer[0], dealer[1]
if player_point > dealer_point:
result = "Player"
elif player_point < dealer_point:
result = "Dealer"
else:
if player_point == 0:
result = "Draw"
else:
for i in range(len(player_num)):
if player_num[i] < dealer_num[i]:
result = "Dealer"
break
elif player_num[i] > dealer_num[i]:
result = "Player"
break
else:
result = "Draw"
return result
#メイン
def play(self):
deck = Poker.trump().setDeck()
game_continue = input("それではドローポーカーを始めます。↩️")
#手札を用意
player_hand = []
dealer_hand = []
for i in range(5):
player_hand.append(Poker.trump().draw(deck))
dealer_hand.append(Poker.trump().draw(deck))
print("あなたのハンドは{}です。".format([card[0] + card[1] for card in player_hand]))
#賭け
bet_money = input("賭け金を入力してください >>>")
while True:
a = Poker.is_int(bet_money)
if a == True:
bet_money = int(bet_money)
break
else:
bet_money = input("数字で入力してください >>>")
#手札の交換
change = input("ハンドを交換しますか? Yes or No >>>")
while True:
if change != "Yes" and change != "No":
change = input("YesかNoで入力してください。 >>>")
else:
break
if change == "Yes":
print("一番左のカードから順番に0,1,2,3,4として、どのカードを交換しますか?")
while True:
change_card = input("複数枚の場合はカンマ','区切りで入力してください。>>>").split(",")
check = Poker.error_check(change_card)
if check != None:
print(check)
else:
change_card = [int(i) for i in change_card]
break
for i in range(len(change_card)):
add_card = Poker.trump().draw(deck)
game_continue = input("{}枚目は{} ↩️".format(i + 1, (add_card[0] + add_card[1])))
player_hand[change_card[i]] = add_card
print("あなたのハンドは{}になりました。".format([card[0] + card[1] for card in player_hand]))
player = Poker.hand_check(player_hand)
player_result = Poker.point_to_hand(player[0])
game_continue = input("あなたの役は{}です。↩️".format(player_result))
#ディーラーハンドの変更
stfla_check_dealer = Poker.stfla_check(dealer_hand)
dealer = Poker.hand_check(dealer_hand)
if stfla_check_dealer[0] == True:
dealer_hand[stfla_check_dealer[1]] = Poker.trump().draw(deck)
count = 1
else:
if dealer[0] <= 3:
dealer_hand_num = [x[1] for x in dealer_hand]
count = 0
for i, card in enumerate(dealer_hand_num):
if dealer_hand_num.count(card) == 1:
dealer_hand[i] = Poker.trump().draw(deck)
count += 1
print("Dealerはハンドを{}枚交換しました。".format(count))
dealer = Poker.hand_check(dealer_hand)
dealer_result = Poker.point_to_hand(dealer[0])
game_continue = input("Dealerのハンドは{}で、{}でした。↩️".format([card[0] + card[1] for card in dealer_hand], dealer_result))
result = Poker.judge(player, dealer)
if result == "Player":
print("おめでとうございます。あなたの勝利です。")
divident = Poker.calc_div(bet_money, player[0])
print("配当は{}円になります。".format(divident))
elif result == "Dealer":
print("Dealerの勝利となりました。")
else:
print("引き分けとなりました。")
print("またの挑戦をお待ちしております。")
# game = Poker()
# game.play() | 193-M/Trump-game | Poker.py | Poker.py | py | 9,206 | python | en | code | 0 | github-code | 36 |
29291642217 | import numpy as np
import statsmodels.api as sm
import pandas as pd
alpha = 0.05
df = pd.read_excel("4_6.xlsx", header=None)
y = df.values # 提取数据矩阵
y = y.flatten()
a = np.array(range(1, 8))
x = np.tile(a, (1, 10)).flatten()
d = {'x': x, 'y': y} # 构造字典
model = sm.formula.ols("y~C(x)", d).fit() # 构建模型
anovat = sm.stats.anova_lm(model) # 进行单因素方差分析
print(anovat)
if anovat.loc['C(x)', 'PR(>F)'] > alpha:
print("实验室对测量值无显著性影响")
else:
print("实验室对测量值有显著性影响")
| BattleforAzeroth/MMHomework | 4.6.py | 4.6.py | py | 565 | python | en | code | 0 | github-code | 36 |
38055178106 | import numpy as np
from tensorflow import keras
from src.util.load_review import return_tensored_review
#cutoff value for the sentiment
cutoff = 0.5
#loading movie review
movie_review = return_tensored_review("pale_blue_eyes.txt")
#loading the saved model
model = keras.models.load_model("src/saved_model")
prediction = model.predict(movie_review.reshape(1,10000))
if prediction[0] < cutoff:
print("negative")
if prediction[0] > cutoff:
print("positive")
| Weierstrash/review_sentiment_analysis | main.py | main.py | py | 467 | python | en | code | 0 | github-code | 36 |
41662398078 | import pandas as pd
import numpy as np
import os
PATH = 'data/movielens/'
TRAINFILE = PATH + 'train.csv'
TESTFILE = PATH + 'test.csv'
VALIDFILE = PATH + 'val.csv'
MAPFILE=PATH+'item2id.map'
def get_item():
train = pd.read_csv(TRAINFILE, sep='\t')
valid = pd.read_csv(VALIDFILE, sep='\t')
test = pd.read_csv(TESTFILE, sep='\t')
data = pd.concat([train, valid, test])
return data.item.unique()
def load_data(f, max_len):
if os.path.exists(MAPFILE):
item2idmap = {}
with open(MAPFILE,'r') as fi:
lines=fi.readlines()
for line in lines:
k, v = line.strip().split('\t')
item2idmap[int(k)] = int(v)
else:
items = get_item()
item2idmap = dict(zip(items, range(items.size)))
with open(MAPFILE, 'w') as fo:
for k, v in item2idmap.items():
fo.write(str(k) + '\t' + str(v) + '\n')
n_items = len(item2idmap)
data = pd.read_csv(f, sep='\t')
data['item'] = data['item'].map(item2idmap)
data = data.sort_values(by=['Time']).groupby('user')['item'].apply(list).to_dict()
new_x = []
new_y = []
for k, v in data.items():
if len(v) < max_len + 1:
continue
x = v[:max_len]
y = [0] * n_items
y[v[max_len]] = 1
new_x.append(x)
new_y.append(y)
return new_x, new_y, n_items
def load_train(max_len):
return load_data(TRAINFILE, max_len)
def load_valid(max_len):
return load_data(VALIDFILE, max_len)
def load_test(max_len):
return load_data(TESTFILE, max_len)
def cal_eval(top_k_index,labels):
users = np.shape(top_k_index)[0]
top_k = np.shape(top_k_index)[1]
hits, ndcg, mrr = 0, 0.0, 0.0
for i in range(users):
cur_user = top_k_index[i]
for j in range(top_k):
if labels[i] == cur_user[j]:
hits += 1
mrr += 1 / (1 + j)
dcg = 1 / np.log2(1 + 1 + j)
idcg = 1 / np.log2(1 + 1)
ndcg += dcg / idcg
break
return hits / users,ndcg / users,mrr / users
if __name__=="__main__":
load_train(16) | TraceIvan/RCNN_for_Recommendation | utils.py | utils.py | py | 2,245 | python | en | code | 5 | github-code | 36 |
12803394908 | import urllib2
import json
headers = {'Content-Type': 'application/json; charset=utf-8'}
XXX_HOST = "http://xxx.xxx.com/xxx-app/"
# post请求,json格式数据
def post_json(url, header, request_data):
req = urllib2.Request(url, request_data, header)
page = urllib2.urlopen(req)
res = page.read()
page.close()
return res
YYY_HOST = "http://yyy.yyy.com/yyy-app/"
# get请求
def get_(param1, param2):
url = YYY_HOST + "yyyy/yyyy?param1=" + \
str(param1) + "¶m2=" + str(param2) + "¶m3=VIP"
req = urllib2.Request(url)
page = urllib2.urlopen(req, timeout=5000)
res = page.read()
page.close()
return json.loads(res)["data"] | AldrichYang/HelloPython2 | src/http/http_helper.py | http_helper.py | py | 690 | python | en | code | 0 | github-code | 36 |
39479105306 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.management.base import BaseCommand, CommandError
from cards.search import searchservice
from cards.models import Card, BaseCard
from cards.models import PhysicalCard
import json
from django.utils import dateparse
import codecs
import sys
from elasticsearch import Elasticsearch, exceptions
from kitchen.text.converters import getwriter
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--full', dest='full', action='store_true',
help='Rebuild the entire index, not just data that has changed.')
def handle(self, *args, **options):
# check the card index
self.checkCardIndex()
self.checkCardnameIndex()
# first, let's get the most recent doc change in ES:
lmt_q = {
"query": {"match_all": {}},
"size": 1,
"sort": [
{
"_update_datetime": {
"order": "desc"
}
}
]
}
lmt_res = searchservice.search(index='card', body=lmt_q)
last_time = None
try:
sys.stdout.write("timestamp: {}\n".format(json.dumps(lmt_res['hits']['hits'][0]['_source']['_update_datetime'])))
last_time = dateparse.parse_datetime(lmt_res['hits']['hits'][0]['_source']['_update_datetime'])
except KeyError:
# no doc, I guess
pass
sys.stdout.write("'card' index last updated {}\n".format(last_time))
pcs = None
if not last_time or options['full']:
sys.stdout.write("Re-indexing entire card database...\n")
pcs = PhysicalCard.objects.all()
#pcs = PhysicalCard.objects.filter(pk__gte=15200, pk__lt=15800)
else:
cards = Card.objects.filter(updated_at__gte=last_time)
bc_ids = {}
for card in cards:
bc_ids[card.basecard_id] = True
basecards = BaseCard.objects.filter(updated_at__gte=last_time)
pc_ids = {}
for basecard in basecards:
#sys.stderr.write("bc -> pc {}\n".format(basecard.physicalcard_id))
pc_ids[basecard.physicalcard_id] = True
basecards = BaseCard.objects.filter(id__in=[bc_id for bc_id in bc_ids])
for basecard in basecards:
pc_ids[basecard.physicalcard_id] = True
pcs = PhysicalCard.objects.filter(id__in=[pc_id for pc_id in pc_ids])
total_count = pcs.count()
counter = 0
sys.stdout.write("Cards to index: {}\n".format(total_count))
for pc in pcs:
searchservice.index_physicalcard(pc)
counter += 1
if counter % 100 == 0:
sys.stdout.write("{:>6} : {:>4.0%} complete\n".format(counter, float(counter) / float(total_count)))
sys.stdout.write("Complete!\n")
def checkCardIndex(self):
index_name = 'card'
try:
val = searchservice._es.indices.get_settings(index_name)
except exceptions.NotFoundError:
sys.stdout.write("'{}' index does not exist. Creating it...\n".format(index_name))
searchservice._es.indices.create(index=index_name,
body={})
return True
def checkCardnameIndex(self):
index_name = 'cardname'
cur_mappings = None
try:
cur_mappings = searchservice._es.indices.get_mapping(index_name)
except exceptions.NotFoundError:
sys.stdout.write("'{}' index does not exist. Creating it...\n".format(index_name))
with open('elasticsearch/cardname_settings.json', 'r') as cnsjson_fh:
cns = json.load(cnsjson_fh)
sys.stdout.write("Creating '{}' index with:\n{}\n".format(index_name, json.dumps(cns, indent=2)))
searchservice._es.indices.create(index=index_name,
body=cns)
if cur_mappings:
# we need to validate that there is an ngram field on the "name" property. If there isn't, we should bail.
# cur_settings['cardname']['settings']['index']
# BOOKMARK - check to see if there is an ngram mappings on "name"
try:
ngram = cur_mappings[index_name]['mappings']['cardname']['properties']['name']['fields']['ngram']
slug = cur_mappings[index_name]['mappings']['cardname']['properties']['slug']
lmvid = cur_mappings[index_name]['mappings']['cardname']['properties']['latest_multiverseid']
except KeyError as ke:
sys.stdout.write("{} index does not have an 'ngram' field on 'name'.\n".format(index_name))
sys.stdout.write("{} index Mappings:\n{}\n".format(index_name, json.dumps(cur_mappings, indent=2)))
sys.stdout.write("Aborting.\n")
# You may need to drop the old index and start over.
sys.stdout.write("Try this to get the index started...\n")
sys.stdout.write("curl -X DELETE '{}:{}/{}?pretty'\n".format(searchservice._host, searchservice._port, index_name))
sys.stdout.write(
"curl -X PUT '{}:{}/{}?pretty' -H 'Content-Type: application/json' -d @elasticsearch/cardname_settings.json\n".format(
searchservice._host,
searchservice._port,
index_name))
raise ke
return True
| jcrickmer/mtgdbpy | cards/management/commands/reindex_es.py | reindex_es.py | py | 5,648 | python | en | code | 0 | github-code | 36 |
42883327134 | class Solution:
def findWinners(self, matches):
ans = [[],[]]
games = {}
for game in matches:
if not (game[0] in games): games[game[0]] = 0
if game[1] in games:
games[game[1]] += 1
continue
else: games[game[1]] = 1
for key in dict(sorted(games.items())):
if games[key] > 1:
continue
elif games[key] == 1: ans[1].append(key)
else: ans[0].append(key)
return ans
if __name__ == "__main__":
test = Solution()
print(test.findWinners([[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]))
pass | pablorenato1/leetcode-problems | Medium/Find-Players-With-Zero-or-One-Losses.py | Find-Players-With-Zero-or-One-Losses.py | py | 684 | python | en | code | 0 | github-code | 36 |
40587003321 | from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.decorators import login_required
from django.http import (HttpRequest, HttpResponse, HttpResponseNotFound,
HttpResponseRedirect)
from django.shortcuts import redirect, render
from django.urls import reverse_lazy
from django.views.decorators.cache import cache_page
from core import constants as const
from core.db_queries import Query
INDEX_URL = reverse_lazy('questions:index')
QUESTIONS_URL = reverse_lazy('questions:questions')
FINISH_URL = reverse_lazy('questions:finish_test')
# @cache_page(timeout=20, key_prefix='index') # 10 minutes
def index(request: HttpRequest):
"""Обработчик для главной страницы.
"""
context = {
'title' : const.TITLE,
'card_header' : const.INDEX_CARD_HEADER,
'index_page_text' : const.INDEX_PAGE_TEXT,
'maximum_grade' : Query.get_maximum_grade(),
}
return render(request, 'index.html', context)
# @cache_page(timeout=60, key_prefix='rating') # 1 minute
def rating(request: HttpRequest):
"""Показывает рейтинг пользователей.
"""
context = {
'title' : const.TITLE,
'header' : const.ALL_RESULTS_CARD_HEADER,
'results' : Query.get_users_rating()
}
return render(request, 'questions/results.html', context)
@login_required
def my_results(request: HttpRequest):
"""Показывает все результаты текущего пользователя.
"""
user: AbstractBaseUser = request.user
context = {
'title' : const.TITLE,
'header' : const.MY_RESULTS_CARD_HEADER,
'results' : Query.get_user_results(user)
}
return render(request, 'questions/results.html', context)
def get_question(
request: HttpRequest
):
"""Выводит очередной вопрос и учитывает ответы.
Если предыдущий тест был случайно прерван, продолжит предыдущий тест.
"""
user: AbstractBaseUser = request.user
if user.is_anonymous:
return redirect(INDEX_URL)
question = Query.get_next_question(user=user)
if question is None:
return redirect(FINISH_URL)
context = {
'title' : const.TITLE,
'question' : question,
'button_type' : ('radio', 'checkbox')[question.many_answers]
}
return render(request, 'questions/question.html', context)
@login_required
def add_answer(
request: HttpRequest,
question_pk: int
):
"""Учитывает переданные пользователем ответы.
"""
question = Query.get_current_question(
question_pk=question_pk
)
if question is None:
return HttpResponseNotFound('<h1>Page not found</h1>')
context = {
'title' : const.TITLE,
'question' : question,
'button_type' : ('radio', 'checkbox')[question.many_answers]
}
choice = request.POST.getlist('answer')
if not choice:
context['error_message'] = const.ERR_NO_ANSWERS
return render(request, 'questions/question.html', context)
if not Query.update_result(
user =request.user,
question_pk =question_pk,
choice =choice
):
context['error_message'] = const.ERR_FALSE_ANSWERS
return render(request, 'questions/question.html', context)
return redirect(QUESTIONS_URL)
def to_finish_test(
request: HttpRequest
) -> HttpResponse | HttpResponseRedirect:
"""Завершает тест.
Если пользователь не проходил тестов, либо пытается завершить без
отмеченных ответов, перекидывает на главную страницу.
Начатый тест будет продолжен в дальнейшем.
"""
user: AbstractBaseUser = request.user
if user.is_anonymous:
return redirect(INDEX_URL)
closed, current_result = Query.close_last_result(user)
if not closed:
return redirect(INDEX_URL)
context = {
'title' : const.TITLE,
'header' : const.FINISH_CARD_HEADER,
'result' : current_result
}
return render(request, 'questions/finish.html', context)
| Xewus/Examiner | src/questions/views.py | views.py | py | 4,430 | python | ru | code | 0 | github-code | 36 |
31635729829 | import os
import torch
import torchvision
import random
import pandas as pd
import numpy as np
import torch.nn as nn
import matplotlib.pyplot as plt
from PIL import Image
import cv2
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision.models as models
from torch.utils.data import Dataset, random_split, DataLoader
from torchvision.datasets import ImageFolder
from torchvision import models
from torch import optim
from torchsummary import summary
from math import atan2, degrees
class CatPicture():
def __init__(self, filename):
self.which_p = 1
self.which_d = 1
self.wear_list = [0, 0, 0]
self.ori_filename = filename
tmp_idx = filename.rfind(".")
self.short_filename = filename[:tmp_idx]
def resize_img(im):
old_size = im.shape[:2] # old_size is in (height, width) format
ratio = float(img_size) / max(old_size)
new_size = tuple([int(x * ratio) for x in old_size])
# new_size should be in (width, height) format
im = cv2.resize(im, (new_size[1], new_size[0]))
delta_w = img_size - new_size[1]
delta_h = img_size - new_size[0]
top, bottom = delta_h // 2, delta_h - (delta_h // 2)
left, right = delta_w // 2, delta_w - (delta_w // 2)
new_im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT,
value=[0, 0, 0])
return new_im, ratio, top, left
class CatDataset(Dataset):
def __init__(self, images, labels, transform):
self.imgs = images
self.labels = labels
self.transform = transform
def __len__(self):
return len(self.imgs) # return DataSet 長度
def __getitem__(self, idx):
image = self.imgs[idx]
image = image[..., ::-1].copy()
image = self.transform(image)
label = np.array(self.labels[idx])
return image, label # return 模型訓練所需的資訊
def Catface_dataloader(img):
test_inputs = []
test_inputs.append(img)
test_labels = [0 for i in range(4)]
test_dataloader = DataLoader(CatDataset(test_inputs, test_labels, test_transformer),
batch_size=1, shuffle=False)
return test_dataloader
def Lmks_dataloader(img):
test_inputs = []
test_inputs.append(img)
test_labels = [0 for i in range(18)]
test_dataloader = DataLoader(CatDataset(test_inputs, test_labels, test_transformer),
batch_size=1, shuffle=False)
return test_dataloader
class CatFaceModule(nn.Module):
def __init__(self):
super(CatFaceModule, self).__init__()
v = torch.hub.load('pytorch/vision:v0.6.0',
'mobilenet_v2', pretrained=True)
v.classifier[1] = nn.Linear(v.last_channel, 4)
self.layer1 = v
def forward(self, x):
out = self.layer1(x)
return out
class LmksModule(nn.Module):
def __init__(self):
super(LmksModule, self).__init__()
v = torch.hub.load('pytorch/vision:v0.6.0',
'mobilenet_v2', pretrained=True)
v.classifier[1] = nn.Linear(v.last_channel, 18)
self.layer1 = v
def forward(self, x):
out = self.layer1(x)
return out
# main program
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
img_size = 224
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
test_transformer = transforms.Compose([
transforms.ToTensor(),
normalize
])
# the path of models
cat_face_model_path = "mobilenet_RMSELoss500.ph"
lmks_model_path = "mobilenet_RMSELoss100_36.ph"
# load the models
cat_model = CatFaceModule().to(device)
cat_model.load_state_dict(torch.load(cat_face_model_path))
cat_model.eval()
lmks_model = LmksModule().to(device)
lmks_model.load_state_dict(torch.load(lmks_model_path))
lmks_model.eval()
# the path of the image you want to test
img_path = filename
# read the image
img = cv2.imread(img_path)
ori_img = img.copy()
result_img = img.copy()
img, ratio, top, left = resize_img(img)
# plt.figure()
# plt.imshow(img)
predicted = []
# catface predicted
catface_dataloader = Catface_dataloader(img)
for i, (x, label) in enumerate(catface_dataloader):
with torch.no_grad():
x, label = x.to(device), label.to(device)
output = cat_model(x)
# loss = criterion(output, label.long())
predicted = output.data[0].reshape((-1, 2))
# the position of the cat face box
pre_bb = predicted.cpu().numpy()
# print(pre_bb)
# the positoin of the cat face box when it at the origin image
ori_bb = ((pre_bb - np.array([left, top])) / ratio).astype(np.int)
# print(ori_bb)
# cut the face image
center = np.mean(ori_bb, axis=0)
face_size = max(np.abs(ori_bb[1] - ori_bb[0]))
new_bb = np.array([
center - face_size * 0.6,
center + face_size * 0.6
]).astype(np.int)
new_bb = np.clip(new_bb, 0, 99999)
face_img = ori_img[new_bb[0][1]:new_bb[1]
[1], new_bb[0][0]:new_bb[1][0]]
# plt.figure()
# plt.imshow(face_img)
face_img, face_ratio, face_top, face_left = resize_img(face_img)
# landmark prediction
lmks_dataloader = Lmks_dataloader(face_img)
for i, (x, label) in enumerate(lmks_dataloader):
with torch.no_grad():
x, label = x.to(device), label.to(device)
output = lmks_model(x)
# loss = criterion(output, label.long()) # 計算測試資料的準確度
predicted = output.data[0].reshape((-1, 2))
pred_lmks = predicted.cpu().numpy()
# print(pred_lmks)
new_lmks = (
(pred_lmks - np.array([face_left, face_top])) / face_ratio).astype(np.int)
self.ori_lmks = new_lmks + new_bb[0]
ori_img = cv2.cvtColor(ori_img, cv2.COLOR_BGR2RGB)
# initial cat
self.ori_pic = result_img
tmp_filename = self.short_filename + "_000.jpg"
cv2.imwrite(tmp_filename, result_img)
# main end
def angle_between(self, p1, p2):
xDiff = p2[0] - p1[0]
yDiff = p2[1] - p1[1]
return degrees(atan2(yDiff, xDiff))
def overlay_transparent(self, background_img, img_to_overlay_t, x, y, overlay_size=None):
bg_img = background_img.copy()
# convert 3 channels to 4 channels
if bg_img.shape[2] == 3:
bg_img = cv2.cvtColor(bg_img, cv2.COLOR_BGR2BGRA)
if overlay_size is not None:
img_to_overlay_t = cv2.resize(
img_to_overlay_t.copy(), overlay_size)
b, g, r, a = cv2.split(img_to_overlay_t)
for i in range(len(a)):
for j in range(len(a[0])):
if a[i][j] < 200:
a[i][j] = 0
#mask = cv2.medianBlur(a, 5)
mask = a
h, w, _ = img_to_overlay_t.shape
roi = bg_img[int(y - h / 2):int(y + h / 2),
int(x - w / 2):int(x + w / 2)]
img1_bg = cv2.bitwise_and(roi.copy(), roi.copy(),
mask=cv2.bitwise_not(mask))
img2_fg = cv2.bitwise_and(
img_to_overlay_t, img_to_overlay_t, mask=mask)
bg_img[int(y - h / 2):int(y + h / 2), int(x - w / 2) :int(x + w / 2)] = cv2.add(img1_bg, img2_fg)
# convert 4 channels to 4 channels
bg_img = cv2.cvtColor(bg_img, cv2.COLOR_BGRA2BGR)
return bg_img
def setWearList(self, which_pattern):
self.wear_list[self.which_d] = which_pattern
def CreateBasePic(self):
tmp_list = self.wear_list[:]
tmp_list[self.which_d] = 0
base_filepath = self.short_filename + "_" + \
str(tmp_list[0]) + str(tmp_list[1]) + str(tmp_list[2]) + ".jpg"
if os.path.isfile(base_filepath):
return
self.WearHat(tmp_list[0], 0, 0)
self.WearBow(tmp_list[0], tmp_list[1], 0)
self.WearGlasses(tmp_list[0], tmp_list[1], tmp_list[2])
def WearDecorate(self):
self.CreateBasePic()
if self.which_d == 0:
self.WearHat(self.wear_list[0],
self.wear_list[1], self.wear_list[2])
elif self.which_d == 1:
self.WearBow(self.wear_list[0],
self.wear_list[1], self.wear_list[2])
else:
self.WearGlasses(self.wear_list[0],
self.wear_list[1], self.wear_list[2])
new_name = self.short_filename + "_" + \
str(self.wear_list[0]) + str(self.wear_list[1]
) + str(self.wear_list[2]) + ".jpg"
return new_name
def WearHat(self, h_n, b_n, g_n):
if h_n == 0:
return
# add hat
hat_name = "hat" + str(h_n) + ".png"
hat = cv2.imread(hat_name, cv2.IMREAD_UNCHANGED)
hat_center = np.mean([self.ori_lmks[5], self.ori_lmks[6]], axis=0)
hat_size = np.linalg.norm(self.ori_lmks[5] - self.ori_lmks[6]) * 3
angle = -self.angle_between(self.ori_lmks[5], self.ori_lmks[6])
M = cv2.getRotationMatrix2D(
(hat.shape[1] / 2, hat.shape[0] / 2), angle, 1)
rotated_hat = cv2.warpAffine(hat, M, (hat.shape[1], hat.shape[0]))
base_name = self.short_filename + "_" + \
"0" + str(b_n) + str(g_n) + ".jpg"
new_name = self.short_filename + "_" + \
str(h_n) + str(b_n) + str(g_n) + ".jpg"
base_pic = cv2.imread(base_name)
try:
cat = self.overlay_transparent(base_pic, rotated_hat, hat_center[0], hat_center[1], overlay_size=(
int(hat_size), int(hat.shape[0] * hat_size / hat.shape[1])))
except:
print('failed overlay image')
cv2.imwrite(new_name, cat)
def WearBow(self, h_n, b_n, g_n):
if b_n == 0:
return
# add bow
bow_name = "bow" + str(b_n) + ".png"
bow = cv2.imread(bow_name, cv2.IMREAD_UNCHANGED)
bow_center = np.mean([self.ori_lmks[3], self.ori_lmks[5]], axis=0)
bow_size = np.linalg.norm(self.ori_lmks[3] - self.ori_lmks[5]) * 1.5
angle = -self.angle_between(self.ori_lmks[3], self.ori_lmks[5])
M = cv2.getRotationMatrix2D(
(bow.shape[1] / 2, bow.shape[0] / 2), angle, 1)
rotated_bow = cv2.warpAffine(bow, M, (bow.shape[1], bow.shape[0]))
base_name = self.short_filename + "_" + \
str(h_n) + "0" + str(g_n) + ".jpg"
new_name = self.short_filename + "_" + \
str(h_n) + str(b_n) + str(g_n) + ".jpg"
base_pic = cv2.imread(base_name)
cat = self.overlay_transparent(base_pic, rotated_bow, bow_center[0], bow_center[1], overlay_size=(
int(bow_size), int(bow.shape[0] * bow_size / bow.shape[1])))
cv2.imwrite(new_name, cat)
def WearGlasses(self, h_n, b_n, g_n):
# add glasses
if g_n == 0:
return
glasses_name = "glasses" + str(g_n) + ".png"
glasses = cv2.imread(glasses_name, cv2.IMREAD_UNCHANGED)
glasses_center = np.mean([self.ori_lmks[0], self.ori_lmks[1]], axis=0)
glasses_size = np.linalg.norm(
self.ori_lmks[0] - self.ori_lmks[1]) * 2.5
angle = -self.angle_between(self.ori_lmks[0], self.ori_lmks[1])
M = cv2.getRotationMatrix2D(
(glasses.shape[1] / 2, glasses.shape[0] / 2), angle, 1)
rotated_glasses = cv2.warpAffine(
glasses, M, (glasses.shape[1], glasses.shape[0]))
base_name = self.short_filename + "_" + \
str(h_n) + str(b_n) + "0" + ".jpg"
new_name = self.short_filename + "_" + \
str(h_n) + str(b_n) + str(g_n) + ".jpg"
base_pic = cv2.imread(base_name)
cat = self.overlay_transparent(base_pic, rotated_glasses, glasses_center[0], glasses_center[1], overlay_size=(
int(glasses_size), int(glasses.shape[0] * glasses_size / glasses.shape[1])))
cv2.imwrite(new_name, cat)
| a20815579/cat_face_detection | cat_CNN.py | cat_CNN.py | py | 13,278 | python | en | code | 1 | github-code | 36 |
31298538173 | def solution(relation):
column = len(relation[0])
row = len(relation)
candidateKey = []
for case in range(1, 2**column):
minimality = True
uniqueness = True
hashmap = {}
for key in candidateKey:
if key & case == key:
minimality = False
break
if minimality == False:
continue
for r in range(row):
tmpStr = ''
curCols = []
for k in range(column):
if case & (1 << k):
curCols.append(k)
for c in curCols:
tmpStr += relation[r][c]
if tmpStr in hashmap:
uniqueness = False
break
hashmap[tmpStr] = True
if uniqueness:
candidateKey.append(case)
answer = len(candidateKey)
return answer
print(solution([
["100", "ryan", "music", "2"],
["200", "apeach", "math", "2"],
["300", "tube", "computer", "3"],
["400", "con", "computer", "4"],
["500", "muzi", "music", "3"],
["600", "apeach", "music", "2"]]))
| shwjdgh34/algorithms-python | codingTest/2019kakao/후보키.py | 후보키.py | py | 1,122 | python | en | code | 2 | github-code | 36 |
39472235141 | import json
from flask import request, jsonify
from flask_restful import Resource
from werkzeug.exceptions import BadRequest
from managers.brand import BrandManager
from models import RoleType
from models.products import *
from schemas.request.brand import CreateBrandRequestSchema, EditBrandRequestSchema
from schemas.response.brand import (
CreateBrandResponseSchema,
BrandNameOnlyResponseSchema,
)
from utils.decorators import validate_schema, token_required, permission_required
from dotenv import load_dotenv
load_dotenv()
import cloudinary
import cloudinary.uploader
import cloudinary.api
config = cloudinary.config(secure=True)
class Brand(Resource):
@validate_schema(CreateBrandRequestSchema)
@permission_required(RoleType.admin)
def post(self):
# uploaded_files = request.files.get('file', '')
# print(uploaded_files)
# a = request
# print(a)
#
# upload_result = cloudinary.uploader.upload(uploaded_files)
# return jsonify(upload_result)
brand = BrandManager.create(request.get_json())
schema = CreateBrandResponseSchema()
return schema.dumps(brand)
@staticmethod
def get():
brand_name = request.args.get("brand")
schema = CreateBrandResponseSchema()
if not brand_name:
brands = BrandManager.get_all()
brand_name_schema = BrandNameOnlyResponseSchema()
return brand_name_schema.dumps(brands, many=True)
if brand_name == "all":
brands = BrandManager.get_all()
return schema.dumps(brands, many=True)
elif brand_name:
brands = BrandManager.get_by_name(brand_name)
return schema.dumps(brands)
raise BadRequest("You should use query parameters, check the documentation!")
class BrandUpdate(Resource):
@staticmethod
@permission_required(RoleType.admin)
def get(id_):
brand = BrandManager.get_by_id(id_)
schema = CreateBrandResponseSchema()
return schema.dumps(brand)
@staticmethod
@permission_required(RoleType.admin)
@validate_schema(EditBrandRequestSchema)
def put(id_):
brand = BrandManager.edit_brand(id_, request.get_json())
schema = CreateBrandResponseSchema()
return schema.dumps(brand)
@staticmethod
@permission_required(RoleType.admin)
def delete(id_):
result = BrandManager.delete(id_)
return json.dumps(result)
| a-angeliev/Shoecommerce | server/resources/brand.py | brand.py | py | 2,486 | python | en | code | 0 | github-code | 36 |
11371604753 | import logging
from sklearn.metrics import accuracy_score
from pytorch_tabular import TabularModel
from pytorch_tabular.config import DataConfig, OptimizerConfig, TrainerConfig
from ml.solvers.base_solver import Solver
class PytorchTabularSolver(Solver):
def init_model(self):
super(PytorchTabularSolver, self).init_model()
data_config = DataConfig(
target=['Y'],
# target should always be a list. Multi-targets are only supported for regression. Multi-Task Classification is not implemented
continuous_cols=list(self.val_loader.df_data[0].select_dtypes(include=['int64']).columns),
categorical_cols=list(self.val_loader.df_data[0].select_dtypes(include=['object', 'uint8']).columns),
validation_split=0.0)
trainer_config = TrainerConfig(**self.config.trainer.params.dict()) # index of the GPU to use. 0, means CPU
optimizer_config = OptimizerConfig()
self.model = TabularModel(data_config=data_config,
model_config=self.model,
optimizer_config=optimizer_config,
trainer_config=trainer_config)
def load_model(self):
try:
self.model = TabularModel.load_from_checkpoint(self.result_dir)
except FileNotFoundError as e:
logging.info('No saved model found: no model is loaded.')
def train(self):
"""
Training the tree based networks.
Save the model if it has better performance than the previous ones.
"""
self.model.fit(train=self.train_loader.df,
validation=self.val_loader.df)
# save model
self.model.save_model(self.result_dir)
self.eval()
self.save_acc()
def eval(self):
"""
Evaluate the model.
"""
preds = self.model.predict(self.val_loader.df_data[0]).prediction.to_numpy()
gt = self.val_loader.data[1]
self.accuracy = accuracy_score(preds, gt)
print(self.accuracy)
if self.config.env.save_preds:
self.save_preds(preds)
| gregiberri/coupon | ml/solvers/pytorch_tabular_solver.py | pytorch_tabular_solver.py | py | 2,165 | python | en | code | 0 | github-code | 36 |
36211707503 | #file a transaction
#any changes to the users balanace should be reflected in the account file
import datetime
def transaction_options(accounts_path, line_number):
stay_logged_in = True
while stay_logged_in == True:
ask = input('Would you like to make a transaction, return to the homepage, or logout (T/H/L)? ').upper()
if ask == 'T':
transaction(accounts_path, line_number)
elif ask == 'H':
return homepage()
elif ask == 'L':
return logout()
else:
print ('Invalid input')
def transaction(accounts_path, line_number):
person_involved = input('First input the other entity involved in the transaction: ')
transaction_amount = ''
continue_transaction = True
while continue_transaction == True:
money = input("Next tell us the money transferred, if you spent money add a '-' in front of the amount: ")
money_list = []
money_list[:0] = money
if money_list[0] == '-':
money_list[0] = '0'
for num in money_list:
if num.isnumeric() == False:
print ('money only contains numbers')
continue
#if the hyphen was changed to a 0, change it back
if money_list[0] == '0':
money_list[0] = '-'
#convert the list back into a string
for num in money_list:
transaction_amount += num
continue_transaction = False
#ask the user for the date of the transaction
#syntax check for the date
#write the other entity, amount of money, and date into the transaction history file
enter_date = True
while enter_date == True:
date_of_transaction = input('Lastly, tell us the date this transaction occurred, use the format yyyy-mm-dd: ')
format = '%Y-%m-%d'
try:
datetime.datetime.strptime(date_of_transaction, format)
except ValueError:
print ('This is the incorrect date format, please try again')
continue
break
#get the account number so we can open their transaction history
with open(accounts_path, 'r') as accounts_file:
#list of all the lines in the accounts file where each item is 1 line from the file
accounts_list = accounts_file.readlines()
#split the string at index line_number into a list of separate values
split_line = accounts_list[line_number].split(', ')
#if the 2nd element in the split_line list matches the inputted password, the user has successfully logged in
account_number = split_line[0]
#this needs to print on a newline
with open (f'{account_number}.txt', 'a') as transaction_history:
transaction_history.write(f'{person_involved}, {transaction_amount}, {date_of_transaction}\n')
#open the file
#find the line where the account number matches
#change the balance value
#re write the whole file
# with open(accounts_path, 'r') as accounts_file:
# #list of all the lines in the accounts file where each item is 1 line from the file
# accounts_list = accounts_file.readlines()
# #split the string at index line_number into a list of separate values
# split_line = accounts_list[line_number].split(', ')
# #if the 2nd element in the split_line list matches the inputted password, the user has successfully logged in
# account_number = split_line[4]
def homepage():
print ('Returning to the homepage')
return True
def logout():
print ('Logging you out now, returning to login screen')
return False
| 2105-may24-devops/fletcher-project0 | transaction_module.py | transaction_module.py | py | 3,661 | python | en | code | 0 | github-code | 36 |
8755383285 | # -*- coding: utf-8 -*-
import json
import logging
from datetime import datetime, date, timedelta
from odoo import api, fields, models
from odoo.addons.muk_dms.models import dms_base
logger = logging.getLogger('FOLLOW-UP')
AVAILABLE_PRIORITIES = [
('0', u'Normale'),
('1', u'Basse'),
('2', u'Haute'),
('3', u'Très haute'),
]
class OFFollowupProject(models.Model):
_name = 'of.followup.project'
_inherit = 'mail.thread'
_description = "Suivi des projets"
_order = "priority desc, reference_laying_date, id desc"
@api.model
def _init_group_of_followup_project_not_migrated(self):
# On utilise une fonction déclenchée par le XML plutôt qu'un auto_init, car au moment de l'auto_init le groupe
# n'existe pas encore.
# Si la migration n'a pas été faite, ajouter le groupe group_of_followup_project_not_migrated à
# tous les utilisateurs
if not self.env['ir.config_parameter'].sudo().get_param('of.followup.migration', False):
group_not_migrated = self.env.ref('of_followup.group_of_followup_project_not_migrated')
group_user = self.env.ref('base.group_user')
if group_not_migrated not in group_user.implied_ids:
group_user.write({'implied_ids': [(4, group_not_migrated.id)]})
def _get_order_values(
self, project, mapping_project_tags, default_of_kanban_step_id, done_of_kanban_step_id,
in_progress_of_kanban_step_id):
"""Helper that return a dict of values to write on a Sale depending of the Project followup"""
otag_ids = []
if project.tag_ids:
otag_ids = [mapping_project_tags[pt.id] for pt in project.tag_ids]
kanban_step_id = in_progress_of_kanban_step_id
if project.state in ('done', 'cancel'):
kanban_step_id = done_of_kanban_step_id
elif not project.reference_laying_date:
kanban_step_id = default_of_kanban_step_id
if not kanban_step_id:
kanban_step_id = default_of_kanban_step_id
return {
'of_priority': project.priority,
'of_notes': project.notes,
'of_info': project.info,
'of_manual_laying_date': project.manual_laying_date,
'of_laying_week': project.laying_week,
'of_reference_laying_date': project.reference_laying_date,
'of_force_laying_date': project.force_laying_date,
'of_sale_followup_tag_ids': otag_ids,
'of_kanban_step_id': kanban_step_id
}
def _update_tables_from_sale_values(self, order_values_to_upd):
def _get_sql_set_string(values):
order_obj = self.env['sale.order']
sql_set_str = ""
len_values = len(values)
for i, (k, v) in enumerate(values.items(), 1):
separator = ', ' if i < len_values else ' '
if not v and order_obj._fields[k].type in ['char', 'text', 'selection', 'date']:
sql_set_str += "%s = %s%s" % (k, 'NULL', separator)
elif v and (order_obj._fields[k].type in ['char', 'text'] or isinstance(v, (str, unicode))):
sql_set_str += "%s = '%s'%s" % (k, v.replace("'", "''"), separator)
else:
sql_set_str += "%s = %s%s" % (k, v, separator)
return sql_set_str
for order_id, order_values in order_values_to_upd.items():
partner_id = order_values.pop('partner_id')
followup_tags_ids = order_values.pop('of_sale_followup_tag_ids')
activities = order_values.pop('of_crm_activity_ids') if 'of_crm_activity_ids' in order_values else []
order_upd_sql = "UPDATE sale_order " \
"SET %s" \
"WHERE id = %s" % (_get_sql_set_string(order_values), order_id)
# update the columns of the sale_order
self._cr.execute(order_upd_sql)
# insert the tags in the relation table of the M2M
for tag_id in followup_tags_ids:
self._cr.execute(
'INSERT INTO sale_order_followup_tag_rel (order_id, tag_id) VALUES (%s, %s)',
(order_id, tag_id)
)
# insert the activities linked to the Sale in their table
for activity in activities:
self._cr.execute(
'INSERT INTO "of_crm_activity" ("create_uid", "uploaded_attachment_id", "type_id", '
'"user_id", "vendor_id", "description", "deadline_date", "sequence", "order_id", '
'"title", "write_uid", "state", "write_date", "report", "create_date", "load_attachment", '
'"origin", "active", "partner_id", "trigger_type") VALUES '
'(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, now(), %s, now(), %s, %s, %s, %s, %s);',
(
activity['create_uid'], None, activity['activity_id'], activity['create_uid'],
activity['vendor_id'], activity['summary'], activity['date_deadline'] or None,
activity['sequence'], order_id, activity['summary'] or None, activity['write_uid'],
activity['state'], None, False, 'sale_order', True, partner_id, 'at_creation'
)
)
def _followup_data_migration(self):
"""
Migration of the Project followup data into the new fields of the linked Order.
Migration of Project followup task and other stuff in the CRM activities, CRM tags, etc.
"""
cr = self._cr
# Follow-up data migration
ir_config_obj = self.env['ir.config_parameter']
logger.info('_followup_data_migration START')
if not ir_config_obj.get_param('of.followup.migration', False):
self = self.with_context(lang='fr_FR')
crm_activity_obj = self.env['crm.activity']
followup_task_obj = self.env['of.followup.task']
followup_task_type_obj = self.env['of.followup.task.type']
followup_project_obj = self.env['of.followup.project']
sale_followup_tag_obj = self.env['of.sale.followup.tag']
followup_project_tag_obj = self.env['of.followup.project.tag']
sale_order_kanban_obj = self.env['of.sale.order.kanban']
# of.followup.project.tag -> of.sale.followup.tag
logger.info(' of.followup.project.tag -> of.sale.followup.tag')
project_tags = followup_project_tag_obj.search([])
mapping_project_tags = {ptag.id: sale_followup_tag_obj.create(
{'name': ptag.name, 'color': ptag.color}).id for ptag in project_tags}
# of.followup.task.type -> crm.activity (loaded via data XML) so we build a data mapping dict
logger.info(' of.followup.task.type -> crm.activity')
task_type_planif_id = self.env.ref('of_followup.of_followup_task_type_planif').id
task_type_vt_id = self.env.ref('of_followup.of_followup_task_type_vt').id
followup_type_values = followup_task_type_obj.with_context(active_test=False).search_read(
['|', ('predefined_task', '=', False), ('id', 'in', [task_type_planif_id, task_type_vt_id])],
['name', 'short_name'])
mapping_task_type = {}
for data in followup_type_values:
act_id = crm_activity_obj.create(
{'name': data['name'], 'of_short_name': data['short_name'], 'of_object': 'sale_order'}).id
k = '%s,%s' % (data['id'], data['short_name'])
mapping_task_type[k] = act_id
# of.followup.task -> of.crm.activity
logger.info(' of.followup.task -> of.crm.activity')
# get the tasks ids
tasks_query = "SELECT DISTINCT(OFT.id) " \
"FROM of_followup_task OFT " \
"INNER JOIN of_followup_project OFP ON OFP.id = OFT.project_id " \
"INNER JOIN of_followup_task_type OFTT ON OFTT.id = OFT.type_id " \
"WHERE OFTT.predefined_task IS NOT TRUE OR OFT.type_id IN %s;"
cr.execute(tasks_query, (tuple([task_type_planif_id, task_type_vt_id]),))
tasks_ids = cr.fetchall()
tasks_ids = map(lambda t: t[0], tasks_ids)
# create sales activities from followup tasks and prepare orders data from the project linked to the task
project_data = {}
for task in followup_task_obj.browse(tasks_ids):
project = task.project_id
type_id = task.type_id.id
partner_id = project.order_id.partner_id.id or False
short_name = task.type_id.short_name
k = '%s,%s' % (type_id, short_name)
activity_state = 'planned' # default value
if task.state_id.final_state:
activity_state = 'done'
if project:
if not project_data.get(project):
project_data[project] = {'partner_id': partner_id, 'of_crm_activity_ids': []}
# try to preload the deadline date dependings on the current follow-up's stage
date_deadline = False
if project.reference_laying_date:
stage_code_tr = {
's': 0,
's+': 1,
's-2': -2,
's-4': -4,
's-6': -6,
's-8': -8
}
reference_laying_date = datetime.strptime(project.reference_laying_date, '%Y-%m-%d')
task_stage = task.state_id.stage_id
if task_stage and stage_code_tr.get(task_stage.code):
days_nbr = stage_code_tr.get(task_stage.code) * 7
date_deadline = reference_laying_date + timedelta(days=days_nbr)
# take the start day of the week for this date
start_date = date_deadline - timedelta(days=date_deadline.weekday())
date_deadline = start_date.strftime('%Y-%m-%d')
if mapping_task_type.get(k):
project_data[project]['of_crm_activity_ids'].append({
'sequence': task.sequence,
'summary': task.name,
'date_deadline': date_deadline,
'activity_id': mapping_task_type.get(k),
'state': activity_state,
'user_id': task.project_id.user_id.id or None,
'vendor_id': task.project_id.vendor_id.id or None,
'create_uid': task.create_uid.id or None,
'write_uid': task.write_uid.id or None
})
order_values_to_upd = {}
# of.followup.project -> sale.order
logger.info(' of.followup.project -> sale.order')
done_project_ids = []
default_of_kanban_step_id = self.env.ref('of_sale_kanban.of_sale_order_kanban_new').id
done_of_kanban_step_id = sale_order_kanban_obj.search([('name', '=', u"Terminé")]).id
in_progress_of_kanban_step_id = sale_order_kanban_obj.search([('name', '=', u"En cours")]).id
for project, data in project_data.items():
values = self._get_order_values(
project, mapping_project_tags, default_of_kanban_step_id, done_of_kanban_step_id,
in_progress_of_kanban_step_id)
values.update(data)
order_values_to_upd[project.order_id.id] = values
done_project_ids.append(project.id)
# other projets that aren't yet migrated from the followup tasks
if done_project_ids:
projects_query = "SELECT DISTINCT(OFP.id) " \
"FROM of_followup_project OFP " \
"WHERE OFP.id NOT IN %s;"
cr.execute(projects_query, (tuple(done_project_ids),))
else:
projects_query = "SELECT DISTINCT(OFP.id) FROM of_followup_project OFP;"
cr.execute(projects_query)
project_ids = cr.fetchall()
project_ids = map(lambda p: p[0], project_ids)
followup_projects = followup_project_obj.browse(project_ids)
for project in followup_projects:
values = self._get_order_values(
project, mapping_project_tags, default_of_kanban_step_id, done_of_kanban_step_id,
in_progress_of_kanban_step_id)
values['partner_id'] = project.order_id.partner_id.id
order_values_to_upd[project.order_id.id] = values
self._update_tables_from_sale_values(order_values_to_upd)
# recompute follow-up fields
logger.info(' recompute follow-up fields')
order_ids = order_values_to_upd.keys()
orders = self.env['sale.order'].browse(order_ids)
orders._compute_of_activities_state()
# set the migration as done
ir_config_obj.set_param('of.followup.migration', 'True')
# Deactivate view to hide migration button
self.env.ref('of_followup.view_sales_config_settings_followup').active = False
# Retirer le groupe group_of_followup_project_not_migrated pour masquer les différents éléments du suivi
group_not_migrated = self.env.ref('of_followup.group_of_followup_project_not_migrated')
group_user = self.env.ref('base.group_user')
if group_not_migrated in group_user.implied_ids:
group_user.write({'implied_ids': [(3, group_not_migrated.id)]})
logger.info('_followup_data_migration END')
stage_id = fields.Many2one(
compute='_compute_stage_id', comodel_name='of.followup.project.stage', string=u"Etape de suivi", store=True,
group_expand='_read_group_stage_ids')
state = fields.Selection(
[('in_progress', u'En cours'),
('late', u'En retard'),
('ready', u'Prêt'),
('done', u'Terminé'),
('cancel', u'Annulé')],
string=u"Etat du dossier", compute='_compute_state', store=True)
is_done = fields.Boolean(string=u"Est terminé")
is_canceled = fields.Boolean(string=u"Est annulé")
order_id = fields.Many2one(
comodel_name='sale.order', string=u"Commande", required=True, copy=False, ondelete='cascade')
partner_id = fields.Many2one(related='order_id.partner_id', string=u"Client", readonly=True)
intervention_address_id = fields.Many2one(
related='order_id.partner_shipping_id', string=u"Adresse d'intervention", readonly=True)
invoice_status = fields.Selection(related='order_id.invoice_status', string=u"État de facturation", readonly=True)
user_id = fields.Many2one(comodel_name='res.users', string=u"Responsable", default=lambda self: self.env.user)
vendor_id = fields.Many2one(related='order_id.user_id', string=u"Vendeur", readonly=True)
reference_laying_date = fields.Date(
compute='_compute_reference_laying_date', string=u"Date de pose de référence", store=True, compute_sudo=True)
force_laying_date = fields.Boolean(string=u"Forcer la date de pose")
manual_laying_date = fields.Date(string=u"Date de pose (manuelle)")
laying_week = fields.Char(
compute='_compute_reference_laying_date', string=u"Semaine de pose", store=True, compute_sudo=True)
task_ids = fields.One2many(comodel_name='of.followup.task', inverse_name='project_id', string=u"Tâches")
predefined_task_ids = fields.One2many(
comodel_name='of.followup.task', inverse_name='project_id', string=u"Tâches pré-définies",
domain=[('predefined_task', '=', True)])
other_task_ids = fields.One2many(
comodel_name='of.followup.task', inverse_name='project_id', string=u"Autres tâches",
domain=[('predefined_task', '=', False)])
template_id = fields.Many2one(comodel_name='of.followup.project.template', string=u"Modèle")
color = fields.Char(string=u"Couleur", compute="_compute_color")
priority = fields.Selection(
AVAILABLE_PRIORITIES, string=u'Priorité', index=True, default=AVAILABLE_PRIORITIES[0][0])
main_product_brand_id = fields.Many2one(
comodel_name='of.product.brand', compute='_compute_main_product_brand_id',
string=u"Marque de l'article principal", store=True)
info = fields.Text(string=u"Infos")
notes = fields.Text(string=u"Notes")
tag_ids = fields.Many2many(comodel_name='of.followup.project.tag', string=u"Étiquettes")
alert_ids = fields.Many2many(
comodel_name='of.followup.project.alert', string=u"Alertes", compute='_compute_alert_ids')
invoice_count = fields.Integer(string=u"Nombre de factures", related='order_id.invoice_count', readonly=True)
purchase_count = fields.Integer(string=u"Nombre d'achats", related='order_id.purchase_count', readonly=True)
intervention_count = fields.Integer(
string=u"Nombre d'interventions", related='order_id.intervention_count', readonly=True)
to_schedule_count = fields.Integer(
string=u"Nombre de DI à programmer", related='order_id.of_service_count', readonly=True)
delivery_count = fields.Integer(string=u"Nombre de livraisons", related='order_id.delivery_count', readonly=True)
picking_count = fields.Integer(string=u"Nombre de réceptions", compute='_compute_picking_count')
# Champs pour affichage vignette kanban
late_tasks_number = fields.Char(string=u"Nombre de tâches en retard", compute='_compute_late_tasks_number')
late_tasks = fields.Text(string=u"Tâches en retard", compute='_compute_late_tasks')
info_display = fields.Text(string=u"Infos pour affichage", compute='_compute_info_display')
date_alert_display = fields.Text(string=u"Infos pour alerte de dates", compute='_compute_alert_display')
picking_alert_display = fields.Text(
string=u"Infos pour alerte de livraison/réception", compute='_compute_alert_display')
amount_untaxed = fields.Monetary(string=u"Montant HT", related='order_id.amount_untaxed', readonly=True)
currency_id = fields.Many2one('res.currency', string=u"Devise", related='order_id.currency_id', readonly=True)
_sql_constraints = [('order_uniq', 'unique (order_id)', u"Un suivi a déjà été créé pour cette commande !")]
@api.multi
def name_get(self):
res = []
for followup in self:
name = "Suivi commande %s" % followup.order_id.name
res.append((followup.id, name))
return res
@api.model
def _read_group_stage_ids(self, stages, domain, order):
stage_ids = self.env['of.followup.project.stage'].search([])
return stage_ids
@api.multi
@api.depends('reference_laying_date', 'state')
def _compute_stage_id(self):
for rec in self:
if rec.state in ('done', 'cancel'):
rec.stage_id = self.env['of.followup.project.stage'].search([('code', '=', 'done')], limit=1)
else:
laying_date = rec.reference_laying_date
if laying_date:
laying_date = datetime.strptime(laying_date, "%Y-%m-%d").date()
today = date.today()
if laying_date < today:
rec.stage_id = self.env['of.followup.project.stage'].search([('code', '=', 's+')], limit=1)
else:
monday1 = (laying_date - timedelta(days=laying_date.weekday()))
monday2 = (today - timedelta(days=today.weekday()))
week_diff = (monday1 - monday2).days / 7
rec.stage_id = self.env['of.followup.project.stage'].search(
[('week_diff_min', '<=', week_diff), ('week_diff_max', '>=', week_diff)], limit=1)
else:
rec.stage_id = self.env['of.followup.project.stage'].search([('code', '=', 'new')], limit=1)
@api.multi
@api.depends('order_id', 'order_id.state', 'is_done', 'is_canceled', 'task_ids', 'task_ids.is_not_processed',
'task_ids.is_done', 'task_ids.is_late')
def _compute_state(self):
for rec in self:
# Si commande annulée, le suivi est à l'état annulé également
if rec.order_id.state == 'cancel':
rec.state = 'cancel'
else:
# Par défaut le projet est en cours
state = 'in_progress'
if rec.is_done:
# Le projet a été marqué comme terminé
state = 'done'
elif rec.is_canceled:
# Le projet a été marqué comme annulé
state = 'cancel'
else:
# Correction d'un bug sur l'ordre de calcul des champs compute : Pour savoir si des tâches
# sont réellement en retard, il faut recalculer l'étape du suivi au préalable
rec.state = state
rec._compute_stage_id()
# Toutes les tâches sont terminées (excepté les non traitées)
if rec.task_ids and not rec.task_ids.filtered(lambda t: not t.is_not_processed and not t.is_done):
state = 'ready'
# Au moins une tâche est en retard
elif rec.task_ids.filtered(lambda t: t.is_late):
state = 'late'
rec.state = state
@api.multi
@api.depends('force_laying_date', 'manual_laying_date', 'order_id', 'order_id.intervention_ids',
'order_id.intervention_ids.date', 'order_id.intervention_ids.tache_id',
'order_id.intervention_ids.tache_id.tache_categ_id')
def _compute_reference_laying_date(self):
for rec in self:
laying_date = False
if rec.force_laying_date:
laying_date = rec.manual_laying_date
elif rec.order_id and rec.order_id.intervention_ids:
planif_task_type = self.env.ref('of_followup.of_followup_task_type_planif')
if planif_task_type:
planif_planning_tache_categs = planif_task_type.planning_tache_categ_ids
interventions = rec.order_id.intervention_ids.filtered(
lambda i: i.tache_id.tache_categ_id.id in planif_planning_tache_categs.ids and
i.date > fields.Datetime.now())
if interventions:
laying_date = interventions[0].date_date
else:
interventions = rec.order_id.intervention_ids.filtered(
lambda i: i.tache_id.tache_categ_id.id in planif_planning_tache_categs.ids)
if interventions:
laying_date = interventions[-1].date_date
rec.reference_laying_date = laying_date
if laying_date:
laying_week = datetime.strptime(laying_date, "%Y-%m-%d").date().isocalendar()[1]
rec.laying_week = "%02d" % laying_week
else:
rec.laying_week = "Non programmée"
@api.multi
def _compute_color(self):
for rec in self:
state = rec.state
if state == 'in_progress':
color = '#ffffff'
elif state == 'late':
color = '#ffa8a8'
elif state == 'ready':
color = '#bcffa8'
elif state == 'done':
color = '#d7d7d7'
elif state == 'cancel':
color = '#eeeeee'
else:
color = '#ffffff'
rec.color = color
@api.multi
@api.depends('order_id', 'order_id.order_line', 'order_id.order_line.of_article_principal',
'order_id.order_line.product_id', 'order_id.order_line.product_id.brand_id')
def _compute_main_product_brand_id(self):
for rec in self:
main_product_lines = rec.order_id.order_line.filtered(lambda l: l.of_article_principal)
if main_product_lines:
rec.main_product_brand_id = main_product_lines[0].product_id.brand_id
@api.multi
def _compute_alert_ids(self):
for rec in self:
if rec.order_id:
alerts = self.env['of.followup.project.alert']
# Vérification des dates
planif_task_type = self.env.ref('of_followup.of_followup_task_type_planif')
if planif_task_type and rec.force_laying_date:
planif_planning_tache_categs = planif_task_type.planning_tache_categ_ids
interventions = rec.order_id.intervention_ids.filtered(
lambda i: i.tache_id.tache_categ_id.id in planif_planning_tache_categs.ids and
i.date > fields.Datetime.now() and i.state != 'cancel')
if interventions:
intervention = interventions[0]
if intervention.date_date != rec.manual_laying_date:
alerts |= self.env.ref('of_followup.of_followup_project_alert_date')
else:
interventions = rec.order_id.intervention_ids.filtered(
lambda i:
i.tache_id.tache_categ_id.id in planif_planning_tache_categs.ids and i.state != 'cancel')
if interventions:
intervention = interventions[-1]
if intervention.date_date != rec.manual_laying_date:
alerts |= self.env.ref('of_followup.of_followup_project_alert_date')
# Vérification BL
if rec.order_id.picking_ids:
late_delivery_pickings = rec.order_id.picking_ids.filtered(
lambda p: p.state not in ['done', 'cancel'] and p.min_date < fields.Datetime.now())
if late_delivery_pickings:
alerts |= self.env.ref('of_followup.of_followup_project_alert_bl')
# Vérification BR
if rec.order_id.purchase_ids.mapped('picking_ids'):
late_receipt_pickings = rec.order_id.purchase_ids.mapped('picking_ids').filtered(
lambda p: p.state not in ['done', 'cancel'] and p.min_date < fields.Datetime.now())
if late_receipt_pickings:
alerts |= self.env.ref('of_followup.of_followup_project_alert_br')
rec.alert_ids = alerts
@api.multi
def _compute_picking_count(self):
for rec in self:
rec.picking_count = sum(rec.order_id.purchase_ids.mapped('picking_count'))
@api.multi
def _compute_late_tasks_number(self):
for rec in self:
rec.late_tasks_number = "(%s/%s)" % (len(rec.task_ids.filtered(lambda t: t.is_late)), len(rec.task_ids))
@api.multi
def _compute_late_tasks(self):
for rec in self:
late_tasks = []
for late_task in rec.task_ids.filtered(lambda t: t.is_late):
if len(late_tasks) < 3:
late_tasks.append(late_task.type_id.short_name)
else:
late_tasks.append("...")
break
rec.late_tasks = json.dumps(late_tasks) if late_tasks else False
@api.multi
def _compute_info_display(self):
for rec in self:
info = []
if rec.info:
for line in rec.info.split('\n'):
info.append(line)
rec.info_display = json.dumps(info) if info else False
@api.multi
def _compute_alert_display(self):
alert_date = self.env.ref('of_followup.of_followup_project_alert_date')
for rec in self:
date_alert = []
picking_alert = []
if rec.alert_ids:
for alert in rec.alert_ids:
if alert == alert_date:
date_alert.append(alert.name)
else:
picking_alert.append(alert.name)
rec.date_alert_display = json.dumps(date_alert) if date_alert else False
rec.picking_alert_display = json.dumps(picking_alert) if picking_alert else False
@api.model
def get_color(self):
state = self.state
if state == 'in_progress':
return 1
elif state == 'late':
return 2
elif state == 'ready':
return 3
elif state == 'done':
return 4
else:
return 0
@api.multi
def set_to_done(self):
self.ensure_one()
self.is_done = True
@api.multi
def set_to_canceled(self):
self.ensure_one()
self.is_canceled = True
@api.multi
def set_to_in_progress(self):
self.ensure_one()
self.is_done = False
@api.multi
def action_send_email(self):
self.ensure_one()
ir_model_data = self.env['ir.model.data']
try:
template_id = ir_model_data.get_object_reference('of_followup', 'of_followup_project_email_template')[1]
except ValueError:
template_id = False
try:
compose_form_id = ir_model_data.get_object_reference('mail', 'email_compose_message_wizard_form')[1]
except ValueError:
compose_form_id = False
ctx = dict()
ctx.update({
'default_model': 'of.followup.project',
'default_res_id': self.ids[0],
'default_use_template': bool(template_id),
'default_template_id': template_id,
'default_partner_ids': self.partner_id.ids,
'default_composition_mode': 'comment',
})
return {
'type': 'ir.actions.act_window',
'view_type': 'form',
'view_mode': 'form',
'res_model': 'mail.compose.message',
'views': [(compose_form_id, 'form')],
'view_id': compose_form_id,
'target': 'new',
'context': ctx,
}
@api.onchange('template_id')
def onchange_template_id(self):
if not self.template_id:
return
predefined_new_tasks = []
other_new_tasks = []
for task in self.template_id.task_ids:
vals = {'sequence': task.sequence, 'type_id': task.type_id.id, 'name': task.name}
state = self.env['of.followup.task.type.state'].search(
[('task_type_id', '=', task.type_id.id), ('starting_state', '=', True)], limit=1)
if state:
if task.predefined_task:
vals.update({'predefined_state_id': state.id})
predefined_new_tasks += [(0, 0, vals)]
else:
vals.update({'state_id': state.id})
other_new_tasks += [(0, 0, vals)]
return {'value': {'predefined_task_ids': predefined_new_tasks, 'other_task_ids': other_new_tasks}}
@api.onchange('force_laying_date')
def onchange_force_laying_date(self):
self.manual_laying_date = False
@api.multi
def action_view_invoice(self):
self.ensure_one()
return self.order_id.action_view_invoice()
@api.multi
def action_view_purchase(self):
self.ensure_one()
return self.order_id.action_view_achats()
@api.multi
def action_view_interventions(self):
self.ensure_one()
return self.order_id.action_view_intervention()
@api.multi
def action_view_to_schedule(self):
self.ensure_one()
return self.order_id.action_view_a_programmer()
@api.multi
def action_view_delivery(self):
self.ensure_one()
return self.order_id.action_view_delivery()
@api.multi
def action_view_picking(self):
self.ensure_one()
action = self.env.ref('stock.action_picking_tree')
result = action.read()[0]
result.pop('id', None)
result['context'] = {}
pick_ids = self.order_id.purchase_ids.mapped('picking_ids').ids or []
if len(pick_ids) > 1:
result['domain'] = "[('id', 'in', [" + ','.join(map(str, pick_ids)) + "])]"
elif len(pick_ids) == 1:
res = self.env.ref('stock.view_picking_form', False)
result['views'] = [(res and res.id or False, 'form')]
result['res_id'] = pick_ids and pick_ids[0] or False
return result
@api.model
def create(self, vals):
res = super(OFFollowupProject, self).create(vals)
res.order_id.write({'of_followup_project_id': res.id})
return res
@api.model
def cron_move_project(self):
for project in self.search([]):
project._compute_stage_id()
@api.model
def cron_recompute_reference_laying_date(self):
for project in self.search([]):
project._compute_reference_laying_date()
@api.multi
def last_step_for_all(self):
for followup in self:
for task in followup.other_task_ids:
states = self.env['of.followup.task.type.state'].search(
[('task_type_id', '=', task.type_id.id), ('sequence', '>', task.state_id.sequence)])
if states:
task.state_id = states[-1].id
class OFFollowupProjectStage(models.Model):
_name = 'of.followup.project.stage'
_description = "Etat de suivi des projets"
_order = 'sequence'
name = fields.Char(string=u"Nom")
code = fields.Char(string=u"Code")
sequence = fields.Integer(string=u"Séquence")
fold = fields.Boolean(string=u"Replié par défaut")
week_diff_min = fields.Integer(string=u"Différence de semaine minimale")
week_diff_max = fields.Integer(string=u"Différence de semaine maximale")
class OFFollowupTask(models.Model):
_name = 'of.followup.task'
_description = u"Tâche liée au suivi des projets"
_order = 'sequence'
project_id = fields.Many2one(
comodel_name="of.followup.project", string=u"Projet", required=True, ondelete='cascade')
sequence = fields.Integer(string=u"Séquence")
type_id = fields.Many2one(comodel_name='of.followup.task.type', string=u"Type", required=True)
name = fields.Char(string=u"Nom", required=True)
state_id = fields.Many2one(comodel_name='of.followup.task.type.state', string=u"Etat")
predefined_state_id = fields.Many2one(
comodel_name='of.followup.task.type.state', string=u"Etat", compute='_compute_predefined_state_id')
global_state = fields.Char(string=u"État", compute='_compute_global_state')
predefined_task = fields.Boolean(string=u"Tâche pré-définie", related='type_id.predefined_task')
force_state = fields.Boolean(string=u"Gestion manuelle de l'état")
is_late = fields.Boolean(string=u"Tâche en retard", compute='_compute_is_late')
is_done = fields.Boolean(string=u"Tâche terminée", compute='_compute_is_done')
is_not_processed = fields.Boolean(string=u"Tâche non traitée", compute='_compute_is_not_processed')
planif_intervention_ids = fields.One2many(
comodel_name='of.planning.intervention', string=u"RDVs d'intervention planifiés",
compute='_compute_planif_intervention_ids')
display_planif_interventions = fields.Boolean(
string=u"Afficher les RDVs d'intervention planifiés ?", compute='_compute_planif_intervention_ids')
vt_intervention_ids = fields.One2many(
comodel_name='of.planning.intervention', string=u"RDVs visite technique",
compute='_compute_vt_intervention_ids')
display_vt_interventions = fields.Boolean(
string=u"Afficher les RDVs visite technique ?", compute='_compute_vt_intervention_ids')
app_order_line_ids = fields.One2many(
comodel_name='sale.order.line', string=u"Lignes de commande appareils", compute='_compute_app_order_line_ids')
display_app_order_lines = fields.Boolean(
string=u"Afficher les lignes de commande appareils ?", compute='_compute_app_order_line_ids')
acc_order_line_ids = fields.One2many(
comodel_name='sale.order.line', string=u"Lignes de commande accessoires", compute='_compute_acc_order_line_ids')
display_acc_order_lines = fields.Boolean(
string=u"Afficher les lignes de commande accessoires ?", compute='_compute_acc_order_line_ids')
app_picking_line_ids = fields.One2many(
comodel_name='stock.move', string=u"Lignes de BL appareils", compute='_compute_app_picking_line_ids')
display_app_picking_lines = fields.Boolean(
string=u"Afficher les lignes de BL appareils ?", compute='_compute_app_picking_line_ids')
acc_picking_line_ids = fields.One2many(
comodel_name='stock.move', string=u"Lignes de BL accessoires", compute='_compute_acc_picking_line_ids')
display_acc_picking_lines = fields.Boolean(
string=u"Afficher les lignes de BL accessoires ?", compute='_compute_acc_picking_line_ids')
@api.multi
def _compute_predefined_state_id(self):
for rec in self:
if not rec.type_id.state_ids or not rec.type_id.state_ids.filtered(lambda s: s.starting_state):
continue
rec.predefined_state_id = rec.type_id.state_ids.filtered(lambda s: s.starting_state)[0]
# Planification
if rec.type_id == self.env.ref('of_followup.of_followup_task_type_planif'):
interventions = rec.planif_intervention_ids
# Il existe des RDV d'intervention et ils sont tous au statut 'Réalisé'
if interventions and not interventions.filtered(lambda i: i.state not in ['done', 'cancel']):
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_planif_03')
# Il existe au moins un RDV d'intervention au statut 'Confirmé'
elif interventions.filtered(lambda i: i.state == 'confirm'):
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_planif_02')
# Visite technique
elif rec.type_id == self.env.ref('of_followup.of_followup_task_type_vt'):
interventions = rec.vt_intervention_ids
# Il existe un RDV d'intervention de tâche "VT" au statut 'Réalisé'
if interventions.filtered(lambda i: i.state == 'done'):
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_vt_03')
# Il existe un RDV d'intervention de tâche "VT" au statut 'Confirmé'
elif interventions.filtered(lambda i: i.state == 'confirm'):
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_vt_02')
# Appareils
elif rec.type_id == self.env.ref('of_followup.of_followup_task_type_app'):
app_order_lines = rec.app_order_line_ids
po_validated = bool(app_order_lines)
receipt_validated = bool(app_order_lines)
# Non kit
for app_order_line in app_order_lines.filtered(lambda l: not l.of_is_kit):
stock_moves = app_order_line.procurement_ids.mapped('move_ids')
# On regarde d'abord si les articles sont déjà en stock/réservés
qty = sum(self.env['stock.quant'].search([('reservation_id', 'in', stock_moves.ids)]).mapped('qty'))
if qty < app_order_line.product_uom_qty:
# On récupère la(les) ligne(s) de commande d'achat validée associée(s)
purchase_procurement_orders = self.env['procurement.order'].search(
[('move_dest_id', 'in', stock_moves.ids)])
validated_purchase_lines = purchase_procurement_orders.mapped('purchase_line_id').filtered(
lambda l: l.order_id.state == 'purchase')
# On contrôle que les quantités commandées correspondent
if app_order_line.product_uom_qty - qty <= sum(validated_purchase_lines.mapped('product_qty')):
receipts = validated_purchase_lines.mapped('order_id').mapped('picking_ids')
if not receipts or receipts != receipts.filtered(lambda r: r.state == 'done'):
receipt_validated = False
else:
po_validated = False
break
# Kit
for app_order_line in app_order_lines.filtered(lambda l: l.of_is_kit):
for kit_line in app_order_line.kit_id.kit_line_ids.filtered(
lambda l: l.product_id.type == 'product'):
stock_moves = kit_line.procurement_ids.mapped('move_ids')
# On regarde d'abord si les articles sont déjà en stock/réservés
qty = sum(
self.env['stock.quant'].search([('reservation_id', 'in', stock_moves.ids)]).mapped('qty'))
if qty < kit_line.qty_per_kit:
# On récupère la(les) ligne(s) de commande d'achat validée associée(s)
purchase_procurement_orders = self.env['procurement.order'].search(
[('move_dest_id', 'in', stock_moves.ids)])
validated_purchase_lines = purchase_procurement_orders.mapped('purchase_line_id').filtered(
lambda l: l.order_id.state == 'purchase')
# On contrôle que les quantités commandées correspondent
if kit_line.qty_per_kit - qty <= sum(validated_purchase_lines.mapped('product_qty')):
receipts = validated_purchase_lines.mapped('order_id').mapped('picking_ids')
if not receipts or receipts != receipts.filtered(lambda r: r.state == 'done'):
receipt_validated = False
else:
po_validated = False
break
if not app_order_lines:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_np')
else:
if po_validated:
if receipt_validated:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_app_03')
else:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_app_02')
# Accessoires
elif rec.type_id == self.env.ref('of_followup.of_followup_task_type_acc'):
acc_order_lines = rec.acc_order_line_ids
po_validated = bool(acc_order_lines)
receipt_validated = bool(acc_order_lines)
# Non kit
for acc_order_line in acc_order_lines.filtered(lambda l: not l.of_is_kit):
stock_moves = acc_order_line.procurement_ids.mapped('move_ids')
# On regarde d'abord si les articles sont déjà en stock/réservés
qty = sum(self.env['stock.quant'].search([('reservation_id', 'in', stock_moves.ids)]).mapped('qty'))
if qty < acc_order_line.product_uom_qty:
# On récupère la(les) ligne(s) de commande d'achat validée associée(s)
purchase_procurement_orders = self.env['procurement.order'].search(
[('move_dest_id', 'in', stock_moves.ids)])
validated_purchase_lines = purchase_procurement_orders.mapped('purchase_line_id').filtered(
lambda l: l.order_id.state == 'purchase')
# On contrôle que les quantités commandées correspondent
if acc_order_line.product_uom_qty - qty <= sum(validated_purchase_lines.mapped('product_qty')):
receipts = validated_purchase_lines.mapped('order_id').mapped('picking_ids')
if not receipts or receipts != receipts.filtered(lambda r: r.state == 'done'):
receipt_validated = False
else:
po_validated = False
break
# Kit
for acc_order_line in acc_order_lines.filtered(lambda l: l.of_is_kit):
for kit_line in acc_order_line.kit_id.kit_line_ids.filtered(
lambda l: l.product_id.type == 'product'):
stock_moves = kit_line.procurement_ids.mapped('move_ids')
# On regarde d'abord si les articles sont déjà en stock/réservés
qty = sum(
self.env['stock.quant'].search([('reservation_id', 'in', stock_moves.ids)]).mapped('qty'))
if qty < kit_line.qty_per_kit:
# On récupère la(les) ligne(s) de commande d'achat validée associée(s)
purchase_procurement_orders = self.env['procurement.order'].search(
[('move_dest_id', 'in', stock_moves.ids)])
validated_purchase_lines = purchase_procurement_orders.mapped('purchase_line_id').filtered(
lambda l: l.order_id.state == 'purchase')
# On contrôle que les quantités commandées correspondent
if kit_line.qty_per_kit - qty <= sum(validated_purchase_lines.mapped('product_qty')):
receipts = validated_purchase_lines.mapped('order_id').mapped('picking_ids')
if not receipts or receipts != receipts.filtered(lambda r: r.state == 'done'):
receipt_validated = False
else:
po_validated = False
break
if not acc_order_lines:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_np')
else:
if po_validated:
if receipt_validated:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_app_03')
else:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_app_02')
# Appareils hors commande
elif rec.type_id == self.env.ref('of_followup.of_followup_task_type_out_app'):
app_picking_lines = rec.app_picking_line_ids
po_validated = bool(app_picking_lines)
receipt_validated = bool(app_picking_lines)
for app_picking_line in app_picking_lines:
# On regarde d'abord si les articles sont déjà en stock/réservés
qty = sum(self.env['stock.quant'].search([('reservation_id', '=', app_picking_line.id)]).
mapped('qty'))
if qty < app_picking_line.product_uom_qty:
# On récupère la(les) ligne(s) de commande d'achat validée associée(s)
purchase_procurement_orders = self.env['procurement.order'].search(
[('move_dest_id', '=', app_picking_line.id)])
validated_purchase_lines = purchase_procurement_orders.mapped('purchase_line_id').filtered(
lambda l: l.order_id.state == 'purchase')
# On contrôle que les quantités commandées correspondent
if app_picking_line.product_uom_qty - qty <= sum(validated_purchase_lines.
mapped('product_qty')):
receipts = validated_purchase_lines.mapped('order_id').mapped('picking_ids')
if not receipts or receipts != receipts.filtered(lambda r: r.state == 'done'):
receipt_validated = False
else:
po_validated = False
break
if not app_picking_lines:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_np')
else:
if po_validated:
if receipt_validated:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_out_app_03')
else:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_out_app_02')
# Accessoires hors commande
elif rec.type_id == self.env.ref('of_followup.of_followup_task_type_out_acc'):
acc_picking_lines = rec.acc_picking_line_ids
po_validated = bool(acc_picking_lines)
receipt_validated = bool(acc_picking_lines)
for acc_picking_line in acc_picking_lines:
# On regarde d'abord si les articles sont déjà en stock/réservés
qty = sum(self.env['stock.quant'].search([('reservation_id', '=', acc_picking_line.id)]).
mapped('qty'))
if qty < acc_picking_line.product_uom_qty:
# On récupère la(les) ligne(s) de commande d'achat validée associée(s)
purchase_procurement_orders = self.env['procurement.order'].search(
[('move_dest_id', '=', acc_picking_line.id)])
validated_purchase_lines = purchase_procurement_orders.mapped('purchase_line_id').filtered(
lambda l: l.order_id.state == 'purchase')
# On contrôle que les quantités commandées correspondent
if acc_picking_line.product_uom_qty - qty <= sum(validated_purchase_lines.
mapped('product_qty')):
receipts = validated_purchase_lines.mapped('order_id').mapped('picking_ids')
if not receipts or receipts != receipts.filtered(lambda r: r.state == 'done'):
receipt_validated = False
else:
po_validated = False
break
if not acc_picking_lines:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_np')
else:
if po_validated:
if receipt_validated:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_out_acc_03')
else:
rec.predefined_state_id = self.env.ref('of_followup.of_followup_task_type_state_out_acc_02')
@api.multi
@api.depends('state_id', 'predefined_state_id', 'predefined_task', 'force_state')
def _compute_global_state(self):
for rec in self:
if rec.predefined_task and not rec.force_state:
rec.global_state = rec.predefined_state_id.name
else:
rec.global_state = rec.state_id and rec.state_id.name or ""
@api.multi
def _compute_is_late(self):
not_processed_state = self.env.ref('of_followup.of_followup_task_type_state_np')
for rec in self:
if rec.predefined_task and not rec.force_state and rec.predefined_state_id == not_processed_state:
rec.is_late = False
else:
if rec.predefined_task and not rec.force_state:
late_stage = rec.predefined_state_id.stage_id
else:
late_stage = rec.state_id.stage_id
if late_stage and late_stage.sequence <= rec.project_id.stage_id.sequence:
rec.is_late = True
else:
rec.is_late = False
@api.multi
def _compute_is_done(self):
not_processed_state = self.env.ref('of_followup.of_followup_task_type_state_np')
for rec in self:
if rec.predefined_task and not rec.force_state and rec.predefined_state_id == not_processed_state:
rec.is_done = False
else:
if rec.predefined_task and not rec.force_state:
final_state = rec.predefined_state_id.final_state
else:
final_state = rec.state_id.final_state
if final_state:
rec.is_done = True
else:
rec.is_done = False
@api.multi
def _compute_is_not_processed(self):
not_processed_state = self.env.ref('of_followup.of_followup_task_type_state_np')
for rec in self:
if rec.predefined_task and not rec.force_state and rec.predefined_state_id == not_processed_state:
rec.is_not_processed = True
else:
rec.is_not_processed = False
@api.multi
def _compute_planif_intervention_ids(self):
planif_task_type = self.env.ref('of_followup.of_followup_task_type_planif')
planning_tache_categs = planif_task_type.planning_tache_categ_ids
for rec in self:
if rec.type_id == planif_task_type:
rec.planif_intervention_ids = rec.project_id.order_id.intervention_ids.filtered(
lambda i: i.tache_id.tache_categ_id.id in planning_tache_categs.ids)
rec.display_planif_interventions = True
else:
rec.planif_intervention_ids = False
rec.display_planif_interventions = False
@api.multi
def _compute_vt_intervention_ids(self):
vt_task_type = self.env.ref('of_followup.of_followup_task_type_vt')
planning_tache_categs = vt_task_type.planning_tache_categ_ids
for rec in self:
if rec.type_id == vt_task_type:
rec.vt_intervention_ids = rec.project_id.order_id.intervention_ids.filtered(
lambda i: i.tache_id.tache_categ_id.id in planning_tache_categs.ids)
rec.display_vt_interventions = True
else:
rec.vt_intervention_ids = False
rec.display_vt_interventions = False
@api.multi
def _compute_app_order_line_ids(self):
app_task_type = self.env.ref('of_followup.of_followup_task_type_app')
product_categs = app_task_type.product_categ_ids
for rec in self:
if rec.type_id == app_task_type:
rec.display_app_order_lines = True
if rec.project_id.order_id.state == 'sale':
rec.app_order_line_ids = rec.project_id.order_id.order_line.filtered(
lambda l: l.product_id.categ_id.id in product_categs.ids and
(l.product_id.type == 'product' or l.of_is_kit) and l.product_uom_qty > 0)
else:
rec.app_order_line_ids = False
else:
rec.app_order_line_ids = False
rec.display_app_order_lines = False
@api.multi
def _compute_acc_order_line_ids(self):
acc_task_type = self.env.ref('of_followup.of_followup_task_type_acc')
app_task_type = self.env.ref('of_followup.of_followup_task_type_app')
product_categs = app_task_type.product_categ_ids
for rec in self:
if rec.type_id == acc_task_type:
rec.display_acc_order_lines = True
if rec.project_id.order_id.state == 'sale':
rec.acc_order_line_ids = rec.project_id.order_id.order_line.filtered(
lambda l: l.product_id.categ_id.id not in product_categs.ids and
(l.product_id.type == 'product' or l.of_is_kit) and l.product_uom_qty > 0)
else:
rec.acc_order_line_ids = False
else:
rec.acc_order_line_ids = False
rec.display_acc_order_lines = False
@api.multi
def _compute_app_picking_line_ids(self):
out_app_task_type = self.env.ref('of_followup.of_followup_task_type_out_app')
product_categs = out_app_task_type.product_categ_ids
for rec in self:
if rec.type_id == out_app_task_type:
rec.app_picking_line_ids = rec.project_id.order_id.picking_ids.mapped('move_lines').\
filtered(lambda l: not l.procurement_id and
l.product_id.categ_id.id in product_categs.ids and l.product_uom_qty > 0)
rec.display_app_picking_lines = True
else:
rec.app_picking_line_ids = False
rec.display_app_picking_lines = False
@api.multi
def _compute_acc_picking_line_ids(self):
out_acc_task_type = self.env.ref('of_followup.of_followup_task_type_out_acc')
out_app_task_type = self.env.ref('of_followup.of_followup_task_type_out_app')
product_categs = out_app_task_type.product_categ_ids
for rec in self:
if rec.type_id == out_acc_task_type:
rec.acc_picking_line_ids = rec.project_id.order_id.picking_ids.mapped('move_lines'). \
filtered(lambda l: not l.procurement_id and l.product_id.categ_id.id not in product_categs.ids and
l.product_uom_qty > 0)
rec.display_acc_picking_lines = True
else:
rec.acc_picking_line_ids = False
rec.display_acc_picking_lines = False
@api.onchange('type_id')
def _onchange_type_id(self):
self.state_id = False
if self.type_id and not self.predefined_task or self.force_state:
state = self.env['of.followup.task.type.state'].search(
[('task_type_id', '=', self.type_id.id), ('starting_state', '=', True)], limit=1)
if state:
self.state_id = state
@api.multi
def next_step(self):
self.ensure_one()
if self.predefined_task and not self.force_state:
# On affiche une pop-up de confirmation
return {
'type': 'ir.actions.act_window',
'name': "Avertissement !",
'view_type': 'form',
'view_mode': 'form',
'res_model': 'of.followup.confirm.next.step',
'target': 'new',
}
else:
# On cherche l'étape suivante
state = self.env['of.followup.task.type.state'].search(
[('task_type_id', '=', self.type_id.id), ('sequence', '>', self.state_id.sequence)], limit=1)
if state:
self.state_id = state.id
return True
@api.model
def create(self, vals):
res = super(OFFollowupTask, self).create(vals)
# Ajout d'un message dans le chatter du projet
self.env['mail.message'].create({
'author_id': self.env.user.partner_id.id,
'model': 'of.followup.project',
'res_id': res.project_id.id,
'type': 'comment',
'body': u"La tâche %s a été ajoutée au suivi." % res.name,
'date': fields.Datetime.now(),
})
return res
@api.multi
def write(self, vals):
res = super(OFFollowupTask, self).write(vals)
if vals.get('state_id', False):
for rec in self:
# Ajout d'un message dans le chatter du projet
self.env['mail.message'].create({
'author_id': self.env.user.partner_id.id,
'model': 'of.followup.project',
'res_id': rec.project_id.id,
'type': 'comment',
'body': u"La tâche %s a été passée à l'état %s." % (rec.name, rec.state_id.name),
'date': fields.Datetime.now(),
})
return res
@api.multi
def unlink(self):
for rec in self:
# Ajout d'un message dans le chatter du projet
self.env['mail.message'].create({
'author_id': self.env.user.partner_id.id,
'model': 'of.followup.project',
'res_id': rec.project_id.id,
'type': 'comment',
'body': u"La tâche %s a été supprimée du suivi." % rec.name,
'date': fields.Datetime.now(),
})
return super(OFFollowupTask, self).unlink()
class OFFollowupTaskType(models.Model):
_name = 'of.followup.task.type'
_description = u"Type de tâches liées au suivi des projets"
name = fields.Char(string=u"Nom", required=True)
short_name = fields.Char(string=u"Nom court", required=True)
active = fields.Boolean(string=u"Actif", default=True)
predefined_task = fields.Boolean(string=u"Tâche pré-définie", readonly=True)
state_ids = fields.One2many(
comodel_name='of.followup.task.type.state', inverse_name='task_type_id', string=u"Etats")
planning_tache_categ_ids = fields.Many2many(
comodel_name='of.planning.tache.categ', string=u"Catégories de tâches planning")
product_categ_ids = fields.Many2many(
comodel_name='product.category', string=u"Catégories d'articles")
class OFFollowupTaskTypeState(models.Model):
_name = 'of.followup.task.type.state'
_description = u"Etat des types de tâches liées au suivi des projets"
_order = 'sequence, id desc'
task_type_id = fields.Many2one(comodel_name='of.followup.task.type', string=u"Type de tâche", ondelete='cascade')
sequence = fields.Integer(string=u"Séquence")
name = fields.Char(string=u"Nom", required=True)
starting_state = fields.Boolean(string=u"Etat de départ")
final_state = fields.Boolean(string=u"Etat final")
stage_id = fields.Many2one(
comodel_name='of.followup.project.stage', string=u"En retard à partir de la période",
domain=[('code', 'not in', ['new', 'coming', 's+'])])
@api.model
def create(self, vals):
# Gestion de la séquence lors de la création
if vals.get('task_type_id'):
other_states = self.search([('task_type_id', '=', vals.get('task_type_id'))])
if other_states:
sequence = max(other_states.mapped('sequence')) + 1
else:
sequence = 0
vals.update({'sequence': sequence})
return super(OFFollowupTaskTypeState, self).create(vals)
class OFFollowupProjectTemplate(models.Model):
_name = 'of.followup.project.template'
_description = "Modèle de suivi des projets"
name = fields.Char(string=u"Nom", required=True)
task_ids = fields.One2many(
comodel_name='of.followup.project.tmpl.task', inverse_name='template_id', string=u"Tâches")
default = fields.Boolean(string=u"Modèle par défaut")
class OFFollowupProjectTmplTask(models.Model):
_name = 'of.followup.project.tmpl.task'
_description = u"Type de tâches liées au modèle de suivi"
_order = 'sequence'
template_id = fields.Many2one(comodel_name='of.followup.project.template', string=u"Modèle de suivi")
sequence = fields.Integer(string=u"Séquence")
type_id = fields.Many2one(comodel_name='of.followup.task.type', string=u"Type de tâche", required=True)
predefined_task = fields.Boolean(string=u"Tâche pré-définie", related='type_id.predefined_task', readonly=True)
name = fields.Char(string=u"Nom", related='type_id.name', readonly=True)
class OFFollowupProjectTag(models.Model):
_name = 'of.followup.project.tag'
_description = u"Étiquette du suivi commande"
name = fields.Char(string=u"Nom", required=True)
color = fields.Integer(string=u"Index couleur")
_sql_constraints = [
('name_uniq', 'unique (name)', u"Ce nom d'étiquette existe déjà !"),
]
class OFFollowupProjectAlert(models.Model):
_name = 'of.followup.project.alert'
_description = u"Alerte du suivi commande"
name = fields.Char(string=u"Nom", required=True)
color = fields.Integer(string=u"Index couleur", default=4)
class SaleOrder(models.Model):
_inherit = 'sale.order'
of_followup_project_id = fields.Many2one(comodel_name='of.followup.project', string=u"Suivi", copy=False)
of_follow_count = fields.Integer(string=u"Nombre de suivi", compute='_compute_of_followup_count')
@api.multi
def _compute_of_followup_count(self):
for rec in self:
if rec.of_followup_project_id:
rec.of_follow_count = 1
else:
rec.of_follow_count = 0
@api.multi
def action_followup_project(self):
self.ensure_one()
followup_project_obj = self.env['of.followup.project']
ir_config_obj = self.env['ir.config_parameter']
followup_project = followup_project_obj.search([('order_id', '=', self.id)])
if not followup_project and not ir_config_obj.get_param('of.followup.migration', False):
template = self.env['of.followup.project.template'].search([('default', '=', True)])
values = {
'order_id': self.id,
'template_id': template and template[0].id or False
}
followup_project = followup_project_obj.create(values)
if followup_project.template_id:
new_tasks = []
for task in followup_project.template_id.task_ids:
vals = {'sequence': task.sequence, 'type_id': task.type_id.id, 'name': task.name}
state = self.env['of.followup.task.type.state'].search(
[('task_type_id', '=', task.type_id.id), ('starting_state', '=', True)], limit=1)
if state:
if task.predefined_task:
vals.update({'predefined_state_id': state.id})
else:
vals.update({'state_id': state.id})
new_tasks += [(0, 0, vals)]
followup_project.task_ids = new_tasks
if self._context.get('auto_followup'):
followup_project.user_id = self._context.get('followup_creator_id')
return True
else:
return {
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'of.followup.project',
'res_id': followup_project.id,
'target': 'current',
'flags': {'initial_mode': 'edit', 'form': {'action_buttons': True, 'options': {'mode': 'edit'}}},
}
else:
if self._context.get('auto_followup') or ir_config_obj.get_param('of.followup.migration', False):
return True
else:
return {
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'of.followup.project',
'res_id': followup_project.id,
'target': 'current',
}
@api.multi
def action_confirm(self):
return super(SaleOrder, self).action_confirm()
ir_config_obj = self.env['ir.config_parameter']
if not self._context.get('order_cancellation', False) and \
not ir_config_obj.get_param('of.followup.migration', False):
for order in self:
order.with_context(auto_followup=True, followup_creator_id=self.env.user.id).sudo().\
action_followup_project()
return True
@api.multi
def action_view_followup(self):
self.ensure_one()
action = self.env.ref('of_followup.of_followup_project_action').read()[0]
if self.of_followup_project_id:
ctx = self._context.copy()
ctx.update({'search_default_order_id': self.id})
action['context'] = ctx
else:
action = {'type': 'ir.actions.act_window_close'}
return action
class File(dms_base.DMSModel):
_inherit = 'muk_dms.file'
@api.model
def of_get_object_partner_and_category(self, obj):
if obj._name == 'of.followup.project':
partner = obj.partner_id
categ = self.env.ref('of_followup.of_followup_project_file_category')
else:
partner, categ = super(File, self).of_get_object_partner_and_category(obj)
return partner, categ
@api.multi
def action_view_linked_record(self):
result = super(File, self).action_view_linked_record()
if self.of_file_type == 'related' and self.of_related_model == 'of.followup.project':
result['view_id'] = self.env.ref('of_followup.of_followup_project_form_view').id
return result
| odof/openfire | of_followup/models/of_followup.py | of_followup.py | py | 70,070 | python | en | code | 3 | github-code | 36 |
38672578742 | import shodan
import requests
from shodan import Shodan
'''
api = Shodan('Insert_your_Shodan_Api_Key')
print(api.search(query='product:nginx', facets='country,org'))
'''
SHODAN_API_KEY = "Insert_your_Shodan_Api_Key"
api = shodan.Shodan(SHODAN_API_KEY)
target = 'www.packtpub.com'
dnsResolve = 'https://api.shodan.io/dns/resolve?hostnames=' + target + '&key=' + SHODAN_API_KEY
Data={}
try:
# First we need to resolve our targets domain to an IP
resolved = requests.get(dnsResolve)
hostIP = resolved.json()[target]
# Then we need to do a Shodan search on that IP
host = api.host(hostIP)
Data['Ip']=host['ip_str']
Data['Organization']=host.get('org')
Data['Operating System']=host.get('OS')
#print ("IP: %s" % host['ip_str'])
#print ("Organization: %s" % host.get('org', 'n/a'))
#print ("Operating System: %s" % host.get('os', 'n/a'))
# Print all banners
for item in host['data']:
Data['Port']=item['port']
Data['Banner']=item['data']
#print ("Port: %s" % item['port'])
#print ("Banner: %s" % item['data'])
# Print vuln information
for item in host['vulns']:
CVE = item.replace('!','')
Data['Vulnerability']=item
print ('Vulns: %s' % item)
exploits = api.exploits.search(CVE)
for item in exploits['matches']:
if item.get('cve')[0] == CVE:
Data['Description']=item.get('description')
print (item.get('description'))
except:
'An error occured'
| MuhammadAli947/shodanCode | ShodanScans.py | ShodanScans.py | py | 1,526 | python | en | code | 0 | github-code | 36 |
38650316304 | #%%
import pyautogui, pyperclip
Y = 550 # 507
X = 800 # 740
pyperclip.copy("직")
pyautogui.moveTo(x=X, y=Y, duration=0.001)
pyautogui.click(clicks=1)
pyautogui.hotkey("ctrl", "v")
pyperclip.copy("업")
pyautogui.moveTo(x=X, y=Y, duration=1)
pyautogui.click(clicks=1)
pyautogui.hotkey("ctrl", "v")
pyperclip.copy("상")
pyautogui.moveTo(x=X, y=Y, duration=1)
pyautogui.click(clicks=1)
pyautogui.hotkey("ctrl", "v")
pyperclip.copy("담")
pyautogui.moveTo(x=X, y=Y, duration=1)
pyautogui.click(clicks=1)
pyautogui.hotkey("ctrl", "v")
pyperclip.copy("사")
pyautogui.moveTo(x=X, y=Y, duration=1)
pyautogui.click(clicks=1)
pyautogui.hotkey("ctrl", "v")
print(pyautogui.position())
print(pyautogui.size())
print(pyautogui.onScreen(1000,2000))
print(pyautogui.onScreen(1000,1000))
# x 740 / y 507
#%%
# OCR
import pytesseract, pyautogui
from PIL import ImageGrab
from textblob import TextBlob
pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract'
screen = ImageGrab.grab(bbox=(600, 300, 1200, 800))
w = screen.convert('L')
w.save('/Users/shetshield/Desktop/python_ws/grabbed.png')
text = pytesseract.image_to_string(w)
arr = text.split('\n')[0:-1]
res = '\n'.join(arr)
# correctedText = TextBlob(text).correct().string
# print(correctedText)
print(res)
| shetshield/src | stitching_img/pymacro.py | pymacro.py | py | 1,353 | python | en | code | 0 | github-code | 36 |
38313990919 | from flask import flash
from flask_app.config.mysqlconnection import connectToMySQL
from flask_app.models import user
from flask_app.models import message
class Event:
db = "plannendar_schema"
def __init__(self, data):
self.id = data['id']
self.event = data['event']
self.description = data['description']
self.activities = data['activities']
self.start_date = data['start_date']
self.end_date = data['end_date']
self.location = data['location']
self.user_id = data['user_id']
self.created_at = data['created_at']
self.updated_at = data['updated_at']
self.creator = None
@classmethod
def save(cls, data):
query = "INSERT INTO events (event, description, activities, start_date, end_date, location, user_id) VALUES (%(event)s,%(description)s,%(activities)s,%(start_date)s,%(end_date)s,%(location)s,%(user_id)s);"
return connectToMySQL(cls.db).query_db(query, data)
@classmethod
def add_guests(cls, data):
query = 'INSERT INTO guests (event_id, user_id) VALUES (%(event_id)s,%(user_id)s);'
return connectToMySQL(cls.db).query_db(query, data)
@classmethod
def get_all(cls):
query = '''SELECT * FROM events
JOIN users
ON events.user_id = users.id;'''
results = connectToMySQL(cls.db).query_db(query)
all_events = []
for row in results:
one_event = cls(row)
user_data = {
"id": row["users.id"],
"first_name": row["first_name"],
"last_name": row["last_name"],
"email": row["email"],
"password": "not telling",
"created_at": row["users.created_at"],
"updated_at": row["users.updated_at"]
}
one_event.guests = user.User.get_event_guests(
{"event_id": one_event.id})
one_event.creator = user.User(user_data)
all_events.append(one_event)
return all_events
@classmethod
def get_user_events(cls, data):
query = """SELECT * FROM events
JOIN users
ON events.user_id = users.id
WHERE events.id = %(id)s;"""
results = connectToMySQL(cls.db).query_db(query, data)
for row in results:
one_event = cls(row)
user_data = {
"id": row["users.id"],
"first_name": row["first_name"],
"last_name": row["last_name"],
"email": row["email"],
"password": "not telling",
"created_at": row["users.created_at"],
"updated_at": row["users.updated_at"]
}
one_event.creator = user.User(user_data)
return one_event
@classmethod # get by the ID, appending the messages into empty list
def get_one(cls, data):
query = """SELECT * FROM events
LEFT JOIN messages
ON events.id = messages.event_id
WHERE events.id = %(id)s;"""
results = connectToMySQL(cls.db).query_db(query, data)
event = cls(results[0])
event.guests = user.User.get_event_guests({"event_id": event.id})
event.messages = []
for row in results:
message_row = {
"id": row['messages.id'],
"content": row['content'],
"user_id": row['messages.user_id'],
"event_id": row['event_id'],
"created_at": row['messages.created_at'],
"updated_at": row['messages.updated_at']
}
one_message = message.Message(message_row)
one_message.creator = user.User.get_from_id(
{"id": row["messages.user_id"]}) # grabbing events user_id
event.messages.append(one_message)
return event
@classmethod # upate function
def update(cls, data):
query = """UPDATE events
SET event= %(event)s,
description= %(description)s,
activities= %(activities)s,
start_date= %(start_date)s,
end_date= %(end_date)s,
location= %(location)s,
updated_at= NOW()
WHERE id= %(id)s;"""
return connectToMySQL(cls.db).query_db(query, data)
@classmethod # delete function
def destroy(cls, data):
query = """DELETE FROM events
WHERE id = %(id)s;"""
return connectToMySQL(cls.db).query_db(query, data)
@staticmethod # validating event details
def validate_event(event):
is_valid = True
if len(event['event']) < 2:
is_valid = False
flash("The event name is too short", "event")
if len(event['activities']) < 2:
is_valid = False
flash("The activities is too short", "event")
if len(event['description']) < 2:
is_valid = False
flash("The description is too short", "event")
if len(event['start_date']) == "":
is_valid = False
flash("missing a date", "event")
if len(event['end_date']) == "":
is_valid = False
flash("missing a date", "event")
if len(event['location']) < 2:
is_valid = False
flash("Location is too short", "event")
return is_valid
| rchuu/plannendar | flask_app/models/event.py | event.py | py | 5,351 | python | en | code | 0 | github-code | 36 |
39524154736 | def zero_matrix(row, colons):
out = [([0] * row) for i in range(colons)]
return out
# test matrix
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
def add_matrix(vec_a, vec_b):
out = zero_matrix(len(a[0]), len(a))
for i in range(len(a)):
for j in range(len(a[0])):
out[i][j] = a[i][j] + b[i][j]
return out
matrix_test = add_matrix(a, b)
print('Matrix add: ', matrix_test)
def substruct_matrix(vec_a, vec_b):
out = zero_matrix(len(a[0]), len(a))
for i in range(len(a)):
for j in range(len(a[0])):
out[i][j] = a[i][j] - b[i][j]
return out
matrix_sub = substruct_matrix(a, b)
print('Subctruct matrx: ', matrix_sub)
def multiplication_matrix(a, b):
r = []
m = []
for i in range(len(a)):
for j in range(len(b[0])):
sums = 0
for k in range(len(b)):
sums = sums + (a[i][k] * b[k][j])
r.append(sums)
m.append(r)
r = []
return m
matrix = multiplication_matrix(a, b)
print('matrix: ', matrix)
| Viachkov/Tutor_ML | test2.py | test2.py | py | 1,051 | python | en | code | 0 | github-code | 36 |
26419037040 | import datetime
from functools import wraps
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils import timezone
def authentication_required(function=None):
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
session = request.session
if session.get("provider") \
and session.get("patient_id") \
and session.get("patient") \
and session.get("access_token") \
and session.get("expiration"):
expiration = session.get("expiration")
if isinstance(expiration, datetime.datetime) and expiration > timezone.now():
return view_func(request, *args, **kwargs)
# Clear the session if authentication failed.
request.session.flush()
return HttpResponseRedirect(reverse("pisces:index"))
return _wrapped_view
if function:
return decorator(function)
return decorator
| qiuosier/Pisces | decorators.py | decorators.py | py | 1,068 | python | en | code | 0 | github-code | 36 |
3270527178 | """
Model implementation.
"""
from helper import cache_func, INIT_METHODS
import tensorflow as tf
class CNNModel:
"""
CNN model implementation. Covers the implementations for both the large and the
compact network.
"""
def __init__(self, data, target, model_params, data_params):
self.data = data
self.target = target
self.params = model_params
self.data_params = data_params
# Weight initialization object arguments.
if self.params["weight_init"] == "gaussian":
init_args = {"mean": 0.0,
"stddev": 1}
else:
init_args = {}
if model_params["model_type"] == "large": # LargeNet Implementation.
self.num_layers = 9 # Number of conv. layers.
self.num_deep = 4 # Number of dense layers.
self.strides = [1, 1, 1, 1, 1, 1, 1, 1]
self.weight_dict = {"W_c_1": tf.compat.v1.get_variable(shape=(7, 7, self.data_params["input_dims"], 16),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_c_1"),
"b_c_1": tf.Variable(tf.zeros([16])),
"W_c_2": tf.compat.v1.get_variable(shape=(7, 7, 16, 16),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_c_2"),
"b_c_2": tf.Variable(tf.zeros([16])),
"W_c_3": tf.compat.v1.get_variable(shape=(5, 5, 16, 32),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_c_3"),
"b_c_3": tf.Variable(tf.zeros([32])),
"W_c_4": tf.compat.v1.get_variable(shape=(5, 5, 32, 32),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_c_4"),
"b_c_4": tf.Variable(tf.zeros([32])),
"W_c_5": tf.compat.v1.get_variable(shape=(5, 5, 32, 64),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_c_5"),
"b_c_5": tf.Variable(tf.zeros([64])),
"W_c_6": tf.compat.v1.get_variable(shape=(3, 3, 64, 128),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_c_6"),
"b_c_6": tf.Variable(tf.zeros([128])),
"W_c_7": tf.compat.v1.get_variable(shape=(3, 3, 128, 256),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_c_7"),
"b_c_7": tf.Variable(tf.zeros([256])),
"W_c_8": tf.compat.v1.get_variable(shape=(3, 3, 256, 512),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_c_8"),
"b_c_8": tf.Variable(tf.zeros([512])),
"W_1": tf.compat.v1.get_variable(shape=(34 ** 2 * 512, 512),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_1"),
"b_1": tf.Variable(tf.zeros([512])),
"W_2": tf.compat.v1.get_variable(shape=[512, 256],
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_2"),
"b_2": tf.Variable(tf.zeros([256])),
"W_3": tf.compat.v1.get_variable(shape=(256, 1),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_3"),
"b_3": tf.Variable(tf.zeros([1]))}
else: # Implementation of the compact network.
self.num_layers = 5
self.num_deep = 4
self.strides = [3, 1, 1, 1]
self.weight_dict = {"W_c_1": tf.compat.v1.get_variable(shape=(5, 5, self.data_params["input_dims"], 16),
initializer=INIT_METHODS[self.params["weight_init"]](
**init_args),
name="W_c_1"),
"b_c_1": tf.Variable(tf.zeros([16])),
"W_c_2": tf.compat.v1.get_variable(shape=(5, 5, 16, 32),
initializer=INIT_METHODS[self.params["weight_init"]](
**init_args),
name="W_c_2"),
"b_c_2": tf.Variable(tf.zeros([32])),
"W_c_3": tf.compat.v1.get_variable(shape=(3, 3, 32, 64),
initializer=INIT_METHODS[self.params["weight_init"]](
**init_args),
name="W_c_3"),
"b_c_3": tf.Variable(tf.zeros([64])),
"W_c_4": tf.compat.v1.get_variable(shape=(3, 3, 64, 128),
initializer=INIT_METHODS[self.params["weight_init"]](
**init_args),
name="W_c_4"),
"b_c_4": tf.Variable(tf.zeros([128])),
"W_1": tf.compat.v1.get_variable(shape=(10 ** 2 * 128, 1024),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_1"),
"b_1": tf.Variable(tf.zeros([1024])),
"W_2": tf.compat.v1.get_variable(shape=[1024, 256],
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_2"),
"b_2": tf.Variable(tf.zeros([256])),
"W_3": tf.compat.v1.get_variable(shape=(256, 1),
initializer=INIT_METHODS[self.params["weight_init"]](**init_args),
name="W_3"),
"b_3": tf.Variable(tf.zeros([1]))}
for key, val in self.weight_dict.items(): # Rename the layers.
self.weight_dict[key] = tf.identity(self.weight_dict[key], name=key)
# Flag indicating whether the current session is training or prediction.
self.training = tf.compat.v1.placeholder(tf.bool, shape=[])
self.layer_out = None
self.convs = {}
self.biass = {}
self.activations = {}
self.pools = {}
self.weight = {"W_c_1": None}
self.densed = {}
self.biased = {}
self.activated = {}
self.dense_weights = {}
self.bias_weights = {}
self._loss = None
# Initialize the lazy properties.
_ = self.optimize
_ = self.eval_loss
self.epoch_counter = 0
@cache_func
def predict(self):
"""
Forward function for the models.
:return: Output of the model.
"""
for c in range(1, self.num_layers):
if c == 1:
input_ = self.data
self.weight["W_c_1"] = tf.transpose(self.weight_dict["W_c_1"], [3, 0, 1, 2])
else:
input_ = pool
conv = tf.nn.conv2d(input_, self.weight_dict[f"W_c_{c}"], self.strides[c-1], "VALID")
self.convs[c] = tf.transpose(conv, [3, 0, 1, 2])
bias = tf.nn.bias_add(conv, self.weight_dict[f"b_c_{c}"])
self.biass[c] = tf.transpose(bias, [3, 0, 1, 2])
if self.params["batch_norm"]:
bias = tf.compat.v1.layers.batch_normalization(bias, axis=-1, training=self.training,
momentum=0.7)
activation = tf.nn.relu(bias)
self.activations[c] = tf.transpose(activation, [3, 0, 1, 2])
pool = tf.nn.pool(activation, (3, 3),
"MAX", padding="VALID")
self.pools[c] = tf.transpose(pool, [3, 0, 1, 2])
flatten = tf.compat.v1.layers.flatten(pool, name=None, data_format='channels_last')
layer_out = flatten
for d in range(1, self.num_deep):
densed = tf.matmul(layer_out, self.weight_dict[f"W_{d}"],
transpose_a=False, transpose_b=False)
self.densed[d] = densed
self.dense_weights[d] = self.weight_dict[f"W_{d}"]
layer_out = densed + self.weight_dict[f"b_{d}"]
self.biased[d] = layer_out
self.bias_weights = self.weight_dict[f"b_{d}"]
if self.params["batch_norm"]:
layer_out = tf.compat.v1.layers.batch_normalization(layer_out, axis=-1, training=self.training,
momentum=0.7)
if d != self.num_deep - 1:
layer_out = tf.nn.relu(layer_out)
self.activated[d] = layer_out
if self.params["dropout"]:
layer_out = tf.cond(self.training, lambda: tf.nn.dropout(layer_out, self.params["keep_rate"]),
lambda: layer_out)
return layer_out
@cache_func
def optimize(self):
"""
One step optimization for the specified loss function.
:return: optimizer.
"""
loss = self.loss
optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=self.params["learning_rate"],
beta1=0.8, beta2=0.8)
train_op = optimizer.minimize(loss)
return train_op
@cache_func
def loss(self):
"""
Overall loss function that contains the data loss and the regularization losses.
:return: Overall loss.
"""
self._loss = self.data_loss
if self.params["l2_loss"]:
self._loss += self.l2_loss
return self._loss
@cache_func
def data_loss(self):
"""
Data loss from the label predictions.
:return: data loss.
"""
if self.params["loss_type"] == "l1":
loss = tf.reduce_mean(tf.abs(tf.subtract(self.target, self.predict)))
elif self.params["loss_type"] == "l2":
loss = tf.reduce_mean(tf.pow(tf.subtract(self.target, self.predict), 2))
else:
loss = 0.0
return loss
@cache_func
def eval_loss(self):
"""
Evaluation loss, L1.
:return: evaluation loss.
"""
loss = tf.reduce_mean(tf.abs(tf.subtract(self.target, tf.math.round(self.predict))))
return loss
@cache_func
def l2_loss(self):
"""
L2 regularization loss.
:return: Regularization loss.
"""
l2_loss = 0.0
for key, val in self.weight_dict.items():
l2_loss += self.params["alpha"] * tf.nn.l2_loss(val)
return l2_loss
def evaluate(self):
"""
:return:
"""
return tf.reduce_mean(tf.abs(tf.subtract(self.target, tf.math.round(self.predict))))
| Oguzhanka/face_attractiveness | models/cnn_model.py | cnn_model.py | py | 13,191 | python | en | code | 0 | github-code | 36 |
7416408824 | import pywt
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
plt.style.use("resources/figstyle.mplstyle")
FIG_WIDTH = 2.3 * 7.16
# Gaussian fitting utils
from scipy import optimize
def fit_generalized_gaussian(x):
μ0 = x.mean()
σ0 = x.std()
β0 = 2
res = optimize.minimize(
neg_gg_likelihood,
(μ0, σ0, β0),
args=(x,),
bounds=[(-np.inf, np.inf), (1e-2, np.inf), (1e-2, np.inf)],
)
return res.x
def neg_gg_likelihood(θ, x):
μ, σ, β = θ
return -stats.gennorm.logpdf(x, loc=μ, scale=σ, beta=β).sum()
# Load data and normalize
eeg = np.load("resources/data/eeg-denoise-net/EEG_all_epochs.npy")
eog = np.load("resources/data/eeg-denoise-net/EOG_all_epochs.npy")
emg = np.load("resources/data/eeg-denoise-net/EMG_all_epochs.npy")
n_eeg = (eeg - eeg.mean(axis=-1).reshape(-1, 1)) / eeg.std(axis=-1).reshape(-1, 1)
n_eog = (eog - eog.mean(axis=-1).reshape(-1, 1)) / eog.std(axis=-1).reshape(-1, 1)
n_emg = (emg - emg.mean(axis=-1).reshape(-1, 1)) / emg.std(axis=-1).reshape(-1, 1)
# Wavelet transform
max_levels = 4
eeg_coeffs = pywt.wavedec(
n_eeg, "sym5", level=max_levels, axis=-1, mode="periodization"
)
eog_coeffs = pywt.wavedec(
n_eog, "sym5", level=max_levels, axis=-1, mode="periodization"
)
emg_coeffs = pywt.wavedec(
n_emg, "sym5", level=max_levels, axis=-1, mode="periodization"
)
level_names = [f"Level $c_{n}$" for n in range(len(eeg_coeffs), 0, -1)]
# Prepare figure
num_levels = 4
xlim = (-8, 8)
fig, axes = plt.subplots(
nrows=num_levels,
sharex=True,
ncols=3,
figsize=(FIG_WIDTH, FIG_WIDTH * 0.3),
)
num_bins = 201
bin_range = (-10, 10)
n = 0
for cs_eeg, cs_eog, cs_emg, name in zip(
eeg_coeffs[:num_levels],
eog_coeffs[:num_levels],
emg_coeffs[:num_levels],
level_names[:num_levels],
):
_, bins, _ = axes[n, 0].hist(
cs_eeg.reshape(-1),
fc="#2D9CDB",
bins=num_bins,
range=bin_range,
density=True,
alpha=0.7,
)
μ, α, β = fit_generalized_gaussian(cs_eeg.reshape(-1))
axes[n, 0].plot(
bins,
stats.gennorm.pdf(bins, loc=μ, scale=α, beta=β),
c="k",
ls="--",
lw=1.5,
label=f"α = {α:.2f}\nβ = {β:.2f}",
)
axes[n, 0].legend(loc="upper right", bbox_to_anchor=(1.03, 1.1))
if n == 0:
μ, α, β = fit_generalized_gaussian(cs_eog.reshape(-1))
axes[n, 1].plot(
bins,
stats.gennorm.pdf(bins, loc=μ, scale=α, beta=β),
c="k",
ls="--",
lw=1,
alpha=0.8,
label=f"α = {α:.2f}\nβ = {β:.2f}",
)
axes[n, 1].legend(loc="upper right", bbox_to_anchor=(1.03, 1.1))
μ, α, β = fit_generalized_gaussian(cs_emg.reshape(-1))
axes[n, 2].plot(
bins,
stats.gennorm.pdf(bins, loc=μ, scale=α, beta=β),
c="k",
ls="--",
lw=1,
alpha=0.8 if n == 2 else 1,
label=f"α = {α:.2f}\nβ = {β:.2f}",
)
axes[n, 2].legend(loc="upper right", bbox_to_anchor=(1.03, 1.1))
axes[n, 2].hist(
cs_emg.reshape(-1),
fc="#2D9CDB",
bins=num_bins,
range=bin_range,
density=True,
alpha=0.7,
)
axes[n, 1].hist(
cs_eog.reshape(-1),
fc="#2D9CDB",
bins=num_bins,
range=bin_range,
density=True,
alpha=0.7,
)
axes[n, 0].set_ylabel(name)
axes[n, 0].set_yticks([])
axes[n, 1].set_yticks([])
axes[n, 2].set_yticks([])
n += 1
axes[0, 0].set_title("EEG", fontsize=14)
axes[0, 1].set_title("EOG", fontsize=14)
axes[0, 2].set_title("EMG", fontsize=14)
axes[0, 0].set_xticks([-5, 0, 5])
axes[0, 1].set_xticks([-5, 0, 5])
axes[0, 2].set_xticks([-5, 0, 5])
axes[0, 0].set_xlim(*xlim)
axes[0, 1].set_xlim(*xlim)
axes[0, 2].set_xlim(*xlim)
axes[-1, 0].set_xlabel("Coefficient value", labelpad=-2)
axes[-1, 1].set_xlabel("Coefficient value", labelpad=-2)
axes[-1, 2].set_xlabel("Coefficient value", labelpad=-2)
fig.subplots_adjust(wspace=0.04, hspace=0.1)
fig.savefig("./output/acha_fig2_coeff_distributions.pdf")
print("Figure saved to `./output/acha_fig2_coeff_distributions.pdf`")
| mattbit/wavelet-wqn-acha | acha_scripts/02_figure_2__coeff_distributions.py | 02_figure_2__coeff_distributions.py | py | 4,260 | python | en | code | 2 | github-code | 36 |
35217860162 | from itertools import product
import sys
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import json
import random
sys.path.append('../..')
from lib import excelUtils
from lib import httpUtils
from lib import textUtil
from lib.htmlEleUtils import getNodeText
from lib.htmlEleUtils import getInnerHtml
products = []
header=['link','type','Product Name']
def addHeader(title):
if title not in header and len(title) > 0:
header.append(title)
chrome_options = webdriver.ChromeOptions()
# chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument("window-size=1024,768")
chrome_options.add_argument("--proxy-server=http://127.0.0.1:33210")
# chrome_options.add_argument("--no-sandbox")
browser = webdriver.Chrome(chrome_options=chrome_options)
def getProductInfo(url):
print(str(len(products)) + ":" + url)
browser.get(url)
sope= BeautifulSoup(browser.page_source, "html.parser")
pInfo = {
"link": url,
}
nameArea = sope.find("div", attrs={"class":"col-lg-12 col-md-12 col-sm-12 col-xs-12 follow-box-title"})
pInfo["Product Name"] = getNodeText(nameArea)
specs = sope.find_all("div", attrs={"class":"prd-des-lis"})
for spec in specs:
titleArea = spec.find("div", attrs={"class":"col-lg-4 col-md-4 col-sm-12 col-xs-12 prod-categorty"})
valArea = spec.find("div", attrs={"class":"col-lg-8 col-md-8 col-sm-12 col-xs-12 clearfix prod-categorty prod-category-back"})
valArea2 = spec.find("div", attrs={"class":"col-lg-8 col-md-8 col-sm-12 col-xs-12 clearfix prod-categorty prod-category-back synonymWrapper"})
if titleArea!=None:
title = getNodeText(titleArea)
value = getNodeText(valArea)
if len(value) == 0:
value = getNodeText(valArea2)
addHeader(title)
pInfo[title] = value
print(pInfo)
products.append(pInfo.copy())
def getProductType(url):
browser.get(url)
sope= BeautifulSoup(browser.page_source, "html.parser")
trs = sope.find_all("div", attrs={"class":"single-details"})
for tr in trs:
pLink = tr.find("a")
if pLink != None:
linkSrc = pLink["href"]
getProductInfo(linkSrc)
# getProductInfo("https://www.lobachemie.com/Alcohols-0059A/tertBUTANOL-CASNO-75-65-0.aspx", 'Alcohols')
for pIndex in range(1, 7):
getProductType("https://www.parchem.com/Solvents-chemicals-supplier-distributor~"+str(pIndex)+".aspx")
# getProductType("https://www.parchem.com/Solvents-chemicals-supplier-distributor~1.aspx")
excelUtils.generateExcel('parchem.xlsx', products, header) | Just-Doing/python-caiji | src/work/20230205/parchem.py | parchem.py | py | 2,568 | python | en | code | 1 | github-code | 36 |
12410410025 | """
Update existing "embargo_approved_no_user" logs to link to registered project instead
of the registration.
"""
from copy import deepcopy
import logging
import sys
from modularodm import Q
from framework.transactions.context import TokuTransaction
from website.models import Node, NodeLog
from website.app import init_app
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main():
targets = get_targets()
fix_embargo_approved_logs(targets)
def get_targets():
return NodeLog.find(Q('action', 'eq', NodeLog.EMBARGO_APPROVED) & Q('params.user', 'eq', None))
def fix_embargo_approved_logs(targets):
count = 0
for log in targets:
node_id = log.params['node']
node = Node.load(node_id)
if node.is_registration:
original_params = deepcopy(log.params)
log.params['node'] = node.registered_from_id
log.params['registration'] = node._id
logger.info('Updating params of log {} from {} to {}'.format(log._id, original_params, log.params))
log.save()
count += 1
logger.info('{} logs migrated'.format(count))
if __name__ == '__main__':
dry = '--dry' in sys.argv
if not dry:
script_utils.add_file_logger(logger, __file__)
init_app(routes=False, set_backends=True)
with TokuTransaction():
main()
if dry:
raise Exception('Dry Run -- Aborting Transaction')
| karenhanson/osf.io_rmap_integration_old | scripts/fix_embargo_approved_logs.py | fix_embargo_approved_logs.py | py | 1,458 | python | en | code | 0 | github-code | 36 |
10246834959 | import os
import argparse
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Some hyperparameters')
parser.add_argument('--epochs', type=int, default=200)
parser.add_argument('--frac', type=float, default=0.1)
parser.add_argument('--iid', type=bool, default=False)
parser.add_argument('--dataset', type=str, default='fashion-mnist')
parser.add_argument('--model', type=str, default='cnn')
args = parser.parse_args()
rootpath = './log'
# full participation
full_acc = []
full_accfile = open(rootpath + '/accfile_fed_{}_{}_{}_C{}_iid{}_{}.dat'.
format(args.dataset, args.model, args.epochs, 1.0, args.iid, 'full'), 'r')
for acc in full_accfile.readlines():
full_acc.append(float(acc))
full_accfile.close()
# random sampling
rand_acc = []
rand_accfile = open(rootpath + '/accfile_fed_{}_{}_{}_C{}_iid{}_{}.dat'.
format(args.dataset, args.model, args.epochs, args.frac, args.iid, 'full'), 'r')
for acc in rand_accfile.readlines():
rand_acc.append(float(acc))
rand_accfile.close()
# power-of-choice
power_acc = []
power_accfile = open(rootpath + '/accfile_fed_{}_{}_{}_C{}_iid{}_{}.dat'.
format(args.dataset, args.model, args.epochs, 1.0, args.iid, 'power-of-choice'), 'r')
for acc in power_accfile.readlines():
power_acc.append(float(acc))
power_accfile.close()
# ideal
ideal_acc = []
ideal_accfile = open(rootpath + '/accfile_fed_{}_{}_{}_C{}_iid{}_{}.dat'.
format(args.dataset, args.model, args.epochs, 0.3, args.iid, 'ideal'), 'r')
for acc in ideal_accfile.readlines():
ideal_acc.append(float(acc))
ideal_accfile.close()
# # practical
# practical_acc = []
# prac_accfile = open(rootpath + '/accfile_fed_{}_{}_{}_C{}_iid{}_{}.dat'.
# format(args.dataset, args.model, args.epochs, 1.0, args.iid, 'practical'), 'r')
# for acc in prac_accfile.readlines():
# practical_acc.append(float(acc))
# prac_accfile.close()
# # divfl
# divfl_acc = []
# divfl_accfile = open(rootpath + '/accfile_fed_{}_{}_{}_C{}_iid{}_{}.dat'.
# format(args.dataset, args.model, args.epochs, 1.0, args.iid, 'divfl'), 'r')
# for acc in divfl_accfile.readlines():
# divfl_acc.append(float(acc))
# divfl_accfile.close()
plt.figure()
plt.plot(range(len(full_acc)), full_acc, linestyle='--', label='Full')
plt.plot(range(len(rand_acc)), rand_acc, label='Random')
plt.plot(range(len(power_acc)), power_acc, label='Power-of-choice')
# plt.plot(range(len(divfl_acc)), divfl_acc, label='DivFL')
plt.plot(range(len(ideal_acc)), ideal_acc, label='Ours (ideal)')
# plt.plot(range(len(practical_acc)), practical_acc, label='Ours (practical)')
plt.legend()
plt.xlabel('Epoch')
plt.ylabel('Test Accuracy')
plt.savefig(rootpath + '/fed_{}_{}_{}_iid{}_acc.png'.format(args.dataset, args.model, args.epochs, args.iid)) | jinwoolim8180/fl-sparse-masking | accuracy.py | accuracy.py | py | 3,163 | python | en | code | 0 | github-code | 36 |
69997777065 | from re import split
from typing import Dict, Mapping
from elasticsearch import Elasticsearch
import cbor
import json
from trec_car.read_data import *
class IndexManagement:
def __init__(self):
self.es_cli = Elasticsearch(
timeout=200, max_retries=15, retry_on_timeout=True)
self.es_cli.info()
# use default setting
self.setting = {
"settings": {
"number_of_shards": 5,
"index": {
"similarity": {
"default": {
"type": "BM25",
"b": 0.75,
"k1": 1.2,
}
}
}
}
}
def index_text_data(self, index_name: str, filepath: str) -> None:
""" Indexes data into the elastics search instance.
Args:
index_name: Name of index.
doc_id: Id of the document to be indexed.
doc: Document to be indexed.
"""
batch_size = 5000
f = open(filepath, 'r', encoding='utf-8')
lines = f.readlines()
for i in range(0, len(lines), batch_size):
bulk_data = []
for line in lines[i:i+batch_size]:
doc = line.split('\t')
curr_doc = {"doc_id": doc[0], "body": doc[1].strip()}
json_doc = json.dumps(curr_doc)
_doc = json.loads(json_doc)
bulk_data.append(
{"index": {"_index": index_name,
"_id": _doc.pop("doc_id")}}
)
bulk_data.append(_doc)
self.es_cli.bulk(index=index_name, body=bulk_data, refresh=True)
def index_cbor_data(self, index_name: str, filepath: str) -> None:
"""[summary]
Args:
index_name (str): [description]
filepath (str): [description]
"""
batch_size = 5000
bulk_data = []
with open(filepath, 'rb') as fp:
for i, para in enumerate(iter_paragraphs(fp)):
para_id = para.para_id
body = [elem.text if isinstance(elem, ParaText)
else elem.anchor_text
for elem in para.bodies]
body = ' '.join(body)
elem = {"doc_id": para_id, "body": body.strip()}
json_elem = json.dumps(elem)
_elem = json.loads(json_elem)
bulk_data.append(
{"index": {"_index": index_name,
"_id": _elem.pop("doc_id")}}
)
bulk_data.append(_elem)
if (i+1) % batch_size == 0:
self.es_cli.bulk(index=index_name,
body=bulk_data, refresh=True)
bulk_data = []
if len(bulk_data) > 0:
self.es_cli.bulk(index=index_name,
body=bulk_data, refresh=True)
def reset_index(self, index_name: str) -> None:
""" Removes instance of elastics search.
Args:
index_name: Name of index.
index_setting: Index setting chosen for the elastics search instance.
"""
if self.es_cli.indices.exists(index_name):
self.es_cli.indices.delete(index=index_name)
# self.es_cli.create(index=index_name)
if __name__ == "__main__":
""" filepath_marco = "D:\data_collection/collection.tsv"
filepath_car = "../data_collection/dedup.articles-paragraphs.cbor"
index_name = 'ms_marco'
index_mng = IndexManagement()
index_mng.reset_index(index_name)
index_mng.index_text_data(index_name, filepath_marco)
index_mng.index_cbor_data(index_name, filepath_car) """
es = Elasticsearch()
print(es.count(index="ms_marco"))
| Hanifff/ConversationalAssistance | index_data.py | index_data.py | py | 3,917 | python | en | code | 0 | github-code | 36 |
216572710 | import time
def measure(f):
t0 = time.time()
result = f()
duration = time.time() - t0
return duration, result
def show_duration(duration):
if duration < 1:
return '%.2fms' % (duration * 1e3)
if duration < 60:
return '%.2fs' % duration
sec = int(duration)
mm, ss = sec / 60, sec % 60
if duration < 3600:
return '%dm%ds' % (mm, ss)
return '%dh%dm%ds' % (mm / 60, mm % 60, ss)
def log_duration(f, *args, **kwargs):
duration, result = measure(lambda: f(*args, **kwargs))
print('%s took %s' % (f, show_duration(duration)))
return result
| kungfu-team/kungfu-mindspore | debug/mindspore_debug/__init__.py | __init__.py | py | 614 | python | en | code | 0 | github-code | 36 |
30793302432 | import cv2
import numpy as np
cap = cv2.VideoCapture(0)
# size = (600, 200, 3) # Указываем желаемый размер окна (высоту, ширину, число каналов)
while True:
ret, frame = cap.read() # ret - успешность захвата кадра. Если кадр был успешно захвачен, ret будет равен True. В противном случае, если что-то пошло не так или видео закончилось, ret будет равен False
width = int(cap.get(3))
height = int(cap.get(4))
image = np.zeros(frame.shape, np.uint8)
# (0, 0) в параметре dsize указывает на то, что размеры выходного изображения будут вычислены автоматически на основе масштабных факторов fx и fy
smaller_image = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)
# первая колонка изображений
image[:height//2, :width//2] = cv2.rotate(smaller_image, cv2.ROTATE_180) # левая верхняя
image[height//2:, :width//2] = smaller_image # левая нижняя
# вторая колонка изображений
image[:height//2, width//2:] = smaller_image # правая верхняя
image[height//2:, width//2:] = cv2.rotate(smaller_image, cv2.ROTATE_180)# правая нижняя
cv2.imshow('frame', image)
if cv2.waitKey(1) == ord('q'):
break
cap.release() # освобождаем память от захвата видео на устройстве
cv2.destroyAllWindows()
| SeVaSe/Open_CV_test_vision | cameras&videocapture.py | cameras&videocapture.py | py | 1,671 | python | ru | code | 0 | github-code | 36 |
42307266488 | # s = "applepenapple", wordDict = ["apple", "pen"]
# 输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
# 输出: false
s = "applepenapple"
wordDict = ["apple", "pen"]
s2 = "catsandog"
wordDict2 = ["cats", "dog", "sand", "and", "cat"]
def isComposed(s,wordDict):
wordDict = set(wordDict)
maxLen = 0
for i in wordDict:
maxLen = max(maxLen,len(i))
return backtrace(0,s,wordDict,maxLen)
def backtrace(idx,s,wordDict,maxLen):
if idx==len(s):
return True
for i in range(maxLen):
tmp = s[idx:idx+i+1]
if tmp in wordDict:
if backtrace(idx+i+1,s,wordDict,maxLen):
return True
return False
print(isComposed(s,wordDict))
print(isComposed(s2,wordDict2)) | jing-ge/Jing-leetcode | offer/2.py | 2.py | py | 758 | python | en | code | 0 | github-code | 36 |
37393448771 | # Dependencies
import json
# Get influencer criteria from config.json file
config_file = open('config.json')
config = json.load(config_file)
influencer = config['influencer']
def is_influencer(tweet):
""" Determines if an user who tweeted a tweet is an influencer """
rts = tweet['retweet_count']
fav = tweet['favorite_count']
user = tweet['user']
followers = user['followers_count']
# Check if user meets the influencer Criteria
if followers >= influencer['followers'] and rts >= influencer['retweets'] and fav >= influencer['likes']:
return True
else:
return False
def not_retweet(tweet):
""" Determines if it's tweet and not a retweet """
# check if tweet has the retweeted status property, if so it's a retweet, if not it's original.
if hasattr(tweet, 'retweeted_status'):
return False
else:
return True
| janielMartell/twitter-influencer-scraper | utils.py | utils.py | py | 860 | python | en | code | 0 | github-code | 36 |
31566863140 | import sys
import csv
# preprocessing
import gensim
from gensim.utils import simple_preprocess
import re
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
# lemmitization
from nltk.stem import WordNetLemmatizer
def pre_processor():
user_input = input('Please enter a dream: ')
data = user_input
# remove punctuatiom
data = re.sub(r'[^\w\s]', '', data)
# lower case
data = data.lower()
# remove numbers
data = re.sub(r'\d+', '', data)
# remove newlines '/n'
data = re.sub('\s+', ' ', data)
# remove non-ASCII characters
data = re.sub(r'[^\x00-\x7f]',r' ',data)
# remove underscores
data = re.sub(r'[_]', '', data)
# remove words less than 3 characters
data = re.sub(r'\b\w{1,2}\b', '', data)
# create stop_words
stop_words = stopwords.words('english')
new_stop_words = ['from', 'subject', 're', 'edu', 'use', 'not', 'would', 'say', 'could', '_', 'be', 'know',
'good', 'go', 'get', 'do', 'done', 'try', 'many', 'some', 'nice', 'thank', 'think', 'see',
'rather', 'easy', 'easily', 'lot', 'lack', 'make', 'want', 'seem', 'run', 'need', 'even',
'right', 'line', 'even', 'also', 'may', 'take', 'come', 'look', 'back', 'start', 'going',
'doing', 'what','whats', 'pron', 'dream', 'and']
stop_words.extend(new_stop_words)
# remove stop words and tokenize
data_words = [i for i in word_tokenize(data.lower()) if i not in stop_words]
# create bigrams
bigram = gensim.models.Phrases(data_words, min_count=5, threshold=100)
bigram_mod = gensim.models.phrases.Phraser(bigram)
data_words_bigrams = bigram_mod[data_words]
# Init the Wordnet Lemmatizer
lemmatizer = WordNetLemmatizer()
data_lemmatized = [lemmatizer.lemmatize(w) for w in data_words_bigrams]
return data_lemmatized
| connormeaton/dream_cluster | src/app/SampleTextPreprocessor.py | SampleTextPreprocessor.py | py | 1,906 | python | en | code | 1 | github-code | 36 |
12185526029 | """Inference for 2D US Echocardiography EchoNet dataset."""
import os
import numpy as np
import torch
import torchvision.transforms as transforms
import torch.nn.functional as F
from PIL import Image
from torch.autograd import Variable
import matplotlib.pyplot as plt
from models.unet import UNet
from models.cenet import CE_Net_OCT
from models.fpn import FPN
import glob
class TTTSInference:
"""EchoCardioInference class."""
def __init__(self, model_path: str = None
) -> None:
"""
Args:
model_path:
"""
self.model_path = model_path
self.model = FPN(num_blocks=[2,4,23,3], num_classes=4, back_bone="resnet101")
self.model.load_state_dict(torch.load(self.model_path,
map_location="cpu"))
self.model.eval()
self.transforms = transforms.Compose([
transforms.Resize(size=(448, 448)),
transforms.ToTensor()
])
def get_visual_prediction(self,
image_name,
mask_name):
"""
Args:
image_name:
mask_name:
Returns:
"""
image = Image.open(image_name)
mask = Image.open(mask_name)
size = (448, 448)
img = self.transforms(image).unsqueeze(0)
mask = self.transforms(mask).unsqueeze(0)
pred_mask = self.model(Variable(img))
pred_mask = F.softmax(pred_mask, dim=1)
pred_mask = pred_mask.squeeze(0)
data = pred_mask.cpu().data
full_mask = torch.argmax(data, 0)
plt.imshow(full_mask[:, :])
#pred_mask = transforms.ToPILImage()(data).resize(size)
#data_mask = mask.squeeze(0).cpu().data
#mask = transforms.ToPILImage()(data_mask)
#ig = plt.imshow(pred_mask)
#ii = plt.imshow(mask.squeeze(0).squeeze(0), alpha=0.4)
plt.show()
if __name__ == "__main__":
fet_reg = TTTSInference(model_path="../data/model-fold-0fpa.pt")
fet_reg.get_visual_prediction(image_name="../data/Video001/images/Video001_frame01250.png",
mask_name="../data/Video001/labels/Video001_frame01250.png") | SanoScience/TTTS_CV | src/inference.py | inference.py | py | 2,235 | python | en | code | 0 | github-code | 36 |
74506400423 | from rest_framework import serializers
from onbici.bike.serializers import BikeSerializer
from onbici.bike.models import Bike
from onbici.station.models import Station
from .models import Slot
class SlotSerializer(serializers.ModelSerializer):
bike = BikeSerializer(required=False)
class Meta:
model = Slot
fields = ['id', 'station', 'bike', 'status', 'created_at', 'modified_at']
def create(self, validated_data):
if self.context['bike'] is not None:
try:
bike = Bike.objects.get(id=self.context['bike'])
except Bike.DoesNotExist:
raise serializers.ValidationError({'error': 'Please enter a valid user.'})
else:
bike = None
try:
station = Station.objects.get(id=self.context['station'])
except Station.DoesNotExist:
raise serializers.ValidationError({'error': 'Please enter a valid slot.'})
slot = Slot.objects.create(bike = bike, station = station, **validated_data)
return slot
def update(self, instance, validated_data):
if self.context['bike']:
try:
bike = Bike.objects.get(id=self.context['bike'])
""" falta comprobar si la bici esta en otro slot """
except Bike.DoesNotExist:
raise serializers.ValidationError({'error': 'Please enter a valid user.'})
instance.bike = bike
elif self.context['bike'] is None:
instance.bike = None
if self.context['station']:
try:
station = Station.objects.get(id=self.context['station'])
except Station.DoesNotExist:
raise serializers.ValidationError({'error': 'Please enter a valid slot.'})
instance.station = station
if validated_data.get('status', instance.status) is not None:
instance.status = validated_data.get('status', instance.status)
instance.save()
return instance | jubelltols/React_DRF_MySql | DRF/src/onbici/slot/serializers.py | serializers.py | py | 2,029 | python | en | code | 0 | github-code | 36 |
26859540681 | # -*- coding: utf-8 -*-
'''
Created on 9 janv. 2019
@author: Nicolas MEO
'''
from Plateforme.Adafruit_PWM_Servo_Driver import PWM
import time
# Definition des constantes de positions des servo-controller
CONST_TRUE_PL1 = 355
CONST_TRUE_PL2 = 120
CONST_TRUE_PL3 = 140
CONST_TRUE_PL4 = 225
CONST_TRUE_PL5 = 125
CONST_TRUE_PL6a = 420
CONST_TRUE_PL6b = 520
CONTS_FALSE_PL1 = 155
CONST_FALSE_PL2 = 632
CONST_FALSE_PL3 = 400
CONST_FALSE_PL4 = 450
CONST_FALSE_PL5 = 635
CONST_FALSE_PL6a = 125
CONST_FALSE_PL6b = 125
class Servo_Controller(object):
"""
Classe en charge du control des moteurs
"""
def __init__(self, pListState):
"""
Constructeur : configuration des etat faux des moteurs
:param pListState: Liste contenant la configuration de chaque plateforme
:ptype pListState: list
"""
# Initialise the PWM device using the default address
# Set frequency to 60 Hz
self._pwm = PWM(0x40)
self._pwm.setPWMFreq(60)
# Mise en place de l'etat faux pour la plateforme 1
self._sfconf1 = bool(int(pListState[0]))
if(self._sfconf1):
self._pwm.setPWM(3, 0,CONST_TRUE_PL1)
self._Plateforme1 = False
else:
self._pwm.setPWM(3, 0,CONTS_FALSE_PL1)
self._Plateforme1=False
time.sleep(1)
# Mise en place de l'etat faux pour la plateforme 2
# Aucune configuration requise pour cette plateforme
self._sfconf2 = False
self._Plateforme2=False
self._pwm.setPWM(2, 0,CONST_FALSE_PL2)
time.sleep(1)
# Mise en place de l'etat faux pour la plateforme 3
self._sfconf3 = bool(int(pListState[2]))
if(self._sfconf3):
self._pwm.setPWM(0, 0,CONST_TRUE_PL3)
self._Plateforme3 = False
else:
self._pwm.setPWM(0, 0,CONST_FALSE_PL3)
self._Plateforme3=False
time.sleep(1)
# Mise en place de l'etat faux pour la plateforme 4
self._sfconf4 = bool(int(pListState[3]))
if(self._sfconf4):
self._pwm.setPWM(6, 0,CONST_TRUE_PL4)
self._Plateforme4 = False
else:
self._pwm.setPWM(6, 0,CONST_FALSE_PL4)
self._Plateforme4=False
time.sleep(1)
# Mise en place de l'etat faux pour la plateforme 5
self._sfconf5 = bool(int(pListState[4]))
if(self._sfconf5):
self._pwm.setPWM(4, 0, CONST_TRUE_PL5)
self._Plateforme5 = False
else:
self._pwm.setPWM(4, 0, CONST_FALSE_PL5)
self._Plateforme5=False
time.sleep(1)
"""
Commentee pour cause d usure materielle
# Mise en place de l'etat faux pour la plateforme 6
self._sfconf6 = bool(int(pListState[5]))
if(self._sfconf6):
self._pwm.setPWM(1, 0, CONST_TRUE_PL6a)
self._pwm.setPWM(5, 0, CONST_TRUE_PL6b)
self._Plateforme6 = False
else:
self._pwm.setPWM(1, 0, CONST_FALSE_PL6a)
self._pwm.setPWM(5, 0, CONST_FALSE_PL6b)
self._Plateforme6=False
time.sleep(1)
"""
def ChangerEtatPalteforme(self, pNumPlateforme, pIsOk):
"""
Methode en charge de changer letat des palteformes
:param pNumPlateforme: Numero de la plateforme a changer
:ptype pNumPlateforme: int
:param pIsOk: Etat de la plateforme
:ptype pIsOk: bool
"""
if pNumPlateforme > 0 and pNumPlateforme < 7:
if pNumPlateforme == 1:
if pIsOk == self._sfconf1 and self._Plateforme1 != self._sfconf1 :
self._Plateforme1 = self._sfconf1
self._pwm.setPWM(3, 0,CONTS_FALSE_PL1)
elif pIsOk != self._sfconf1 and self._Plateforme1 == self._sfconf1 :
self._Plateforme1 = not self._sfconf1
self._pwm.setPWM(3, 0,CONST_TRUE_PL1)
if pNumPlateforme == 2:
if pIsOk == self._sfconf2 and self._Plateforme2 != self._sfconf2:
self._Plateforme2 = self._sfconf2
self._pwm.setPWM(2, 0,CONST_FALSE_PL2)
elif pIsOk != self._sfconf2 and self._Plateforme2 == self._sfconf2:
self._Plateforme2 = not self._sfconf2
self._pwm.setPWM(2, 0,CONST_TRUE_PL2)
if pNumPlateforme == 3:
if pIsOk == self._sfconf3 and self._Plateforme3 != self._sfconf3:
self._Plateforme3 = self._sfconf3
self._pwm.setPWM(0, 0,CONST_FALSE_PL3)
elif pIsOk != self._sfconf3 and self._Plateforme3 == self._sfconf3:
self._Plateforme3 = not self._sfconf3
self._pwm.setPWM(0, 0,CONST_TRUE_PL3)
if pNumPlateforme == 4:
if pIsOk == self._sfconf4 and self._Plateforme4 != self._sfconf4:
self._Plateforme4 = self._sfconf4
self._pwm.setPWM(6, 0,CONST_FALSE_PL4)
elif pIsOk != self._sfconf4 and self._Plateforme4 == self._sfconf4:
self._Plateforme4 = not self._sfconf4
self._pwm.setPWM(6, 0,CONST_TRUE_PL4)
if pNumPlateforme == 5:
if pIsOk == self._sfconf5 and self._Plateforme5 != self._sfconf5:
self._Plateforme5 = self._sfconf5
self._pwm.setPWM(4, 0, CONST_FALSE_PL5)
elif pIsOk != self._sfconf5 and self._Plateforme5 == self._sfconf5:
self._Plateforme5 = not self._sfconf5
self._pwm.setPWM(4, 0, CONST_TRUE_PL5)
"""
Commente pour cause d usure materielle
if pNumPlateforme == 6:
if pIsOk == self._sfconf6 and self._Plateforme6 != self._sfconf6:
self._Plateforme6 = self._sfconf6
self._pwm.setPWM(1, 0, CONST_FALSE_PL6a)
self._pwm.setPWM(5, 0, CONST_FALSE_PL6b)
elif pIsOk != self._sfconf6 and self._Plateforme6 == self._sfconf6:
self._Plateforme6 = not self._sfconf6
self._pwm.setPWM(1, 0, CONST_TRUE_PL6a)
self._pwm.setPWM(5, 0, CONST_TRUE_PL6b)
"""
else:
print("ERR : Numero de plateforme incorrect ")
time.sleep(1)
| Lancey139/GamificationDevOps | Plateforme/Servo_Controller.py | Servo_Controller.py | py | 5,382 | python | en | code | 0 | github-code | 36 |
33532112483 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A script to test if the associations.csv are good.
Typically you would run this file from a command line like this:
ipython3.exe -i -- /deploy/cbmcfs3_runner/scripts/check_associations.py
"""
# Built-in modules #
# Third party modules #
import pandas
from tqdm import tqdm
# First party modules #
from autopaths.auto_paths import AutoPaths
from plumbing.cache import property_cached
from plumbing.databases.access_database import AccessDatabase
# Internal modules #
from cbmcfs3_runner.core.continent import continent
# Constants #
###############################################################################
class AssociationsChecker(object):
keys = ['MapAdminBoundary', 'MapEcoBoundary', 'MapSpecies',
'MapDisturbanceType', 'MapNonForestType']
all_paths = """
/orig/calibration.mdb
/orig/aidb_eu.mdb
/orig/associations.csv
"""
def __init__(self, country):
# Default attributes #
self.country = country
# Automatically access paths based on a string of many subpaths #
self.paths = AutoPaths(self.country.data_dir, self.all_paths)
@property_cached
def aidb(self):
"""Shortcut to the AIDB."""
database = AccessDatabase(self.paths.aidb_eu_mdb)
database.convert_col_names_to_snake = True
return database
@property_cached
def calib(self):
"""Shortcut to the Calibration DB."""
database = AccessDatabase(self.paths.calibration_mdb)
database.convert_col_names_to_snake = True
return database
@property_cached
def df(self):
"""Load the CSV that is 'associations.csv'."""
self.paths.associations.must_exist()
return pandas.read_csv(str(self.paths.associations))
def key_to_rows(self, mapping_name):
"""
Here is an example call:
>>> self.key_to_rows('MapDisturbanceType')
{'10% commercial thinning': '10% Commercial thinning',
'Deforestation': 'Deforestation',
'Fire': 'Wild Fire',
'Generic 15%': 'generic 15% mortality',
'Generic 20%': 'generic 20% mortality',
'Generic 30%': 'generic 30% mortality',
'Spruce Beetle 2% mortality (Ice sleet)': 'Spruce Beetle 2% mortality'}
"""
query = "A == '%s'" % mapping_name
mapping = self.df.query(query).set_index('B')['C'].to_dict()
return mapping
def list_missing(self):
"""
A method to predict what errors the Standard Import Tool will throw
in advance, by checking the contents of the AIDB.
"""
# Print function #
def print_messages(default, names, key):
template = "%s - %s - '%s' missing from archive index database."
for name in names:
if name not in default:
print(template % (key, self.parent.parent.country_iso2, name))
# Admin boundaries #
default = set(self.aidb['tblAdminBoundaryDefault']['AdminBoundaryName'])
names = self.key_to_rows(self.keys[0]).values()
print_messages(default, names, self.keys[0])
# Eco boundaries #
default = set(self.aidb['tblEcoBoundaryDefault']['EcoBoundaryName'])
names = self.key_to_rows(self.keys[1]).values()
print_messages(default, names, self.keys[1])
# Species #
default = set(self.aidb['tblSpeciesTypeDefault']['SpeciesTypeName'])
names = self.key_to_rows(self.keys[2]).values()
print_messages(default, names, self.keys[2])
# Disturbances #
default = set(self.aidb['tblDisturbanceTypeDefault']['dist_type_name'])
names = self.key_to_rows(self.keys[3]).values()
print_messages(default, names, self.keys[3])
# Disturbances also have to match with disturbance_types.csv #
types = set(self.country.parent.csv_to_xls.read_csv('disturbance_types')['dist_desc_input'])
names = set(self.key_to_rows(self.keys[3]).keys())
unmatched = types ^ names
if unmatched:
print('disturbance_types.csv - %s - %s ' % (self.parent.parent.country_iso2, unmatched))
# Non-forest #
default = set(self.aidb['tblAfforestationPreTypeDefault']['Name'])
names = self.key_to_rows(self.keys[4]).values()
print_messages(default, names, self.keys[4])
###############################################################################
if __name__ == '__main__':
checkers = [AssociationsChecker(c) for c in continent]
for checker in tqdm(checkers): checker()
| xapple/cbmcfs3_runner | scripts/associations/check_associations.py | check_associations.py | py | 4,628 | python | en | code | 2 | github-code | 36 |
20240238686 | class Solution:
def numDecodings(self, s: str) -> int:
# list: s[i]
# メモするべきもの: その単語の長さまでの組み合わせの数
# 考慮するべきもの: 0は単体で使用できない(10, 20として使用するしかない)
# arr = list(s)
# if arr[0] == "0":
# return 0
# # そこまでに格納できる組み合わせのtotal
# dp = [0] * (len(arr))
# # init
# dp[0] = 1
# # ! これだとだめ
# for w in range(1, len(arr)):
# # ? 含めていい数字は何か -> 1~26
# # -> つまり、以下の条件なら含める
# # 1. i: 1~9
# # 2. i-1: 1or2 and i: 0~6
# if arr[w - 1] == "1" or arr[w - 1] == "2":
# dp[w] = dp[w - 1] + 2
# else:
# dp[w] = dp[w - 1] + 1
# return dp[-1]
# @see https://www.tutorialspoint.com/decode-ways-in-python
dp = [0] * len(s)
# init
if s[0] != "0":
dp[0] = 1
for w in range(1, len(s)):
x = int(s[w])
# 手前の数と合わせて2けた
y = int(s[w - 1 : w + 1])
if x != 0:
dp[w] += dp[w - 1]
if y >= 10 and y <= 26:
# dpのいつものこれまでdのやつをを足し合わせるやつ
if w - 2 >= 0:
dp[w] += dp[w - 2]
else:
# w = 1の場合のみ
dp[w] += 1
return dp[-1]
| sugitata/leetCode | dp/decode_ways.py | decode_ways.py | py | 1,605 | python | ja | code | 0 | github-code | 36 |
39804183733 | import os
from celery import Celery
# Set the default Django settings module for the 'celery' program.
# similar to the setup in asgi.py
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'prolube76site.settings')
app = Celery('prolube76site')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
# We also add the Django settings module as a configuration source for Celery. This means that you don’t have to use multiple configuration files, and instead configure Celery directly from the Django settings;
# but you can also separate them if wanted.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django apps.
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print(f'Request: {self.request!r}')
| zjgcainiao/new_place_at_76 | prolube76site/celery.py | celery.py | py | 952 | python | en | code | 0 | github-code | 36 |
74876500585 | t=int(input())
while(t):
t-=1
n,m=list(map(int,input().split()))
a=input().split()
for i in a:
i=list(i)
#print(a)
count=0
for i in range(1,n):
if(len(set(a[i])&(set(a[i-1])))==0):
count+=1
if(count<=m):
print("Welcome to a world without rules")
else:
print("Very poor choice of words") | anirudhkannanvp/CODECHEF | Shaastra Online Programming Contest 2018/Let us put a smile on that face-- OPC1701.py | Let us put a smile on that face-- OPC1701.py | py | 382 | python | en | code | 0 | github-code | 36 |
23670018346 | guess = input('Digite numeros naturais separados por virgula: ')
formated = guess.split(",")
add = 0
for number in formated:
if not number.isdigit():
print(f"Erro ao somar valores, {number} é um valor inválido”")
else:
add += int(number)
print(f"A soma dos valores válidos é: {add}")
| Andreyrvs/trybe-exercicios | T20A-Ciencia-da-Computacao/sessao-01-Introducao-a-Python/dia-02-Entrada-e-Saida-de-Dados/para-fixar/exercicio-02.py | exercicio-02.py | py | 318 | python | pt | code | 0 | github-code | 36 |
71788582503 | # TAGS: input(), end=' '
# () <-- parenthesis
age = input("How old are you? ") # you can put what you wanna ask inside ()
height = input("How tall are you? ")
weight = input("How much do you weigh? ")
print(f"So you're {age} old, {height} tall and {weight} heavy.")
#print("How old are you? ", input())
'''
this is not working because input() is getting excuted first then
print function
''' | jakszewa/Python-Notes | lpthw/ex12.py | ex12.py | py | 424 | python | en | code | 1 | github-code | 36 |
19348729652 | from app import app
from flask import request, jsonify, make_response
from api_exception import ApiException
from data.internal_configurations.internal_configurations import InternalConfigurations
@app.errorhandler(ApiException)
def handle_invalid_service(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/api/internal-configurations', methods=['GET', 'POST', 'PUT'])
def internal_configurations():
query_params = request.args
if request.method == "GET":
internal_configs = InternalConfigurations()
if query_params.get("feature"):
return jsonify(internal_configs.find_by("feature", query_params.get("feature"))), 200
else:
return jsonify(internal_configs.all), 200
elif request.method == "POST":
internal_configs = InternalConfigurations(params=request.get_json())
if internal_configs.save:
return jsonify({"message": "Internal Configuration created."}), 200
else:
return jsonify({"message": "Internal Configuration not created."}), 400
elif request.method == "PUT":
if not query_params.get("feature"):
return jsonify({"missing query `feature`."}), 400
internal_configs = InternalConfigurations(
feature=query_params.get("feature"))
if internal_configs.exists:
try:
if internal_configs.update(request.get_json()):
return jsonify({"message": "Succssefuly upated."}), 200
else:
return jsonify({"message": "Something went wrong while upating."}), 200
except Exception as e:
raise ApiException(e.message, 500)
else:
return jsonify({"message": "`{}`feature not found.".format(query_params.get("feature"))}), 404
| mbast100/st-joseph-backend-services | routes/internal_configurations.py | internal_configurations.py | py | 1,885 | python | en | code | 1 | github-code | 36 |
26531156238 | #!/usr/bin/env python
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class DebugNode(Node):
def __init__(self):
super().__init__("debug_node")
self.robot_mode_subs = self.create_subscription(String, "/robot_mode", self.callback_robot_mode_subs, 1)
self.go_to_goal_state_subs = self.create_subscription(String, "/go_to_goal_state", self.callback_go_to_goal_subs, 1)
self.wall_follow_state_subs = self.create_subscription(String, "/wall_follow_state", self.callback_wall_follow_subs, 1)
def callback_robot_mode_subs(self, msg):
print("--------------------")
print(f'robot_mode: {msg.data}')
def callback_go_to_goal_subs(self, msg):
print("--------------------")
print(f'go_to_goal_state : {msg.data}')
def callback_wall_follow_subs(self, msg):
print("--------------------")
print(f'wall_follow_state : {msg.data}')
def main():
rclpy.init() #init routine needed for ROS2.
debug_node = DebugNode()
rclpy.spin(debug_node)
#Clean up and shutdown.
debug_node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
| gautamr0312/Obstacle-Avoidance-and-Waypoint-Navigation | Obstacle Avoidance and Waypoint Navigation/hr13_navigate_to_goal/hr13_navigate_to_goal/debug_node.py | debug_node.py | py | 1,205 | python | en | code | 0 | github-code | 36 |
16721355609 | import torch
import torch.nn.functional as F
from torch.distributions import Normal
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
from torch.nn.utils import clip_grad_norm_
from PPO_Continuous.version2.Network import Actor, Critic
class PPO(object):
def __init__(self,
state_dim,
action_dim,
lr_a=0.001,
lr_c=0.001,
reward_decay=0.99,
memory_size=1000,
batch_size=32,
update_times=10,
clip_param=0.2,
max_grad_norm=0.5,
device='cpu'):
self.state_dim = state_dim
self.action_dim = action_dim
self.lr_a = lr_a
self.lr_c = lr_c
self.gamma = reward_decay
self.capacity = memory_size
self.batch_size = batch_size
self.update_times = update_times
self.clip_param = clip_param
self.max_grad_norm = max_grad_norm
self.device = device
self.ReplayBuffer = []
self.counter = 0
self.actor = Actor(self.state_dim, self.action_dim)
self.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=self.lr_a)
self.critic = Critic(self.state_dim)
self.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=self.lr_c)
self.counter = 0
self.training_step = 0
def choose_action(self, state):
state = torch.from_numpy(state).float().unsqueeze(0)
mu, sigma = self.actor(state)
dist = Normal(mu, sigma)
action = dist.sample()
action_log_prob = dist.log_prob(action)
action = action.clamp(-2, 2)
return action.item(), action_log_prob.item()
def store_transition(self, transition):
self.ReplayBuffer.append(transition)
self.counter += 1
return self.counter % self.capacity == 0
def update(self):
old_state = torch.Tensor([t.state for t in self.ReplayBuffer]).float()
old_action = torch.Tensor([t.action for t in self.ReplayBuffer]).float().view(-1, 1)
reward = torch.Tensor([t.reward for t in self.ReplayBuffer]).float().view(-1, 1)
next_state = torch.Tensor([t.next_state for t in self.ReplayBuffer]).float()
old_action_log_prob = torch.Tensor([t.a_log_prob for t in self.ReplayBuffer]).float().view(-1, 1)
reward = (reward - reward.mean()) / (reward.std() + 1e-10)
with torch.no_grad():
gt = reward + self.gamma * self.critic(next_state)
for i in range(self.update_times):
for index in BatchSampler(SubsetRandomSampler(range(len(self.ReplayBuffer))), self.batch_size, False):
gt_value = gt[index].view(-1, 1)
value = self.critic(old_state[index])
advantage = (gt_value - value).detach()
mu, sigma = self.actor(old_state[index])
m = Normal(torch.squeeze(mu), torch.squeeze(sigma))
action_log_prob = m.log_prob(torch.squeeze(old_action[index])).view(-1, 1)
ratio = torch.exp(action_log_prob - old_action_log_prob[index])
surr1 = ratio * advantage
surr2 = torch.clamp(ratio, 1 - self.clip_param, 1 + self.clip_param) * advantage
action_loss = -torch.min(surr1, surr2).mean()
self.actor_optimizer.zero_grad()
action_loss.backward()
clip_grad_norm_(self.actor.parameters(), self.max_grad_norm)
self.actor_optimizer.step()
# update critic network
value_loss = F.mse_loss(gt_value, value)
self.critic_optimizer.zero_grad()
value_loss.backward()
clip_grad_norm_(self.critic.parameters(), self.max_grad_norm)
self.critic_optimizer.step()
self.training_step += 1
del self.ReplayBuffer[:]
| zhihangmuzi/deep-reinforcement-learning-with-pytorch | PPO_Continuous/version2/Agent.py | Agent.py | py | 3,981 | python | en | code | 0 | github-code | 36 |
70597091303 | from mpio import LED
import time
from mpio import GPIO
import mpio
#Press the user push button for LED's to trigger
def main():
red = LED("red")
green = LED("green")
blue = LED("blue")
pin_out=GPIO(84,GPIO.OUT)
pin_out.set(False)
while(True):
print("Please Press The User Push Button On The Board")
device_id=("event0")
button=mpio.Input(device_id)
(tv_sec, tv_usec, evtype, code, value) = button.read()
if(value==1):
print("Button Pressed")
pin_out.set(True)
#time.sleep(10)
for i in range(2):
red.brightness = 51
green.brightness = 0
blue.brightness = 0
time.sleep(1)
red.brightness = 253
green.brightness = 253
blue.brightness = 0
time.sleep(1)
red.brightness = 0
green.brightness = 0
blue.brightness = 50
time.sleep(1)
red.brightness = 0
green.brightness = 0
blue.brightness = 0
time.sleep(1)
print("Action Completed")
pin_out.set(False)
pin_out.close() # if program exits pin is closed
if __name__ == "__main__":
main() | epsilon1234/SAMA-5D-I-O-Triggering | output_trigger.py | output_trigger.py | py | 1,375 | python | en | code | 0 | github-code | 36 |
37248697117 | # Importing libraries and modules
from tkinter import *
from PIL import ImageTk, Image
import time
from tkinter import messagebox
from tkinter.filedialog import askopenfilename
# Start of GUI
root = Tk()
root.title("A-Star Grid World")
# Grid Initialization
# Ask the user if he wants to load a pre-deined world map
result = messagebox.showinfo("Choose Location","Give path of A-Star Grid World Map")
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
# filename = "/Users/abhianshusingla/Documents/IS_Project/A-Star/map1.txt"
# Read a grid world from pre-defined values
read_file = open(filename, "r")
read_str = str(read_file.read())
read_str = read_str.split("\n")
# Initialize start point
token = read_str[0].split(" ")
init = []
init.append(int(token[0]))
init.append(int(token[1]))
# Initialize goal point
token = read_str[1].split(" ")
goal = []
goal.append(int(token[0]))
goal.append(int(token[1]))
# Create grid
grid = []
for i in range(2, len(read_str)):
token = read_str[i].split(" ")
if(len(token) != 1):
grid.append(list(map(int, token)))
# Size of Grid
rows = len(grid)
columns = len(grid[0])
# GUI Parameters
sleep_time = 9.9
bg_color = "PINK"
fg_color1 = "BLACK"
fg_color2 = "PURPLE"
fontStyle = "Chalkboard"
cell_size = 50
offset = 10
grids = {}
# Frames
main_frame = Frame(root, bg = bg_color)
main_frame.pack()
left_frame = Frame(main_frame, bg = bg_color)
left_frame.pack(side=LEFT)
right_frame = Frame(main_frame, bg = bg_color)
right_frame.pack(side=TOP)
# Left Frame Functionality
# Creating a 2D Grid
def createGrid():
for i in range(0,rows + 1):
x_start = offset
y = i * cell_size + offset
x_end = columns * cell_size + offset
gridCanvas.create_line([(x_start,y),(x_end,y)])
for i in range(0,columns + 1):
y_start = offset
x = i * cell_size + offset
y_end = rows * cell_size + offset
gridCanvas.create_line([(x,y_start),(x,y_end)])
for i in range(0, rows):
temp = []
for j in range(0, columns):
x = i * cell_size + offset
y = j * cell_size + offset
grids[(i,j)] = (x,y)
temp.append((x,y))
return grids
# Load all images
def loadImages():
img_robot = Image.open("/Users/abhianshusingla/Documents/DynamicPathPlanning/images/robot1.png")
img_robot = img_robot.resize((cell_size, cell_size))
gridCanvas.img_robot = (ImageTk.PhotoImage(img_robot))
img_target = Image.open("/Users/abhianshusingla/Documents/DynamicPathPlanning/images/target.png")
img_target = img_target.resize((cell_size, cell_size))
gridCanvas.img_target = (ImageTk.PhotoImage(img_target))
img_start = Image.open("/Users/abhianshusingla/Documents/DynamicPathPlanning/images/start.png")
img_start = img_start.resize((cell_size, cell_size))
gridCanvas.img_start = (ImageTk.PhotoImage(img_start))
img_wall2 = Image.open("/Users/abhianshusingla/Documents/DynamicPathPlanning/images/wall2.png")
img_wall2 = img_wall2.resize((cell_size, cell_size))
gridCanvas.img_wall2 = (ImageTk.PhotoImage(img_wall2))
img_wall1 = Image.open("/Users/abhianshusingla/Documents/DynamicPathPlanning/images/wall1.png")
img_wall1 = img_wall1.resize((cell_size, cell_size))
gridCanvas.img_wall1 = (ImageTk.PhotoImage(img_wall1))
# Draws robot at cell coordinates x and y
def drawRobot(x,y):
x1 = grids[(x,y)][0]
y1 = grids[(x,y)][1]
gridCanvas.create_image(y1, x1, image=gridCanvas.img_robot, anchor='nw')
# Draws house at cell coordinates x and y
def drawStart(x,y):
x1 = grids[(x,y)][0]
y1 = grids[(x,y)][1]
gridCanvas.create_image(y1, x1, image=gridCanvas.img_robot, anchor='nw')
# Draws wall at cell coordinates x and y
def drawWall(x,y):
x1 = grids[(x,y)][0]
y1 = grids[(x,y)][1]
gridCanvas.create_image(y1, x1, image=gridCanvas.img_wall1, anchor='nw')
# Draws wall at cell coordinates x and y
def drawWall2(x,y):
x1 = grids[(x,y)][0]
y1 = grids[(x,y)][1]
gridCanvas.create_image(y1, x1, image=gridCanvas.img_wall2, anchor='nw')
# Draws flag at cell coordinates x and y
def drawTarget(x,y):
x1 = grids[(x,y)][0]
y1 = grids[(x,y)][1]
gridCanvas.create_image(y1, x1, image=gridCanvas.img_target, anchor='nw')
# Writes text at cell coordinates x and y
def drawText(x,y,f,g,h,c):
x1 = grids[(x,y)][0]
y1 = grids[(x,y)][1]
costs = str(str(f) + "\n" + str(g) + "\n" + str(h))
if(not (goal[0] == x and goal[1] == y)):
gridCanvas.create_rectangle(y1, x1, y1 + cell_size, x1 + cell_size, fill=c)
gridCanvas.create_text(y1, x1, text = costs, anchor='nw', state = 'disabled')
# Reinitialization of code
def restart():
for i in range(rows):
for j in range(columns):
x1 = grids[(i,j)][0]
y1 = grids[(i,j)][1]
if(grid[i][j] != 1):
gridCanvas.create_rectangle(y1, x1, y1 + cell_size, x1 + cell_size, fill = "white")
if(i == init[0] and j == init[1]):
drawStart(i,j)
if(i == goal[0] and j == goal[1]):
drawTarget(i,j)
# if(grid[i][j] == 1):
# drawWall2(i,j)
# Creation of Grid Canvas
gridCanvas = Canvas(left_frame, height = rows * cell_size + 2 * offset, width = columns * cell_size + 2 * offset)
gridCanvas.pack(fill=BOTH, expand = True)
# Creation of Grid
grids = createGrid()
# Loading all the images
loadImages()
# Draw Start, Obstacle and Goal Images
drawStart(init[0],init[1])
drawTarget(goal[0],goal[1])
for i in range(rows):
for j in range(columns):
if(grid[i][j] == 1):
drawWall2(i,j)
# Right Frame Functionality
which_heuristic = True
isplay = False
cost = 1
D = 1
# Selection of Heuristic
def selectHeuristic():
global which_heuristic
which_heuristic = (env.get() == 1)
return which_heuristic
# check Play Pause Button
def play():
global isplay
if(isplay):
isplay = False
else:
isplay = True
return isplay
# Get sleep time for speed purpose
def get_sleep():
global sleep_time
sleep_time = speed_bar.get()
return sleep_time
# G- cost
def g_cost():
global cost
cost = float(cost_entry.get())
return cost
# D cost
def get_D():
global D
D = float(D_entry.get())
return D
# Controls
control_label = Label(right_frame, text="Controls",font=("Chalkboard", 20), fg = "RED", bg = bg_color)
control_label.pack(anchor = N)
# Heuristics
heuristic_label = Label(right_frame, text="Heuristsics", font=(fontStyle, 16), fg = fg_color1, bg = bg_color)
heuristic_label.pack(anchor = W)
env = IntVar()
env.set(1)
Radiobutton(right_frame, text="Manhattan", variable=env, value=1, command = selectHeuristic, font=(fontStyle, 16), fg = fg_color2, bg = bg_color).pack(anchor=W)
Radiobutton(right_frame, text="Euclidean", variable=env, value=2, command = selectHeuristic, font=(fontStyle, 16), fg = fg_color2, bg = bg_color).pack(anchor=W)
# Play/Pause
play_button = Button(right_frame, command = play, bg = bg_color, fg = fg_color2)
photo_button = ImageTk.PhotoImage(Image.open("/Users/abhianshusingla/Documents/DynamicPathPlanning/images/play1.png").resize((30, 30)))
play_button.config(image=photo_button,width="30",height="30")
play_button.pack()
# Speed Bar
speed_bar = Scale(right_frame, from_= 0, to= 10,length = 200, orient=HORIZONTAL, font=(fontStyle, 16), fg = fg_color2, bg = bg_color)
speed_bar.set(7)
speed_bar.pack(anchor=W)
speed_label = Label(right_frame, text="Speed", font=(fontStyle, 16), fg = fg_color2, bg = bg_color)
speed_label.pack()
# g-Cost
cost_frame = Frame(right_frame)
cost_frame.pack(anchor = W)
cost_label = Label(cost_frame, text = "G-Cost", font=(fontStyle, 16), fg = fg_color2, bg = bg_color)
cost_label.pack(side = LEFT)
cost_entry = Entry(cost_frame, width = 3, bg = bg_color, fg = fg_color2)
cost_entry.pack()
cost_entry.insert(0,1)
# D-value
D_frame = Frame(right_frame)
D_frame.pack(anchor = W)
D_label = Label(D_frame, text = "D-value", font=(fontStyle, 16), fg = fg_color2, bg = bg_color)
D_label.pack(side = LEFT)
D_entry = Entry(D_frame, width = 3, bg = bg_color, fg = fg_color2)
D_entry.pack(side = RIGHT)
D_entry.insert(3,1)
# Main Loop
def start():
root.mainloop()
time.sleep(0.1)
| abhianshi/DynamicPathPlanning | src/AStarGUI.py | AStarGUI.py | py | 8,336 | python | en | code | 1 | github-code | 36 |
8491596435 |
class Student:
def __init__(self, name, major, gpa, is_on_probation):
self.name = name
self.major = major
self.gpa = gpa
self.is_on_probation = is_on_probation
'''
We created this student class here in this file.
If we are in another file/program, we an import this class, and then create a student-object.
from ClassesAndObject import Student
''' | ncterry/Python | CLASSES MAIN/class_Student.py | class_Student.py | py | 397 | python | en | code | 0 | github-code | 36 |
72640625383 | """
Project: SSITH CyberPhysical Demonstrator
health.py
Author: Ethan Lew <elew@galois.com>
Date: 08/23/2021
Python 3.8.3
O/S: Windows 10
Component Health Monitoring Objects and Components
"""
import threading
import abc
import collections
import re
import requests
import typing
import struct
import socket
import time
import fabric
import can
import subprocess
from cyberphyslib.canlib import TcpBus, UdpBus
import cyberphyslib.canlib.canspecs as canspecs
import cyberphyslib.canlib.componentids as cids
import cyberphyslib.demonstrator.component as cycomp
import cyberphyslib.demonstrator.can as cycan
from cyberphyslib.demonstrator.logger import health_logger
def ip2int(ip):
"""Convert an IP string to an int"""
packedIP = socket.inet_aton(ip)
return struct.unpack("!L", packedIP)[0]
class HealthMonitor(abc.ABC):
"""Health Monitor Interface
Define test interface and health properties
"""
@abc.abstractmethod
def run_health_test(self) -> bool:
"""test to determine if the system monitored is healthy"""
return True
@property
def is_healthy(self) -> bool:
"""health property"""
return self.run_health_test()
@property
def is_unhealthy(self) -> bool:
return not self.is_healthy
class SshMonitor(HealthMonitor):
"""
Health monitoring involving Ssh Connections
"""
def __init__(self, addr: str, user=None, password=None, **kwargs):
# user and password need to be transformed into proper level of fabric
# kwarg hierarchy
if user:
kwargs["user"] = user
if password:
if "connect_kwargs" in kwargs:
kwargs["connect_kwargs"] = {**{"password": password}, **kwargs}
else:
kwargs["connect_kwargs"] = {"password": password}
self.connection_kwargs = kwargs
self.addr: str = addr
def command(self, command: str):
# NOTE: should I persist the connect rather than make a new one each time?
result = fabric.Connection(self.addr, **self.connection_kwargs).run(command, hide=True)
return result
class PingMonitor(HealthMonitor):
"""
If this monitor receives can succesfully ping the component,
it considers it healthy
"""
def __init__(self, addr: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self.addr = addr
def run_health_test(self) -> bool:
retCode = subprocess.call(["ping","-w","1",self.addr],
stdout=subprocess.DEVNULL)
if retCode == 0:
return True
else:
return False
class HttpMonitor(HealthMonitor):
"""
Health monitoring involving http connections
"""
request_timeout = 1.0
def __init__(self, addr: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self.addr = addr
@abc.abstractmethod
def check_response(self, ret: requests.Response) -> bool:
raise NotImplementedError
def run_health_test(self) -> bool:
try:
ret = requests.get(self.addr, timeout = self.request_timeout)
# check for OK status code
return self.check_response(ret)
except Exception as exc:
health_logger.debug(f"<{self.__class__.__name__}> Exception {exc} has occurred")
return False
class ServiceMonitor(SshMonitor):
"""
Health monitoring of a service on a remote machine (via Ssh)
"""
def __init__(self, service_name: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self.service_name = service_name
def run_health_test(self) -> bool:
try:
ret = self.command(rf"systemctl status {self.service_name}")
# regex match for active and running service
return re.search(r"(Active: active \(running\))", ret.stdout) is not None
except Exception as exc:
health_logger.debug(f"<{self.__class__.__name__}> Exception {exc} has occurred")
return False
class OtaMonitor(HttpMonitor):
"""
Monitor Infotainment Ota Process (via HTTP request)
"""
def check_response(self, ret: requests.Response) -> bool:
return ret.status_code == 200
HeartbeatResponseType = typing.Tuple[float, float]
class BusHeartbeatMonitor(HealthMonitor):
"""
Heartbeat monitor is responsible for
1. sending out the heartbeat requests (REQ)
2. listening for heartbeat acknowledgements (ACK)
3. determining system health from ACK patterns
"""
# length of response buffers (time horizon of ACKs)
maxlen = 5
wait_period = 10.0
@staticmethod
def form_heartbeat_req_msg(req_number: int):
"""form REQ can packet"""
msg = can.Message(arbitration_id=canspecs.CAN_ID_HEARTBEAT_REQ,
data=struct.pack(canspecs.CAN_FORMAT_HEARTBEAT_REQ, req_number))
return msg
def __init__(self, client_ids: typing.Sequence[int]):
self.curr_req_number = 0
self.response_buffer: typing.Dict[int, typing.Deque[float]] = {
c: collections.deque(maxlen=self.maxlen) for c in client_ids
}
self.start_time = time.time()
def submit_response(self, client_id: int, response: HeartbeatResponseType):
"""submit a response from client_id to the ACK buffer"""
if client_id not in self.response_buffer:
# TODO: FIXME: add fault location
idmap = {v: k for k, v in cids.__dict__.items() if isinstance(v, int)}
cname = idmap.get(client_id, "<UNKNOWN>")
print(f"WARNING! Received unanticipated response {client_id} ({cname})")
else:
if response is not None:
self.response_buffer[client_id].append(time.time())
def get_req_msg(self) -> can.Message:
"""generate REQ msg"""
m = self.form_heartbeat_req_msg(self.curr_req_number)
self.curr_req_number += 1
return m
def run_health_test(self) -> bool:
"""implement the heartbeat health:
for a given history of component with component id cid, if the maximum value is
within MAXLEN of the current REQ number, the component is considered healthy
"""
return all(self.run_health_tests())
def run_health_tests(self) -> typing.Dict[typing.Hashable, bool]:
"""return health result for each component entered in the response buffer"""
outcome = {k: True for k in self.response_buffer.keys()}
for cid, buff in self.response_buffer.items():
if len(buff) > 0:
ltime = max(buff)
delta = time.time() - ltime
if delta > self.maxlen:
health_logger.debug(f"ERROR: Component with ID {cid} Has Failed Heartbeat Health Test!")
outcome[cid] = False
else:
if time.time() - self.start_time > self.wait_period:
health_logger.debug(f"ERROR: Component with ID {cid} Has Failed Heartbeat Health Test (No Submissions)!")
outcome[cid] = False
return outcome
class HeartbeatMonitor(threading.Thread):
FREQUENCY = 0.1
def __init__(self):
threading.Thread.__init__(self,daemon=True)
self.services = {
cids.CAN_DISPLAY_FRONTEND:
{
"user" : "pi",
"password": "WelcomeToGalois",
"address" : "10.88.88.5",
"service_name": "can-ui"
},
cids.HACKER_KIOSK_FRONTEND:
{
"user" : "galoisuser",
"password": "WelcomeToGalois",
"address" : "10.88.88.3",
"service_name": "hacker-ui"
},
cids.INFOTAINMENT_THIN_CLIENT:
{
"user" : "pi",
"password": "WelcomeToGalois",
"address" : "10.88.88.2",
"service_name": "infotainment"
}
}
self.https = {
cids.OTA_UPDATE_SERVER_1 : "http://10.88.88.11:5050",
cids.OTA_UPDATE_SERVER_2 : "http://10.88.88.21:5050",
cids.OTA_UPDATE_SERVER_3 : "http://10.88.88.31:5050"
}
self.pings = {
cids.DEBIAN_1 : "10.88.88.11",
cids.FREERTOS_1: "10.88.88.12",
cids.DEBIAN_2_LMCO : "10.88.88.21",
cids.FREERTOS_2_CHERI: "10.88.88.22",
cids.DEBIAN_3 : "10.88.88.31",
cids.FREERTOS_3: "10.88.88.32"
}
self.heartbeat_desc = {
# TCP components
cids.BESSPIN_TOOL_FREERTOS: cids.BESSPIN_TOOL_FREERTOS,
cids.BESSPIN_TOOL_DEBIAN: cids.BESSPIN_TOOL_DEBIAN,
cids.CAN_DISPLAY_BACKEND: cids.CAN_DISPLAY_BACKEND,
cids.HACKER_KIOSK_BACKEND: cids.HACKER_KIOSK_BACKEND,
cids.INFOTAINMENT_BACKEND: cids.INFOTAINMENT_BACKEND,
# UDP components
# NOTE: only active network components can respond
#cids.INFOTAINMENT_SERVER_1: ip2int('10.88.88.11'),
#cids.INFOTAINMENT_SERVER_2: ip2int('10.88.88.21'),
#cids.INFOTAINMENT_SERVER_3: ip2int('10.88.88.31'),
# FreeRTOS is temporaily handled via pings
#cids.FREERTOS_1: ip2int('12.88.88.10'),
#cids.FREERTOS_2_CHERI: ip2int('22.88.88.10'),
#cids.FREERTOS_3: ip2int('32.88.88.10')
}
self.component_monitor = BusHeartbeatMonitor(self.heartbeat_desc)
self.ping_monitors = {k: PingMonitor(addr) for k, addr in self.pings.items()}
self.ota_monitors = {k: OtaMonitor(addr) for k, addr in self.https.items()}
self.service_monitors = {k: ServiceMonitor(params["service_name"], params["address"],
user=params["user"],
password=params["password"]) for k, params in self.services.items()}
self._health_report = {}
def run(self):
while True:
ret = {}
health_logger.debug("Testing OTA")
for k, v in self.ota_monitors.items():
hs = v.is_healthy
ret[k] = hs
if not hs:
health_logger.debug(f"WARNING! {k} HTTP failed health check")
health_logger.debug("Testing Services")
for k, v in self.service_monitors.items():
hs = v.is_healthy
ret[k] = hs
if not hs:
health_logger.debug(f"WARNING! {k} Service failed health check")
health_logger.debug("Testing Ping")
for k, v in self.ping_monitors.items():
hs = v.is_healthy
ret[k] = hs
if not hs:
health_logger.debug(f"WARNING! {k} Ping failed health check")
health_logger.debug("Testing TCP")
health_report = self.component_monitor.run_health_tests()
kmap = {v: k for k, v in self.heartbeat_desc.items()}
ret.update({kmap[k]: v for k, v in health_report.items()})
if not all(health_report.values()):
health_logger.debug(f"Health Status: {health_report}")
health_logger.debug(f"ERROR! TCP Failed")
self._health_report = ret
@property
def health_report(self):
return self._health_report
| GaloisInc/BESSPIN-Tool-Suite | besspin/cyberPhys/cyberphyslib/cyberphyslib/demonstrator/healthmonitor.py | healthmonitor.py | py | 11,624 | python | en | code | 5 | github-code | 36 |
25969594435 | """
Given an array A of integers, return true if and only if it is a valid mountain array.
Recall that A is a mountain array if and only if:
A.length >= 3
There exists some i with 0 < i < A.length - 1 such that:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[B.length - 1]
Example 1:
Input: [2,1]
Output: false
Example 2:
Input: [3,5,5]
Output: false
Example 3:
Input: [0,3,2,1]
Output: true
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
"""
class Solution(object):
def validMountainArray(self, A):
"""
:type A: List[int]
:rtype: bool
"""
a_l = len(A)
if a_l >= 3:
i = 1
while i < a_l - 1 and A[i] > A[i - 1]:
i += 1
if i - 1 > 0 and i - 1 < a_l - 1:
while i < a_l and A[i] < A[i - 1]:
i += 1
if i == a_l:
return True
return False
| wqh872081365/leetcode | Python/941_Valid_Mountain_Array.py | 941_Valid_Mountain_Array.py | py | 939 | python | en | code | 0 | github-code | 36 |
12259799552 | from PySide2 import QtWidgets
import ui.devicesDialog_ui
import input.audio
class form(QtWidgets.QDialog, ui.devicesDialog_ui.Ui_Dialog):
def __init__(self):
super(form, self).__init__()
self.setupUi(self) #setup user interface
self.currentDevice = 0 #set default device
self.buttonBox.accepted.connect(self.btnOk_callback)
def show(self, audio: input.audio.audio):
self.lstDevices.clear()
for i in range (0, audio.getDeviceCount()):
devName = audio.getDeviceName(i)
if (devName != ""):
self.lstDevices.addItem(devName)
self.lstDevices.setCurrentRow(self.currentDevice)
super(form, self).show() #show dialog
self.activateWindow() #make sure window shows right away
def btnOk_callback(self):
self.currentDevice = self.lstDevices.currentRow()
def getCurrentDevice(self):
return self.currentDevice
| HamerKits/RoscoeQRSSViewer | devicesDialog.py | devicesDialog.py | py | 948 | python | en | code | 0 | github-code | 36 |
71578985703 | #!/usr/bin/env python
import vtk
def main():
pd_fn, scene_fn = get_program_parameters()
colors = vtk.vtkNamedColors()
polyData = ReadPolyData(pd_fn)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(polyData)
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetDiffuseColor(colors.GetColor3d("Crimson"))
actor.GetProperty().SetSpecular(.6)
actor.GetProperty().SetSpecularPower(30)
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
renderer.AddActor(actor)
renderer.SetBackground(colors.GetColor3d("Silver"))
# Interact to change camera.
renderWindow.Render()
renderWindowInteractor.Start()
# After the interaction is done, save the scene.
SaveSceneToFile(scene_fn, actor, renderer.GetActiveCamera())
renderWindow.Render()
renderWindowInteractor.Start()
# After interaction , restore the scene.
RestoreSceneFromFile(scene_fn, actor, renderer.GetActiveCamera())
renderWindow.Render()
renderWindowInteractor.Start()
def get_program_parameters():
import argparse
description = 'Saving a scene to a file.'
epilogue = '''
'''
parser = argparse.ArgumentParser(description=description, epilog=epilogue,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('data_file', help='A polydata file e.g. Armadillo.ply.')
parser.add_argument('scene_file', help='The file to save the scene to.')
args = parser.parse_args()
return args.data_file, args.scene_file
def ReadPolyData(file_name):
import os
path, extension = os.path.splitext(file_name)
extension = extension.lower()
if extension == ".ply":
reader = vtk.vtkPLYReader()
reader.SetFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
elif extension == ".vtp":
reader = vtk.vtkXMLpoly_dataReader()
reader.SetFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
elif extension == ".obj":
reader = vtk.vtkOBJReader()
reader.SetFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
elif extension == ".stl":
reader = vtk.vtkSTLReader()
reader.SetFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
elif extension == ".vtk":
reader = vtk.vtkpoly_dataReader()
reader.SetFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
elif extension == ".g":
reader = vtk.vtkBYUReader()
reader.SetGeometryFileName(file_name)
reader.Update()
poly_data = reader.GetOutput()
else:
# Return a None if the extension is unknown.
poly_data = None
return poly_data
def SaveSceneToFile(file_name, actor, camera):
# Actor
# Position, orientation, origin, scale, usrmatrix, usertransform
# Camera
# FocalPoint, Position, ViewUp, ViewAngle, ClippingRange
fp_format = '{0:.6f}'
res = dict()
res['Camera:FocalPoint'] = ', '.join(fp_format.format(n) for n in camera.GetFocalPoint())
res['Camera:Position'] = ', '.join(fp_format.format(n) for n in camera.GetPosition())
res['Camera:ViewUp'] = ', '.join(fp_format.format(n) for n in camera.GetViewUp())
res['Camera:ViewAngle'] = fp_format.format(camera.GetViewAngle())
res['Camera:ClippingRange'] = ', '.join(fp_format.format(n) for n in camera.GetClippingRange())
with open(file_name, 'w') as f:
for k, v in res.items():
f.write(k + ' ' + v + '\n')
def RestoreSceneFromFile(file_name, actor, camera):
import re
# Some regular expressions.
reCP = re.compile(r'^Camera:Position')
reCFP = re.compile(r'^Camera:FocalPoint')
reCVU = re.compile(r'^Camera:ViewUp')
reCVA = re.compile(r'^Camera:ViewAngle')
reCCR = re.compile(r'^Camera:ClippingRange')
keys = [reCP, reCFP, reCVU, reCVA, reCCR]
# float_number = re.compile(r'[^0-9.\-]*([0-9e.\-]*[^,])[^0-9.\-]*([0-9e.\-]*[^,])[^0-9.\-]*([0-9e.\-]*[^,])')
# float_scalar = re.compile(r'[^0-9.\-]*([0-9.\-e]*[^,])')
res = dict()
with open(file_name, 'r') as f:
for cnt, line in enumerate(f):
if not line.strip():
continue
line = line.strip().replace(',', '').split()
for i in keys:
m = re.match(i, line[0])
if m:
k = m.group(0)
if m:
# Convert the rest of the line to floats.
v = list(map(lambda x: float(x), line[1:]))
if len(v) == 1:
res[k] = v[0]
else:
res[k] = v
for k, v in res.items():
if re.match(reCP, k):
camera.SetPosition(v)
elif re.match(reCFP, k):
camera.SetFocalPoint(v)
elif re.match(reCVU, k):
camera.SetViewUp(v)
elif re.match(reCVA, k):
camera.SetViewAngle(v)
elif re.match(reCCR, k):
camera.SetClippingRange(v)
if __name__ == '__main__':
main()
| lorensen/VTKExamples | src/Python/Utilities/SaveSceneToFile.py | SaveSceneToFile.py | py | 5,409 | python | en | code | 319 | github-code | 36 |
24347527125 | # :參閱5-17頁
import os
from os import path
import platform
def pyTube_folder():
sys = platform.system()
home = path.expanduser('~')
if sys == 'Windows':
folder = path.join(home, 'Videos', 'PyTube')
elif sys == 'Darwin':
folder = path.join(home, 'Movies', 'PyTube')
if not os.path.isdir(folder): # 若'PyTube'資料夾不存在…
os.mkdir(folder) # 則新增資料夾
return folder
| theoyu13/python3 | python程式設計入門/F9796/ch05/ch5_2.py | ch5_2.py | py | 473 | python | en | code | 0 | github-code | 36 |
21848108182 | import numpy as np
from sklearn.externals.joblib import Parallel, delayed
from multiprocessing import cpu_count
def apply_parallel_joblib(func, data, *args, chunk=None, overlap=10,
n_jobs=None, **kwargs):
"""
Apply a function in parallel to overlapping chunks of an array
Parameters
----------
func : function
name of function. Its first argument needs to be ``data``
data : ndarray
data to be chunked
chunk : int
chunk size (default value 100)
overlap : int
size of overlap between consecutive chunks
n_jobs : int
number of jobs to be used by joblib for parallel processing
*args, **kwargs : other arguments to be passed to func
Examples
--------
>>> from skimage import data, filters
>>> coins = data.coins()
>>> res = apply_parallel_joblib(filters.gaussian, coins, 2)
"""
if chunk is None:
l = len(data)
try:
ncpu = cpu_count()
except NotImplementedError:
ncpu = 4
chunk = l // ncpu
if n_jobs is None:
n_jobs = -1
sh0 = data.shape[0]
nb_chunks = sh0 // chunk
end_chunk = sh0 % chunk
arg_list = [data[max(0, i*chunk - overlap):
min((i+1)*chunk + overlap, sh0)]
for i in range(0, nb_chunks)]
if end_chunk > 0:
arg_list.append(data[-end_chunk - overlap:])
res_list = Parallel(n_jobs=n_jobs, backend="threading")(delayed(func)
(sub_im, *args, **kwargs) for sub_im in arg_list)
output_dtype = res_list[0].dtype
out_data = np.empty(data.shape, dtype=output_dtype)
for i in range(1, nb_chunks):
out_data[i*chunk:(i+1)*chunk] = res_list[i][overlap:overlap+chunk]
out_data[:chunk] = res_list[0][:-overlap]
if end_chunk>0:
out_data[-end_chunk:] = res_list[-1][overlap:]
return out_data
| emmanuelle/skimage-sprint | chunk_joblib.py | chunk_joblib.py | py | 1,921 | python | en | code | 0 | github-code | 36 |
30523769752 | #设立一个哨兵
#为负数的哨兵
#虽然可行,但是不是最好的,因为不能累加负数了...
#改进的版本看Average4
def main():
sum = 0.0
count=0
x = eval(input("Enter a number (negative to quit)>> "))
while x>=0:
sum+=x
count += 1
x=eval(input("Enter a number (negative to quit)>> "))
print("\n The average of the numbers is",sum/count)
main()
| ZTYZZ/learnPython | Average3.py | Average3.py | py | 411 | python | en | code | 0 | github-code | 36 |
33377706423 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
eps = 1e-7
class SCELoss(nn.Module):
def __init__(self, num_classes=10, a=1, b=1):
super(SCELoss, self).__init__()
self.num_classes = num_classes
self.a = a
self.b = b
self.cross_entropy = nn.CrossEntropyLoss()
def forward(self, pred, labels):
ce = self.cross_entropy(pred, labels)
# RCE
pred = F.softmax(pred, dim=1)
pred = torch.clamp(pred, min=eps, max=1.0)
label_one_hot = F.one_hot(labels, self.num_classes).float().to(pred.device)
label_one_hot = torch.clamp(label_one_hot, min=1e-4, max=1.0)
rce = (-1 * torch.sum(pred * torch.log(label_one_hot), dim=1))
loss = self.a * ce + self.b * rce.mean()
return loss
class RCELoss(nn.Module):
def __init__(self, num_classes=10, scale=1.0):
super(RCELoss, self).__init__()
self.num_classes = num_classes
self.scale = scale
def forward(self, pred, labels):
pred = F.softmax(pred, dim=1)
pred = torch.clamp(pred, min=eps, max=1.0)
label_one_hot = F.one_hot(labels, self.num_classes).float().to(pred.device)
label_one_hot = torch.clamp(label_one_hot, min=1e-4, max=1.0)
loss = (-1 * torch.sum(pred * torch.log(label_one_hot), dim=1))
return self.scale * loss.mean()
class NRCELoss(nn.Module):
def __init__(self, num_classes, scale=1.0):
super(NRCELoss, self).__init__()
self.num_classes = num_classes
self.scale = scale
def forward(self, pred, labels):
pred = F.softmax(pred, dim=1)
pred = torch.clamp(pred, min=eps, max=1.0)
label_one_hot = F.one_hot(labels, self.num_classes).float().to(pred.device)
label_one_hot = torch.clamp(label_one_hot, min=1e-4, max=1.0)
norm = 1 / 4 * (self.num_classes - 1)
rce = (-1 * torch.sum(pred * torch.log(label_one_hot), dim=1))
return self.scale * norm * rce.mean()
class NCELoss(nn.Module):
def __init__(self, num_classes, scale=1.0):
super(NCELoss, self).__init__()
self.num_classes = num_classes
self.scale = scale
def forward(self, pred, labels):
pred = F.log_softmax(pred, dim=1)
label_one_hot = F.one_hot(labels, self.num_classes).float().to(pred.device)
loss = -1 * torch.sum(label_one_hot * pred, dim=1) / (-pred.sum(dim=1))
return self.scale * loss.mean()
class MAELoss(nn.Module):
def __init__(self, num_classes=10, scale=2.0):
super(MAELoss, self).__init__()
self.num_classes = num_classes
self.scale = scale
def forward(self, pred, labels):
pred = F.softmax(pred, dim=1)
label_one_hot = F.one_hot(labels, self.num_classes).float().to(pred.device)
loss = 1. - torch.sum(label_one_hot * pred, dim=1)
return self.scale * loss.mean()
class NMAE(nn.Module):
def __init__(self, num_classes=10, scale=1.0):
super(NMAE, self).__init__()
self.num_classes = num_classes
self.scale = scale
def forward(self, pred, labels):
pred = F.softmax(pred, dim=1)
label_one_hot = F.one_hot(labels, self.num_classes).float().to(pred.device)
norm = 1 / (self.num_classes - 1)
loss = 1. - torch.sum(label_one_hot * pred, dim=1)
return self.scale * norm * loss.mean()
class GCELoss(nn.Module):
def __init__(self, num_classes=10, q=0.7):
super(GCELoss, self).__init__()
self.q = q
self.num_classes = num_classes
def forward(self, pred, labels):
pred = F.softmax(pred, dim=1)
pred = torch.clamp(pred, min=eps, max=1.0)
label_one_hot = F.one_hot(labels, self.num_classes).float().to(pred.device)
loss = (1. - torch.pow(torch.sum(label_one_hot * pred, dim=1), self.q)) / self.q
return loss.mean()
class NGCELoss(nn.Module):
def __init__(self, num_classes=10, q=0.7, scale=1.0):
super(NGCELoss, self).__init__()
self.num_classes = num_classes
self.q = q
self.scale = scale
def forward(self, pred, labels):
pred = F.softmax(pred, dim=1)
pred = torch.clamp(pred, min=eps, max=1.0)
label_one_hot = F.one_hot(labels, self.num_classes).float().to(pred.device)
numerators = 1. - torch.pow(torch.sum(label_one_hot * pred, dim=1), self.q)
denominators = self.num_classes - pred.pow(self.q).sum(dim=1)
loss = numerators / denominators
return self.scale * loss.mean()
class NCEandRCE(nn.Module):
def __init__(self, alpha=1., beta=1., num_classes=10):
super(NCEandRCE, self).__init__()
self.num_classes = num_classes
self.nce = NCELoss(num_classes=num_classes, scale=alpha)
self.rce = RCELoss(num_classes=num_classes, scale=beta)
def forward(self, pred, labels):
return self.nce(pred, labels) + self.rce(pred, labels)
class NCEandMAE(nn.Module):
def __init__(self, alpha=1., beta=1., num_classes=10):
super(NCEandMAE, self).__init__()
self.num_classes = num_classes
self.nce = NCELoss(num_classes=num_classes, scale=alpha)
self.mae = MAELoss(num_classes=num_classes, scale=beta)
def forward(self, pred, labels):
return self.nce(pred, labels) + self.mae(pred, labels)
class NLNL(torch.nn.Module):
def __init__(self, train_loader, num_classes=10, ln_neg=1):
super(NLNL, self).__init__()
self.num_classes = num_classes
self.ln_neg = ln_neg
weight = torch.FloatTensor(num_classes).zero_() + 1.
if not hasattr(train_loader.dataset, 'targets'):
weight = [1] * num_classes
weight = torch.FloatTensor(weight)
else:
for i in range(num_classes):
weight[i] = (torch.from_numpy(np.array(train_loader.dataset.targets)) == i).sum()
weight = 1 / (weight / weight.max())
self.weight = weight.cuda()
self.criterion = torch.nn.CrossEntropyLoss(weight=self.weight)
self.criterion_nll = torch.nn.NLLLoss()
def forward(self, pred, labels):
labels_neg = (labels.unsqueeze(-1).repeat(1, self.ln_neg)
+ torch.LongTensor(len(labels), self.ln_neg).cuda().random_(1, self.num_classes)) % self.num_classes
labels_neg = torch.autograd.Variable(labels_neg)
assert labels_neg.max() <= self.num_classes-1
assert labels_neg.min() >= 0
assert (labels_neg != labels.unsqueeze(-1).repeat(1, self.ln_neg)).sum() == len(labels)*self.ln_neg
s_neg = torch.log(torch.clamp(1. - F.softmax(pred, 1), min=1e-5, max=1.))
s_neg *= self.weight[labels].unsqueeze(-1).expand(s_neg.size()).cuda()
labels = labels * 0 - 100
loss = self.criterion(pred, labels) * float((labels >= 0).sum())
loss_neg = self.criterion_nll(s_neg.repeat(self.ln_neg, 1), labels_neg.t().contiguous().view(-1)) * float((labels_neg >= 0).sum())
loss = ((loss+loss_neg) / (float((labels >= 0).sum())+float((labels_neg[:, 0] >= 0).sum())))
return loss
class FocalLoss(torch.nn.Module):
'''
https://github.com/clcarwin/focal_loss_pytorch/blob/master/focalloss.py
'''
def __init__(self, gamma=0.5, alpha=None, size_average=True):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.alpha = alpha
if isinstance(alpha, (float, int)):
self.alpha = torch.Tensor([alpha, 1-alpha])
if isinstance(alpha, list):
self.alpha = torch.Tensor(alpha)
self.size_average = size_average
def forward(self, input, target):
if input.dim() > 2:
input = input.view(input.size(0), input.size(1), -1) # N,C,H,W => N,C,H*W
input = input.transpose(1, 2) # N,C,H*W => N,H*W,C
input = input.contiguous().view(-1, input.size(2)) # N,H*W,C => N*H*W,C
target = target.view(-1, 1)
logpt = F.log_softmax(input, dim=1)
logpt = logpt.gather(1, target)
logpt = logpt.view(-1)
pt = torch.autograd.Variable(logpt.data.exp())
if self.alpha is not None:
if self.alpha.type() != input.data.type():
self.alpha = self.alpha.type_as(input.data)
at = self.alpha.gather(0, target.data.view(-1))
logpt = logpt * torch.autograd.Variable(at)
loss = -1 * (1-pt)**self.gamma * logpt
if self.size_average:
return loss.mean()
else:
return loss.sum()
class NormalizedFocalLoss(torch.nn.Module):
def __init__(self, gamma=0.5, num_classes=10, alpha=None, size_average=True, scale=1.0):
super(NormalizedFocalLoss, self).__init__()
self.gamma = gamma
self.size_average = size_average
self.num_classes = num_classes
self.scale = scale
def forward(self, input, target):
target = target.view(-1, 1)
logpt = F.log_softmax(input, dim=1)
normalizor = torch.sum(-1 * (1 - logpt.data.exp()) ** self.gamma * logpt, dim=1)
logpt = logpt.gather(1, target)
logpt = logpt.view(-1)
pt = torch.autograd.Variable(logpt.data.exp())
loss = -1 * (1-pt)**self.gamma * logpt
loss = self.scale * loss / normalizor
if self.size_average:
return loss.mean()
else:
return loss.sum()
class NFLandRCE(torch.nn.Module):
def __init__(self, alpha=1., beta=1., num_classes=10, gamma=0.5):
super(NFLandRCE, self).__init__()
self.num_classes = num_classes
self.nfl = NormalizedFocalLoss(gamma=gamma, num_classes=num_classes, scale=alpha)
self.rce = RCELoss(num_classes=num_classes, scale=beta)
def forward(self, pred, labels):
return self.nfl(pred, labels) + self.rce(pred, labels)
class NFLandMAE(torch.nn.Module):
def __init__(self, alpha=1., beta=1., num_classes=10, gamma=0.5):
super(NFLandMAE, self).__init__()
self.num_classes = num_classes
self.nfl = NormalizedFocalLoss(gamma=gamma, num_classes=num_classes, scale=alpha)
self.mae = MAELoss(num_classes=num_classes, scale=beta)
def forward(self, pred, labels):
return self.nfl(pred, labels) + self.mae(pred, labels)
| hitcszx/lnl_sr | losses.py | losses.py | py | 10,369 | python | en | code | 42 | github-code | 36 |
30003125789 | memo = set()
def get_first_lowercase(a):
for i, c in enumerate(a):
if c == c.lower():
return i
return -1
def solve(a, b):
global memo
if f"{a}{b}" in memo:
return False
memo.add(f"{a}{b}")
i = get_first_lowercase(a)
if (i == -1 and a != b) or len(a) < len(b) or (a[0] == a[0].upper() and a[0] != b[0]):
return False
if a == b:
return True
new_a_1 = f"{a[:i]}{a[i + 1:]}"
new_a_2 = f"{a[:i]}{a[i].upper()}{a[i + 1:]}"
return solve(new_a_1, b) or solve(new_a_2, b)
if __name__ == '__main__':
tc = 1
tc = int(input())
for i in range(tc):
a = input()
b = input()
result = "YES" if solve(a, b) else "NO"
print(result)
| dimgatz98/coding_challenges | hackerrank/abbreviation/abbreviation.py | abbreviation.py | py | 752 | python | en | code | 0 | github-code | 36 |
24396409804 | import logging
logger = logging.getLogger(__name__)
def do_something():
logger.debug(
'Detailed information, typically of interest only when diagnosing problems.')
logger.info('Confirmation that things are working as expected.')
logger.warning(
'An indication that something unexpected happened. The software is still working as expected.')
logger.error(
'Due to a more serious problem, the software has not been able to perform some function.')
logger.critical(
'A serious error, indicating that the program itself may be unable to continue running.')
def fail_something():
raise SystemError()
| jmhart/python-template | src/stuff/thing.py | thing.py | py | 656 | python | en | code | 0 | github-code | 36 |
13425691279 | ### Unzip the Dataset
# importing the zipfile module
from zipfile import ZipFile
import pandas as pd
import random
# loading the temp.zip and creating a zip object
with ZipFile("./resources/Sentences_from_Stormfront_dataset.zip", 'r') as zip_oject:
# Extracting all the members of the zip
# into a specific location.
zip_oject.extractall(path="./resources/")
path_to_extracted_folder = './resources/Sentences_from_Stormfront_dataset/'
path_to_data_files = './resources/Sentences_from_Stormfront_dataset/all_files/'
def get_500_stormfront_non_hateful_data():
annotation_metadata = pd.read_csv(path_to_extracted_folder + 'annotations_metadata.csv')
list_of_additional_data = []
hard_labels_of_additional_data = []
for i in range(500):
rand_num = random.randint(0, len(annotation_metadata) - 1)
while annotation_metadata['label'][rand_num] == 'hate':
rand_num = random.randint(0, len(annotation_metadata) - 1)
file_address = path_to_data_files + annotation_metadata['file_id'][rand_num] + '.txt'
text = open(file_address, "r").read()
list_of_additional_data.append(text)
hard_labels_of_additional_data.append(0.0)
return list_of_additional_data, hard_labels_of_additional_data
def get_stormfront_hateful_data():
annotation_metadata = pd.read_csv(path_to_extracted_folder + 'annotations_metadata.csv')
list_of_additional_data = []
hard_labels_of_additional_data = []
for i in range(len(annotation_metadata)):
if annotation_metadata['label'][i] == 'hate':
file_address = path_to_data_files + annotation_metadata['file_id'][i] + '.txt'
text = open(file_address, "r").read()
list_of_additional_data.append(text)
hard_labels_of_additional_data.append(1.0)
return list_of_additional_data, hard_labels_of_additional_data
| Speymanhs/SemEval_2023_Task_11_Lonea | reading_dataset_stormfront.py | reading_dataset_stormfront.py | py | 1,887 | python | en | code | 0 | github-code | 36 |
17093960893 | #!/usr/bin/env python
from __future__ import print_function
import sys
data = ''
for line in open(sys.argv[1], 'r'):
if len(line.strip()) == 0:
# skip the label
lines = data.splitlines()
print('\n'.join(lines[1:]))
data = ''
else:
data += line
| Oneplus/learn2compose | scripts/yelp/remove_document_splitter_and_label.py | remove_document_splitter_and_label.py | py | 293 | python | en | code | 7 | github-code | 36 |
3479784873 | # This is the model definition of retrieval model.
from typing import List, Dict, Tuple, Text
import os
import tensorflow as tf
import tensorflow_recommenders as tfrs
import numpy as np
from . import dataset as ds, params
# Get unique query and candidate and timestamp.
unique_user_ids, unique_therapist_ids = ds.get_unique_query_candidate()
timestamps, timestamps_buckets = ds.get_timestamps()
# Get candidate from dataset.
candidate = ds.get_candidate()
embedding_dimension = params.embedding_dimension
class UserModel(tf.keras.Model):
def __init__(self, use_timestamps=False):
super(UserModel, self).__init__()
# self.use_timestamps = use_timestamps
self.user_model = tf.keras.Sequential([
tf.keras.layers.StringLookup(
vocabulary=unique_user_ids, mask_token=None),
# We add an additional embedding to account for unknown tokens.
tf.keras.layers.Embedding(
len(unique_user_ids) + 1, embedding_dimension)
])
# if self.use_timestamps:
# self.timestamp_model = tf.keras.Sequential([
# tf.keras.layers.Discretization(timestamps_buckets.tolist()),
# tf.keras.layers.Embedding(
# len(timestamps_buckets) + 1, embedding_dimension)
# ])
# self.normalized_timestamp = tf.keras.layers.Normalization(
# axis=None
# )
# self.normalized_timestamp.adapt(timestamps)
def call(self, inputs):
# if not self.use_timestamps:
return self.user_model(inputs["user_id"])
# return tf.concat([
# self.user_model(inputs["user_id"]),
# self.timestamp_model(inputs["timestamp"]),
# tf.reshape(self.normalized_timestamp(inputs["timestamp"]), (-1, 1))
# ], axis=1)
class QueryModel(tf.keras.Model):
"""Model for encoding user queries."""
def __init__(self, layer_sizes):
"""Model for encoding user queries.
Args:
layer_sizes:
A list of integers where the i-th entry represents the number of units
the i-th layer contains.
"""
super().__init__()
# We first use the user model for generating embeddings.
self.embedding_model = UserModel()
# Then construct the layers.
self.dense_layers = tf.keras.Sequential()
# Use the ReLU activation for all but the last layer.
for layer_size in layer_sizes[:-1]:
self.dense_layers.add(tf.keras.layers.Dense(
layer_size, activation="relu"))
# No activation for the last layer.
for layer_size in layer_sizes[-1:]:
self.dense_layers.add(tf.keras.layers.Dense(layer_size))
def call(self, inputs):
feature_embedding = self.embedding_model(inputs)
return self.dense_layers(feature_embedding)
class TherapistModel(tf.keras.Model):
def __init__(self):
super().__init__()
max_token = 10_000
self.title_embedding = tf.keras.Sequential([
tf.keras.layers.StringLookup(
vocabulary=unique_therapist_ids, mask_token=None),
tf.keras.layers.Embedding(
len(unique_therapist_ids) + 1, embedding_dimension)
])
self.title_vectorizer = tf.keras.layers.TextVectorization(
max_tokens=max_token
)
self.title_text_embedding = tf.keras.Sequential([
self.title_vectorizer,
tf.keras.layers.Embedding(
max_token, embedding_dimension, mask_zero=True),
tf.keras.layers.GlobalAveragePooling1D()
])
self.title_vectorizer.adapt(candidate)
def call(self, inputs):
return tf.concat([
self.title_embedding(inputs),
self.title_text_embedding(inputs)
], axis=1)
class CandidateModel(tf.keras.Model):
"""Model for encoding therapists."""
def __init__(self, layer_sizes):
"""Model for encoding therapists.
Args:
layer_sizes:
A list of integers where the i-th entry represents the number of units
the i-th layer contains.
"""
super().__init__()
self.embedding_model = TherapistModel()
# Then construct the layers.
self.dense_layers = tf.keras.Sequential()
# Use the ReLU activation for all but the last layer.
for layer_size in layer_sizes[:-1]:
self.dense_layers.add(tf.keras.layers.Dense(
layer_size, activation="relu"))
# No activation for the last layer.
for layer_size in layer_sizes[-1:]:
self.dense_layers.add(tf.keras.layers.Dense(layer_size))
def call(self, inputs):
feature_embedding = self.embedding_model(inputs)
return self.dense_layers(feature_embedding)
class RetrievalDefinition(tfrs.Model):
def __init__(self):
super().__init__()
self.query_model: tf.keras.Model = QueryModel(params.layer_size)
self.candidate_model: tf.keras.Model = CandidateModel(
params.layer_size)
self.task: tf.keras.layers.Layer = tfrs.tasks.Retrieval(
metrics=tfrs.metrics.FactorizedTopK(
candidates=candidate.batch(128).map(self.candidate_model)
)
)
def compute_loss(self, features: Dict[Text, tf.Tensor], training=False) -> tf.Tensor:
# We pick out the user features and pass them into the user model.
user_embeddings = self.query_model({
"user_id": features["user_id"],
})
# And pick out the therapist features and pass them into the therapist model,
# getting embeddings back.
positive_therapist_embeddings = self.candidate_model(
features["therapist_id"])
# The task computes the loss and the metrics.
return self.task(user_embeddings, positive_therapist_embeddings, compute_metrics=not training)
| thomiaditya/theia | theia/config/recommender/retrieval_definition.py | retrieval_definition.py | py | 6,028 | python | en | code | 0 | github-code | 36 |
8024464551 | """
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
"""
class Solution:
# @param A, a list of integers
# @return a boolean
def canJump(self, A):
return self.canJump_1(A)
# Real DP way, but TLE. This is a O(n^2)'s solution
def canJump_3(self, A):
if A[0] == 0:
return False
N = len(A)
dp = [False for i in range(N)]
dp[0] = True
for i in range(1, N):
for j in range(i)[::-1]:
if dp[j] and j + A[j] >= i:
dp[i] = True
break
return dp[N-1]
# Note:
# 1. dp[i] means whether we can jump to i
# 2. dp[0] = True
# 3. dp[i] = True if from i-1 ... 0 if we can jump to i
# 4. dp[N-1]
# Constant DP
def canJump_1(self, A):
pre_max = A[0]
for i in range(1, len(A)):
max_jump = max(pre_max-1, A[i-1]-1)
if max_jump < 0: # Note this is < 0 but not <= 0
return False
pre_max = max_jump
return True
# Another DP
def canJump_2(self, A):
dp = [0 for i in range(len(A))]
dp[0] = A[0]
for i in range(1, len(A)):
dp[i] = max(dp[i-1]-1, A[i-1]-1)
if dp[i] < 0:
return False
return True
# Note:
# 1. dp[i] means at i, we can jump to where
# 2. dp[0] = A[0]
# 3. dp[i] = max(A[i-1]-1, dp[i-1]-1), if dp[i] < 0: then return False
# return True if we can finish the loop
| cyandterry/Python-Study | Ninja/Leetcode/55_Jump_Game.py | 55_Jump_Game.py | py | 1,784 | python | en | code | 62 | github-code | 36 |
74430413223 | class PushingList(list):
""" При переполнении выталкивает первый элемент. Стандартная максимальная длинна 10 элементов. """
max_len = 10
def append(self, *args):
for arg in args:
super(PushingList, self).append(arg)
if self.__len__() > self.max_len:
self.pop(0)
| Apolliner/Field-Mini-Game | libraryNPC/classes.py | classes.py | py | 401 | python | ru | code | 0 | github-code | 36 |
33532139383 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A script to convert the column names from CamelCase to snake_case.
Typically you would run this file from a command line like this:
ipython3.exe -i -- /deploy/cbmcfs3_runner/scripts/orig/convert_column_case.py
"""
# Built-in modules #
import os
# Third party modules #
import pandas
from tqdm import tqdm
# First party modules #
import autopaths
from autopaths import Path
from autopaths.auto_paths import AutoPaths
from plumbing.common import camel_to_snake
from plumbing.cache import property_cached
# Internal modules #
from cbmcfs3_runner.core.continent import continent
# Constants #
home = os.environ.get('HOME', '~') + '/'
###############################################################################
class CaseConverter(object):
"""
This class takes many of the CSV files in "export/" and "orig/" and
converts their title case in their column names.
"""
all_paths = """
/orig/coefficients.csv
/orig/silv_treatments.csv
/export/ageclass.csv
/export/inventory.csv
/export/classifiers.csv
/export/disturbance_events.csv
/export/disturbance_types.csv
/export/transition_rules.csv
/export/yields.csv
/export/historical_yields.csv
/fusion/back_inventory_aws.csv
"""
def __init__(self, country):
# Default attributes #
self.country = country
# Automatically access paths based on a string of many subpaths #
self.paths = AutoPaths(self.country.data_dir, self.all_paths)
def __call__(self):
for p in self.paths:
# Some countries don't have that fusion file #
if not p: continue
# Read into memory #
df = pandas.read_csv(str(p))
# Change #
df = df.rename(columns = camel_to_snake)
# Write back to disk #
df.to_csv(str(p), index=False, float_format='%g')
def fix_spelling(self):
"""Some words were written wrongly but not in all countries."""
# Read #
df = pandas.read_csv(str(self.paths.disturbance_events))
# Change #
df = df.rename(columns = {'efficency': 'efficiency',
'sor_type': 'sort_type'})
# Write #
df.to_csv(str(self.paths.disturbance_events), index=False, float_format='%g')
###############################################################################
class CaseRenamer(object):
"""
This class takes our python source files and renames the column variables
to match the new case. It can also operate on the jupyter notebooks.
"""
def __init__(self, base_dir, extension):
# Default attributes #
self.base_dir = Path(base_dir)
self.extension = extension
col_names = {
'ageclass': 'AgeClassID,Size',
'classifiers': 'ClassifierNumber,ClassifierValueID',
'disturbances': 'UsingID,SWStart,SWEnd,HWStart,HWEnd,Min_since_last_Dist,'
'Max_since_last_Dist,Last_Dist_ID,Min_tot_biom_C,Max_tot_biom_C,'
'Min_merch_soft_biom_C,Max_merch_soft_biom_C,Min_merch_hard_biom_C,'
'Max_merch_hard_biom_C,Min_tot_stem_snag_C,Max_tot_stem_snag_C,'
'Min_tot_soft_stem_snag_C,Max_tot_soft_stem_snag_C,Min_tot_hard_stem_snag_C,'
'Max_tot_hard_stem_snag_C,Min_tot_merch_stem_snag_C,Max_tot_merch_stem_snag_C,'
'Min_tot_merch_soft_stem_snag_C,Max_tot_merch_soft_stem_snag_C,'
'Min_tot_merch_hard_stem_snag_C,Max_tot_merch_hard_stem_snag_C,Efficency,'
'Sort_Type,Measurement_type,Amount,Dist_Type_ID,Step',
'yields': 'Sp',
'inventory': 'UsingID,Age,Area,Delay,UNFCCCL,HistDist,LastDist',
'transitions': 'UsingID,SWStart,SWEnd,HWStart,HWEnd,Dist_Type_ID,RegenDelay,ResetAge,Percent',
'treatments': 'Dist_Type_ID,Sort_Type,Efficiency,Min_age,Max_age,Min_since_last,'
'Max_since_last,HWP,RegenDelay,ResetAge,Percent,WD,OWC_Perc,Snag_Perc,'
'Perc_Merch_Biom_rem,Man_Nat',
'database': 'TimeStep, UserDefdClassID, UserDefdClassSetID, UserDefdSubclassID,'
'UserDefdSubClassName, AveAge, Biomass, DistArea,'
'BEF_Tot, BG_Biomass, Tot_Merch, Tot_ABG, BG_Biomass,'
'Vol_Merch, Vol_SubMerch, Vol_Snags, TC, TC_FW_C,'
'Vol_Merch_FW_B, Vol_SubMerch_FW_B, Vol_Snags_FW_B,'
'Vol_SubMerch_IRW_B, Vol_Snags_IRW_B,'
'TOT_Vol_FW_B, DMStructureID, DMColumn, DMRow, DMID',
'products': 'SW_Merch, SW_Foliage, SW_Other, HW_Merch, HW_Foliage, HW_Other, SW_Coarse,'
'SW_Fine, HW_Coarse, HW_Fine, Merch_C_ha,'
'Snag_Perc, OWC_Perc, FW_amount, IRW_amount,'
'SoftProduction, HardProduction, DOMProduction,'
'CO2Production, MerchLitterInput, OthLitterInput,'
'Prov_Carbon, Vol_forest_residues,',
'extras': 'IRW_C, FW_C, IRW_B, FW_B'
}
@property_cached
def cols_before(self):
cols_before = ','.join(self.col_names.values()).split(',')
return list(set(name.strip() for name in cols_before))
@property_cached
def cols_after(self):
return [camel_to_snake(col) for col in self.cols_before]
@property_cached
def code_files(self):
return [f for f in self.base_dir.files if f.extension == self.extension]
def __call__(self):
for file in tqdm(self.code_files):
for old_name, new_name in zip(self.cols_before, self.cols_after):
# Only if it is found enclosed in quotes #
file.replace_word("'%s'" % old_name, "'%s'" % new_name)
# Only if it is with the word 'query' on the same line #
self.replace_word_if_other_word(file, old_name, 'query', new_name)
def replace_word_if_other_word(self, path, word1, word2, replacement_word):
"""
Search the file for a given word, and if found,
check the line in which it appears for another second word,
if both the first and second word are found on the same line,
then replace every occurrence of the first word with
the replacement word.
"""
# The original file #
orig_file = Path(path)
# Create a new file #
result_file = autopaths.tmp_path.new_temp_file()
# Generate the lines #
def new_lines():
for line in orig_file:
if word2 in line: yield line.replace(word1, replacement_word)
else: yield line
# Open input/output files, note: output file's permissions lost #
result_file.writelines(new_lines())
# Switch the files around #
orig_file.remove()
result_file.move_to(orig_file)
###############################################################################
if __name__ == '__main__':
# First part #
converters = [CaseConverter(c) for c in continent]
for converter in tqdm(converters): converter()
for converter in tqdm(converters): converter.fix_spelling()
# Second part #
code_dir = home + "repos/cbmcfs3_runner/cbmcfs3_runner/"
renamer = CaseRenamer(code_dir, '.py')
renamer()
# Third part #
code_dir = home + "repos/bioeconomy_notes/notebooks/"
renamer = CaseRenamer(code_dir, '.md')
renamer()
| xapple/cbmcfs3_runner | scripts/orig/convert_column_case.py | convert_column_case.py | py | 7,647 | python | en | code | 2 | github-code | 36 |
4828779456 | import torch
from torch import nn
import pickle
from model import WideResNet
from autoattack import AutoAttack
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torchvision import datasets, transforms, models
class ImageDataset(Dataset):
def __init__(self, file):
super().__init__()
data, label = pickle.load(open(file,'rb'))
self.data = self.transform(data)
self.label = label
def transform(self, data):
data = torch.Tensor(data).permute(0,3,1,2).contiguous().div(255)
transform_func = transforms.Compose([
transforms.RandomCrop(size = data.shape[-1], padding = 2),
transforms.RandomHorizontalFlip(),
transforms.Normalize(mean=(0.4914, 0.4822, 0.4465),
std=(0.247, 0.243, 0.261))]
)
augmented_data = transform_func(data)
return augmented_data
def __getitem__(self, idx):
return self.data[idx], self.label[idx]
def __len__(self):
return len(self.label)
device = 2
batch_size = 1024
#model = WideResNet(32,10).to(device)
ds = ImageDataset('./data/cifar_train.pt')
model = models.__dict__['resnet50']().to(device)
model.load_state_dict(torch.load('./save/model.pt'))
transform_func = transforms.Compose([transforms.ToTensor(),
transforms.RandomCrop(size = 32, padding = 2),
transforms.RandomHorizontalFlip(),
transforms.Normalize(mean=(0.4914, 0.4822, 0.4465),
std=(0.247, 0.243, 0.261))])
#ds = datasets.CIFAR10('data',train=True,transform=transform_func)
dl = DataLoader(ds,batch_size=batch_size,shuffle=True,pin_memory=True)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), 0.001)
model.eval()
while True:
for i, (x,y) in enumerate(dl,start=1):
x = x.to(device)
y = y.to(device)
optimizer.zero_grad()
pred = model(x)
loss = criterion(pred, y)
loss.backward()
optimizer.step()
print(i, ((pred.argmax(-1)==y).sum()/len(y)).item(), loss.item())
if i%10==0: torch.save(model.state_dict(),'./save/model.pt')
| AmadeusloveIris/AutoAdversarialTraining | test.py | test.py | py | 2,316 | python | en | code | 0 | github-code | 36 |
12234497572 | import datetime
from typing import List
from sqlalchemy.orm import make_transient
from data_access.entities.person import Person
from data_access.entities.policy import Policy
from data_access.entities.policy_offer_template import PolicyOfferTemplate
from data_access.entities.policy_risk import PolicyRisk
from data_access.entities.vehicle import Vehicle
from data_access.repositories.person_repository import PersonRepository
from data_access.repositories.policy_offer_template_repository import PolicyOfferTemplateRepository
from data_access.repositories.policy_repository import PolicyRepository
from data_access.repositories.policy_risk_repository import PolicyRiskRepository
from data_access.repositories.vehicle_repository import VehicleRepository
from services.broker_service import BrokerService
from services.calculation_service import CalculationService
from services.errors import Errors
from services.models.offer_template_creation_model import OfferTemplateCreationModel
from services.models.service_message import ServiceMessage
from services.models.offer_creation_model import OfferCreationModel
class PolicyService:
__person_repository: PersonRepository
__policy_repository: PolicyRepository
__policy_offer_template_repository: PolicyOfferTemplateRepository
__policy_risk_repository: PolicyRiskRepository
__vehicle_repository: VehicleRepository
__broker_service: BrokerService
__calculation_service: CalculationService
def __init__(
self,
policy_repository: PolicyRepository,
broker_service: BrokerService,
policy_offer_template_repository: PolicyOfferTemplateRepository,
vehicle_repository: VehicleRepository,
calculation_service: CalculationService,
policy_risk_repository: PolicyRiskRepository,
person_repository: PersonRepository
):
self.__policy_repository = policy_repository
self.__broker_service = broker_service
self.__policy_offer_template_repository = policy_offer_template_repository
self.__vehicle_repository = vehicle_repository
self.__calculation_service = calculation_service
self.__policy_risk_repository = policy_risk_repository
self.__person_repository = person_repository
def get_by_broker(self, api_key: str, is_offer: bool = False) -> [Policy]:
broker = self.__broker_service.get_by_api_key(api_key)
if broker is None:
return []
return self.__policy_repository.get_by_broker(broker.Id, is_offer)
def get_by_id(self, policy_id: int) -> [Policy]:
return self.__policy_repository.get_by_id(policy_id)
def get_by_vehicle(self, vehicle_id: int):
return self.__policy_repository.get_by_vehicle(vehicle_id)
def get_by_person(self, person_id: int):
return self.__policy_repository.get_by_person(person_id)
def get_by_insurer(self, insurer_id: int, is_summary: bool):
return self.__policy_repository.get_premium_sum_by_insurer(insurer_id)\
if is_summary\
else self.__policy_repository.get_by_insurer(insurer_id)
def create_offer_template(self, offer_template_model: OfferTemplateCreationModel) -> int:
policy_offer_template = PolicyOfferTemplate()
policy_offer_template.Id = self.__policy_offer_template_repository.create_id()
policy_offer_template.Name = offer_template_model.name
policy_offer_template.InsurerId = offer_template_model.insurerId
policy_offer_template.QuotationAlgorithm = offer_template_model.quotationAlgorithm
policy_offer_template.ValidFrom = offer_template_model.validFrom
policy_offer_template.ValidTo = offer_template_model.validTo
self.__policy_offer_template_repository.session().add(policy_offer_template)
self.__policy_offer_template_repository.session().commit()
return policy_offer_template.Id
def create_offer_from_template(self, template_id: int, offer_model: OfferCreationModel, broker_id: int) -> ServiceMessage:
service_message = ServiceMessage()
template = self.__policy_offer_template_repository.get_by_id(template_id)
if template is None:
service_message.errors.append(Errors.NO_POLICY_OFFER_TEMPLATE)
return service_message
vehicle = self.__vehicle_repository.get_by_vin(offer_model.vehicle.vin)
if vehicle is None:
vehicle = Vehicle()
vehicle.Id = self.__vehicle_repository.create_id()
vehicle.Make = offer_model.vehicle.make
vehicle.Model = offer_model.vehicle.model
vehicle.RegistrationNumber = offer_model.vehicle.registrationNumber
vehicle.Vin = offer_model.vehicle.vin
vehicle.ProductionYear = offer_model.vehicle.productionYear
vehicle.RegistrationDate = offer_model.vehicle.registrationDate
vehicle.OwnerCount = offer_model.vehicle.ownerCount
self.__vehicle_repository.session().add(vehicle)
self.__vehicle_repository.session().commit()
person = self.__person_repository.get_by_pesel(offer_model.person.pesel)
if person is None:
person = Person()
person.Id = self.__person_repository.create_id()
person.Name = offer_model.person.name
person.LastName = offer_model.person.lastName
person.BirthDate = offer_model.person.birthDate
person.Pesel = offer_model.person.pesel
person.Email = offer_model.person.email
person.PhoneNumber = offer_model.person.phoneNumber
self.__person_repository.session().add(person)
self.__person_repository.session().commit()
offer = Policy()
offer.Id = self.__policy_repository.create_id()
offer.VehicleId = vehicle.Id
offer.InsurerId = template.InsurerId
offer.BrokerId = broker_id
offer.PersonId = person.Id
offer.CreationDate = datetime.date.today()
offer.IsOffer = True
offer.Version = 1
self.__policy_repository.session().add(offer)
self.__policy_repository.session().commit()
risks = self.calculate_risks(vehicle, template)
for index, risk in enumerate(risks):
risks[index].PolicyId = offer.Id
risks[index].Id = self.__policy_risk_repository.create_id()
self.__policy_risk_repository.session().add(risks[index])
self.__policy_risk_repository.session().commit()
service_message.content = offer.Id
return service_message
def issue_policy(self, offer_id: int) -> ServiceMessage:
service_message = ServiceMessage()
offer = self.__policy_repository.get_by_id(offer_id)
if not offer.IsOffer:
service_message.errors.append(Errors.NO_OFFER_WITH_ID)
else:
risks = offer.PolicyRisks
make_transient(offer)
policy = offer
policy.OfferId = offer.Id
policy.Id = self.__policy_repository.create_id()
policy.IsOffer = False
self.__policy_repository.session().add(policy)
self.__policy_repository.session().commit()
for index, risk in enumerate(risks):
new_risk = PolicyRisk()
new_risk.Id = self.__policy_risk_repository.create_id()
new_risk.PolicyId = policy.Id
new_risk.CurrencyId = risk.CurrencyId
new_risk.RiskId = risk.RiskId
new_risk.CreationDate = datetime.date.today()
new_risk.StartDate = risk.StartDate
new_risk.EndDate = risk.EndDate
new_risk.Premium = risk.Premium
self.__policy_risk_repository.session().add(new_risk)
self.__policy_risk_repository.session().commit()
service_message.content = offer.Id
return service_message
def calculate_risks(self, vehicle: Vehicle, policy_offer_template: PolicyOfferTemplate) -> list[PolicyRisk]:
return self.__calculation_service.calculate(vehicle, policy_offer_template)
| bastyje/policyapp | python/src/services/policy_service.py | policy_service.py | py | 8,189 | python | en | code | 0 | github-code | 36 |
12487564602 | import filecmp
import subprocess
import pytest
from typer.testing import CliRunner
import erdantic as erd
from erdantic.cli import app, import_object_from_name
import erdantic.examples.dataclasses as examples_dataclasses
import erdantic.examples.pydantic as examples_pydantic
from erdantic.examples.pydantic import Party, Quest
from erdantic.exceptions import ModelOrModuleNotFoundError
from erdantic.version import __version__
runner = CliRunner()
def test_import_object_from_name():
assert import_object_from_name("erdantic.examples.pydantic.Party") is Party
assert import_object_from_name("erdantic.examples.pydantic.Quest") is Quest
assert import_object_from_name("erdantic") is erd
assert import_object_from_name("erdantic.examples.pydantic") is examples_pydantic
with pytest.raises(ModelOrModuleNotFoundError):
import_object_from_name("erdantic.not_a_module")
with pytest.raises(ModelOrModuleNotFoundError):
import_object_from_name("erdantic.examples.pydantic.not_a_model_class")
def test_draw(tmp_path):
# With library for comparison
path_base = tmp_path / "diagram_base.png"
erd.draw(Party, out=path_base)
assert path_base.exists()
# With CLI
path1 = tmp_path / "diagram1.png"
result = runner.invoke(app, ["erdantic.examples.pydantic.Party", "-o", str(path1)])
assert result.exit_code == 0
assert path1.exists()
assert filecmp.cmp(path1, path_base)
# python -m erdantic
path2 = tmp_path / "diagram2.png"
result = subprocess.run(
["python", "-m", "erdantic", "erdantic.examples.pydantic.Party", "-o", str(path2)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
assert result.returncode == 0
assert path2.exists()
assert filecmp.cmp(path2, path_base)
def test_with_terminus(tmp_path):
# With library for comparison
path_base = tmp_path / "diagram_base.png"
erd.draw(Party, out=path_base, termini=[Quest])
assert path_base.exists()
# With CLI
path1 = tmp_path / "diagram1.png"
result = runner.invoke(
app,
[
"erdantic.examples.pydantic.Party",
"-t",
"erdantic.examples.pydantic.Quest",
"-o",
str(path1),
],
)
assert result.exit_code == 0
assert path1.exists()
assert filecmp.cmp(path1, path_base)
def test_with_modules(tmp_path):
# With library for comparison
path_base = tmp_path / "diagram_base.png"
erd.draw(Quest, examples_dataclasses, out=path_base)
assert path_base.exists()
# With CLI
path1 = tmp_path / "diagram1.png"
result = runner.invoke(
app,
[
"erdantic.examples.pydantic.Quest",
"erdantic.examples.dataclasses",
"-o",
str(path1),
],
)
assert result.exit_code == 0
assert path1.exists()
assert filecmp.cmp(path1, path_base)
# With library for comparison, all pydantic classes
path_base_all_pydantic = tmp_path / "diagram_base_all_pydantic.png"
erd.draw(Quest, examples_dataclasses, examples_pydantic, out=path_base_all_pydantic)
assert path_base_all_pydantic.exists()
# With CLI without limit_search_models_to
path2 = tmp_path / "diagram2.png"
result = runner.invoke(
app,
[
"erdantic.examples.pydantic.Quest",
"erdantic.examples.dataclasses",
"erdantic.examples.pydantic",
"-o",
str(path2),
],
)
assert result.exit_code == 0
assert path2.exists()
assert filecmp.cmp(path2, path_base_all_pydantic)
# With CLI with limit_search_models_to
path3 = tmp_path / "diagram3.png"
result = runner.invoke(
app,
[
"erdantic.examples.pydantic.Quest",
"erdantic.examples.dataclasses",
"erdantic.examples.pydantic",
"-o",
str(path3),
"-m",
"dataclasses",
],
)
assert result.exit_code == 0
assert path3.exists()
assert filecmp.cmp(path3, path_base)
def test_missing_out():
result = runner.invoke(app, ["erdantic.examples.pydantic.Party"])
assert result.exit_code == 2
assert "Error" in result.stdout
assert "Missing option '--out' / '-o'." in result.stdout
def test_no_overwrite(tmp_path):
path = tmp_path / "diagram.png"
path.touch()
# With no-overwrite
result = runner.invoke(
app, ["erdantic.examples.pydantic.Quest", "-o", str(path), "--no-overwrite"]
)
assert result.exit_code == 1
assert path.stat().st_size == 0
# Overwrite
result = runner.invoke(app, ["erdantic.examples.pydantic.Quest", "-o", str(path)])
assert result.exit_code == 0
assert path.stat().st_size > 0
def test_dot(tmp_path):
result = runner.invoke(app, ["erdantic.examples.pydantic.Party", "-d"])
assert result.exit_code == 0
assert erd.to_dot(Party).strip() == result.stdout.strip()
path = tmp_path / "diagram.png"
result = runner.invoke(app, ["erdantic.examples.pydantic.Party", "-d", "-o", str(path)])
assert result.exit_code == 0
assert not path.exists() # -o is ignored and no file created
assert erd.to_dot(Party).strip() == result.stdout.strip()
# python -m erdantic
result = subprocess.run(
["python", "-m", "erdantic", "erdantic.examples.pydantic.Party", "-d"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
assert result.returncode == 0
assert not path.exists() # -o is ignored and no file created
assert erd.to_dot(Party).strip() == result.stdout.strip()
def test_help():
"""Test the CLI with --help flag."""
result = runner.invoke(app, ["--help"])
assert result.exit_code == 0
assert (
"Draw entity relationship diagrams (ERDs) for Python data model classes." in result.output
)
def test_version():
"""Test the CLI with --version flag."""
result = runner.invoke(app, ["--version"])
assert result.exit_code == 0
assert result.output.strip() == __version__
| drivendataorg/erdantic | tests/test_cli.py | test_cli.py | py | 6,182 | python | en | code | 205 | github-code | 36 |
10208120572 | import socket
import threading
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from jsock.protocol import Protocol
from jsock.message import MessageHeader, Message
from jsock.errors import Errors
from jsock.client import Client
from jsock.config import Config
PORT = 1337
LISTEN_NUM = 50
AWAIT_LIMIT_NUM = 1000
# JacobSocks
#
# Features:
# Multithreading
# Simple
# Customisable
# Auto documentation your API
# Error handling
# Get message by callbacks and by (self made) await (await per socket)
# Expandable
# How to use:
# Show code
class InvalidProtocol(Exception):
pass
# TODO: make a lib for socket server in python
# TODO: Threw a exception
# TODO: make the config
# TODO: Make the chat server
# TODO: Upload to git and readme
# TODO: Finish the server
# TODO: + add on await failed (disconnected)
# TODO: + delete unuse messages
# TODO: do on code and on code socket function callbakcs (no necessary)
# TODO: + improve message read (first read code and len)
# TODO: make the chat_example docs automatic
# TODO: DEBUG
# TODO: config the server how I like (return format error, auto correct and so on, encryption or not)
# (make the class first)
# TODO: make tls
class ThreadedServer(object):
def __init__(self, config: Config, protocol: Protocol):
self._config = config
self._protocol = protocol
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._sock.bind((self._config.host, self._config.port))
self._input_lock = threading.Lock()
self._input_cv = threading.Condition(self._input_lock)
self._input_queue = deque()
self._input_callback = dict()
self._input_awaits = dict()
self._await_lock = threading.Lock()
self._await_cv = threading.Condition(self._await_lock)
self._on_disconnect_dict = dict()
self._on_connect = None
self._await_socks = dict()
# self.output_lock = threading.Lock()
# self.output_cv = threading.Condition(self.output_lock)
# self.output_queue = deque()
self._output_executor = ThreadPoolExecutor()
self._callbacks_executor = ThreadPoolExecutor()
def start(self):
threading.Thread(target=self._await_start).start()
def _await_start(self):
self._sock.listen(LISTEN_NUM)
threading.Thread(target=self._get_message_listener).start()
while True:
client = Client(*self._sock.accept())
# TODO: need "client.settimeout(120)" ?
if self._on_connect is not None:
self._callbacks_executor.submit(lambda: self._on_connect(client))
threading.Thread(target=self._on_listen_to_client, args=(client,)).start()
@staticmethod
def _send(sock, message):
sock.send(message.to_bytes())
def set_on_disconnect(self, sock, func):
if func is None:
del self._on_disconnect_dict[sock]
else:
self._on_disconnect_dict[sock] = func
def set_on_connector(self, func):
self._on_connect = func
def set_on_message(self, client, code, func):
if func is None:
del self._input_callback[(client, code)]
else:
print(func)
self._input_callback[(client, code)] = func
def send_message(self, client, message):
func = lambda: self._send(client.sock, message)
self._output_executor.submit(func)
# TODO: remove size limit and add dict of requests and not save every message
# TODO: timeout
def await_for_response(self, client, code, timeout=None, config=None):
with self._await_cv:
self._input_awaits[(client, code)] = None
if client not in self._await_socks:
self._await_socks[client] = []
self._await_socks[client].apppend(code)
while self._input_awaits[(client, code)] is None:
self._await_cv.wait()
return_value = self._input_awaits[(client, code)]
del self._input_awaits[(client, code)]
self._await_socks[client].remove(code)
if len(self._await_socks[client]) == 0:
del self._await_socks[client]
return return_value
# sorter
def _get_message_listener(self):
while True:
with self._input_cv:
while len(self._input_queue) == 0:
self._input_cv.wait()
while len(self._input_queue) != 0:
client, message = self._input_queue.pop()
# print(f"{client.sock} send: {message}")
# check if someone need the message of there is a callback
func = self._input_callback.get((client, message.code))
have_callback_code = func is not None
if have_callback_code:
self._callbacks_executor.submit(lambda: func(client, message))
else:
with self._await_cv:
if (client, message.code) in self._input_awaits:
self._input_awaits[(client, message.code)] = message
self._await_cv.notify_all()
def _add_to_queue(self, client, message):
with self._input_cv:
self._input_queue.append((client, message))
self._input_cv.notify_all()
# TODO: don't listen to non use code
def _on_listen_to_client(self, client):
while True:
try:
header_data = client.sock.recv(MessageHeader.get_size())
header = MessageHeader.format(header_data, self._config.code_enum_type)
if header.code == Errors.LOCAL_FORMAT_ERROR:
raise InvalidProtocol('Client disconnected')
data = client.sock.recv(header.get_size())
class_type = self._protocol.get_class(header)
if class_type is not None:
message = Message.format(header, class_type.from_json(data.decode()))
self._add_to_queue(client, message)
except InvalidProtocol as e: # TODO: to not kick
print(e)
client.sock.close()
func = self._on_disconnect_dict.get(client)
if func is not None:
self._callbacks_executor.submit(lambda: func(client))
return False
except OSError as e:
print(e)
client.sock.close()
func = self._on_disconnect_dict.get(client)
if func is not None:
self._callbacks_executor.submit(lambda: func(client))
return False
def _on_disconnect(self, client):
with self._await_cv:
if client in self._await_socks:
for code in self._await_socks[client]:
self._input_awaits[(client, code)] = Message.error()
del self._await_socks[client]
self._await_cv.notify_all()
client.sock.close()
func = self._on_disconnect_dict.get(client)
if func is not None:
self._callbacks_executor.submit(lambda: func(client))
| jacobggman/python_black_jack_server | jsock/server.py | server.py | py | 7,368 | python | en | code | 0 | github-code | 36 |
35183490035 | import asyncio
import os
import oneai
from oneai import Input, Output
oneai.api_key = os.getenv("ONEAI_KEY")
async def split(filepath):
pipeline = oneai.Pipeline(
steps=[
oneai.skills.SplitByTopic(),
]
)
with open(filepath, 'r') as file_input:
output = await pipeline.run_batch_async([file_input], on_output=handle_success, on_error=handle_error)
print(f'OUTPUT = {output}')
def handle_success(input, output_map: [Input, Output]) -> None:
print(f'success: spans = ')
for span in output_map.segments.output_spans:
print(span)
def handle_error(input, output_map: [Input, Exception]) -> None:
print(f'failure: {output_map}')
asyncio.run(split('file_store/Auburn.txt'))
# asyncio.run(split('file_store/1_min_sample.mp3.txt'))
| clande/demo | oneai_splitbytopic_repro.py | oneai_splitbytopic_repro.py | py | 808 | python | en | code | 0 | github-code | 36 |
20604733756 | from sklearn import preprocessing
from pandas import read_csv
from sklearn.model_selection import train_test_split
from keras.layers import Dense
from keras.models import Sequential
from keras.optimizers import Adam
from sklearn.metrics import r2_score
from matplotlib import pyplot as plt
df = read_csv("C:\Code\RNASeqAnalysis\Data\CentData.csv", header = 0)
survival = df.Survival
genelist = df.drop(["UUID", "Survival"], axis = 1)
scaler = preprocessing.StandardScaler().fit(genelist)
X_train, X_val, Y_train, Y_val = train_test_split(genelist, survival, test_size = .2)
X_tprep = scaler.transform(X_train)
X_vprep = scaler.transform(X_val)
#print(X_vprep, X_vprep, Y_train, Y_val)
model = Sequential()
model.add(Dense(750, input_shape = (60488,), activation ='relu'))
model.add(Dense(750, activation = 'relu'))
model.add(Dense(750, activation = 'relu'))
model.add(Dense(750, activation = 'relu'))
model.add(Dense(750, activation = 'relu'))
model.add(Dense(750, activation = 'relu'))
model.add(Dense(750, activation = 'relu'))
model.add(Dense(750, activation = 'relu'))
model.add(Dense(750, activation = 'relu'))
model.add(Dense(750, activation = 'relu'))
model.add(Dense(1,))
model.compile(Adam(lr = .00000075), 'mean_squared_error')
history = model.fit(X_tprep,Y_train, epochs = 6500, validation_split = .25, verbose = 0)
print("Model compiled and trained")
Yval_pred = model.predict(X_vprep)
rscore = r2_score(Y_val,Yval_pred)
Yval_pred2 = model.predict(X_tprep)
rscore1 = r2_score(Y_train, Yval_pred2)
print("R2 score (Validation Data): " + str(rscore))
print("R2 score (Training Data): " + str(rscore1))
model.save(R'C:\Users\tjmcg\source\repos\RNAseqFinal\RNAseqFinal\weights.h5')
history_dict = history.history
plt.figure()
plt.yscale("log")
plt.plot(history_dict['loss'], 'bo', label = 'training loss')
plt.plot(history_dict['val_loss'], 'r', label = 'val training loss')
plt.show()
| taytay191/RNAseqAnalysis | RNAseqFinal/model.py | model.py | py | 1,905 | python | en | code | 0 | github-code | 36 |
2063569811 | from functools import cache
from . import get_track_data, get_countries_charts
import pandas as pd
@cache
def get_basic_track_features():
tracks = get_track_data()
isrc_cols = tracks.columns[tracks.columns.str.contains("isrc")].tolist()
album_cols = tracks.columns[tracks.columns.str.contains("album")].tolist()
artist_cols = tracks.columns[tracks.columns.str.contains("artist")].tolist()
other_irrelevant_cols = ["name", "preview_url", "genres"]
irrelevant_cols = isrc_cols + album_cols + artist_cols + other_irrelevant_cols
track_feats = tracks.drop(columns=irrelevant_cols)
track_feats["single_release"] = tracks.album_type == "single"
track_feats = track_feats.dropna()
return track_feats
countries_charts = get_countries_charts()
track_feats = get_basic_track_features()
@cache
def get_track_feature_region_dataset():
"""
Returns a dataframe with the track features for each track that only charted in one region. Oceania is removed because of low number of observations.
"""
charting_tracks_by_region = countries_charts.drop_duplicates(
subset=["id", "geo_region"]
)[["id", "geo_region"]].rename(columns={"geo_region": "region"})
tracks_charting_only_in_one_region = charting_tracks_by_region[
~charting_tracks_by_region.duplicated(keep=False, subset=["id"])
].reset_index(drop=True)
region_tracks_features = pd.merge(
track_feats, tracks_charting_only_in_one_region, on="id"
).set_index("id")
region_track_feats_dataset = region_tracks_features.copy().loc[
region_tracks_features.region != "Oceania"
]
region_track_feats_dataset.region = (
region_track_feats_dataset.region.cat.remove_unused_categories()
)
return region_track_feats_dataset
@cache
def get_track_feature_subregion_dataset():
"""
Returns a dataframe with the track features for each track that only charted in one out of four hand-picked subregion
(Western Europe, Northern America, Eastern Asia, or Latin America and the Caribbean).
"""
charting_tracks_by_subregion = countries_charts.drop_duplicates(
subset=["id", "geo_subregion"]
)[["id", "geo_region", "geo_subregion"]].rename(
columns={"geo_region": "region", "geo_subregion": "subregion"}
)
tracks_charting_only_in_one_subregion = charting_tracks_by_subregion[
~charting_tracks_by_subregion.duplicated(keep=False, subset="id")
].reset_index(drop=True)
subregion_tracks_features = pd.merge(
track_feats, tracks_charting_only_in_one_subregion, on="id"
).set_index("id")
subregion_selection = subregion_tracks_features.copy().loc[
subregion_tracks_features.subregion.isin(
[
"Northern America",
"Latin America and the Caribbean",
"Western Europe",
"Eastern Asia",
]
)
]
subregion_selection.subregion = (
subregion_selection.subregion.cat.remove_unused_categories()
)
subregion_selection.region = (
subregion_selection.region.cat.remove_unused_categories()
)
return subregion_selection
if __name__ == "__main__":
print(get_track_feature_region_dataset())
| Sejmou/exploring-spotify-charts | data-collection-and-exploration/helpers/model.py | model.py | py | 3,256 | python | en | code | 2 | github-code | 36 |
34448705706 | """Test model file for users."""
from app.api.v1.models.user_models import UserModel, database
from .import BaseClass
class TestUserModel(BaseClass):
"""docstring for TestUserModel."""
def test_can_save_user(self):
"""Test if we can save a user."""
user = self.user1.save()
self.assertEqual(1, len(database.users))
self.assertTrue(isinstance(user, dict))
def test_can_delete_user(self):
"""Test suucessful deletion of user."""
self.user1.save()
self.assertEqual(1, len(database.users))
user = UserModel.get_all_user(id=1)
user.delete()
self.assertEqual(0, len(database.users))
def test_get_a_none_registered_user(self):
"""Test cannot get a non registerd user."""
user = UserModel.get(id)
self.assertEqual('User does not exist', user['message'])
def test_get_user(self):
"""Test successfully get a user."""
self.user1.save()
user = UserModel.get(id=1)
self.assertIsInstance(user, UserModel)
| Bakley/SendIT-Api-V1 | test/test_user_model.py | test_user_model.py | py | 1,054 | python | en | code | 0 | github-code | 36 |
16589607570 | import random
import requests
import codecs
import json
import re
import queue
import time
from threading import Thread
requests.packages.urllib3.disable_warnings()
proxy = '127.0.0.1:8888'
def sec():
while True:
headers = {
'Referer': 'https://www.achievemint.com/signup?referral=1&utm_campaign=YOaBLXQNLBg%3D%0A',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2767.4 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded'
}
try:
c = '{0}@gmail.com'.format(random.randint(999999,999999999999))
work = False
prozy = {
'http': proxy,
'https': proxy
}
s = requests.session()
r = s.get(
"http://tinyurl.com/k44xy3f",
verify=False,
timeout=6,
proxies=prozy,
headers=headers
)
auth = re.findall('authenticity_token" value="(.*?)"', r.text)[0]
va = re.findall('acceptedTos" type="checkbox" value="(.*?)"', r.text)[0]
r = s.post(
"https://www.achievemint.com/",
'utf8=%e2%9c%93&authenticity_token={0}&after_sign_up_path=&user[confirmation_token]=&user[signup_token]=&user[email]={1}&user[password]=dsfdsf@D&user[accepted_tos]=1&user[accepted_tos]={2}&button='.format(auth, c, va),
verify=False,
timeout=6,
proxies=prozy,
headers=headers
)
if 'Welcome to Achievemint!' in r.text:
print(1)
except:
pass
def main():
for _ in range(3):
worker = Thread(target=sec, args=())
worker.start()
if __name__ == '__main__':
main() | breitingerchris/public_code | Python/Achievemint/anker.py | anker.py | py | 1,509 | python | en | code | 0 | github-code | 36 |
40988144291 | from pathlib import Path
from typing import Any, Dict
import json
MockData = Dict[str, Any]
class Mock:
"""
A class that holds the `mock.json` file contents
"""
mock: MockData = {}
@staticmethod
def populate(mock_path: Path) -> None:
if not mock_path.exists():
raise Exception(f"Mock file {mock_path} does not exists!")
with mock_path.open("r") as f:
mock_data: MockData = json.load(f)
Mock.mock = mock_data
| viscript/Ox4Shell | lib/mock.py | mock.py | py | 490 | python | en | code | null | github-code | 36 |
19915052730 | """
Write a function that takes directory path, a file extension and an optional tokenizer.
It will count lines in all files with that extension if there are no tokenizer.
If a the tokenizer is not none, it will count tokens.
For dir with two files from hw1.py:
#>>> universal_file_counter(test_dir, "txt")
6
#>>> universal_file_counter(test_dir, "txt", str.split)
6
"""
import glob
import os
from pathlib import Path
from typing import Callable, Optional, TextIO
def tokenizer_generator(file_handler: TextIO, tok: Optional[Callable]) -> Generator[int, None, None]:
buffer = ""
char = " "
while True:
char = file_handler.read(1)
if not char:
yield 1 # buffer
break
buffer += char
if len(tok(buffer)) == 1:
continue
else:
yield 1 # tok(buffer)[0]
buffer = tok(buffer)[1]
def universal_file_counter(
dir_path: Path, file_extension: str, tokenizer: Optional[Callable] = None
) -> int:
counter = 0
for file in Path(dir_path).glob("*." + file_extension):
with open(file) as f:
if tokenizer is not None:
for token in tokenizer_generator(f, tokenizer):
counter += token
else:
counter += sum(1 for _ in f)
return counter
| Abbath90/python_epam | homework9/task3/file_counter.py | file_counter.py | py | 1,333 | python | en | code | 0 | github-code | 36 |
938934612 | import os
import json
class Settings:
def __init__(self, settings_directory, settings_default):
self.settings_directory = settings_directory
self.settings_default = settings_default
self.settings_file = os.path.join(self.settings_directory, "settings.json")
# Make sure a settings file with all expected values exists
self.__add_new_settings()
def __add_new_settings(self):
if not os.path.isdir(self.settings_directory):
os.makedirs(self.settings_directory)
settings = self.get_settings()
for key in self.settings_default:
try:
settings[key]
except KeyError:
self.set_setting(key, self.settings_default[key])
def save(self, settings) -> None:
with open(self.settings_file, "w") as file:
file.write(json.dumps(settings))
file.close()
def set_setting(self, key, value) -> None:
settings = self.get_settings()
settings[key] = value
self.save(settings)
def get_setting(self, setting: str) -> any:
with open(self.settings_file, "r") as file:
settings = json.loads(file.read())
try:
return settings[setting]
except KeyError:
return None
def get_settings(self) -> dict:
if os.path.isfile(self.settings_file):
with open(self.settings_file, "r") as file:
results = json.loads(file.read())
changed = False
if 'ftp_password' in results and results['ftp_password'] and len(results['ftp_password']) < 8:
results['ftp_password'] = self.settings_default['ftp_password']
changed = True
if 'ftp_username' in results and results['ftp_username'] and len(results['ftp_username']) < 5:
results['ftp_username'] = self.settings_default['ftp_username']
changed = True
if changed:
results['enable_ftp_server'] = False
self.save(results)
return results
return {}
| ChimeraOS/chimera | chimera_app/settings.py | settings.py | py | 2,180 | python | en | code | 189 | github-code | 36 |
37989832631 | """
Steps to run:
python python policy_list_report_scraper.py
Program written in Python 3
Program Output:
1 file:
Exported_data.csv - csv file that contains the policy list report data
Program Description:
Progam first fetches the ASP login page paramters - __VIEWSTATE, __VIEWSTATEGENERATOR,
etc and then inputs these paramters and the login credentials to login
Then the program stores cookie info and uses it along with the new page parameters
to access the policy list reports page.
The code then mimics the "Go" POST request with the date parameters (hardcoded)
along with other parameters to get the report details.
The export POST request is then performed using the new set of form paramters.
The response contains the final exported csv contents which are written to a csv file:
Exported_data.csv
"""
import sys
import requests
from bs4 import BeautifulSoup
import json
# Main Function
def main():
# Login credentials
credentials = dict()
credentials['username'] = 'sample'
credentials['password'] = 'sample'
print("Getting login session parameters to login")
# Home page URL
home_page_url = 'https://secure.financepro.net/financepro/default.aspx?company=deltafinance'
# Storing the session info
session = requests.Session()
response = session.get(home_page_url)
# Parsing the response using Beautiful Soup
soup = BeautifulSoup(response.content, 'html.parser')
# Storing 3 ASP web-page specific form parameters to use to login
viewstate = soup.select('input[name=__VIEWSTATE]')[0]['value']
viewstate_generator = soup.select('input[name=__VIEWSTATEGENERATOR]')[0]['value']
event_validation = soup.select('input[name=__EVENTVALIDATION]')[0]['value']
login_form_parameters = dict()
login_form_parameters['__VIEWSTATE'] = viewstate
login_form_parameters['__VIEWSTATEGENERATOR'] = viewstate_generator
login_form_parameters['__EVENTVALIDATION'] = event_validation
login_form_parameters['tblForm$txtUserName'] = credentials['username']
login_form_parameters['tblForm$txtPassword'] = credentials['password']
login_form_parameters['tblForm$btnLogin'] = 'Log In'
login_form_parameters['tblForm$txtCompanyCode'] = 'deltafinance'
# Storing the cookies post login
response = session.post(home_page_url, login_form_parameters)
cookies = session.cookies.get_dict()
# Logging in
response = requests.post(home_page_url, login_form_parameters)
print("Logged in")
# Hardcoded Policy list data parameters
policy_list_date_params = dict()
policy_list_date_params['Date_Activated_Start_Date'] = '8/1/2009'
policy_list_date_params['Date_Activated_End_Date'] = '8/31/2019'
policy_list_date_params['Date_Change_Status_Start_Date'] = '8/1/2019'
policy_list_date_params['Date_Change_Status_End_Date'] = '8/31/2019'
print("\nPolicy List Dates that will be used:\n")
for key, val in policy_list_date_params.items():
print(key, ":", val)
print("\nAccessing Policy List Report Page")
reports_home_url = 'https://secure.financepro.net/financepro/Reports/ReportsHome.aspx'
policy_list_url = 'https://secure.financepro.net/financepro/Reports/PolicyList.aspx'
response = session.get(policy_list_url, cookies=cookies)
soup = BeautifulSoup(response.content, 'html.parser')
script_tags = soup.find_all("script")
# Retrieving the form paramters to send in the POST request
# 16th script tag contains json form paramters to send in the POST request
parameters = script_tags[15].text
# Retaining only the relevant json form parameters
start_ind = parameters.find("JSON.parse")
end_ind = parameters.find('")', start_ind)
parameters = parameters[start_ind + len("JSON.parse") + 2:end_ind]
parameters = parameters.replace("\\", "")
policy_list_info_params = dict()
# Getting the ASP accounts web page session paramters
viewstate = soup.select('input[name=__VIEWSTATE]')[0]['value']
viewstate_generator = soup.select('input[name=__VIEWSTATEGENERATOR]')[0]['value']
event_validation = soup.select('input[name=__EVENTVALIDATION]')[0]['value']
print("Parameters retrieved for making to Go POST request")
# Storing paramters to get account details page
policy_list_info_params['__VIEWSTATE'] = viewstate
policy_list_info_params['__VIEWSTATEGENERATOR'] = viewstate_generator
policy_list_info_params['__EVENTVALIDATION'] = event_validation
policy_list_info_params['PolicyDateRange'] = 'rbPolicyActivation'
# The data parameters need to manually changed
policy_list_info_params['DateActivatedFilter$txtStartDate'] = policy_list_date_params['Date_Activated_Start_Date']
policy_list_info_params['DateActivatedFilter$txtEndDate'] = policy_list_date_params['Date_Activated_End_Date']
policy_list_info_params['DateChangeStatusFilter$txtStartDate'] = policy_list_date_params['Date_Change_Status_Start_Date']
policy_list_info_params['DateChangeStatusFilter$txtEndDate'] = policy_list_date_params['Date_Change_Status_End_Date']
policy_list_info_params['ddlAgent$ctlAjaxDropDown$hidSelectedItem'] = parameters
policy_list_info_params['ddlGroupBy'] = 'AgentName, AccountNumber'
policy_list_info_params['btnGo'] = 'Go'
# Mimicing the POST request on clicking the "Go" button
response = requests.post(policy_list_url, policy_list_info_params, cookies=cookies)
soup = BeautifulSoup(response.content, 'html.parser')
print("Go button POST request sent")
viewstate = soup.select('input[name=__VIEWSTATE]')[0]['value']
viewstate_generator = soup.select('input[name=__VIEWSTATEGENERATOR]')[0]['value']
event_validation = soup.select('input[name=__EVENTVALIDATION]')[0]['value']
policy_list_info_params['__VIEWSTATE'] = viewstate
policy_list_info_params['__VIEWSTATEGENERATOR'] = viewstate_generator
policy_list_info_params['__EVENTVALIDATION'] = event_validation
policy_list_info_params['__EVENTARGUMENT'] = 'EXPORT'
policy_list_info_params['__EVENTTARGET'] = 'Report'
policy_list_info_params.pop('btnGo', None)
print("Parameters retrieved for export csv POST request")
# HTTP POST request to export CSV data
response = requests.post(policy_list_url, policy_list_info_params, cookies=cookies)
soup = BeautifulSoup(response.content, 'html.parser')
# Response contains the exported CSV file
final_csv_output_string = str(soup).strip()
print("\nCSV File contents exported:\n")
print(final_csv_output_string)
final_csv_output_string += "\n"
# Writing the CSV contents to a CSV file
csv_file_name = "Exported_data.csv"
with open(csv_file_name, "w") as csv_file_handler:
csv_file_handler.write(final_csv_output_string)
print("\nCSV contents exported to file:")
print(csv_file_name)
print("\nLogging off")
# Log off page called with cookie info
log_off_url = 'https://secure.financepro.net/financepro/logoff.aspx'
response = requests.get(log_off_url, cookies=cookies)
final_url = 'https://www.deltafinanceoftexas.com/'
response = requests.get(final_url)
# Entry point of code
if __name__ == "__main__":
main()
| tebbythomas/Freelance_Projects | Web_Data_Extraction_Projects/J11_Finance_Pro_Policy_List_Report_Generator/Policy_List_Report/policy_list_report_scraper.py | policy_list_report_scraper.py | py | 7,187 | python | en | code | 1 | github-code | 36 |
74436898025 | t = int(input())
for _ in range(t):
n,m = [int(x) for x in input().split()]
a = []
for i in range(n):
a.append(input())
s = input()
l = len(s)
flag = 0
for i in range(l):
if(s[i] in a[i%n]):
f = a[i%n].index(s[i])
a[i%n] = a[i%n][:f]+a[i%n][f+1:]
else:
flag = 1
break
if flag == 0:
print('Yes')
else:
print('No')
| hamdan-codes/codechef-unrated-contests | HackCon_String Generation.py | HackCon_String Generation.py | py | 449 | python | en | code | 2 | github-code | 36 |
21138228098 | import os, sys
path = "outages/"
dirs = os.listdir(path)
total_count = 0
total_count2 = 0
for filename in dirs:
count = 0
count2 = 0
with open(path+filename, "r") as f:
lines = f.readlines()
for line in lines:
word = line.split(" ")
if word and word[0] == "Message-ID:":
count+=1
if word and word[0] == "In-Reply-To:":
count2+=1
print(filename+ " has " + str(count) + " posts.")
print(filename+ " has " + str(count2) + " repliess.")
total_count +=count
total_count2 +=count2
print("Total posts = " + str(total_count))
print("Total replies = " + str(total_count2))
'''
In-Reply-To:
''' | zhasun/CSE534Project | Data_Preprocessing/Tim/extract_and_assign_content/count_post.py | count_post.py | py | 617 | python | en | code | 0 | github-code | 36 |
9109984564 | from pwn import *
import struct
import re
def recvall(conn):
msg = b''
while True:
try:
new_block = conn.recv(timeout=1)
if new_block == b'':
break
msg += new_block
except EOFError as e:
break
return msg
def ret_to_main(pie_base_addr, conn):
payload = b'a'*0x2c
payload += struct.pack("<I", pie_base_addr + 0x11b9)
log.info("Sending payload to ret_main.")
log.info("Payload length : {}".format(hex(len(payload))))
conn.send(payload)
HOST = "chal.tuctf.com"
PORT = 30505
conn = remote(HOST, PORT)
msg = conn.recvline()
msg = conn.recvline()
msg = conn.recvline()
payload = b"a"*0x4
conn.send(payload)
#msg = recvall(conn)
msg = conn.recvline()
#recvall(conn)
msg = msg[10+len(payload):]
msg = msg[:-2]
print(msg)
print(len(msg))
leaks = re.findall(".{4}",msg)
print(leaks)
pie_base_addr = struct.unpack("<I",bytes(leaks[2]))[0] - 0x12ab
buffer_addr = struct.unpack("<I",bytes(leaks[0]))[0]
read_plt = pie_base_addr + 0x4000 + 0xc
msg = recvall(conn)
print(msg)
ret_to_main(pie_base_addr,conn)
msg = recvall(conn)
print(msg)
ret_to_main(pie_base_addr,conn)
msg =recvall(conn)
print(msg)
#conn.interactive()
#############NEW PAYLOAD#############
# Getting a libc.so inst addr (puts)
payload = b'a'*0x20
recvall(conn)
conn.send(payload)
msg = conn.recvline()
leaks = re.findall(".{4}",msg)
print(leaks)
leak_libc_inst_puts = struct.unpack("<I",bytes(leaks[10]))[0]
system_addr = leak_libc_inst_puts - 0x24f00
bin_sh_addr = leak_libc_inst_puts + 0xfbd6b
msg = recvall(conn)
print(msg)
ret_to_main(pie_base_addr,conn)
msg =recvall(conn)
print(msg)
ret_to_main(pie_base_addr,conn)
recvall(conn)
payload = b'b'*0x10
conn.send(payload)
msg = conn.recvline()
leaks = re.findall(".{4}",msg)
print(leaks)
unknown1 = struct.unpack("<I",bytes(leaks[13]))[0]
payload = b'a'*0x2c
payload += struct.pack("<I",system_addr)
payload += b'\xff'*4
payload += struct.pack("<I",bin_sh_addr)
#payload = b'a'*0x2c
#payload += struct.pack("<I", leak_libc_inst_puts)
#payload += b'\xff'*4
#payload += struct.pack("<I", pie_base_addr + 0x4000 + 0x18)
conn.send(payload)
msg = recvall(conn)
print(msg)
conn.send(payload)
#msg = recvall(conn)
#log.info(msg)
#print(hex(struct.unpack("<I",bytes(msg[:4]))[0]))
conn.interactive()
conn.close()
| Altelus1/Hacking_Adventures | TUCTF2019/pwn/leakalicious_prob/leakalicious_exploit.py | leakalicious_exploit.py | py | 2,287 | python | en | code | 0 | github-code | 36 |
477236470 | import io, os
from .comment_parser import CommentParser
from .create_parser import CreateParser
from .insert_parser import InsertParser
class Reader:
def __init__(self):
self._tables = {}
self._rows = {}
self._global_errors = []
self._global_warnings = []
self._parsing_errors = []
self._parsing_warnings = []
self._schema_errors = []
self._schema_warnings = []
self._matched = False
@property
def matched(self):
""" Public getter. Returns whether or not the content was successfully parsed
:returns: Whether or not parsing was successful
:rtype: bool
"""
return self._matched
@property
def parsing_errors(self):
""" Public getter. Returns a list of parsing errors
:returns: A list of parsing errors
:rtype: list
"""
return [] if self._parsing_errors is None else self._parsing_errors
@property
def parsing_warnings(self):
""" Public getter. Returns a list of parsing/table warnings
:returns: A list of parsing/table warnings
:rtype: list
"""
return [] if self._parsing_warnings is None else self._parsing_warnings
@property
def schema_errors(self):
""" Public getter. Returns a list of schema errors
:returns: A list of schema errors
:rtype: list
"""
return [] if self._schema_errors is None else self._schema_errors
@property
def schema_warnings(self):
""" Public getter. Returns a list of schema warnings
:returns: A list of schema warnings
:rtype: list
"""
return [] if self._schema_warnings is None else self._schema_warnings
@property
def global_errors(self):
""" Public getter. Returns a list of schema errors
:returns: A list of schema errors
:rtype: list
"""
return [] if self._global_errors is None else self._global_errors
@property
def global_warnings(self):
""" Public getter. Returns a list of schema warnings
:returns: A list of schema warnings
:rtype: list
"""
return [] if self._global_warnings is None else self._global_warnings
@property
def tables(self):
""" Public getter. Returns a list of table definitions
:returns: A list of table definitions
:rtype: dict[mygrations.formats.mysql.definitions.table]
"""
return self._tables
@property
def rows(self):
""" Public getter. Returns a dictionary containing a lists of rows by table name
:returns: A dictionary containing list of rows by table name
:rtype: {table_name: [mygrations.formats.mysql.defintions.row]}
"""
return self._rows
""" Helper that returns info about the current filename (if present) for error messages
:returns: Part of an error message
:rtype: string
"""
def _filename_notice(self):
if self.filename:
return ' in file %s' % self.filename
return ''
""" Reads the file, if necessary
Reader is a bit more flexible than the other parsers. It can accept a filename,
file-like object, or a string. This method handles that flexibility, taking
the input from the _parse method and extracting the actual contents no matter
what was passed in.
:returns: The data to parse
:rtype: string
"""
def _unpack(self, filename):
# be flexible about what we accept
# file pointer
self.filename = ''
if isinstance(filename, io.IOBase):
contents = filename.read()
# and an actual string
elif isinstance(filename, str):
# which could be a filename
if os.path.isfile(filename):
self.filename = filename
fp = open(filename, 'r')
contents = fp.read()
fp.close()
else:
contents = filename
else:
raise ValueError(
"Unknown type for filename: must be an ascii string, a filename, file pointer, or StringIO"
)
return contents
""" Main parsing loop: attempts to find create, insert, and comments in the SQL string
"""
def parse(self, filename):
data = self._unpack(filename)
# okay then! This is our main parsing loop.
c = 0
while data:
c += 1
if c > 10000:
raise ValueError("Exceeded max parse depth")
# never hurts
data = data.strip()
# now we are looking for one of three things:
# comment, create, insert
if data[:2] == '--' or data[:2] == '/*' or data[0] == '#':
parser = CommentParser()
data = parser.parse(data)
elif data[:6].lower() == 'create':
parser = CreateParser()
data = parser.parse(data)
self._tables[parser.name] = parser
elif data[:6].lower() == 'insert':
parser = InsertParser()
data = parser.parse(data)
if not parser.table in self._rows:
self._rows[parser.table] = []
self._rows[parser.table].append(parser)
else:
if self._global_errors is None:
self._global_errors = []
self._global_errors.append("Unrecognized MySQL command: %s%s" % (data, self._filename_notice()))
return data
self._matched = True
return data
| cmancone/mygrations | mygrations/formats/mysql/file_reader/reader.py | reader.py | py | 5,702 | python | en | code | 10 | github-code | 36 |
523657887 | #REGINALD HUEY TAN IAN JAY (S10239913) - IT01 (P01)
#============================== IMPORTING RESOURCES ===============================
import random, math, time
import os, asyncio
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" #hide pygame initialisation message
from pygame import mixer
from S10239913E_Assignment_gameData import game_vars, defender_list, monster_list, defenders, monsters, alphabet, field, turnEvents
#=============================== GAME FUNDAMENTALS ================================
def initialize_game(): #Initializes all the game variables for a new game
game_vars['turn'] = 1
game_vars['monster_kill_target'] = 20
game_vars['monsters_killed'] = 0
game_vars['num_monsters'] = 0
game_vars['gold'] = 10
game_vars['threat'] = 10
game_vars['max_threat'] = 10
game_vars['danger_level'] = 1
def show_main_menu(): #Displays the main menu & all of its options
print()
print(f'{" MAIN MENU ":-^55}') #f-formatting to show header of main menu
print("1. Start new game 2. Load saved game")
print("3. Alter game options 4. Show unit information")
print("5. Timed Game Mode 6. Quit game")
print('-' * 55) #f-formatting to end start of main menu
def show_combat_menu(game_vars, back): #Displays the main menu & all of its options
if back == False:
print(f' Turn {game_vars.get("turn")} \t Threat = {threat_bar(game_vars)} \t Danger Level = {game_vars.get("danger_level")}') #Displays game status: Turn, Threat Metre, Danger Level
print(f' Gold = {game_vars.get("gold")} \t Monsters killed = {game_vars.get("monsters_killed")}/{game_vars.get("monster_kill_target")}') #Displays game status: Gold, Number of Monster Kills out of the Target Monster Kills
print()
print(f'{" COMBAT MENU ":-^55}') #f-formatting to show header of combat menu
print("1. Buy unit 2. End turn")
print("3. Upgrade Archers 4. Upgrade Walls")
print("5. Save game 6. Quit")
print('-'*55) #f-formatting to show end of combat menu
def alter_game_options(): #function to display alter game options menu
print(f'{" ALTER GAME OPTIONS ":-^55}') # f-formatting to show header of alter game options menu
print("1. Field Size 2. Defender Spawn Area")
print("3. Number of Kills to Win 4. Gold Increase per Turn")
print('-' * 55) # f-formatting to end start of alter game options menu
def draw_field(field): #Draws the field of play
columnHeader, divisor = '', ' +'
for i in range(game_vars.get('defender_spawn_boundary', 3)): columnHeader += f'{i+1:6}' #concatenates a string to be the headers for the columns (1,2,3)
fieldLength, fieldWidth = len(field[0]), len(field) #declaring dimensions of field
for j in range(fieldLength): divisor += '-----+' #for loop to concatenate a string to be the horizontal divisor
print(f'{columnHeader}\n{divisor}') #outputs the column headers and 1 horizontal divisor
for lane in range(fieldWidth): #iterates through field with iterator, lane
nameLane, hpLane = f'{alphabet[lane]} |', f' |' #declares 2 strings, one for unit name, and one for unit hp
for tile in range(fieldLength): #nested loop to iterate through lane with iterator, tile
if field[lane][tile] == [None, None]: #checks that tile is emptyr
nameLane += f'{"":5}|' #adds 5 blank spaces to unit name string since tile is empty
hpLane += f'{"":5}|' #adds 5 blank spaces to unit hp string since tile is empty
else: #tile is not empty
nameLane += f'{field[lane][tile][0]:5}|' #adds name to unit name string using f-formatting to centralise name in string
hpLane += f'{field[lane][tile][1]:^5}|' #adds hp to unit hp string using f-formatting to centralise hp in string
print(f'{nameLane}\n{hpLane}\n{divisor}') #outputs the unit name string, creates a new line, outputs the unit hp string, creates a new line, outputs 1 horizontal divisor
def quit_game():
#Function prints a default message whenever game is quit
print('\nTHANKS FOR PLAYING! :)')
print('CLOSING GAME', end='')
time.sleep(0.25)
for i in range(3): #loop to add a . to "CLOSING GAME" every 0.25s, gives a sense of progression
print('.', end='')
time.sleep(0.25)
print()
quit() #Exits code in interpreter
#================================ GAME SAVE & LOAD ================================
def save_game(): #Saves the game in the file 'save.txt'
save_file = open("save.txt", "w")
save_file.write(f'{game_vars["turn"]+1}\n') #stores game variable "turn" in 'save.text'
save_file.write(f'{game_vars["monster_kill_target"]}\n') #stores game variable "monster_kill_target" in 'save.text'
save_file.write(f'{game_vars["monsters_killed"]}\n') #stores game variable "monsters_killed" in 'save.text'
save_file.write(f'{game_vars["num_monsters"]}\n') #stores game variable "num_monsters" in 'save.text'
save_file.write(f'{game_vars["gold"]}\n') #stores game variable "gold" in 'save.text'
save_file.write(f'{game_vars["threat"]}\n') #stores game variable "threat" in 'save.text'
save_file.write(f'{game_vars["max_threat"]}\n') #stores game variable "max_threat" in 'save.text'
save_file.write(f'{game_vars["danger_level"]}\n') #stores game variable "danger_level" in 'save.text'
for lane in range(len(field)): #for loop that iterates through each tile in field, saving the tile data in a specified format
for tile in range(len(field[0])):
if field[lane][tile] is not None:
save_file.write(f'{lane}|{tile}|{field[lane][tile][0]}|{field[lane][tile][1]}')
save_file.write('\n')
save_file.close()
print("GAME SAVED")
def load_game(game_vars): #Loads the game data from 'save.txt'
filename = 'save.txt'
save_file = open(filename, "r")
firstLine = save_file.readline() #stores first line of file in case it needs to be used multiple times
if firstLine == '': #check if file is empty
print(f'FILE <{filename}> IS EMPTY')
quit_game()
else:
print('LOADING SAVED GAME', end='')
time.sleep(0.25)
for i in range(3): #loop to add a . to "LOADING SAVED GAME" every 0.25s, gives a sense of progression
print('.', end='')
time.sleep(0.25)
print()
game_vars["turn"] = int(firstLine) #stores game variable "turn" in game_vars dictionary
game_vars["monster_kill_target"] = int(save_file.readline()) #stores game variable "monster_kill_target" in game_vars dictionary
game_vars["monsters_killed"] = int(save_file.readline()) #stores game variable "monsters_killed" in game_vars dictionary
game_vars["num_monsters"] = int(save_file.readline()) #stores game variable "num_monsters" in game_vars dictionary
game_vars["gold"] = int(save_file.readline()) #stores game variable "gold" in game_vars dictionary
game_vars["threat"] = int(save_file.readline()) #stores game variable "threat" in game_vars dictionary
game_vars["max_threat"] = int(save_file.readline()) #stores game variable "max_threat" in game_vars dictionary
game_vars["danger_level"] = int(save_file.readline()) #stores game variable "danger_level" in game_vars dictionary
for line in save_file: #nested loop that iterates line by line through save.txt and obtains field data
line = line.strip("\n")
item = line.split("|")
if [item[2], item[3]] == ['None', 'None']:
field[int(item[0])][int(item[1])] = [None, None]
else:
field[int(item[0])][int(item[1])] = [item[2], item[3]]
save_file.close()
#=================================== GAME LOGIC ===================================
def navigate_main_menu(choice, field): #Function to navigate main menu
if choice == 1: #check to start new game
initialize_game() #reset the game variables data to ensure a new game
run_game(game_vars, field, monster_list, turnEvents) #begin the game, incrememnting by turns and ending when the monsters killed is equal to the monster kills target
elif choice == 2: #load most recent saved game
load_game(game_vars)
run_game(game_vars, field, monster_list, turnEvents) #begin the game, incrememnting by turns and ending when the monsters killed is equal to the monster kills target
elif choice == 3:
alter_game_options()
while True:
choice = get_input('alter-game-settings')
if choice == 1: #change field size
field = change_field_size()
draw_field(field)
elif choice == 2: game_vars['defender_spawn_boundary'] = get_input('defender-spawn-area') #change defender spawn boundary
elif choice == 3: game_vars['monster_kill_target'] = get_input('kills-to-win') #change number of kills required to win
elif choice == 4: game_vars['gold_increase_by_turn'] = get_input('gold_increase_by_turn') #change the gold increase every turn
playGame = get_input('play-game')
if playGame == True: break #start game or alter more settings
if playGame == False: alter_game_options()
run_game(game_vars, field, monster_list, turnEvents) #begin the game, incrememnting by turns and ending when the monsters killed is equal to the monster kills target
elif choice == 4: unit_information(defenders, monsters)
elif choice == 5:
game_vars['timed'] = get_input('timed')
if game_vars['timed'] == True: print('TIMED MODE - ON')
else: print('TIMED MODE - OFF')
elif choice == 6: quit_game() #quit game
def navigate_combat_menu(choice): #Function to navigate combat menu
if choice == 1: buy_unit() #allows player to choose which unit they want to buy and where to place it
elif choice == 3: upgrade_archers(game_vars, field, turnEvents)
elif choice == 4: upgrade_walls(game_vars, field, turnEvents)
elif choice == 5:
save_game() # saves game progress in 'save.txt'
quit_game() # calls function to close game
elif choice == 6: quit_game() # calls function to close game
elif choice == 2: pass # end turn
def check_spawn(game_vars): #function to check spawn requirements
if game_vars.get('threat') >= game_vars.get('max_threat'): #checks if the threat level is greater than the maximum threat level
game_vars['threat'] -= game_vars.get('max_threat')
return True #returns True, which is used to confirm the spawn of monsters when function is called
elif game_vars['num_monsters'] == 0: return True #returns True, which is used to confirm the spawn of monsters when function is called
else: return False #returns False, which prevents the spawn of monsters when function is called
def check_place(field, placement):
selectedLane, selectedTile = alphabet.index(placement[0]), int(placement[1]) #obtains data on placement argument
if field[selectedLane][selectedTile-1] == [None, None]: return True #checks if the placement tile is empty
else: return False
def buy_unit(): #function to handle the purchasing
i = 0
for unit, info in defenders.items(): # loop to iterate through defenders dictionary
print(
f'{i + 1}. {info.get("name").capitalize():6} {"-" * 15} {info.get("price")} Gold') # outputs unit number, unit name, and unit cost
i += 1 # counts for unit number
print(
f"{i + 1}. Don't Purchase") # outputs a 'cancel' option that allows user to not purchase anything and skip the turn
choice = get_input('buy-unit') # obtains validated input on which unit to buy
flag = True
while True:
if choice <= len(defender_list) and flag is True: # checks if user purchased a defender
unitName = defender_list[choice - 1]
if game_vars["gold"] < defenders[unitName].get("price"):
print('NOT ENOUGH GOLD') # validates if there is enough gold
show_combat_menu(game_vars, True)
else:
game_vars["gold"] -= defenders[unitName].get("price")
for unit, info in defenders.items(): # loop to obtain unit name and max hp for placing
if unitName == unit:
hp = f"{info.get('maxHP')}/{info.get('maxHP')}"
break
place_unit(field, unitName, hp)
break
elif choice == len(
defender_list) + 1: # changes option number for dont purchase depending on number of defenders
print('NO PURCHASE') # checks if user cancelled purchase
show_combat_menu(game_vars, True) # displays combat menu again
flag = False
choice = get_input('combat') # obtains validated input on combat menu navigation
if choice == 2: break # special exception for end turn
navigate_combat_menu(choice) # calls function to navigate combat menu
def place_unit(field, unitName, hp): #function to check if user-chosen placement space is available
while True:
placement = get_input('place-unit') # obtains validated input on where to place unit
if check_place(field, placement) == True: # if True, defender will be placed there
selectedLane, selectedTile = alphabet.index(placement[0]), int(placement[1])
field[selectedLane][selectedTile - 1] = [unitName, hp] # changes placement tile data
break
else:
print('POSITION ERROR: POSITION ALREADY OCCUPIED') # outputs error message if the placement tile is already occupied
def spawn_monster(field, monster_list, turnEvents): #function to spawn in monsters
while True: #infinite loop to check if position is empty
spawnPosition = random.randint(0,len(field)-1) #generates a random number within the number of lanes
placement = f'{alphabet[spawnPosition]}{len(field[0])}'
if check_place(field, placement) == True: #calls function, check_place(), to verify that placement tile is empty
selectedLane = alphabet.index(placement[0])
monsterName = monster_list[random.randint(0,len(monster_list)-1)] #generates a monster from monster_list
hp = f"{monsters[monsterName].get('maxHP')}/{monsters[monsterName].get('maxHP')}" #generates the monster at full HP
field[selectedLane][-1] = [monsterName, hp] #replaces the placement tile with randomly generated monster name and monster HP
break
game_vars['num_monsters'] += 1 #adds to the total number of monsters alive on the field
turnEvents += [f'A monster has spawned in Lane {alphabet[selectedLane]}'] #adds string to turnEvents to be output as a turn event
def monster_advance(field, turnEvents): #function that advances monster & deals damage
for lane in field: #iterates through field
for tile in lane:
if tile[0] in monster_list:
speed = monsters[tile[0]].get('moves') #obtains how many tiles a monster can move at once from monsters dictionary
monsterPosition = tile
i, j = lane.index(tile) - speed, lane.index(tile) #intended tile to advance to, current tile
flag = False
for index in range(j-i):
if lane[i + index][0] in defender_list:
flag = True
break
if flag is False and i < 0:
game_vars['game_lost'] = True
game_vars['monster_end_game'] = monsters[tile[0]].get("name")
for index in range(j - i):
if lane[i + index][0] in defender_list:
monsterDamage = random.randint(monsters[tile[0]].get('min_damage'), monsters[tile[0]].get('max_damage'))
if tile[0] == 'ZOMBI': #special string for zombies, as they bite
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition)+1} bites {defenders[lane[i][0]].get("name")} for {monsterDamage} damage!'] #adds string to turnEvents to be output as a turn event
else:
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition) + 1} hits {defenders[lane[i+index][0]].get("name")} for {monsterDamage} damage!'] #adds string to turnEvents to be output as a turn event
unitTotalHp = lane[i+index][1].split('/')
unitHp = int(unitTotalHp[0])
unitHp -= monsterDamage
if unitHp <= 0: #checks if the defender died to monster
turnEvents += [f'{defenders[lane[i+index][0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition) + 1} was slain by {monsters[tile[0]].get("name")}'] #adds string to turnEvents to be output as a turn event
lane[i+index] = [None, None] #resets the tile
lane[i+index], lane[j] = lane[j], lane[i+index] # swaps tiles to advance monster
else: #change the defender HP after being attacked
unitTotalHp = f'{unitHp}/{defenders[lane[i+index][0]].get("maxHP")}'
lane[i+index][1] = unitTotalHp
elif lane[i][0] in monster_list and lane[j][0] in monster_list: #monster is blocked by a monster in front
if lane[i + index][0] is None:
lane[i + index], lane[j] = lane[j], lane[i + index] # swaps tiles to advance monster
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition) + 1} is blocked from advancing!'] # adds string to turnEvents to be output as a turn event
break
else: #advance monster by speed
if lane[i][0] in monster_list and lane[j][0] in monster_list: #checks if the unit in tiles are monsters
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition) + 1} is blocked from advancing'] #adds string to turnEvents to be output as a turn event
else: #monster can advance
if monsters[tile[0]].get("moves") > 1:
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition)+1} advances by {monsters[tile[0]].get("moves")} spaces!'] #adds string to turnEvents to be output as a turn event
else:
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition) + 1} advances!'] #adds string to turnEvents to be output as a turn event
lane[i + index], lane[j] = lane[j], lane[i + index] # swaps tiles to advance monster
break
def defender_attack(field, turnEvents): #function to handle the attacks of the defenders
for lane in field: #iterates through field
defenderName, damageDealt = '', 0 #protects code from crashes due to undeclared variables
for defenderTile in lane[:game_vars.get('defender_spawn_boundary', 3)]: #iterates through the defenders spawn area
if defenderTile[0] in defender_list: #checks if the iterated tile is a defender
if defenderTile[0] == 'CANON':
defenderName = defenders[defenderTile[0]].get('name')
damageDealt = random.randint(defenders[defenderTile[0]].get('min_damage'), defenders[defenderTile[0]].get('max_damage'))
for monsterTile in lane: #iterates through lane to detect first monster
if monsterTile[0] in monster_list: # checks if the iterated tile is a monster
if damageDealt != 0 and defenderName != '': # prevents turn events that show 0 damage was done
if defenderName == 'Cannon':
turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} shot a cannonball at {monsters[monsterTile[0]].get("name")} for {damageDealt} damage!'] # adds string to turnEvents to be output as a turn event
if game_vars.get('turn') % 2 == 0:
hp = monsterTile[1].split('/') # obtains the HP of unit
monsterHp = int(hp[0]) - damageDealt # subtracts damage dealt from unit HP
if monsterHp <= 0: # MONSTER DIES
turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} slays {monsters[monsterTile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterTile) + 1}!']
turnEvents += [f'You gain {monsters[monsterTile[0]].get("reward")} gold for slaying a {monsters[monsterTile[0]].get("name")}!']
game_vars['monsters_killed'] += 1 # increases monsters_killed game variable by 1 every time a monster is killed
game_vars['gold'] += monsters[monsterTile[0]].get('reward') # increases gold game variable by monster reward every time a monster is killed
game_vars['threat'] += monsters[monsterTile[0]].get('reward') # increases threat level game variable by monster reward every time a monster is killed
spawn_monster(field, monster_list, turnEvents) # spawns a new monster to compensate for death of monster
game_vars['num_monsters'] -= 1 # decreases total number of monsters by 1 every time a monster is killed
monsterTile[0], monsterTile[1] = None, None # resets the tile to be empty
else:
monsterTile[1] = f'{str(monsterHp)}/{hp[1]}' # changes the tile data to show the monster HP after being damaged
chance = random.randint(0,1)
if chance == 1: #knockback monsters in lane by 1
for index in range(len(lane)):
if lane[index][0] in monster_list and lane[index+1][0] is None:
lane[index+1] = lane[index]
lane[index] = [None, None]
break
break
else:
defenderName = defenders[defenderTile[0]].get('name')
damageDealt = random.randint(defenders[defenderTile[0]].get('min_damage'), defenders[defenderTile[0]].get('max_damage'))
for monsterTile in lane: #iterates through lane to detect first monster
if monsterTile[0] in monster_list: #checks if the iterated tile is a monster
if damageDealt != 0 and defenderName != '': #prevents turn events that show 0 damage was done
if defenderName == 'Archer': turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} fires an arrow at {monsters[monsterTile[0]].get("name")} for {damageDealt} damage!'] #adds string to turnEvents to be output as a turn event
elif defenderName == 'Ninja': turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} throws a shuriken at {monsters[monsterTile[0]].get("name")} for {damageDealt} damage!'] #adds string to turnEvents to be output as a turn event
else: turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} deals {damageDealt} damage to {monsters[monsterTile[0]].get("name")}!'] #adds string to turnEvents to be output as a turn event
hp = monsterTile[1].split('/') #obtains the HP of unit
monsterHp = int(hp[0]) - damageDealt #subtracts damage dealt from unit HP
if monsterHp <= 0: # MONSTER DIES
turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} slays {monsters[monsterTile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterTile) + 1}!']
turnEvents += [f'You gain {monsters[monsterTile[0]].get("reward")} gold for slaying a {monsters[monsterTile[0]].get("name")}!']
game_vars['monsters_killed'] += 1 #increases monsters_killed game variable by 1 every time a monster is killed
game_vars['gold'] += monsters[monsterTile[0]].get('reward') #increases gold game variable by monster reward every time a monster is killed
game_vars['threat'] += monsters[monsterTile[0]].get('reward') #increases threat level game variable by monster reward every time a monster is killed
spawn_monster(field, monster_list, turnEvents) #spawns a new monster to compensate for death of monster
game_vars['num_monsters'] -= 1 #decreases total number of monsters by 1 every time a monster is killed
monsterTile[0], monsterTile[1] = None, None #resets the tile to be empty
else: monsterTile[1] = f'{str(monsterHp)}/{hp[1]}' #changes the tile data to show the monster HP after being damaged
break
def run_game(game_vars, field, monster_list, turnEvents): #runs game, each iteration counts as 1 turn
while True: #infinite loop, each iteration of the loop counts as 1 turn
if game_vars.get('game_lost') is True: #checks if game has been lost
print(f'A {game_vars["monster_end_game"]} has reached the city! All is lost!')
print('You have lost the game :(')
quit_game() #calls function to close game
if game_vars['timed'] is True:
start_time = time.time()
if check_spawn(game_vars) is True: spawn_monster(field, monster_list, turnEvents) #spawns a monster if spawn conditions are met
defender_attack(field, turnEvents) #defenders attack monsters
game_transcript(turnEvents) #outputs all of the events that occured over the turn
if game_vars.get('monsters_killed') >= game_vars.get('monster_kill_target'): #checks if game has been won
print('You have protected the city! You win!')
quit_game() #calls function to close game
draw_field(field) #displays updated field
show_combat_menu(game_vars, False) #displays combat menu
choice = get_input('combat') #obtains validated user input to use for combat menu navigation
navigate_combat_menu(choice) #calls function to navigate combat menu
monster_advance(field, turnEvents)
if game_vars['timed'] is True:
end_time = time.time()
if timer(start_time, end_time) > 12.5:
if game_vars.get('time_out_chance') == 0:
print('You ran out of time!')
print('You have lost the game :(')
quit_game() # calls function to close game
else:
game_vars['time_out_chance'] -= 1
print('You ran out of time!')
print(f'{game_vars.get("time_out_chance")} chances left!')
game_vars['turn'] += 1 #increases game variable 'turn' by 1
game_vars['gold'] += game_vars.get('gold_increase_by_turn') #increases game variable 'gold' by the game variable 'gold_increase_by_turn'
game_vars['threat'] += random.randint(1, game_vars.get('danger_level')) #increases threat level by a random number between 1 and danger level (inclusive)
if (game_vars.get('turn') % 12) == 0 and (game_vars.get('turn') != 0): #checks if conditions are met for a danger level increase
danger_level_increase(game_vars, turnEvents)
#=========================== EXTRA & ADVANCED FUNCTIONS ===========================
def timer(start, end): #function to record time taken for something (can only be used one at a time as there is no threading)
sec = math.floor(end - start)
return sec
def change_field_size(): #changes number of lanes and number of tiles per lane
field = []
dimensions = get_input('change-field-size') #return as a list instead of string in case of double digit dimensions
fieldWidth, fieldLength = dimensions[0], dimensions[1]
for i in range(fieldWidth): #iterates the number of times the player defined the number of lanes in field
row = [] #declares an empty lane for every iteration of a lane
for j in range(fieldLength): row.append([None, None]) #iterates the number of times the player defined the length of each lane
field.append(row) #adds the updated lane for every iteration of a lane
return field #outputs the new player-defined field
def threat_bar(game_vars): #concatenates strings to form the threat bar used in combat menu game status
threatLevel = '['
threatLevel += '-' * game_vars.get('threat', 0) #.get() second parameter to handle data file errors
threatLevel += ' ' * (game_vars.get('max_threat', 10) - game_vars.get('threat', 0)) #.get() second parameter to handle data file errors
threatLevel += ']'
return threatLevel
def upgrade_archers(game_vars, field, turnEvents): #function to upgrade archers
if game_vars['gold'] >= defenders['ARCHR']['upgrade_cost']:
game_vars['gold'] -= defenders['ARCHR']['upgrade_cost']
defenders['ARCHR']['maxHP'] += 1
defenders['ARCHR']['min_damage'] += 1
defenders['ARCHR']['max_damage'] += 1
defenders['ARCHR']['upgrade_cost'] += 2
defenders['ARCHR']['level'] += 1
turnEvents += [f"Archers upgraded to Level {defenders['ARCHR'].get('level', 1)}!"] # adds string to turnEvents to be output as a turn event
for lane in field:
for tile in lane:
if tile[0] == 'ARCHR':
unitHp = tile[1].split('/')
tile[1] = f'{int(unitHp[0])+1}/{defenders["ARCHR"].get("maxHP")}'
else:
print('NOT ENOUGH GOLD')
show_combat_menu(game_vars, True)
def upgrade_walls(game_vars, field, turnEvents): #function to upgrade walls
if game_vars['gold'] >= defenders['WALL']['upgrade_cost']:
game_vars['gold'] -= defenders['WALL']['upgrade_cost']
defenders['WALL']['maxHP'] += 5
defenders['WALL']['upgrade_cost'] += 2
defenders['WALL']['level'] += 1
turnEvents += [f"Walls upgraded to Level {defenders['WALL'].get('level', 1)}!"] # adds string to turnEvents to be output as a turn event
for lane in field:
for tile in lane:
if tile[0] == 'WALL':
unitHp = tile[1].split('/')
tile[1] = f'{int(unitHp[0]) + 5}/{defenders["WALL"].get("maxHP")}'
else:
print('NOT ENOUGH GOLD')
show_combat_menu(game_vars, True)
def unit_information(defenders, monsters): #function to output all information on both defenders and monsters
print(f'{"Defenders":~^55}', end='')
for unit, unitInfo in defenders.items():
print()
print(f'Name: {unitInfo.get("name")}')
print(f'CodeName: {unit}')
print(f'Full HP: {unitInfo.get("maxHP")}')
print(f'Min-Max Damage: {unitInfo.get("min_damage")}-{unitInfo.get("max_damage")} ')
print(f'Price: {unitInfo.get("price")}')
print(f'{"Monsters":~^55}', end ='')
for unit, unitInfo in monsters.items():
print()
print(f'Name: {unitInfo.get("name")}')
print(f'CodeName: {unit}')
print(f'Full HP: {unitInfo.get("maxHP")}')
print(f'Min-Max Damage: {unitInfo.get("min_damage")}-{unitInfo.get("max_damage")} ')
print(f'Speed: {unitInfo.get("moves")}')
print(f'Rewards: {unitInfo.get("rewards")}')
print('~' * 55)
def get_input(menuClass): #function to obtain input and validate it, menuClass parameter identifies which input it is obtaining and validating accordingly, depending on function arguments
x = 1
while True: #input loop
if menuClass == 'main' or menuClass == 'combat': choice = input('>>> Your choice: ')
elif menuClass == 'buy-unit': choice = input('>>> Unit to Purchase: ')
elif menuClass == 'place-unit': choice = input('>>> Position to Place Unit: ')
elif menuClass == 'alter-game-settings': choice = input('>>> Your choice: ')
elif menuClass == 'change-field-size':
while True:
fieldWidth = input('>>> Number of Lanes: ')
if fieldWidth.isnumeric() is not True: print('INPUT TYPE ERROR: NUMBER OF LANES SHOULD BE A NUMBER')
elif int(fieldWidth) == 0: print('RANGE ERROR: NUMBER OF LANES CANNOT BE 0')
elif int(fieldWidth) < 3: print('RANGE ERROR: NUMBER OF LANES CANNOT BE LESS THAN 3')
elif int(fieldWidth) > 26: print('RANGE ERROR: NUMBER OF LANES CANNOT BE GREATER THAN 26')
else: break
while True:
fieldLength = input('>>> Number of Tiles in Each Lane: ')
if fieldLength.isnumeric() is not True: print('INPUT TYPE ERROR: NUMBER OF TILES PER LANE SHOULD BE A NUMBER')
elif int(fieldLength) == 0: print('RANGE ERROR: NUMBER OF TILES PER LANE CANNOT BE 0')
elif int(fieldLength) < 5: print('RANGE ERROR: NUMBER OF TILES PER LANE CANNOT BE LESS THAN 5') #CHANGE LATER
else: break
elif menuClass == 'defender-spawn-area': boundary = input('>>> New Furthest Tile for Defender Spawn: ')
elif menuClass == 'kills-to-win': kills = input('>>> New Monster Kills Target: ')
elif menuClass == 'gold_increase_by_turn': gold = input('>>> New Gold Increase per Turn: ')
elif menuClass == 'play-game': choice = input('>>> Start Game? [Y/n]: ')
elif menuClass == 'timed': time = input('>>> Timed Mode? [On/Off]: ')
else: #in case function is called with an incorrect menuClass, prevents crashes with expansion of program
print('PROGRAM ERROR: "menuClass" VARIABLE UNDETECTED')
menuClass = input('>>> PLEASE MANUALLY INPUT "menuClass" VARIABLE: ')
if x == 3:
print('\nGAME SHUT DOWN DUE TO REPEATED ERROR', end='')
quit_game()
x += 1
if menuClass == 'main': #data validation for main menu
if not choice.isnumeric():
print('TYPE ERROR: PLEASE ENTER A NUMBER')
continue #prevents a ValueError because of the type casting on the next line
choice = int(choice)
if not (choice >= 1 and choice <= 6): print('RANGE ERROR: PLEASE ENTER A NUMBER BETWEEN 1 TO 6')
else:
output = choice
break
elif menuClass == 'combat': #data validation for combat menu
if not choice.isnumeric(): # check for number
print('INPUT TYPE ERROR: PLEASE ENTER A NUMBER')
continue #prevents a ValueError because of the type casting on the next line
choice = int(choice)
if not (choice >= 1 and choice <= 6): print('RANGE ERROR: PLEASE ENTER A NUMBER BETWEEN 1 TO 6')
else:
output = choice
break
elif menuClass == 'buy-unit': #data validation for purchasing defenders
if choice.isalpha() is True:
defenderFullName = []
for unit, info in defenders.items(): defenderFullName += [info.get('name').upper()] #loop to iterate through defenders dictionary and obtain names, capitalise them, and add them to the list, defenderFullName
if choice.upper() in defenderFullName:
output = defenderFullName.index(choice.upper()) + 1
break
else: print("INPUT ERROR: PLEASE ENTER UNIT NAME CORRECTLY")
elif choice.isnumeric():
output = int(choice)
if output <= len(defender_list): break
elif output == len(defender_list)+1: break
else: print("INPUT ERROR: PLEASE ENTER UNIT NUMBER CORRECTLY")
elif menuClass == 'place-unit': # data validation for placing of purchased defenders
if not choice.isalnum():
print('TYPE ERROR: PLEASE ENTER ALPHANUMERIC CHARACTERS')
else:
choice = choice.capitalize()
if len(choice) != 2:
print('LENGTH ERROR: PLEASE INPUT USING THE FOLLOWING FORMAT: LaneColumn (e.g. A1)')
elif (not choice[0].isalpha()) and (not choice[1].isnumeric()):
print('FORMAT ERROR: PLEASE INPUT USING THE FOLLOWING FORMAT: LaneColumn (e.g. A1)')
elif alphabet.index(choice[0]) >= alphabet.index(alphabet[len(field)]):
print(f'RANGE ERROR: PLEASE ENSURE LANE LETTER COMES BETWEEN A & {alphabet[len(field)-1]}')
elif int(choice[1]) > game_vars.get('defender_spawn_boundary', 3):
print(f'RANGE ERROR: PLEASE ENSURE SELECTED TILE IS BETWEEN 1 & {game_vars.get("defender_spawn_boundary", 3)} (INCLUSIVE)')
else:
output = choice
break
elif menuClass == 'alter-game-settings':
if not choice.isnumeric():
print('TYPE ERROR: PLEASE ENTER A NUMBER')
continue #prevents a ValueError because of the type casting on the next line
choice = int(choice)
if not (choice >= 1 and choice <= 4): print('RANGE ERROR: PLEASE ENTER A NUMBER BETWEEN 1 TO 4')
else:
output = choice
break
elif menuClass == 'change-field-size':
output = [int(fieldWidth), int(fieldLength)]
break
elif menuClass == 'defender-spawn-area':
if not boundary.isnumeric():
print('INPUT TYPE ERROR: PLEASE ENTER A NUMBER')
continue #prevents a ValueError because of the type casting on the next line
elif int(boundary) == 0: print('RANGE ERROR: DEFENDER SPAWN BOUNDARY CANNOT BE 0')
elif int(boundary) < 3: print('RANGE ERROR: DEFENDER SPAWN BOUNDARY CANNOT BE LESS THAN 3')
else:
output = int(boundary)
break
elif menuClass == 'kills-to-win':
if kills.isnumeric() is not True: print('INPUT TYPE ERROR: PLEASE INPUT A NUMBER')
elif int(kills) == 0:
print('RANGE ERROR: MONSTER KILLS TARGET CANNOT BE 0')
elif int(kills) < 5:
print('RANGE ERROR: MONSTER KILLS TARGET CANNOT BE LESS THAN 5')
else:
output = int(kills)
break
elif menuClass == 'gold_increase_by_turn':
if gold.isnumeric() is not True: print('INPUT TYPE ERROR: PLEASE INPUT A NUMBER')
elif int(gold) == 0: print('RANGE ERROR: GOLD INCREASE PER TURN CANNOT BE 0')
else:
output = int(gold)
break
elif menuClass == 'play-game':
if choice.isalpha() is not True: print('INPUT TYPE ERROR: PLEASE INPUT "YES" OR "NO"')
elif choice.upper() == 'YES' or choice.upper() == 'Y':
output = True
break
elif choice.upper() == 'NO' or choice.upper() == 'N':
output = False
break
else: print('INPUT ERROR: PLEASE INPUT "YES" OR "NO"')
elif menuClass == 'timed':
if time.isalpha() is not True: print('INPUT TYPE ERROR: PLEASE INPUT "ON" OR "OFF"')
elif time.upper() == 'ON':
output = True
break
elif time.upper() == 'NO':
output = False
break
else: print('INPUT ERROR: PLEASE INPUT "ON" OR "OFF"')
return output #returns user input after validation
def game_transcript(turnEvents): #outputs all the events that occured in a single turn
header = f' TURN {game_vars.get("turn")} EVENTS: ' #f-formatting to make the header for each time function is called
print(f'{header:~^55}') #f-formatting to show header of turn events
while turnEvents != []: #iterates through turnEvents while removing elements
print(turnEvents[0])
turnEvents.pop(0)
print('~' * 55) #f-formatting to show end of main menu
def danger_level_increase(game_vars, turnEvents): #changes game data every time danger level increases
game_vars['danger_level'] += 1 #increases game variable 'danger_level' by 1 every time the function is called
turnEvents += ['The evil grows stronger!'] #adds string to turnEvents to be output as a turn event
for mob in monster_list: #iterates through monster_list to obtain each element inside
monsters[mob]['maxHP'] += 1 #increases every monsters maximum HP by 1 every time the function is called
monsters[mob]['min_damage'] += 1 #increases every monsters minimum damage by 1 every time the function is called
monsters[mob]['max_damage'] += 1 #increases every monsters maximum damage by 1 every time the function is called
monsters[mob]['reward'] += 1 #increases every monsters reward by 1 every time the function is called
async def play_music(): #asynchronous function to play background music 'evolution.mp3'
mixer.init()
mixer.music.load("evolution.mp3")
mixer.music.set_volume(0.15)
mixer.music.play(10)
#================================= START PROGRAM ==================================
asyncio.run(play_music()) #running the asynchronous function for background music
print(f'{"="*55}\n{"Desperate Defenders":^55}\n{"Defend the city from undead monsters!":^55}\n{"="*55}') #display start of game header
while True:
show_main_menu() # show start menu options
choice = get_input('main') #obtain validated input to use as navigation
navigate_main_menu(choice, field)
#==================================== CREDITS =====================================
#Music I Used: https://www.bensound.com/free-music-for-videos
| klystrn/Tower-Defence-Game | towerDefence.py | towerDefence.py | py | 42,879 | python | en | code | 0 | github-code | 36 |
26290834166 | """Tests for common_utils.py."""
import common_utils
import pytest
class TestCommonUtils:
def testGetFilePathShouldRaiseError(self):
common_utils.input = lambda _: 'foo'
with pytest.raises(FileNotFoundError):
common_utils.get_file_path()
common_utils.input = input
def testGetFilePathShouldNotRaiseError(self, tmp_path):
directory = tmp_path / 'audio'
directory.mkdir()
file_path = directory / 'test.wav'
file_path.write_text('')
common_utils.input = lambda _: file_path
try:
common_utils.get_file_path()
assert True
except FileNotFoundError as err:
assert False, err
finally:
common_utils.input = input
| thompsond/PyAVMisc | com/AVMisc/common_utils_test.py | common_utils_test.py | py | 687 | python | en | code | 0 | github-code | 36 |
6296104681 | import requests
import urllib.parse
from models import PlayByPlay
from constants import headers
from db_utils import insert_many
class PlayByPlayRequester:
url = 'https://stats.nba.com/stats/playbyplayv2'
def __init__(self, settings):
self.settings = settings
self.settings.db.bind([PlayByPlay])
def create_ddl(self):
"""
Initialize the table schema.
"""
self.settings.db.create_tables([PlayByPlay], safe=True)
def fetch_game(self, game_id):
"""
Build GET REST request to the NBA for a game, iterate over
the results and return them.
"""
params = self.build_params(game_id)
# Encode without safe '+', apparently the NBA likes unsafe url params.
params_str = urllib.parse.urlencode(params, safe=':+')
response = requests.get(url=self.url, headers=headers, params=params_str).json()
# pulling just the data we want
player_info = response['resultSets'][0]['rowSet']
rows = []
# looping over data to return.
for row in player_info:
new_row = {
'game_id': row[0],
'event_num': row[1],
'event_msg_type': row[2],
'event_msg_action_type': row[3],
'period': row[4],
'wc_time': row[5],
'home_description': row[7],
'neutral_description': row[8],
'visitor_description': row[9],
'score': row[10],
'score_margin': row[11],
'player1_id': self.get_null_id(row[13]),
'player1_team_id': self.get_null_id(row[15]),
'player2_id': self.get_null_id(row[20]),
'player2_team_id': self.get_null_id(row[22]),
'player3_id': self.get_null_id(row[27]),
'player3_team_id': self.get_null_id(row[29])
}
rows.append(new_row)
return rows
def insert_batch(self, rows, player_id_set):
"""
Batch insertion of records.
"""
# It looks like the NBA API returns some bad data that
# doesn't conform to their advertized schema:
# (team_id in the player_id spot).
# We can maybe get away with ignoring it.
# Check if id is in player_id cache.
# We need to preserve the row in general becuase it could still have
# good data for the correctly returned players.
for row in rows:
for key in ['player1_id', 'player2_id', 'player3_id']:
if row[key] is not None and row[key] not in player_id_set:
row[key] is None
insert_many(self.settings, PlayByPlay, rows)
def build_params(self, game_id):
"""
Create required parameters dict for the request.
"""
return {
'EndPeriod': 6,
'GameId': game_id,
'StartPeriod': 1
}
def get_null_id(self, id):
"""
This endpoint will return a player's id or player's team id as 0
sometimes. We will store 'null', as 0 breaks the foriegn key
constraint.
"""
if id == 0:
return None
return id
| Promise-Igbo/nba-sql | stats/play_by_play.py | play_by_play.py | py | 3,273 | python | en | code | null | github-code | 36 |
36057963305 | lst = [10, 5, 2, 7, 4, 9, 12, 1, 15]
l = list()
r = list()
#print(len(lst))
#print(len(list)//2)
for i in range(0, (len(lst)//2)):
l.append(lst[i])
print(l.__len__())
print(len(l))
for i in range((len(lst)//2), len(lst)):
r.append(lst[i])
print(r)
| srikloud/PyProjects | Sorts/mergesort.py | mergesort.py | py | 261 | python | en | code | 0 | github-code | 36 |
23219260357 | import random
def get_random_word():
words = ["pizza", "cheese", "apples"]
word = words[random.randint(0, len(words)-1)]
return word
def show_word(word):
for character in word:
print(character, end="")
def play_word_game():
strikes = 0
max_strikes = 3
playing = True
word = get_random_word()
blanked_word = "_" * len(word)
while playing:
show_word(blanked_word)
letter = get_guess()
strikes += 1
if strikes >= max_strikes:
playing = False
if strikes >= max_strikes:
print("Loser!")
else:
print("Winner!")
print("Game started")
play_word_game()
print("Game over") | sizif/python-path-one | main.py | main.py | py | 723 | python | en | code | 0 | github-code | 36 |
71666166824 | # The following code was adapted from Week 3 Programming Assignment 2 in the Convolutional Neural Networks course by DeepLearning.AI offered on Coursera
# https://www.coursera.org/learn/convolutional-neural-networks/home/week/3
import tensorflow as tf
import numpy as np
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Conv2DTranspose
from tensorflow.keras.layers import concatenate
import os
import numpy as np
import pandas as pd
import imageio
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# load and split data
path = ''
image_path = os.path.join(path, './data/CameraRGB/')
mask_path = os.path.join(path, './data/CameraMask/')
image_list = os.listdir(image_path)
mask_list = os.listdir(mask_path)
image_list = [image_path+i for i in image_list]
mask_list = [mask_path+i for i in mask_list]
image_list_ds = tf.data.Dataset.list_files(image_list, shuffle=False)
mask_list_ds = tf.data.Dataset.list_files(mask_list, shuffle=False)
image_filenames = tf.constant(image_list)
masks_filenames = tf.constant(mask_list)
dataset = tf.data.Dataset.from_tensor_slices((image_filenames, masks_filenames))
# preprocess data
def process_path(image_path, mask_path):
img = tf.io.read_file(image_path)
img = tf.image.decode_png(img, channels=3)
img = tf.image.convert_image_dtype(img, tf.float32)
mask = tf.io.read_file(mask_path)
mask = tf.image.decode_png(mask, channels=3)
mask = tf.math.reduce_max(mask, axis=-1, keepdims=True)
return img, mask
def preprocess(image, mask):
input_image = tf.image.resize(image, (96, 128), method='nearest')
input_mask = tf.image.resize(mask, (96, 128), method='nearest')
return input_image, input_mask
image_ds = dataset.map(process_path)
processed_image_ds = image_ds.map(preprocess)
"""
This function implements the convolutional decoder block
"""
def upsampling_block(expansive_input, contractive_input, n_filters=32):
# expansive_input is the input from the previous layer
# contractive_input is the input from the previous skip layer
up = Conv2DTranspose(n_filters, 3, strides=2, padding='same')(expansive_input)
# merge the previous output and the contractive_input
merge = concatenate([up, contractive_input], axis=3)
conv = Conv2D(n_filters, 3, activation='relu', padding='same', kernel_initializer='HeNormal')(merge)
conv = Conv2D(n_filters, 3, activation='relu', padding='same', kernel_initializer='HeNormal')(conv)
return conv
"""
This function implements the U-Net model by combining the encoder and decoder paths
"""
def unet_model(input_size=(96, 128, 3), n_filters=32, n_classes=23):
# input_size is the shape of the input
# n_filters is the number of filters for convolutional layers
# n_classes is the number of output classes
inputs = Input(input_size)
# encoding path
cblock1 = conv_block(inputs, n_filters)
# the first element of the output of each block will be the input of the next block
# the number of filters at each new step doubles
cblock2 = conv_block(cblock1[0], n_filters*2)
cblock3 = conv_block(cblock2[0], n_filters*4)
cblock4 = conv_block(cblock3[0], n_filters*8, dropout_prob=0.3)
cblock5 = conv_block(cblock4[0], n_filters*16, dropout_prob=0.3, max_pooling=False)
# decoding path
ublock6 = upsampling_block(cblock5[0], cblock4[1], n_filters*8)
# the output of the previous block is the expansive_input and the corresponding encoder output skip connection is the contractive_input
# the number of filters at each new step halves
ublock7 = upsampling_block(ublock6, cblock3[1], n_filters*4)
ublock8 = upsampling_block(ublock7, cblock2[1], n_filters*2)
ublock9 = upsampling_block(ublock8, cblock1[1], n_filters)
conv9 = Conv2D(n_filters, 3, activation='relu', padding='same', kernel_initializer='he_normal')(ublock9)
conv10 = Conv2D(n_classes, 1, padding='same')(conv9)
model = tf.keras.Model(inputs=inputs, outputs=conv10)
return model
# set model dimensions
img_height = 96
img_width = 128
num_channels = 3
unet = unet_model((img_height, img_width, num_channels))
unet.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
"""
This function displays both the input image and the corresponding true mask (desired output)
"""
def display(display_list):
plt.figure(figsize=(15, 15))
title = ['Input Image', 'True Mask', 'Predicted Mask']
for i in range(len(display_list)):
plt.subplot(1, len(display_list), i+1)
plt.title(title[i])
plt.imshow(tf.keras.preprocessing.image.array_to_img(display_list[i]))
plt.axis('off')
plt.show()
# create prediction
def create_mask(pred_mask):
pred_mask = tf.argmax(pred_mask, axis=-1)
pred_mask = pred_mask[..., tf.newaxis]
return pred_mask[0]
# train the model
EPOCHS = 40
VAL_SUBSPLITS = 5
BUFFER_SIZE = 500
BATCH_SIZE = 32
processed_image_ds.batch(BATCH_SIZE)
train_dataset = processed_image_ds.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
print(processed_image_ds.element_spec)
model_history = unet.fit(train_dataset, epochs=EPOCHS)
"""
This function displays the input, prediction, and true images
"""
def show_predictions(dataset=None, num=1):
"""
Displays the first image of each of the num batches
"""
if dataset:
for image, mask in dataset.take(num):
pred_mask = unet.predict(image)
display([image[0], mask[0], create_mask(pred_mask)])
else:
display([sample_image, sample_mask,
create_mask(unet.predict(sample_image[tf.newaxis, ...]))])
# show results
show_predictions(train_dataset, 6)
# References
# [1] https://www.coursera.org/learn/convolutional-neural-networks/programming/omqTR/image-segmentation-with-u-net
| AndrewZhang126/Neural-Networks | U-Net.py | U-Net.py | py | 6,154 | python | en | code | 1 | github-code | 36 |
40083862973 | #!/usr/bin/env python3
import argparse
import random
import json
import re
import importlib.util
import os.path
import sys
import types
import inspect
import pandas as pd
import numpy as np
MAX_SLOT=8
SMART_COMMENT="\\s*#+\\s*(fastscore|odg)\\.(\\S*)\\s*:\\s*(\\S*)\\s*$"
def is_input_slot(s):
return s % 2 == 0
## Parse command line
parser = argparse.ArgumentParser()
parser.add_argument("source_file", metavar="MODEL")
parser.add_argument("-i", "--input:0", action="store", help="Name of the input file (slot 0)", metavar="FILE")
parser.add_argument("-o", "--output:1", action="store", help="Name of the output file (slot 1)", metavar="FILE")
parser.add_argument("-b", "--batch-size", action="store", type=int, default=10, help="Name of the output file (slot 1)", metavar="NUM")
#parser.add_argument("-v", "--verbose", action="store_true", help="Increase verbosity")
# Add more --input/--output options
for s in range(2,MAX_SLOT):
tag = "input" if is_input_slot(s) else "output"
parser.add_argument("--{}:{}".format(tag,s), action="store", help="Name of the {} file (slot {})".format(tag,s), metavar="FILE")
args = parser.parse_args()
def check_scope(scope):
if scope in ["$all", "$in", "$out"]:
return scope
else:
try:
return int(scope)
except ValueError:
print("Smart comment not recognized")
def default_scope(item):
if item == "recordsets":
return "$all"
elif item == "action":
return "$in"
elif item == "slot":
return "$all"
elif item == "schema":
return "$all"
else:
return None
def parse_comments1(line, slots):
if re.match(SMART_COMMENT, line):
tokens = re.split(SMART_COMMENT,line)
item0=tokens[2]
value=tokens[3]
x=item0.split(".")
item=x[0]
scope = check_scope(x[1]) if len(x) > 1 else default_scope(item)
for s in range(0,MAX_SLOT):
if scope is None:
continue
is_deprecated=False
if (scope == "$all" or
scope == "$in" and is_input_slot(s) or
scope == "$out" and not is_input_slot(s) or
scope == s):
if (item == "recordsets"):
if (value in ["both","none","input","output"]):
# deprecated style
if scope != "$all":
sys.exit("Invalid scope")
is_deprecated=True
if (s == 0 or s == 1):
if (value == "both"):
slots[s]['recordsets'] = True
elif (value == "none"):
slots[s]['recordsets'] = False
elif (value == "input"):
slots[s]['recordsets'] = (s == 0)
elif (value == "output"):
slots[s]['recordsets'] = (s == 1)
else:
# new style
flag = None
if (value == "true" or value == "yes"):
flag = True
elif (value == "false" or value == "no"):
flag = False
else:
sys.exit("Value '{}' not recognized (use 'true', 'false', 'yes', or 'no')".format(value))
slots[s]['recordsets']=flag
elif (item == "action"):
if not is_input_slot(s):
sys.exit("An action callback being assigned to an output slot {}".format(s))
slots[s]['action'] = None if (value == "unused") else value
# Any mention of a slot makes it active
if (value != "unused"):
if (not is_deprecated or s == 0 or s == 1):
slots[s]['active'] = True
if (item == "slot"):
if (value != "unused"):
sys.exit("Value '{}' not supported (set to 'unused' to disable the slot)".format(value))
slots[s]['active'] = False
def parse_comments():
slots = []
for s in range(0,MAX_SLOT):
slots.append({
'action': None,
'recordsets': False,
'active': False,
'file': None
})
if is_input_slot(s):
slots[s]['action'] = "action"
# By default, slots 0 and 1 are active
slots[0]['active'] = True
slots[1]['active'] = True
f = open(args.source_file)
for l in f:
parse_comments1(l, slots)
f.close()
return slots
model_slots = parse_comments()
# Collect all data-related options
for k in args.__dict__:
if (k.startswith("input:") or k.startswith("output:")):
s = int(k.split(":")[1])
data_file = args.__dict__[k]
if not data_file is None:
if (is_input_slot(s) and not os.path.isfile(data_file)):
sys.exit("{} not found".format(data_file))
model_slots[s]['file'] = data_file
# Either all or none input slots must have action set
all_actions=True
none_actions=True
for s in range(0,MAX_SLOT):
if (not is_input_slot(s)):
continue
if (model_slots[s]['action'] is None):
all_actions=False
else:
none_actions=False
if (not all_actions and not none_actions):
sys.exit("Either all input slots must have action callbacks set or none of them should")
# Check for dangling slots/files
for s in range(0,MAX_SLOT):
active=model_slots[s]['active']
data_file=model_slots[s]['file']
if (active and data_file is None and s != 0 and s != 1):
sys.exit("Model uses slot {} but there is no data file attached to it".format(s))
if (not active and not data_file is None):
sys.exit("Model does not use slot {} but the data file {} is attached to it".format(s,data_file))
inputs=[]
outputs=[]
for s in range(0,MAX_SLOT):
if not model_slots[s]['active']:
continue
if is_input_slot(s):
inputs.append({
'slot': s,
'seq_no': 1,
'conn': None,
'entry': None
})
else:
outputs.append({
'slot': s,
'conn': None
})
# Open input files
for i in inputs:
s = i['slot']
data_file = model_slots[s]['file']
conn = open(0) if (s == 0 and data_file is None) else open(data_file)
i['conn'] = conn
# Open output files
for i in outputs:
s = i['slot']
data_file = model_slots[s]['file']
conn = open(1,'w') if (s == 1 and data_file is None) else open(data_file,'w')
i['conn'] = conn
# Read a batch of records from the slot
def read_records(s):
ii = None
for i in range(0,len(inputs)):
if inputs[i]['slot'] == s:
ii = i
break
if ii is None:
if model_slots[s]['active']:
return None
else:
sys.exit("Slot {} is not in use".format(s))
conn = inputs[ii]['conn']
seq_no = inputs[ii]['seq_no']
records = []
at_eof = False
while len(records) < args.batch_size:
l = conn.readline()
if len(l) == 0:
if conn.name != 0:
conn.close()
inputs.pop(ii)
at_eof = True
break
x = json.loads(l)
#TODO
#if (is.list(x) && x$`$fastscore` == "set"):
# break
records.append(x)
if at_eof and len(records) == 0:
return []
if not at_eof:
old_seq_no = seq_no
seq_no = seq_no + len(records)
inputs[ii]['seq_no'] = seq_no
return records
def as_recordset(records):
if records is None:
return None
return records
#TODO
#if (len(records) == 0):
# pd.DataFrame(records)
#else:
# head = records[0]
class Slot(object):
def __init__(self, n):
self.n = n
def __iter__(self):
return self
def __next__(self):
data = self.read()
if data is None:
raise StopIteration
else:
return data
def read(self):
if (not is_input_slot(self.n)):
sys.exit("Model attempts to explicitly read from an output slot {}".format(self.n))
records = read_records(self.n)
data = as_recordset(records)
return data
def write(self, rec):
if (is_input_slot(self.n)):
sys.exit("Model emits data to an input slot {}:".format(s))
conn = None
for i in outputs:
if i['slot'] == self.n:
conn = i['conn']
break
if conn is None:
sys.exit("Model emits data to an unknown slot {}".format(self.n))
recordsets = model_slots[self.n]['recordsets']
if not recordsets:
print(json.dumps(rec), file=conn)
else:
sys.exit("TOODOO")
fio = types.ModuleType("fastscore.io")
fio.__dict__['Slot'] = Slot
sys.modules["fastscore.io"] = fio
spec = importlib.util.spec_from_file_location('model', args.source_file)
mod = importlib.util.module_from_spec(spec)
# Callbacks not resolved yet
spec.loader.exec_module(mod)
# TODO Check/wrap action callbacks
for s in range(0,MAX_SLOT):
slot = model_slots[s]
if not slot['active']:
continue
if not slot['action'] is None:
entry = getattr(mod,slot['action'])
if entry is None:
sys.exit("A slot {} callback function named '{}' not found".format(s,slot['action']))
if not isinstance(entry, types.FunctionType):
sys.exit("A slot {} callback named '{}' must be a function".format(s,slot['action']))
sig = inspect.signature(entry)
arity = len(sig.parameters)
if (arity < 1 or arity > 3):
sys.exit("A slot {} callback function named '{}' must have arity 1, 2, or 3 (not {})".format(s,slot['action'],arity))
wrapped_entry = entry
if arity == 1:
wrapped_entry = lambda data,slot,seqno: entry(data)
elif arity == 2:
wrapped_entry = lambda data,slot,seqno: entry(data,seqno)
for i in inputs:
if i['slot'] == s:
i['entry'] = wrapped_entry
model_uses_callbacks = False
if len(inputs) > 0:
model_uses_callbacks = isinstance(inputs[0]['entry'], types.FunctionType)
if model_uses_callbacks:
while len(inputs) > 0:
# Pick a random slot
select = random.choice(inputs)
s = select['slot']
seq_no = select['seq_no']
records = read_records(s)
action = model_slots[s]['action']
recordsets = model_slots[s]['recordsets']
if recordsets:
sys.exit("TODO recordests")
else:
# Invoke the callback for each record
for rec in records:
print(*select['entry'](rec, s, seq_no)) ## calls 'action'
seq_no = seq_no + 1
| modelop/modelop.github.io | Product Manuals/Model Launchers/Python Launcher/lh.py | lh.py | py | 9,190 | python | en | code | 1 | github-code | 36 |
19568803995 | from random import randint
y = randint(1,5)
hscore = 0
cscore = 0
print("Winners and Losers - Human is Even, Computer is Odd")
for i in range (1, 6) :
print("Round: {}".format(i))
x = int(input("Enter Your Guess: "))
print ("Human Guess: {} - Computer Guess: {}".format(x , y))
sum = x + y
if sum % 2 :
print("Sum is Even")
hscore = hscore + 1
else:
print("Sum is Odd")
cscore = cscore + 1
print ("Human Score: {} - Computer Score: {}".format (hscore, cscore))
if hscore > cscore :
print ("Human Wins")
else :
print ("Computer Wins") | wgrevis/ifsc1202 | Exam One.py | Exam One.py | py | 609 | python | en | code | 0 | github-code | 36 |
10567641757 | import time
from datetime import datetime, timedelta
from pydantic import BaseModel
from fastapi import FastAPI, Depends, File, UploadFile, HTTPException, Request, status
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
import uvicorn
import os
from pytube import YouTube
from pytube import Playlist
from pytube.cli import on_progress
app = FastAPI()
class Info(BaseModel):
author: str
title: str
view: float
length: int
description: str
thumbnail: str
fileSizeHD: str
@app.get("/")
async def hello():
return {"result": "Its working YES! This is a miracle!"}
@app.get("/info")
async def info(url: str = None):
try:
yt = YouTube(url)
videoSize = yt.streams.get_highest_resolution()
Info.author = yt.author
Info.title = yt.title
Info.view = yt.views
Info.length = ("%.2f" % float(yt.length / 60))
Info.description = yt.description
Info.thumbnail = yt.thumbnail_url
Info.fileSizeHD = str(round(videoSize.filesize * 0.000001, 2)) + " Mb"
res = {None}
for i in yt.streams:
res.add(i.resolution)
res.remove(None)
res = [int(i) for i in [sub.replace('p', '') for sub in res]]
sres = sorted(res)
return { "Title": Info.title, "Resolution": sres, "Author": Info.author, "Thumbnail": Info.thumbnail, "View": Info.view,
"Length": Info.length, "Description": Info.description,
"File size": Info.fileSizeHD}
except Exception as e:
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content={'message': str(e)})
else:
return JSONResponse(
status_code=status.HTTP_200_OK,
content={"result": 'success'})
@app.get("/video")
async def video(url: str = None):
try:
yt = YouTube(url, on_progress_callback=on_progress)
yd = yt.streams.get_highest_resolution()
folder_name = "FILE_NAME"
file_path = os.getcwd() + "/" + folder_name
video = yd.download(file_path)
yt.title
print(file_path)
headers = {'success': f'video is ready, filename= {yt.title}'}
return FileResponse(path=video, headers=headers, media_type='application/mp4', filename=(yt.title + ".mp4"))
except Exception as e:
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content={'message': str(e)}
)
else:
return JSONResponse(
status_code=status.HTTP_200_OK,
content={"result": 'success, video is ready'}
)
@app.get("/audio")
async def audio(url: str = None):
try:
ya = YouTube(url)
folder_name = "FILE_NAME"
# DEPENDS ON WHERE YOUR FILE LOCATES
file_path = os.getcwd() + "/" + folder_name
video = ya.streams.filter(only_audio=True).first()
downloaded_file = video.download(file_path)
base, ext = os.path.splitext(downloaded_file)
audio = base + 'Audio.mp3'
os.rename(downloaded_file, audio)
ya.title
print(file_path)
print(audio)
headers = {'success': f'audio is ready, filename= {ya.title}'}
return FileResponse(path=audio, headers=headers, media_type='application/mp4', filename=(ya.title+".mp3"))
except Exception as e:
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content={'message': str(e)}
)
else:
return JSONResponse(
status_code=status.HTTP_200_OK,
content={"result": 'success, audio is ready'}
)
@app.get("/delete")
async def delete_files(min: int = 10):
try:
response_msg = []
folder_name = "FILE_NAME"
file_path = os.getcwd() + "/" + folder_name
path = file_path
files = os.listdir(file_path)
print(files)
print(f"file_path: {file_path}")
file_name_delete = []
dir_name = file_path
# Get list of all files only in the given directory
list_of_files = filter(lambda x: os.path.isfile(os.path.join(dir_name, x)),
os.listdir(dir_name))
# Sort list of files based on last modification time in ascending order
list_of_files = sorted(list_of_files,
key=lambda x: os.path.getmtime(os.path.join(dir_name, x))
)
for file_name in list_of_files:
file_path = os.path.join(dir_name, file_name)
timestamp_str = time.strftime('%m/%d/%Y :: %H:%M:%S', time.gmtime(os.path.getmtime(file_path)))
print(timestamp_str, ' -->', file_name)
#filter by minite
now = datetime.now()
timestamp = datetime.timestamp(now)
f = os.path.getmtime(file_path)
file_date = datetime.fromtimestamp(f)
file_date_age = file_date + timedelta(minutes=min)
duration = now - file_date_age
duration_in_s = duration.total_seconds()
minut = (int(round(duration_in_s / 60, 0)))
print(f"duration: {minut}")
if minut > min:
file_name_delete.append(file_name)
### create a list of old file by date
print(f"file_name_delete {len(file_name_delete)}, {file_name_delete}")
#print(os.listdir(path))
for i in file_name_delete:
#for file_name_delete in os.listdir(path):
print(f"file_name: {file_name_delete}")
#print(f"path: {path}")
# construct full file path
del_file = path + "/" + i
#print(f"file: {del_file}")
if os.path.isfile(del_file):
response_msg.append(f"Deleting file: {del_file}")
print('Deleting file:', del_file)
os.remove(del_file)
print(len(del_file))
if len(response_msg) < 1:
# response_msg.clear()
response_msg.append(f"no files to delete after: {min} min")
return response_msg
except Exception as e:
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content={'message': str(e)})
else:
return JSONResponse(
status_code=status.HTTP_200_OK,
content={"result": 'success'})
@app.get("/aws")
async def aws_files():
folder_name = "FILE_NAME"
file_path = os.getcwd() + "/" + folder_name
files = os.listdir(file_path)
result = []
dir_name = file_path
# Get list of all files only in the given directory
list_of_files = filter(lambda x: os.path.isfile(os.path.join(dir_name, x)),
os.listdir(dir_name))
# Sort list of files based on last modification time in ascending order
list_of_files = sorted(list_of_files,
key=lambda x: os.path.getmtime(os.path.join(dir_name, x))
)
for file_name in list_of_files:
file_path = os.path.join(dir_name, file_name)
size = ("%.2f" % float(os.path.getsize(file_path)*0.000001))
timestamp_str = time.strftime('%m/%d/%Y :: %H:%M:%S', time.gmtime(os.path.getmtime(file_path)))
result.append(f"({timestamp_str}, ' -->', {file_name}, ' -->', {size}' MB')")
return result
def raise_exception():
return HTTPException(status_code=404,
detail="Input is Not valid!",
headers={"X-Header_Error":
f"Nothing to be seen"})
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=5000, reload=True, log_level="info", workers=2)
print('Download Complete')
| uponex/YoutubeAPI | main.py | main.py | py | 7,761 | python | en | code | 0 | github-code | 36 |
21704376256 | #
# @lc app=leetcode.cn id=40 lang=python3
#
# [40] 组合总和 II
#
from typing import List
# @lc code=start
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
current = []
def dfs(i, target):
if target == 0:
ans.append(current[:])
return
if i >= len(candidates):
return
next_target = target - candidates[i]
if next_target >= 0:
current.append(candidates[i])
dfs(i + 1, next_target)
current.pop()
j = i + 1
while j < len(candidates) and candidates[i] == candidates[j]:
j += 1
dfs(j, target)
candidates.sort()
dfs(0, target)
return ans
# @lc code=end
Solution().combinationSum2([2,5,2,1,2], 5) | LinkTsang/.leetcode | solutions/40.组合总和-ii.py | 40.组合总和-ii.py | py | 780 | python | en | code | 0 | github-code | 36 |
69812436265 | import numpy as np
import cv2
from PIL import Image
#В этом скрипте делаем маску
#С помощью манипуляций с opencv создаем два файла
#первый - с контрастными крышами, второй - с выделенными дорогами
#затем - используя второй файл, убираем дороги с первого
image = "ZRYNEEUSVQ213QTY.png"
input = cv2.imread(image)
_, th = cv2.threshold(input, 130, 160, cv2.THRESH_TOZERO)
cv2.imwrite("th.png", th)
image = "th.png"
img = cv2.imread(image)
lower = np.array([0, 1, 1])
upper = np.array([0, 255, 255])
mask = cv2.inRange(img, lower, upper)
roads = cv2.bitwise_and(img, img, mask=mask)
height = int(np.size(img, 0))
width = int(np.size(img, 1))
for h in range(1, 500):
for w in range(1, 500):
color = str(roads[w, h])
if color != "[0, 145, 153]":
pass
else:
roads[h, w] = [0, 0, 255]
cv2.imwrite("roads.png", roads)
mask = Image.open("roads.png")
mask1 = Image.open("th.png")
for i in range (1, 6528):
for j in range (1, 7733):
if mask1.getpixel((i,j))[0] != 0 or mask1.getpixel((i,j))[1] != 0 or \
mask1.getpixel((i,j))[2] != 0:
mask1.putpixel((i, j), (255, 255, 255))
if (mask.getpixel((i, j))[0] != 0) or (mask.getpixel((i, j))[1] != 0) or (mask.getpixel((i, j))[2] != 0):
mask1.putpixel((i, j), (0, 0, 0))
mask1.save("dengi3.jpg", "JPEG") | kekartem/BuildingDefine | RunFirst.py | RunFirst.py | py | 1,512 | python | ru | code | 0 | github-code | 36 |
70537874663 | import unittest
import player_factory
from inning_creator import Inning
from positional_data import StandardPosition
def collect_benched_players(inning):
bench_assignments = [
assignment for assignment in inning.assignments
if assignment.position.title == "Bench"
]
return bench_assignments
def find_by_player(assignments, search_player):
player_list = [
position for position, player in assignments.items()
if player == search_player
]
if len(player_list) > 0:
return player_list.pop()
def player_has_assignment(player, assignments):
assignment = find_by_player(assignments, player)
return assignment is not None
class MyTestCase(unittest.TestCase):
def setUp(self) -> None:
self.players = player_factory.generate_full_cardinals()
self.inning = Inning(self.players.copy())
self.assignments = self.inning.assignments
def test_all_positions_covered_on_inning_creation(self):
assignments_dict = {assignment.position: assignment.player
for assignment
in self.assignments}
for position in StandardPosition:
self.assertTrue(position.value in assignments_dict.keys())
player_at_position = assignments_dict[position.value]
self.assertIsNotNone(player_at_position)
def test_all_players_assigned_to_position_and_bench(self):
assigned_players = set(
[assignment.player for assignment in self.assignments]
)
self.assertEqual(len(self.players), len(assigned_players))
benched_players = collect_benched_players(self.inning)
self.assertEqual(4, len(benched_players))
def test_players_assign_to_fielder_group(self):
non_bench_assignments = [
assignment for assignment in self.assignments
if assignment.position.title != 'Bench'
]
for assignment in non_bench_assignments:
player = assignment.player
self.assertEqual(
player.field_group,
assignment.position.field_group
)
import unittest
if __name__ == '__main__':
unittest.main()
| jasonmrimer/roster | test_inning.py | test_inning.py | py | 2,193 | python | en | code | 0 | github-code | 36 |
34141195826 | import numpy as np
import torch
from snownlp import SnowNLP
from common_utils import *
from preprocessing.clean_data import batchify
def get_overlap(list1, list2):
"""
Returns a list of words that occur in both list1 and list2.
Also returns total number of words in list1 and in list2 (can be used
to compute similarity as a percentage, if desired)
Args:
list1 (string): filename corresponding to a list of words
list2 (string): filename corresponding to a list of words
Returns:
overlap (list of string): words occuring in both list1 and list2
len1 (int): number of words in list1
len2 (int): number of words in list2
"""
# File to List
wordlist1 = file_to_str(list1)
wordlist2 = file_to_str(list2)
# Tokenize Lists
s1 = SnowNLP(wordlist1) # need to use SnowNLP for Chinese-character lists
s2 = SnowNLP(wordlist2)
# Get List Lengths
wordlist1 = list(set(s1.words))
wordlist2 = list(set(s2.words))
len1 = len(wordlist1)
len2 = len(wordlist2)
# Count Overlapping Words
# overlap = [w2 for w2 in wordlist2 if w2 in wordlist1]
# Alternative to "Count Overlapping Words" with potentially better time complexity
combined_wordset = set(wordlist1).union(set(wordlist2))
overlap = len1 + len2 - len(combined_wordset)
return overlap, len1, len2
def get_embedding_similarity(list1, list2, emb):
"""
Given an embedding for a vocabulary and two lists of words from
that vocabulary, return the cosine distance between the average
word embeddings from each list.
Args:
list1 (string): filename corresponding to a list of words
list2 (string): filename corresponding to a list of words
emb (??): word embedding
"""
raise NotImplementedError
def get_political_diff(list1, list2, model_file):
# Load model and data
model = torch.load(model_file)
model.eval()
data1 = batchify(list1)
data2 = batchify(list2)
# Inference
positives1, positives2 = 0, 0
for in1 in data1:
output1 = model(in1[0]) # no labels
positives1 += (output1.argmax(1) == 1).sum().item()
for in2 in data2:
output2 = model(in2[0])
positives2 += (output2.argmax(1) == 1).sum().item() / len(data2)
return positives1, positives2, len(data1.dataset), len(data2.dataset)
def get_political_ratio(list, model_file):
# Load model and data
model = torch.load(model_file)
model.eval()
data = batchify(list)
# Inference
positives = 0
for in1 in data:
output = model(in1[0]) # no labels
positives += (output.argmax(1) == 1).sum().item()
return positives / len(data.dataset)
def get_longest_subsequence_length(list1, list2):
"""
Returns length of longest subsequence common to list1 and list2.
Also returns total number of words in list1 and in list2 (can be used
to compute similarity as a percentage, if desired)
Args:
list1 (string): filename corresponding to a list of words
list2 (string): filename corresponding to a list of words
Returns:
length (int): length of longest subsequence
len1 (int): number of words in list1
len2 (int): number of words in list2
"""
# File to List
wordlist1 = file_to_str(list1)
wordlist2 = file_to_str(list2)
# Tokenize Lists
s1 = SnowNLP(wordlist1)
s2 = SnowNLP(wordlist2)
# Get List Lengths
wordlist1 = list(s1.words)
wordlist2 = list(s2.words)
len1 = len(wordlist1)
len2 = len(wordlist2)
length = longest_subsequence(wordlist1, wordlist2)
return length, len1, len2
def longest_subsequence(list1, list2):
"""
Return length of longest subsequence common to list1 and list2.
Here, a subsequence is defined as a list of ordered entries
occuring consecutively in a list.
Example:
[1,2,3] and [4] are subsequences of [1,2,3,4]
[1,3,4] and [1,3,2] are not subsequences of [1,2,3,4]
Args:
list1 (list): a list whose elements can be of any class
that implements __eq__
list2 (list): a list whose elements are the same class as
those of list1
Returns:
l (int): the length of the longest subsequence
"""
# T[i, j] will store the length of longest substring
# ending at list1[i] and list2[j]
n = len(list1)
m = len(list2)
T = np.zeros((n, m))
for i in range(n):
for j in range(m):
if list1[i] == list2[j]:
if i == 0 or j == 0:
T[i, j] = 1
else:
T[i, j] = T[i-1, j-1] + 1
return np.max(T)
def _cosine_dist(v1, v2):
return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
def _euclidean_dist(v1, v2):
return np.linalg.norm(v1 - v2)
def _manhattan_dist(v1, v2):
raise np.linalg.norm(v1 - v2, ord=1)
| JasmineZhangxyz/ewb-ml-censorship | similarity/metrics/list_metrics.py | list_metrics.py | py | 4,969 | python | en | code | 0 | github-code | 36 |
11571428709 | from django.utils.module_loading import import_string
from django.urls import (RegexURLResolver, RegexURLPattern)
from CRM import settings
from collections import OrderedDict
def recursion_urls(pre_namespace, pre_url, urlpatterns, url_ordered_dict):
# None, '/', urlpatterns, url_ordered_dict
'''
第一次递归:
url(r'^', include('web.urls')),
url(r'^rbac/', include('rbac.urls', namespace='rbac')),
第二次递归:
'rbac','/^rbac/', rbac.urls文件下的urlpatterns变量, url_ordered_dict
'''
for url in urlpatterns:
if isinstance(url, RegexURLResolver):
if pre_namespace:
if url.namespace:
namespace = '%s:%s' % (pre_namespace, url.namespace)
else:
namespace = pre_namespace
else:
if url.namespace:
namespace = url.namespace # 'rbac'
else:
namespace = None
recursion_urls(namespace, pre_url + url.regex.pattern, url.url_patterns, url_ordered_dict)
else:
if pre_namespace:
name = '%s:%s' % (pre_namespace, url.name) # rbac:role_list
else:
name = url.name
if not url.name:
raise Exception('URL路由中必须设置name属性')
url = pre_url + url._regex # /^^login/
url_ordered_dict[name] = {
'url_name': name, 'url': url.replace('^', '').replace('$', '')
} # {'login':{'url_name': name, 'url': /login/},}
def all_url(ignore_namespace_list=None):
ignore_list = ignore_namespace_list or []
# 存放项目所有URL的有序字典
url_ordered_dict = OrderedDict()
# 获取项目的所以URL
urls = import_string(settings.ROOT_URLCONF)
urlpatterns = []
'''
# urlpatterns = [
# url(r'^', include('web.urls')),
# url(r'^rbac/', include('rbac.urls', namespace='rbac')),
# ]
'''
for url in urls.urlpatterns:
if isinstance(url, RegexURLResolver) and url.namespace in ignore_list:
continue
urlpatterns.append(url)
recursion_urls(None, '/', urlpatterns, url_ordered_dict)
return url_ordered_dict
| heyhito/CRM | rbac/server/routes.py | routes.py | py | 2,278 | python | en | code | 0 | github-code | 36 |
18913603323 | from collections import defaultdict
class Solution:
def valid_tree(self, n: int, edges: list[list[int]]) -> bool:
seen: set[int] = set()
children: dict[int, list[int]] = defaultdict(list)
for x, y in edges:
children[x].append(y)
children[y].append(x)
def dfs(node: int, prev: int) -> bool:
if node in seen:
return False
seen.add(node)
for child in children[node]:
if child == prev:
continue
if not dfs(child, node):
return False
return True
return dfs(0, 0) and len(seen) == n
| lancelote/leetcode | src/graph_valid_tree.py | graph_valid_tree.py | py | 689 | python | en | code | 3 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.