index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
48,088 | whiterson/mockingJay | refs/heads/master | /mapReader.py | __author__ = 'Whitney'
import sys
import PIL
import pygame
from locationDef import locationDef
from PIL import Image
def deepForest(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID DeepForest\n')
testFile.close()
terrainType = 0
definition.setTerrain(terrainType)
definition.setFoodChance(0.3)
definition.setWaterChance(0)
definition.setShortStickChance(0.8)
definition.setVisibility(0.2)
definition.setSharpStoneChance(0.1)
definition.setFeatherChance(0.2)
definition.setVineChance(0.4)
definition.setSpeedChange(2)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.6)
definition.setBroadStoneChance(0.05)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.05)
definition.setThornsChance(0.3)
return definition
def dirt(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID Dirt\n')
testFile.close()
terrainType = 1
definition.setTerrain(terrainType)
definition.setFoodChance(0.0)
definition.setWaterChance(0.0)
definition.setShortStickChance(0.0)
definition.setVisibility(1)
definition.setSharpStoneChance(0.5)
definition.setFeatherChance(0.05)
definition.setVineChance(0.0)
definition.setSpeedChange(1)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.1)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.2)
definition.setThornsChance(0.0)
return definition
def grass(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID Grass\n')
testFile.close()
terrainType = 2
definition.setTerrain(terrainType)
definition.setFoodChance(0.1)
definition.setWaterChance(0.0)
definition.setShortStickChance(0.0)
definition.setVisibility(1)
definition.setSharpStoneChance(0.1)
definition.setFeatherChance(0.2)
definition.setVineChance(0.0)
definition.setSpeedChange(1)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.1)
definition.setLongGrassChance(0.2)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.1)
definition.setThornsChance(0.0)
return definition
def ice(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID Ice\n')
testFile.close()
terrainType = 3
definition.setTerrain(terrainType)
definition.setFoodChance(0.0)
definition.setWaterChance(0.6)
definition.setShortStickChance(0.0)
definition.setVisibility(1)
definition.setSharpStoneChance(0.0)
definition.setFeatherChance(0.0)
definition.setVineChance(0.0)
definition.setSpeedChange(3)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.0)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.0)
definition.setThornsChance(0.0)
return definition
def lightForest(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID lightForest\n')
testFile.close()
terrainType = 4
definition.setTerrain(terrainType)
definition.setFoodChance(0.3)
definition.setWaterChance(0.0)
definition.setShortStickChance(0.9)
definition.setVisibility(0.9)
definition.setSharpStoneChance(0.3)
definition.setFeatherChance(0.6)
definition.setVineChance(0.05)
definition.setSpeedChange(1)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.6)
definition.setBroadStoneChance(0.1)
definition.setLongGrassChance(0.1)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.1)
definition.setThornsChance(0.1)
return definition
def lowVegetation(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID lowVegetation\n')
testFile.close()
terrainType = 5
definition.setTerrain(terrainType)
definition.setFoodChance(0.6)
definition.setWaterChance(0.0)
definition.setShortStickChance(0.05)
definition.setVisibility(0.05)
definition.setSharpStoneChance(0.2)
definition.setFeatherChance(0.2)
definition.setVineChance(0.0)
definition.setSpeedChange(1)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.1)
definition.setLongGrassChance(0.1)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.05)
definition.setThornsChance(0.6)
return definition
def mud(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID Mud\n')
testFile.close()
terrainType = 6
definition.setTerrain(terrainType)
definition.setFoodChance(0.0)
definition.setWaterChance(0.05)
definition.setShortStickChance(0.0)
definition.setVisibility(1)
definition.setSharpStoneChance(0.1)
definition.setFeatherChance(0.0)
definition.setVineChance(0.0)
definition.setSpeedChange(1)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.1)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.1)
definition.setThornsChance(0.0)
return definition
def rock(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID Rock\n')
testFile.close()
terrainType = 7
definition.setTerrain(terrainType)
definition.setFoodChance(0.0)
definition.setWaterChance(0.0)
definition.setShortStickChance(0.0)
definition.setVisibility(1)
definition.setSharpStoneChance(0.9)
definition.setFeatherChance(0.0)
definition.setVineChance(0.0)
definition.setSpeedChange(1)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.7)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.8)
definition.setThornsChance(0.0)
return definition
def sand(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID Sand\n')
testFile.close()
terrainType = 8
definition.setTerrain(terrainType)
definition.setFoodChance(0.0)
definition.setWaterChance(0.0)
definition.setShortStickChance(0.0)
definition.setVisibility(1)
definition.setSharpStoneChance(0.2)
definition.setFeatherChance(0.0)
definition.setVineChance(0.0)
definition.setSpeedChange(1)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.0)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.1)
definition.setThornsChance(0.0)
return definition
def shallowWater(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID shallowWater\n')
testFile.close()
terrainType = 9
definition.setTerrain(terrainType)
definition.setFoodChance(0.0)
definition.setWaterChance(1)
definition.setShortStickChance(0.0)
definition.setVisibility(0.0)
definition.setSharpStoneChance(0.2)
definition.setFeatherChance(0.0)
definition.setVineChance(0.05)
definition.setSpeedChange(1)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.05)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.6)
definition.setPebblesChance(0.5)
definition.setThornsChance(0.0)
return definition
def snow(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID snow\n')
testFile.close()
terrainType = 10
definition.setTerrain(terrainType)
definition.setFoodChance(0.0)
definition.setWaterChance(0.2)
definition.setShortStickChance(0.0)
definition.setVisibility(0.0)
definition.setSharpStoneChance(0.1)
definition.setFeatherChance(0.0)
definition.setVineChance(0.0)
definition.setSpeedChange(2)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.05)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.1)
definition.setThornsChance(0.0)
return definition
def swimmingWater(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID swimmingWater\n')
testFile.close()
terrainType = 11
definition.setTerrain(terrainType)
definition.setFoodChance(0)
definition.setWaterChance(1)
definition.setShortStickChance(0.0)
definition.setVisibility(0.5)
definition.setSharpStoneChance(0.0)
definition.setFeatherChance(0.0)
definition.setVineChance(0.0)
definition.setSpeedChange(1)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0)
definition.setBroadStoneChance(0.1)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.5)
definition.setThornsChance(0.0)
return definition
def tallGrass(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID tallGrass\n')
testFile.close()
terrainType = 12
definition.setTerrain(terrainType)
definition.setFoodChance(0.2)
definition.setWaterChance(0.0)
definition.setShortStickChance(0.1)
definition.setVisibility(0.7)
definition.setSharpStoneChance(0.2)
definition.setFeatherChance(0.2)
definition.setVineChance(0.4)
definition.setSpeedChange(1)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.05)
definition.setBroadStoneChance(0.0)
definition.setLongGrassChance(1)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.05)
definition.setThornsChance(0.05)
return definition
def wadingWater(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID wadingWater\n')
testFile.close()
terrainType = 13
definition.setTerrain(terrainType)
definition.setFoodChance(0.0)
definition.setWaterChance(1)
definition.setShortStickChance(0.0)
definition.setVisibility(1)
definition.setSharpStoneChance(0.4)
definition.setFeatherChance(0.0)
definition.setVineChance(0.1)
definition.setSpeedChange(3)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.2)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.7)
definition.setPebblesChance(0.2)
definition.setThornsChance(0.0)
return definition
def cornucopia(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID cornucopia\n')
testFile.close()
terrainType = 14
definition.setTerrain(terrainType)
definition.setFoodChance(0.5)
definition.setWaterChance(0.3)
definition.setShortStickChance(0.0)
definition.setVisibility(1)
definition.setSharpStoneChance(0.0)
definition.setFeatherChance(0.0)
definition.setVineChance(0.0)
definition.setSpeedChange(1)
definition.setWeaponChance(0.9)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.0)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.0)
definition.setThornsChance(0.0)
return definition
def startSpot(definition):
testFile = open('maptest.txt', 'a')
testFile.write('Pixel ID startSpot\n')
testFile.close()
terrainType = 15
definition.setTerrain(terrainType)
definition.setFoodChance(0.0)
definition.setWaterChance(0.0)
definition.setShortStickChance(0.0)
definition.setVisibility(1)
definition.setSharpStoneChance(0.0)
definition.setFeatherChance(0.0)
definition.setVineChance(0.0)
definition.setSpeedChange(1)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.0)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.0)
definition.setThornsChance(0.0)
return definition
def colorError(definition):
terrainType = 16
definition.setTerrain(terrainType)
definition.setFoodChance(0.0)
definition.setWaterChance(0.0)
definition.setShortStickChance(0.0)
definition.setVisibility(0)
definition.setSharpStoneChance(0.0)
definition.setFeatherChance(0.0)
definition.setVineChance(0.0)
definition.setSpeedChange(0)
definition.setWeaponChance(0.0)
definition.setLongStickChance(0.0)
definition.setBroadStoneChance(0.0)
definition.setLongGrassChance(0.0)
definition.setReedsChance(0.0)
definition.setPebblesChance(0.0)
definition.setThornsChance(0.0)
return definition
"""My Python Switch Case Based on Pixel Value"""
switch = {(1, 35, 18) : deepForest,
(97, 63, 2) : dirt,
(70, 152, 18) : grass,
(233, 244, 248) : ice,
(2, 117, 62) : lightForest,
(104, 142, 65) : lowVegetation,
(58, 43, 20) : mud,
(155, 154, 150) : rock,
(246, 238, 176) : sand,
(184, 224, 236) : shallowWater,
(247, 249, 248) : snow,
(38, 100, 121): swimmingWater,
(169, 153, 18): tallGrass,
(88, 156, 179): wadingWater,
(0,0,0): cornucopia,
(84,86,90): startSpot,
(300,300,300): colorError
}
def readMap(mapInput):
testFile = open('maptest.txt', 'a')
testFile.write('\n\n=============================\nNew Map Test\n=============================\n\n')
map = Image.open(mapInput)
gameMap = [[0 for t in xrange(map.size[0])] for r in xrange(map.size[1])]
pixelMap = map.load()
for i in range(map.size[0]): # for every pixel:
for j in range(map.size[1]):
pixel = pixelMap[i,j]
if pixel in switch:
definition = locationDef()
locDef = switch[pixel](definition)
gameMap[i][j] = locDef
else:
definition = locationDef()
locDef = switch[(300,300,300)](definition)
gameMap[i][j] = locDef
testFile.close()
return gameMap
def get_neighbors(map, location):
w = len(map)
h = len(map[0])
up = (location[0], (location[1] - 1) % h)
left = ((location[0] - 1) % w, location[1])
down = (location[0], (location[1] + 1) % h)
right = ((location[0] + 1) % w, location[1])
return [up, left, down, right]
def get_neighbors2(map, location):
w = len(map)
h = len(map[0])
up = (location[0], (location[1] - 1) % h)
left = ((location[0] - 1) % w, location[1])
down = (location[0], (location[1] + 1) % h)
right = ((location[0] + 1) % w, location[1])
return [up, down, right, left]
def l1_dist(state1, state2):
return abs(state1[0] - state2[0]) + abs(state1[1] - state2[1])
def add_states(state1, state2):
t = (state1[0] + state2[0], state1[1] + state2[1])
return t | {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,089 | whiterson/mockingJay | refs/heads/master | /game.py | __author__ = 'Nathan'
import random as r
import tribute
class GameState(object):
"""
represents, well, the state of the game.
how should we separate the line between the map and the game state?
for now, I'm making the crude assumption that the map read parses to an empty game-state
"""
def __init__(self, particles, width=50, height=50):
self.width, self.height = width, height
self.world = {
'ground': (),
'particle': ()
}
self.particles = particles
self.grid = {
'ground': [(x, y, (r.randint(0, 255), r.randint(0, 255), r.randint(0, 255), 0), None) for x in range(width) for y in range(height)],
'particle': [(p.state[0], p.state[1],
((255 * (1 - (p.stats['health'] / p.attributes['max_health']))), 0,
(255 * ((p.stats['health'] / p.attributes['max_health']))), 0), p) for p in self.particles]
}
def update(self):
self.grid['particle'] = [(p.state[0], p.state[1],
(int(round(min(max((255 * (1 - (float(p.stats['health']) / p.attributes['max_health']))), 0), 255))), 0,
int(round(min(max((255 * ((float(p.stats['health']) / p.attributes['max_health']))), 0), 255))), 0), p) for p in self.particles]
def apply_action(self):
pass | {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,090 | whiterson/mockingJay | refs/heads/master | /locationDef.py | import tribute
class locationDef(object):
def __init__(self):
self.startSpace = False #True/False
self.playerThere = False #True/False
self.tribute = None #Tribute that is in a space. Null otherwise
self.terrain = 0 #0-15 Value for terrain Type
self.foodChance = 0 #integer value for probability of food
self.waterChance = 0 #integer value for probability of water
self.visibility = 0 #integer value for visibility
self.shortStickChance = 0 #for crafting: Integer Value probability of stick
self.sharpStoneChance = 0 #for crafting: integer value probablity of sharp stone
self.featherChance = 0 #for crafting: integer value probablilty of feather
self.vineChance = 0 #for crafting: integer value probablity of vine
self.speedChange = 0 #integer value movement speed changes
self.weaponChance = 0 #inter value for probability of weapon
self.longStickChance = 0
self.broadStoneChance = 0
self.longGrassChance = 0
self.reedsChance = 0
self.pebblesChance = 0
self.thornsChance = 0
########### GETS ##############
def getStartSpace(self):
return self.startSpace
def getPlayerThere(self):
return self.playerThere
def getTribute(self):
return self.tribute
def getTerrain(self):
return self.terrain
def getFoodChance(self):
return self.foodChance
def getWaterChance(self):
return self.waterChance
def getShortStickChance(self):
return self.stickChance
def getVisibility(self):
return self.visibility
def getSharpStoneChance(self):
return self.sharpStoneChance
def getFeatherChance(self):
return self.featherChance
def getVineChance(self):
return self.vineChance
def getSpeedChange(self):
return self.speedChange
def getWeaponChance(self):
return self.weaponChance
def getLongStickChance(self):
return self.longStickChance
def getBroadStoneChance(self):
return self.broadStoneChance
def getLongGrassChance(self):
return self.longGrassChance
def getReedsChance(self):
return self.reedsChance
def getPebblesChance(self):
return self.pebblesChance
def getThornsChance(self):
return self.thornsChance
########### SETS ##############
def setStartSpace(self, input):
self.startSpace = input
def setPlayerThere(self, input):
self.playerThere = input
def setTribute(self, input):
self.tribute = input
def setTerrain(self, input):
self.terrain = input
def setFoodChance(self, input):
self.foodChance = input
def setWaterChance(self, input):
self.waterChance = input
def setShortStickChance(self, input):
self.stickChance = input
def setVisibility(self, input):
self.visibility = input
def setSharpStoneChance(self, input):
self.sharpStoneChance = input
def setFeatherChance(self, input):
self.featherChance = input
def setVineChance(self, input):
self.vineChance = input
def setSpeedChange(self, input):
self.speedChange = input
def setWeaponChance(self, input):
self.weaponChance = input
def setLongStickChance(self, input):
self.longStickChance = input
def setBroadStoneChance(self, input):
self.broadStoneChance = input
def setLongGrassChance(self, input):
self.longGrassChance = input
def setReedsChance(self, input):
self.reedsChance = input
def setPebblesChance(self, input):
self.pebblesChance = input
def setThornsChance(self, input):
self.thornsChance = input
| {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,091 | whiterson/mockingJay | refs/heads/master | /weapon.py | import random
from weaponInfo import weaponInfo
class weapon:
def __init__(self, type):
## All weapons start w/ a base d, and they gain or lose depending on what kind of weapon they're fighting against
self.weaponInfo = weaponInfo()
self.type = type
self.damageCap = 0
self.isRanged = False
self.range = 1
self.damage = self.findDamage()
self.selfConstructed = False
self.usesLeft = 50
self.setRanged()
self.damageCap = self.weaponInfo.weaponStrength(self.type)
def __repr__(self):
return '<Weapon>(' + str(self.type) + ', ' + str(self.damage) + ')'
def findDamage(self):
return random.randint(1,self.weaponInfo.weaponStrength(self.type))
def isInRange(self, distToTarget):
inRange = False
if(self.isRanged and distToTarget <= 1):
inRange = False
elif(self.isRanged and (distToTarget > 1) and (distToTarget < self.range)):
inRange = True
elif((not self.isRanged) and distToTarget > 1):
inRange = False
elif((not self.isRanged) and distToTarget <= 1):
inRange = True
else:
inRange = False
return inRange
def setRanged(self):
if(self.type == 'bow'):
self.isRanged = True
elif(self.type == 'slingshot'):
self.isRanged = True
elif(self.type == 'blowgun'):
self.isRanged = True
else:
self.isRanged = False
self.range = self.weaponInfo.weaponRange(self.type)
def getRanged(self):
return self.isRanged
#First is the weapon that we're looking for the damage for
#Second it the weapon that it's fighting against
def getDamage(self, wepAgainst):
against = wepAgainst.type
weapon = self.type
damage = self.damage
if((not wepAgainst.isRanged) and (not self.isRanged)):
if(weapon == 'spear'):
if(against == 'none'):
damage += 4
elif(against == 'axe' or against == 'sword' or against == 'dagger'):
damage += 3
else:
damage += -1
elif(weapon == 'axe'):
if(against == 'none'):
damage += 4
elif(against == 'sword' or against == 'dagger' or against == 'mace' or against == 'hammer'):
damage += 3
else:
damage += -1
elif(weapon == 'sword'):
if(against == 'none'):
damage += 4
elif(against == 'dagger' or against == 'mace' or against == 'hammer'):
damage += 3
else:
damage += -1
elif(weapon == 'dagger'):
if(against == 'none'):
damage += 4
elif(against == 'mace' or against == 'hammer' or against == 'trident'):
damage += 3
else:
damage += -1
elif(weapon == 'mace'):
if(against == 'none'):
damage += 4
elif(against == 'hammer' or against == 'trident' or against == 'spear'):
damage += 3
else:
damage += -1
elif(weapon == 'hammer'):
if(against == 'none'):
damage += 4
elif(against == 'trident' or against == 'spear'):
damage += 3
else:
damage += -1
elif(weapon == 'trident'):
if(against == 'none'):
damage += 4
elif(against == 'spear' or against == 'axe' or against == 'sword'):
damage += 3
else:
damage += -1
else:
damage += 0
elif(wepAgainst.isRanged and (not self.isRanged)):
damage += 4
elif((not wepAgainst.isRanged) and self.isRanged):
damage -= 1
elif(wepAgainst.isRanged and self.isRanged):
if(weapon == 'slingshot'):
if(against == 'none'):
damage += 1
elif(against == 'blowgun'):
damage += 2
else:
damage += -1
elif(weapon == 'blowgun'):
if(against == 'none'):
damage += 1
elif(against == 'bow'):
damage += 2
else:
damage += -1
elif(weapon == 'bow'):
if(against == 'none'):
damage += 1
elif(against == 'slingshot'):
damage += 2
else:
damage -= 1
else:
damage += 0
else:
damage += 0
return damage
| {"/main.py": ["/engine.py", "/tribute.py"], "/map.py": ["/mapReader.py", "/game.py"], "/mapReader.py": ["/locationDef.py"], "/game.py": ["/tribute.py"], "/locationDef.py": ["/tribute.py"], "/weapon.py": ["/weaponInfo.py"]} |
48,094 | PatCondit03/PyDaVinci | refs/heads/main | /PaintFunctions.py | import time
import pyautogui
import random
time.sleep(4)
distance = 200
pyautogui.click(477,412)
#list of all the locations of colors in MS Paint
colorlist = [1090, 1123, 1153, 1189, 1223, 1255, 1290, 1323, 1353, 1390]
rows = [100, 120]
# function to draw a square shaped spiral
def squarespiral():
pyautogui.click(colorlist[random.randint(0,9)], rows[random.randint(0,1)], 2, 0.2)
pyautogui.click(random.randint(0,1880),random.randint(200, 756))
distance = random.randint(20,300)
increment = random.randint(4,10)
while distance > 0:
pyautogui.dragRel(distance, 0) # move right
distance -= increment
pyautogui.dragRel(0, distance) # move down
pyautogui.dragRel(-distance, 0) # move left
distance -= increment
pyautogui.dragRel(0, -distance) # move up
# function to draw a square
def square():
pyautogui.click(colorlist[random.randint(0,9)], rows[random.randint(0,1)], 2, 0.2)
pyautogui.click(random.randint(0,1700),random.randint(300, 700))
distance = random.randint(1,300)
pyautogui.dragRel(distance, -distance) # move right
pyautogui.dragRel(distance, distance) # move down
pyautogui.dragRel(-distance, distance) # move left
pyautogui.dragRel(-distance, -distance) # move up
# function to draw a line
def line():
pyautogui.click(colorlist[random.randint(0,9)], rows[random.randint(0,1)], 2, 0.2)
pyautogui.click(random.randint(0,1880),random.randint(200, 756))
pyautogui.dragRel(random.randint(-300,300), random.randint(-300,300))
# function to choose the "fill" tool and fill in the area clicked with a color
def click():
pyautogui.click(379,110)
pyautogui.click(random.randint(0,1880),random.randint(200, 756))
pyautogui.click(345,110)
x = 1
count = 0
'''
# This section is commented out becuase it is an alternative method of drawing.
# Essentially, the loops are skewed so that ceratin functions are used more often
# than others for a different style of drawing
while count < 100:
choice = random.randint(1,10)
if choice == 1:
click()
count = count + 1
elif choice == 2:
square()
count = count + 1
elif choice == 3:
line()
count = count + 1
else:
squarespiral()
count = count +1
while count >=100:
choice = random.randint(1,10)
if choice == 1:
squarespiral()
count = count + 1
elif choice == 2:
square()
count = count + 1
elif choice == 3:
line()
count = count + 1
else:
click()
count = count +1
'''
# working code, loop will have the program commit 200 actions
while count < 200:
choice = random.randint(1,10)
if choice == 1:
click()
count = count + 1
elif choice == 2:
squarespiral()
count = count + 1
elif choice == 3:
line()
count = count + 1
else:
square()
count = count +1
# After the above 200 actions, it will do 100 click functions to try and have a more common color
while count >=200 and count <= 300:
click()
count = count +1
| {"/Final Project Main.py": ["/ChooseColor.py"], "/DaVinci.py": ["/PaintFunctions.py"], "/Master_PyDaVinci.py": ["/PaintFunctions.py"]} |
48,095 | PatCondit03/PyDaVinci | refs/heads/main | /ChooseColor.py | # Defining the function to choose color, with RGB as inputs
import pyautogui as gui
def choosecolor(R, G, B):
gui.click(1440, 110)
gui.click(1260, 630)
gui.press('backspace', presses = 3)
for c in str(R):
gui.press(c)
gui.click(1260, 670)
gui.press('backspace', presses = 3)
for c in str(G):
gui.press(c)
gui.click(1260, 690)
gui.press('backspace', presses = 3)
for c in str(B):
gui.press(c)
gui.press('enter') | {"/Final Project Main.py": ["/ChooseColor.py"], "/DaVinci.py": ["/PaintFunctions.py"], "/Master_PyDaVinci.py": ["/PaintFunctions.py"]} |
48,096 | PatCondit03/PyDaVinci | refs/heads/main | /Final Project Main.py | # IMPORTS
import time
from PIL import Image
import numpy as np
import pyautogui as gui
from ChooseColor import choosecolor
#opening image and getting 3d RGB pixel information
im = Image.open('Colorwheel.jpg')
pixels = np.array(im)
# rep is the varible defining how compressed we want the image. can be between 2-6, the higher rep is the less pixellation
rep = 5
x = 0
while x <= rep:
print(len(pixels), len(pixels[1]))
pixels = np.delete(pixels, list(range(0, len(pixels), 2)), axis = 0)
pixels = np.delete(pixels, list(range(0, pixels.shape[1], 2)), axis = 1)
x += 1
#print(len(pixels), len(pixels[1]))
# Rough calculation of how long the program will take with a
seconds = (len(pixels) * len(pixels[1])) + 7
minutes = (seconds*2) / 60
minutes = str(minutes)
minutes = minutes[0:4]
gui.alert(text='This drawing will take roughly'+ '\n' + minutes + ' minutes',
title='Program Information', button='Begin Drawing')
time.sleep(1)
column = 5 #column begins at 5 to avoid the program writing off screen for the first few pixels
row = 0
for pixel in pixels:
while (column - 5) <= len(pixels[1]):
for cell in pixel:
choosecolor(cell[0], cell[1], cell[2])
time.sleep(.2)
gui.click(column, row + 300, clicks = 2)
column+=1
row += 1
column = 5
gui.alert(text='Drawing Complete', title='Program Information', button='End Program')
| {"/Final Project Main.py": ["/ChooseColor.py"], "/DaVinci.py": ["/PaintFunctions.py"], "/Master_PyDaVinci.py": ["/PaintFunctions.py"]} |
48,113 | st-tse/neuron_poker_bot | refs/heads/master | /gym_env/__init__.py | """Registration to the gym"""
from gym.envs.registration import register
register(id='neuron_poker-v0',
entry_point='gym_env.env:HoldemTable')
register(id='neuron_poker-v1',
entry_point='gym_env.env_v1:HoldemTable')
register(id='neuron_poker-v2',
entry_point='gym_env.env_v2:HoldemTable')
| {"/run_ppo.py": ["/agents/agent_consider_equity.py", "/agents/agent_ppo.py"], "/agents/agent_custom_q1.py": ["/gym_env/__init__.py"]} |
48,114 | st-tse/neuron_poker_bot | refs/heads/master | /agents/agent_random.py | """Random player"""
import random
autplay = True # play automatically if played against keras-rl
class Player:
"""Mandatory class with the player methods"""
def __init__(self, env='env', name='Random'):
"""Initiaization of an agent"""
my_import = __import__('gym_env.'+env, fromlist=['Action'])
self.Action = getattr(my_import, 'Action')
self.equity_alive = 0
self.actions = []
self.last_action_in_stage = ''
self.temp_stack = []
self.name = name
self.autoplay = True
def action(self, action_space, observation, info): # pylint: disable=no-self-use
"""Mandatory method that calculates the move based on the observation array and the action space."""
_ = observation # not using the observation for random decision
_ = info
this_player_action_space = {self.Action.FOLD, self.Action.CHECK, self.Action.CALL, self.Action.RAISE_POT, self.Action.RAISE_HALF_POT,
self.Action.RAISE_2POT}
possible_moves = this_player_action_space.intersection(
set(action_space))
action = random.choice(list(possible_moves))
return action
| {"/run_ppo.py": ["/agents/agent_consider_equity.py", "/agents/agent_ppo.py"], "/agents/agent_custom_q1.py": ["/gym_env/__init__.py"]} |
48,115 | st-tse/neuron_poker_bot | refs/heads/master | /run_ppo.py | import gym
from agents.agent_consider_equity import Player as EquityPlayer
from gym_env.env import PlayerShell
from agents.agent_ppo import Player as PPOPlayer
import argparse
parser = argparse.ArgumentParser(description="Train a PPO agent for Poker")
parser.add_argument('--model_name', type=str, default='test', help='file to save the model in')
parser.add_argument('--episodes', type=int, default=500, help='# of episodes to train agent')
parser.add_argument('--env_version', type=int, default=0, help='Specifies the version of environment to train on')
parser.add_argument('--eval', type=bool, default=False, help='Determines if we want to evaluate the agent or not')
args = parser.parse_args()
if __name__ == '__main__':
poker_env = gym.make(f'neuron_poker-v{args.env_version}', initial_stacks=500, render=False, funds_plot=False)
poker_env.add_player(EquityPlayer(name='equity/60/80', min_call_equity=.6, min_bet_equity=.8))
poker_env.add_player(PlayerShell(name='ppo_agent', stack_size=500))
poker_env.reset()
ppo_agent = PPOPlayer(env=poker_env)
if not args.eval:
ppo_agent.train(args.model_name, num_ep=args.episodes)
else:
ppo_agent.play(args.model_name) | {"/run_ppo.py": ["/agents/agent_consider_equity.py", "/agents/agent_ppo.py"], "/agents/agent_custom_q1.py": ["/gym_env/__init__.py"]} |
48,116 | st-tse/neuron_poker_bot | refs/heads/master | /agents/agent_ppo.py | from tensorforce.agents import Agent
from tensorforce.environments import Environment
from tensorforce.execution import Runner
from gym_env.env import Action
import tensorflow as tf
import logging
import time
from tensorflow.keras.callbacks import TensorBoard
log = logging.getLogger(__name__)
class Player:
"""Mandatory class with the player methods"""
def __init__(self, name='ppo_agent', load_model=None, env=None):
"""Initialization of an agent"""
self.equity_alive = 0
self.actions = []
self.last_action_in_stage = ''
self.temp_stack = []
self.name = name
self.autoplay = True
self.ppo_agent = None
self.poker_env = Environment.create(environment=env, max_episode_timesteps=100)
self.runner = None
if load_model:
self.load(load_model)
def load(self, model_name):
print("Loading model...")
self.ppo_agent = Agent.load(directory=model_name, format='hdf5')
def start_step_policy(self, observation):
log.info("Random action")
_ = observation
action = self.poker_env.action_space.sample()
return action
def train(self, model_name, num_ep=500):
print('Training...')
self.runner = Runner(agent='ppo.json', environment=dict(type=self.poker_env),
num_parallel=5, remote='multiprocessing')
self.runner.run(num_episodes=num_ep)
self.runner.agent.save(directory=model_name, format='hdf5')
self.runner.close()
def play(self, model_name, num_ep=5):
self.load(model_name)
print('Evaluating...')
self.runner = Runner(agent=self.ppo_agent, environment=dict(type=self.poker_env))
self.runner.run(num_episodes=num_ep, evaluation=True)
self.runner.close()
def action(self, action_space, observation, info):
_ = observation
_ = info
this_player_action_space = {Action.FOLD, Action.CHECK, Action.CALL, Action.RAISE_POT, Action.RAISE_HALF_POT,
Action.RAISE_2POT}
action = this_player_action_space.intersection(set(action_space))
return action
| {"/run_ppo.py": ["/agents/agent_consider_equity.py", "/agents/agent_ppo.py"], "/agents/agent_custom_q1.py": ["/gym_env/__init__.py"]} |
48,117 | st-tse/neuron_poker_bot | refs/heads/master | /agents/SAC_agent.py | import tensorflow as tf
import json
import gym
from gym_env.env import Action
import spinup.utils.logx
from spinup import sac_tf1
import time
class Player:
def __init__(self, name='SAC', load_model=None, env=None):
self.equity_alive = 0
self.actions = []
self.last_action_in_stage = ''
self.temp_stack = []
self.name = name
self.autoplay = True
self.sac = None
self.env = env
if load_model:
self.load(load_model)
def train(self, env_fn):
# need to pass in function that can make copy of the env...
# observation space needs to be a Space object but it is currently a tuple
sac_tf1(env_fn, actor_critic='pi', ac_kwargs={},
seed=0, steps_per_epoch=4000, epochs=100, replay_size=1000000,
gamma=0.99, polyak=0.995, lr=0.001, alpha=0.2, batch_size=100,
start_steps=10000, update_after=1000, update_every=50,
num_test_episodes=5, max_ep_len=1000, logger_kwargs={},
save_freq=1)
def load(self, env_name):
pass
def play(self, nb_episodes=5, render=False):
pass
| {"/run_ppo.py": ["/agents/agent_consider_equity.py", "/agents/agent_ppo.py"], "/agents/agent_custom_q1.py": ["/gym_env/__init__.py"]} |
48,118 | st-tse/neuron_poker_bot | refs/heads/master | /agents/agent_consider_equity.py | """Random player"""
autoplay = True # play automatically if played against keras-rl
class Player:
"""Mandatory class with the player methods"""
def __init__(self, env='env', name='Random', min_call_equity=None, min_bet_equity=None):
"""Initiaization of an agent"""
my_import = __import__('gym_env.'+env, fromlist=['Action'])
self.Action = getattr(my_import, 'Action')
self.equity_alive = 0
self.name = name
self.min_call_equity = min_call_equity
self.min_bet_equity = min_bet_equity
self.autoplay = True
def action(self, action_space, observation, info): # pylint: disable=no-self-use
"""Mandatory method that calculates the move based on the observation array and the action space."""
_ = observation
equity_alive = info['player_data']['equity_to_river_alive']
incremen1 = .1
increment2 = .2
if equity_alive > self.min_bet_equity + increment2 and self.Action.ALL_IN in action_space:
action = self.Action.ALL_IN
elif equity_alive > self.min_bet_equity + incremen1 and self.Action.RAISE_2POT in action_space:
action = self.Action.RAISE_2POT
elif equity_alive > self.min_bet_equity and self.Action.RAISE_POT in action_space:
action = self.Action.RAISE_POT
elif equity_alive > self.min_bet_equity - incremen1 and self.Action.RAISE_HALF_POT in action_space:
action = self.Action.RAISE_HALF_POT
elif equity_alive > self.min_call_equity and self.Action.CALL in action_space:
action = self.Action.CALL
elif self.Action.CHECK in action_space:
action = self.Action.CHECK
else:
action = self.Action.FOLD
return action
| {"/run_ppo.py": ["/agents/agent_consider_equity.py", "/agents/agent_ppo.py"], "/agents/agent_custom_q1.py": ["/gym_env/__init__.py"]} |
48,119 | st-tse/neuron_poker_bot | refs/heads/master | /tools/setup.py | """Setup py distutils"""
# pylint: skip-file
from distutils.core import setup
from Cython.Build import cythonize
setup(name='montecarlo_cython',
ext_modules=cythonize("montecarlo_cython.pyx"))
| {"/run_ppo.py": ["/agents/agent_consider_equity.py", "/agents/agent_ppo.py"], "/agents/agent_custom_q1.py": ["/gym_env/__init__.py"]} |
48,120 | st-tse/neuron_poker_bot | refs/heads/master | /agents/agent_custom_q1.py | """manual keypress agent"""
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from rl.memory import SequentialMemory
from agents.agent_keras_rl_dqn import TrumpPolicy, memory_limit, window_length
from gym_env import env
class Player:
"""Mandatory class with the player methods"""
def __init__(self, name='Custom_Q1'):
"""Initiaization of an agent"""
self.equity_alive = 0
self.actions = []
self.last_action_in_stage = ''
self.temp_stack = []
self.name = name
self.autoplay = True
self.model = None
def initiate_agent(self, nb_actions):
"""initiate a deep Q agent"""
self.model = Sequential()
self.model.add(Dense(512, activation='relu', input_shape=env.observation_space)) # pylint: disable=no-member
self.model.add(Dropout(0.2))
self.model.add(Dense(512, activation='relu'))
self.model.add(Dropout(0.2))
self.model.add(Dense(512, activation='relu'))
self.model.add(Dropout(0.2))
self.model.add(Dense(nb_actions, activation='linear'))
# Finally, we configure and compile our agent. You can use every built-in Keras optimizer and
# even the metrics!
memory = SequentialMemory(limit=memory_limit, window_length=window_length) # pylint: disable=unused-variable
policy = TrumpPolicy() # pylint: disable=unused-variable
def action(self, action_space, observation, info): # pylint: disable=no-self-use,unused-argument
"""Mandatory method that calculates the move based on the observation array and the action space."""
_ = (observation, info) # not using the observation for random decision
action = None
# decide if explore or explot
# forward
# save to memory
# backward
# decide what to use for training
# update model
# save weights
return action
| {"/run_ppo.py": ["/agents/agent_consider_equity.py", "/agents/agent_ppo.py"], "/agents/agent_custom_q1.py": ["/gym_env/__init__.py"]} |
48,280 | GuiterMan/fypForDemo | refs/heads/master | /main.py | import pygame
import random
import time
import openpyxl
import threading
import os
from background import Background
from color import Color
from car import Car
from pedestrian import Pedestrian
from checkCollision import isTooCloseToCarInFront, isCarCollided, pedLightIsWalking, line56IsCarCollided
from carLight import carTrafficLightSignalSwitching
from pedLight import pedTrafficLightSignalSwitching
def main_sim(threshold1, threshold2, threshold3, threshold4, threshold5, threshold6, threshold7):
pygame.init()
# Set Simulator changeable variable
itlsMode = True # Use ITLS mode or Normal Light
simulatorSpeed = 1 # Simulator speed (default = 1)
totalCarNum = 2000 / 6 # How many car generate in the sim period (2000 to 3000)
totalPedNum = 623 / 6 # How many pedestrian generate in the sim period (623)
totalGrandMotherNum = 12 / 6 # How many grandmother generate in the sim period
simTimePeriod = 3600 / 6 # How long the simulation run (in sec)
carMaxNumAtJunction = threshold1 # Max number of pedstrain wait at junction (default = 15)
carLightGreenMinTime = threshold2 #The least Carlight Green time last (default = 10)
carMaxWaitingtimeAtJunction = threshold3 # Switch light if a car wait more than x sec (default = 30)(Must Be > 16)
pedMaxNumAtJunction = threshold4 # Max number of pedstrain wait at junction (default = 20)
pedLightGreenMinTime = threshold5 # The least Carlight Green time last (default = 10)
pedMaxWaitingtimeAtJunction = threshold6 # Switch light if a ped wait more than x sec (default = 30)
pedLightFlashLongerTime = threshold7 # Exetend Flashing Green Time for pedLight (default = 6)
carLightGreenMaxTime = simTimePeriod # Car green light max time (For fixing bug only)
pedLightGreenMaxTime = simTimePeriod # Car green light max time (For fixing bug only)
# No need to change (just calculation)
carGenRate = (simTimePeriod * 30) / totalCarNum # sec * frames / total carNum
pedGenRate = (simTimePeriod * 30) / totalPedNum # sec * frames / total carNum
grandMotherGenRate = (simTimePeriod * 30) / totalGrandMotherNum
# Set Simulator counting variable
clock = pygame.time.Clock()
running = True
waitingTime = 0
carLight = "green"
pedLight = "red"
frameCount = 0
simTime = 0
# 1400 / (3600 * 30)
# Traffic elements
carArray = []
pedArray = []
carLineArray = []
carArray2 = []
carArray3 = []
carArray4 = []
carLineArray2 = []
carLineArray3 = []
carLineArray4 = []
# Count TrafficModel Time
countCarLightTime = True # For Carlight switch
countPedLightTime = True # For Pedlight switch
countCarWaitAtJunctionTime = True # For counting car waiting at junction
countPedWaitAtJunctionTime = False # For counting ped waiting at junction
carWaitingtimeAtJunctionTimeStamp = 0
pedWaitingtimeAtJunctionTimeStamp = 0
carWaitingtimeAtJunction = 0
pedWaitingtimeAtJunction = 0
totalCarWaitingTime = 0
totalPedWaitingTime = 0
simStartTime = 0
if __name__ == "__main__":
# count real time
simStartTime = time.time()
# Simulation Start
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
# set simulation time period
if int(simTime) == simTimePeriod:
running = False
# count Frame pass in scale
simTime = frameCount / 30
frameCount += 1 * simulatorSpeed
# Draw screen
Background.screen.fill((255, 255, 255))
Background.screen.blit(Background.image, (0, 0))
# Draw title
sys_font = pygame.font.SysFont("None", 30)
rendered = sys_font.render("Traffic Model(Intelligent Traffic Light System)", 0, Color.black)
Background.screen.blit(rendered, (Background.res_x * 0.05, Background.res_y * 0.05))
# Draw road description(carLight, pedStart)
sys_font = pygame.font.SysFont("None", 15)
rendered = sys_font.render("carLight", 0, Color.black)
Background.screen.blit(rendered, (Background.res_x * 0.375, Background.res_y * 0.725))
rendered = sys_font.render("pedStart", 0, Color.black)
Background.screen.blit(rendered, (Background.res_x * 0.3, Background.res_y * 0.725))
# Draw video record area line
pygame.draw.rect(Background.screen, (200, 0, 0), (Background.res_x * 0.498, Background.res_y * 0.48, 5, 200))
rendered = sys_font.render("Car Record Line", 0, Color.black)
# Draw video record area words
sys_font = pygame.font.SysFont("None", 15)
Background.screen.blit(rendered, (Background.res_x * 0.47, Background.res_y * 0.455))
# Draw data area
pygame.draw.rect(Background.screen, (180, 180, 180), (Background.res_x * 0.49, Background.res_y * 0.75, 450, 150))
rendered = sys_font.render("Car Record Line", 0, Color.black)
sys_font = pygame.font.SysFont("None", 20)
rendered = sys_font.render("ITLS data: ", 0, Color.black)
Background.screen.blit(rendered, (Background.res_x * 0.5, Background.res_y * 0.76))
# Draw simulation time
sys_font = pygame.font.SysFont("None", 20)
rendered = sys_font.render("Simulation time: " + str(round(simTime, 2)) + " sec.", 0, Color.black)
Background.screen.blit(rendered, (Background.res_x * 0.05, Background.res_y * 0.15))
# Draw simulation running speed
rendered = sys_font.render("Simulation running at " + str(simulatorSpeed) + "X speed.", 0, Color.black)
Background.screen.blit(rendered, (Background.res_x * 0.05, Background.res_y * 0.1))
# Car traffic light1 signal switching
carTrafficLightSignalSwitching(carLight, Background.screen, Background.res_x, Background.res_y, Color.green,
Color.yellow, Color.red)
# ped traffic light1 signal switching
pedTrafficLightSignalSwitching(pedLight, Background.screen, Background.res_x, Background.res_y, Color.green,
Color.darkGreen, Color.black, Color.red, simStartTime, simTime)
# Count traffic flow at junction
carCountAtCarLight = 0
pedCountAtPedStart = 0
for wCar in carArray:
if 520 > wCar.x > 370:
carCountAtCarLight += 1
for ped in pedArray:
if ped.y == Background.pedStart0YAry[0] and ped.pedStartNum == 0:
pedCountAtPedStart += 1
if ped.y == Background.pedStart0YAry[1] and ped.pedStartNum == 1:
pedCountAtPedStart += 1
sys_font = pygame.font.SysFont("None", 16)
rendered = sys_font.render("Car at carLight: " + str(carCountAtCarLight), 0, Color.black)
Background.screen.blit(rendered, (Background.res_x * 0.51, Background.res_y * 0.79))
rendered = sys_font.render("Ped at pedStart: " + str(pedCountAtPedStart), 0, Color.black)
Background.screen.blit(rendered, (Background.res_x * 0.51, Background.res_y * 0.81))
# CarLight ITLS
if itlsMode == True:
if countCarLightTime:
carLightChgTime = simTime
countCarLightTime = False
if countPedLightTime:
pedLightChgTime = simTime
countPedLightTime = False
if (carCountAtCarLight > 0) and (countCarWaitAtJunctionTime == True) and (carLight == "red"): # At least one car waiting at intersection
carWaitingtimeAtJunctionTimeStamp = simTime
countCarWaitAtJunctionTime = False
if (countCarWaitAtJunctionTime == False) and (carLight == "red"):
carWaitingtimeAtJunction = simTime - carWaitingtimeAtJunctionTimeStamp
else:
carWaitingtimeAtJunction = 0
if (pedCountAtPedStart > 0) and (countPedWaitAtJunctionTime == True) and ((pedLight == "red") or (pedLight == "flashingGreen")): # At least one ped waiting at intersection
pedWaitingtimeAtJunctionTimeStamp = simTime
countPedWaitAtJunctionTime = False
if (countPedWaitAtJunctionTime == False) and (pedCountAtPedStart > 0) and ((pedLight == "red") or (pedLight == "flashingGreen")):
pedWaitingtimeAtJunction = simTime - pedWaitingtimeAtJunctionTimeStamp
else:
pedWaitingtimeAtJunction = 0
if (carLight == "green" and
(((simTime - carLightChgTime >= carLightGreenMinTime) and ((pedCountAtPedStart >= pedMaxNumAtJunction) or (pedWaitingtimeAtJunction > pedMaxWaitingtimeAtJunction))) or (simTime - carLightChgTime >= carLightGreenMaxTime))): # CarLight switch to red conditiion
carLight = "greenToYellow"
# print("carLight switched to yellow.")
# print("carLight status: " + carLight1 + ".\n")
countCarLightTime = True
elif carLight == "greenToYellow" and simTime - carLightChgTime >= 3: # Light yellow last for 3 second
carLight = "red"
pedLight = "green"
# print("carLight switched to red.")
# print("carLight status: " + carLight + ".\n")
countCarLightTime = True
countCarWaitAtJunctionTime = True
countPedLightTime = True
elif (pedLight == "green" and
(((simTime - pedLightChgTime >= carLightGreenMinTime) and ((carCountAtCarLight >= carMaxNumAtJunction) or (carWaitingtimeAtJunction > carMaxWaitingtimeAtJunction))) or (simTime - pedLightChgTime >= pedLightGreenMaxTime))): # CarLight switch to red conditiion
pedLight = "flashingGreen"
countPedWaitAtJunctionTime = True
countPedLightTime = True
elif pedLight == "flashingGreen" and simTime - pedLightChgTime > 10:
if pedLightIsWalking(pedArray, Background.pedStart0YAry):
pedLight = "flashingGreenLonger"
else:
pedLight = "red"
carLight = "redToYellow"
countCarLightTime = True
elif pedLight == "flashingGreenLonger" and simTime - pedLightChgTime > (10 + pedLightFlashLongerTime):
pedLight = "red"
carLight = "redToYellow"
countCarLightTime = True
elif carLight == "redToYellow" and simTime - carLightChgTime >= 3:
carLight = "green"
# print("carLight switched to green.")
# print("carLight status: " + carLight + ".\n")
countCarLightTime = True
# Normal Traffic Light Switching
if itlsMode == False:
if countCarLightTime:
carLightChgTime = simTime
countCarLightTime = False
if carLight == "green" and simTime - carLightChgTime >= 86: # 86
carLight = "greenToYellow"
# print("carLight1 switched to yellow.")
# print("carLight1 status: " + carLight1 + ".\n")
countCarLightTime = True
elif carLight == "greenToYellow" and simTime - carLightChgTime >= 3:
carLight = "red"
# print("carLight1 switched to red.")
# print("carLight1 status: " + carLight1 + ".\n")
countCarLightTime = True
elif carLight == "red" and simTime - carLightChgTime >= 39: # 39
carLight = "redToYellow"
# print("carLight1 switched to yellow")
# print("carLight1 status: " + carLight1 + ".\n")
countCarLightTime = True
elif carLight == "redToYellow" and simTime - carLightChgTime >= 3:
carLight = "green"
# print("carLight1 switched to green")
# print("carLight1 status: " + carLight1 + ".\n")
countCarLightTime = True
# Ped light normal switch
if countPedLightTime:
pedLightChgTime = simTime
countPedLightTime = False
if pedLight == "red" and simTime - pedLightChgTime >= 92: # 92
pedLight = "green"
# print("pedLight1 switched to green.")
# print("pedLight1 status: " + pedLight1 + ".\n")
countPedLightTime = True
elif pedLight == "green" and simTime - pedLightChgTime >= 23: # 23
pedLight = "flashingGreen"
# print("pedLight1 switched to red.")
# print("pedLight1 status: " + pedLight1 + ".\n")
countPedLightTime = True
elif pedLight == "flashingGreen" and simTime - pedLightChgTime >= 10: # 10
pedLight = "bufferRed"
# print("pedLight1 switched to yellow")
# print("pedLight1 status: " + pedLight1 + ".\n")
countPedLightTime = True
elif pedLight == "bufferRed" and simTime - pedLightChgTime >= 6: # 3 + 3
pedLight = "red"
# print("pedLight1 switched to yellow")
# print("pedLight1 status: " + pedLight1 + ".\n")
countPedLightTime = True
# Put car on the road
if random.randint(0, int(carGenRate / simulatorSpeed / 2)) == 1:
line = random.randint(0, 3)
if random.randint(0, 10) == 1:
c = Car(Background.res_x - 100, Background.yArray[line], random.uniform(2, 4) * simulatorSpeed, 0,
line, True) # The place that car start
else:
c = Car(Background.res_x - 100, Background.yArray[line], random.uniform(2, 4) * simulatorSpeed, 0,
line, False) # The place that car start
carArray.append(c)
carLineArray.append([line, c, c.isBus])
for c in carArray:
if c.x > 100 and c.isBus: # The place that car out
c.busStart(Background.screen, Color.darkBlue)
elif c.x > 100 and not(c.isBus):
c.carStart(Background.screen, Color.darkBlue)
if isTooCloseToCarInFront(carLineArray, c) and c.x > 150:
c.speed = 1.5 * simulatorSpeed
else:
c.speed = random.uniform(3, 4) * simulatorSpeed
if isCarCollided(carLineArray, c) and c.x > 150:
c.x -= 0
c.waitingTime += 1 * simulatorSpeed
# Car postition
else:
# 1st part Route movement
if c.x >= 588:
c.x -= c.speed
# 2nd part Route movement
elif 588 > c.x > 395:
c.x -= c.speed * 0.97 # slope of cars
c.y += c.speed * 0.03
# Check 3rd part carlight junction movement
elif 395 >= c.x > 360:
if carLight == "green":
if pedLightIsWalking(pedArray, Background.pedStart0YAry):
c.x -= 0
c.waitingTime += 1 * simulatorSpeed
else:
c.x -= c.speed * 0.97
c.y += c.speed * 0.03
elif carLight == "greenToYellow" or carLight == "redToYellow":
if c.x >= 360:
c.x -= 0
c.waitingTime += 1 * simulatorSpeed
else:
c.x -= c.speed * 0.97
c.y += c.speed * 0.03
elif carLight == "red":
c.x -= 0
c.waitingTime += 1 * simulatorSpeed
# 4rd part Route movement
elif 360 >= c.x > 100:
c.x -= c.speed * 0.91
c.y += c.speed * 0.09
# Put Car on the road 6th line(For demo)
if random.randint(0, int(carGenRate / simulatorSpeed/ 2 * 5)) == 1:
line2 = 1
c2 = Car(Background.res_x - 100, Background.yArray2[1], random.uniform(2, 4) * simulatorSpeed, 0,
line2, False) # The place that car start
carArray2.append(c2)
carLineArray2.append([line2, c2])
for c2 in carArray2:
if c2.x > 100 and c2.y > 400: # The place that car out
c2.carStartImg(Background.screen)
if line56IsCarCollided(carLineArray2, c2) and (c2.x > 150 and c2.y > 400):
print("collided")
pygame.draw.rect(Background.screen, (200, 0, 0),
(500, 400, 150, 1))
c2.x -= 0
else:
# Car postition
# 1st part Route movement
if c2.x >= 588 and 400 <= c2.y:
c2.x -= c2.speed
# 2nd part Route movement
elif 588 > c2.x > 470 and 400 <= c2.y:
c2.x -= 4 * 0.97 # slope of cars
c2.y += 4 * 0.03
# Check 3rd part carlight junction movement
elif 470 >= c2.x > 465 and 400 <= c2.y:
if carLight == "green":
if pedLightIsWalking(pedArray, Background.pedStart0YAry):
c2.x -= 0
c2.waitingTime += 1 * simulatorSpeed
else:
c2.x -= 4 * 0.97
c2.y += 4 * 0.03
elif carLight == "greenToYellow" or carLight == "redToYellow":
if c2.x >= 360:
c2.x -= 0
c2.waitingTime += 1 * simulatorSpeed
else:
c2.x -= 4 * 0.97
c2.y += 4 * 0.03
elif carLight == "red":
c2.x -= 0
c2.waitingTime += 1 * simulatorSpeed
# 4th part Route movement
elif 465 >= c2.x >= 440 and 400 <= c2.y:
pygame.draw.rect(Background.screen, (200, 0, 0),
(500, 370, 150, 1))
c2.x -= 4 * 0.37
c2.y += 4 * -0.63
elif 470 >= c2.x >= 410 and 400 >= c2.y >= 360:
c2.carStartImgAndRotate(Background.screen)
c2.x -= 4 * 0.5
c2.y += 4 * -0.5
elif 120 <=c2.y <= 360:
c2.carStartImgAndRotate2(Background.screen)
c2.x -= 4 * -0.39
c2.y += 4 * -0.61
# Put Car on the road 5th line(For demo)
if random.randint(0, int(carGenRate / simulatorSpeed * 5)) == 1:
line3 = 0
c3 = Car(Background.res_x - 100, Background.yArray2[0], random.uniform(2, 4) * simulatorSpeed, 0,
line3, False) # The place that car start
carArray3.append(c3)
carLineArray3.append([line3, c3])
for c3 in carArray3:
if c3.x > 100 and c3.y > 415: # The place that car out
c3.carStartImg(Background.screen)
if line56IsCarCollided(carLineArray3, c3) and (c3.x > 150 and c3.y > 400):
print("collided")
pygame.draw.rect(Background.screen, (200, 0, 0),
(500, 400, 150, 1))
c3.x -= 0
else:
# Car postition
# 1st part Route movement
if c3.x >= 588 and 415 <= c3.y:
c3.x -= c3.speed
# 2nd part Route movement
elif 588 > c3.x > 470 and 415 <= c3.y:
c3.x -= 4 * 0.97 # slope of cars
c3.y += 4 * 0.03
# Check 3rd part carlight junction movement
elif 470 >= c3.x > 443 and 415 <= c3.y:
if carLight == "green":
if pedLightIsWalking(pedArray, Background.pedStart0YAry):
c3.x -= 0
c3.waitingTime += 1 * simulatorSpeed
else:
c3.x -= 4.5 * 0.97
c3.y += 4.5 * 0.03
elif carLight == "greenToYellow" or carLight == "redToYellow":
if c3.x >= 360:
c3.x -= 0
c3.waitingTime += 1 * simulatorSpeed
else:
c3.x -= 4.5 * 0.97
c3.y += 4.5 * 0.03
elif carLight == "red":
c3.x -= 0
c3.waitingTime += 1 * simulatorSpeed
# 4th part Route movement
elif 445 >= c3.x >= 430 and 415 <= c3.y:
pygame.draw.rect(Background.screen, (200, 0, 0),
(500, 370, 150, 1))
c3.x -= 4.5 * 0.34
c3.y += 4.5 * -0.63
elif 470 >= c3.x >= 350 and 415 >= c3.y >= 360:
c3.carStartImgAndRotate(Background.screen)
c3.x -= 4.5 * 0.40
c3.y += 4.5 * -0.65
elif 120 <= c3.y <= 360:
c3.carStartImgAndRotate2(Background.screen)
c3.x -= 4.5 * -0.39
c3.y += 4.5 * -0.61
# Put Car on left in rd
if random.randint(0, int(carGenRate / simulatorSpeed * 10)) == 1:
line4 = 0
c4 = Car(50, 453, 3 * simulatorSpeed, 0,
line4, False) # The place that car start
carArray4.append(c4)
carLineArray4.append([line4, c4])
for c4 in carArray4:
if c4.x >= 50 and c4.y >= 434: # The place that car out
c4.carStartImg(Background.screen)
c4.x += 5 * 0.93
c4.y -= 5 * 0.07
elif c4.x >= 50 and 434 >= c4.y >= 370:
c4.carStartImgAndRotate2(Background.screen)
c4.x += 5 * 0.50
c4.y += 5 * -0.50
elif 120 <= c4.y <= 370:
c4.carStartImgAndRotate2(Background.screen)
c4.x += 5 * 0.4
c4.y -= 5 * 0.6
# Put Ped on the road (For demo)
# Put pedestrian on the road
if random.randint(0, int(pedGenRate / simulatorSpeed * 5)) == 1:
line = random.randint(0, 3)
pedStartNum = random.randint(0, 1)
c = Pedestrian(Background.pedStart0XAry[line], Background.pedStart0YAry[pedStartNum],
random.uniform(0.2, 0.4) * simulatorSpeed, 0, line, pedStartNum)
pedArray.append(c)
# Put Grand mother on the road
if random.randint(0, int(grandMotherGenRate / simulatorSpeed)) == 1: # Put Grandmother on the road
line = random.randint(0, 3)
pedStartNum = random.randint(0, 1)
c = Pedestrian(Background.pedStart0XAry[line], Background.pedStart0YAry[pedStartNum],
random.uniform(0.09, 0.1) * simulatorSpeed, 0, line, pedStartNum)
pedArray.append(c)
for p in pedArray:
# pedStart0 to pedStart1
if p.y >= Background.pedStart0YAry[1] and p.pedStartNum == 0:
p.pedStart(Background.screen, Color.lightBlue)
# Check Traffic light
if pedLight == "red" and p.y == Background.pedStart0YAry[0]:
p.y -= 0
p.waitingTime += 1 * simulatorSpeed
elif pedLight == "green" or p.y != Background.pedStart0YAry[0]:
p.y -= p.speed
# pedStart1 to pedStart0
if p.y <= Background.pedStart0YAry[0] and p.pedStartNum == 1:
p.pedStart(Background.screen, Color.lightBlue)
# Check Traffic light
if pedLight == "red" and p.y == Background.pedStart0YAry[1]:
p.y += 0
p.waitingTime += 1 * simulatorSpeed
elif pedLight == "green" or p.y != Background.pedStart0YAry[1]:
p.y += p.speed
# Print pedestrian number
for ped in pedArray:
if ped.y == Background.pedStart0YAry[0] and ped.pedStartNum == 0:
Background.pedStart[0] += 1
if ped.y == Background.pedStart0YAry[1] and ped.pedStartNum == 1:
Background.pedStart[1] += 1
sys_font = pygame.font.SysFont("None", 16)
rendered = sys_font.render(str(Background.pedStart[0]), 0, (35, 20, 245))
Background.screen.blit(rendered, (Background.res_x * 0.335, Background.res_y * 0.71))
rendered = sys_font.render(str(Background.pedStart[1]), 0, (35, 20, 245))
Background.screen.blit(rendered, (Background.res_x * 0.335, Background.res_y * 0.546))
rendered = sys_font.render(str(Background.pedStart[2]), 0, (35, 20, 245))
Background.screen.blit(rendered, (Background.res_x * 0.34, Background.res_y * 0.505))
Background.pedStart[0] = 0
Background.pedStart[1] = 0
sys_font = pygame.font.SysFont("None", 16)
rendered = sys_font.render("Pedestrain waiting time at junction counter(for ITLS switching): " + str(round(pedWaitingtimeAtJunction, 2)), 0, (0, 0, 0))
Background.screen.blit(rendered, (Background.res_x * 0.51, Background.res_y * 0.83))
sys_font = pygame.font.SysFont("None", 16)
rendered = sys_font.render("Car waiting time at junction counter(for ITLS switching): " + str(round(carWaitingtimeAtJunction, 2)), 0, (0, 0, 0))
Background.screen.blit(rendered, (Background.res_x * 0.51, Background.res_y * 0.85))
sys_font = pygame.font.SysFont("None", 16)
rendered = sys_font.render( "carlight status: " + carLight, 0, (0, 0, 0))
Background.screen.blit(rendered, (Background.res_x * 0.51, Background.res_y * 0.87))
rendered = sys_font.render("pedlight status: " + pedLight, 0, (0, 0, 0))
Background.screen.blit(rendered, (Background.res_x * 0.51, Background.res_y * 0.89))
rendered = sys_font.render("pervious carlight time: " + str(carLightChgTime), 0, (0, 0, 0))
Background.screen.blit(rendered, (Background.res_x * 0.7, Background.res_y * 0.87))
rendered = sys_font.render("pervious pedlight time: " + str(pedLightChgTime), 0, (0, 0, 0))
Background.screen.blit(rendered, (Background.res_x * 0.7, Background.res_y * 0.89))
# Update Game
clock.tick(30)
pygame.display.update()
# Print Simulation data
print()
print("Simulation has run for " + str(time.time() - simStartTime) + " second(s) real time")
print("Simulation has run for " + str(simTime) + " second(s) simulating time")
print(str(frameCount) + " of frames has pass ")
print("Total car number on the street: " + str(len(carArray)))
for car in carArray:
totalCarWaitingTime += car.waitingTime
print("Average car watiting time: " + str(totalCarWaitingTime / len(carArray) / 30) + " seconds")
print("Total pedestrian number on the street: " + str(len(pedArray)))
for ped in pedArray:
totalPedWaitingTime += ped.waitingTime
print("Average pedestrian watiting time: " + str(totalPedWaitingTime / len(carArray) / 30) + " seconds")
# Save data to file
book = openpyxl.load_workbook('result.xlsx')
sheet = book.active
# K1 default = 1
countSave = sheet['U1']
countSave.value += 1
sheet['U1'] = countSave.value
sheet[str('A' + str(countSave.value))] = countSave.value - 1
sheet[str('B' + str(countSave.value))] = simTime
sheet[str('C' + str(countSave.value))] = len(carArray)
sheet[str('D' + str(countSave.value))] = len(pedArray)
sheet[str('E' + str(countSave.value))] = totalCarWaitingTime / len(carArray) / 30
sheet[str('F' + str(countSave.value))] = totalPedWaitingTime / len(pedArray) / 30
sheet[str('G' + str(countSave.value))] = carMaxNumAtJunction # Max number of car wait at junction
sheet[str('H' + str(countSave.value))] = carMaxWaitingtimeAtJunction # Switch light if a car wait more than x sec (Must Be > 16)
sheet[str('I' + str(countSave.value))] = carLightGreenMinTime #The least Carlight Green time last
sheet[str('J' + str(countSave.value))] = pedMaxNumAtJunction # Max number of pedstrain wait at junction
sheet[str('K' + str(countSave.value))] = pedMaxWaitingtimeAtJunction # Switch light if a ped wait more than x sec
sheet[str('L' + str(countSave.value))] = pedLightGreenMinTime #The least Carlight Green time last
sheet[str('M' + str(countSave.value))] = pedLightFlashLongerTime # Exetend Flashing Green Time for pedLight
book.save("result2.xlsx")
if __name__ == "__main__":
index = 0
for i in range(1):
try:
x = threading.Thread(target=main_sim(random.randint(5, 15), random.randint(5, 20), random.randint(5, 60), random.randint(5, 20), random.randint(5, 20), random.randint(5, 60), random.randint(3, 10)), args=(index,))
# x = threading.Thread(target=main_sim(7, 22, 6, 17, 16, 10, 5), args=(index,))
# 1 = 5, 15 carMaxNumAtJunction
# 2 = 5 , 20 carLightGreenMinTime
# 3 = 5 , 60 carMaxWaitingtimeAtJunction
# 4 = 5, 20 pedMaxNumAtJunction
# 5 = 5 , 20 pedLightGreenMinTime
# 6 = 5, 60 pedMaxWaitingtimeAtJunction
# 7 = 3 , 10 pedLightFlashLongerTime
x.start()
x.join()
index += 1
print("the no " + str(i) + "'s sim")
except Exception as e:
print("Error: unable to start Simulation. Reason:")
print(e) | {"/main.py": ["/background.py", "/color.py", "/car.py", "/pedestrian.py", "/checkCollision.py", "/carLight.py", "/pedLight.py"]} |
48,281 | GuiterMan/fypForDemo | refs/heads/master | /car.py | import pygame
import os
# Car object
class Car:
isBus = False
waitingTime = 0
x = 0
y = 0
speed = 0
line = 0
carImg = pygame.image.load(os.path.join('car.png'))
carImgRot = pygame.image.load(os.path.join('car2.png'))
carImgRot2 = pygame.image.load(os.path.join('car3.png'))
def __init__(self, x, y, speed, waitingTime, line, isBus):
self.waitingTime = 0
self.x = x
self.y = y
self.speed = speed
self.waitingTime = waitingTime
self.line =line
self.isBus = isBus
def carStart(self, screen, color):
pygame.draw.rect(screen, color, (self.x, self.y, 24, 12))
def busStart(self, screen, color):
pygame.draw.rect(screen, color, (self.x, self.y, 45, 12))
# pygame.draw.rect(screen, darkBlue, (self.x, self.y, 40, 20))
def carStartImg(self, screen):
screen.blit(self.carImg, (self.x, self.y))
def carStartImgAndRotate(self, screen):
# carImgRot = pygame.transform.rotate(self.carImg, angle)
#screen.blit(carImgRot, (self.x, self.y))
screen.blit(self.carImgRot2, (self.x, self.y))
def carStartImgAndRotate2(self, screen):
screen.blit(self.carImgRot, (self.x, self.y)) | {"/main.py": ["/background.py", "/color.py", "/car.py", "/pedestrian.py", "/checkCollision.py", "/carLight.py", "/pedLight.py"]} |
48,282 | GuiterMan/fypForDemo | refs/heads/master | /color.py | import pygame
# Color set
class Color:
darkBlue = (140, 60, 10)
# darkBlue = (30, 30, 130)
black = (50, 50, 50)
red = (255, 0, 0)
yellow = (255, 211, 0)
green = (0, 255, 0)
lightBlue = (153, 204, 255)
darkGreen = (0, 200, 0)
| {"/main.py": ["/background.py", "/color.py", "/car.py", "/pedestrian.py", "/checkCollision.py", "/carLight.py", "/pedLight.py"]} |
48,283 | GuiterMan/fypForDemo | refs/heads/master | /pedestrian.py | import pygame
# Pedestrain object
class Pedestrian:
waitingTime = 0
x = 0
y = 0
speed = 0
pedStartNum = 0
def __init__(self, x, y, speed, waitingTime, line, pedStartNum):
self.x = x
self.y = y
self.speed = speed
self.waitingTime = waitingTime
self.pedStartNum = pedStartNum
def pedStart(self, screen, color):
pygame.draw.rect(screen, color, (self.x, self.y, 2.5, 2.5))
| {"/main.py": ["/background.py", "/color.py", "/car.py", "/pedestrian.py", "/checkCollision.py", "/carLight.py", "/pedLight.py"]} |
48,284 | GuiterMan/fypForDemo | refs/heads/master | /pedLight.py | import pygame
import time
# ped traffic light1 signal switching
def pedTrafficLightSignalSwitching(pedLight, screen, res_x, res_y, green, darkGreen, black, red, simStartTime, simTime):
if pedLight == "green":
pygame.draw.rect(screen, green, (res_x * 0.348, res_y * 0.703, 10, 10))
elif pedLight == "flashingGreen" or pedLight == "flashingGreenLonger":
if (int(simTime)) % 2 > 0:
pygame.draw.rect(screen, darkGreen, (res_x * 0.348, res_y * 0.703, 10, 10))
else:
pygame.draw.rect(screen, black, (res_x * 0.348, res_y * 0.703, 10, 10))
elif pedLight == "red" or pedLight == "bufferRed":
pygame.draw.rect(screen, red, (res_x * 0.348, res_y * 0.703, 10, 10))
| {"/main.py": ["/background.py", "/color.py", "/car.py", "/pedestrian.py", "/checkCollision.py", "/carLight.py", "/pedLight.py"]} |
48,285 | GuiterMan/fypForDemo | refs/heads/master | /background.py | import pygame
# Draw screen data
class Background:
res_x = 1024
res_y = 768
screen = pygame.display.set_mode((res_x , res_y))
image = pygame.image.load("rdbg.png")
# Pedstrian startPosition array
pedStart = [0, 0, 0]
pedStart0XAry = [res_x * 0.35, res_x * 0.355, res_x * 0.36, res_x * 0.365]
pedStart0YAry = [res_y * 0.695, res_y * 0.5695]
# Car start Y position
yArray = [res_y * 0.654, res_y * 0.63, res_y * 0.604, res_y * 0.578]
yArray2 = [res_y * 0.552, res_y * 0.525] | {"/main.py": ["/background.py", "/color.py", "/car.py", "/pedestrian.py", "/checkCollision.py", "/carLight.py", "/pedLight.py"]} |
48,286 | GuiterMan/fypForDemo | refs/heads/master | /carLight.py | import pygame
# Car traffic light1 signal switching
def carTrafficLightSignalSwitching(carLight, screen, res_x, res_y, green, yellow, red):
if carLight == "green":
pygame.draw.rect(screen, green, (res_x * 0.377, res_y * 0.7, 15, 15))
elif carLight == "greenToYellow" or carLight == "redToYellow":
pygame.draw.rect(screen, yellow, (res_x * 0.377, res_y * 0.7, 15, 15))
elif carLight == "red":
pygame.draw.rect(screen, red, (res_x * 0.377, res_y * 0.7, 15, 15))
| {"/main.py": ["/background.py", "/color.py", "/car.py", "/pedestrian.py", "/checkCollision.py", "/carLight.py", "/pedLight.py"]} |
48,287 | GuiterMan/fypForDemo | refs/heads/master | /checkCollision.py | # check tooCloseToCarInFront
def isTooCloseToCarInFront(carLineArray, c):
for row in carLineArray:
if row[0] == c.line:
if 50 > (c.x - row[1].x) > 0:
return True
return False
# check collision 4line
def isCarCollided(carLineArray, c):
for row in carLineArray:
if row[0] == c.line:
if 35 > (c.x - row[1].x) > 0:
return True
elif row[2] and 60 > c.x - row[1].x > 0:
return True
return False
# check collision left road
def line56IsCarCollided(carLineArray, c):
for row in carLineArray:
if row[0] == c.line:
if 40 > (c.x - row[1].x) > 0 and 5 > c.y - row[1].y > -5:
return True
return False
def pedLightIsWalking(pedArray, pedStart0YAry):
for ped in pedArray:
if ped.y <= pedStart0YAry[0] and ped.pedStartNum == 1 and ped.y != pedStart0YAry[1]:
return True
if ped.y >= pedStart0YAry[1] and ped.pedStartNum == 0 and ped.y != pedStart0YAry[0]:
return True
return False
| {"/main.py": ["/background.py", "/color.py", "/car.py", "/pedestrian.py", "/checkCollision.py", "/carLight.py", "/pedLight.py"]} |
48,338 | singlemice/e_monitor | refs/heads/master | /new_sysinfo.py | # -*- coding: utf-8 -*-
__author__ = 'TaurenDruid'
from fun_sysinfo import disk_func
disk_func()
| {"/new_sysinfo.py": ["/fun_sysinfo.py"], "/py_unit_test.py": ["/readconfig.py"]} |
48,339 | singlemice/e_monitor | refs/heads/master | /e_monitor.py | # -*- coding: utf-8 -*-
__author__ = 'TaurenDruid'
import tornado.ioloop
import tornado.web
from tornado.options import define,options
import tornado.options
import os
import time
import json
from tornado import httpserver
class MainHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.render('html/index.html')
class ChartsHandler(tornado.web.RequestHandler):
def get(self):
self.render('html/charts.html')
class QueryHandler(tornado.web.RequestHandler):
def get(self):
time.sleep(1)
result={'result':{'res':"success",'status':200}}
print type(result)
js=json.dumps(result,ensure_ascii=False)
print js
self.write(js)
if __name__=="__main__":
define("port", default=8999, help="run on the given port", type=int)
define("debug", default=0, help="debug mode", type=int)
css_path = os.path.join(os.getcwd(),'html/css')
print css_path
server_settings = {'debug' : options.debug}
handles = [
(r"/", MainHandler),
(r"/css/(.*)",tornado.web.StaticFileHandler,{'path':css_path}),
(r"/js/(.*)", tornado.web.StaticFileHandler,{'path': os.path.join(os.getcwd(),'html/js')}),
(r"/font-awesome-4.1.0/(.*)", tornado.web.StaticFileHandler,{'path': os.path.join(os.getcwd(),'html/font-awesome-4.1.0')}),
(r"/fonts/(.*)", tornado.web.StaticFileHandler,{'path': os.path.join(os.getcwd(),'html/fonts')}),
(r"/charts.html",ChartsHandler),
(r"/query",QueryHandler)
]
tornado.options.parse_command_line()
application = tornado.web.Application(handles, **server_settings)
application.listen(options.port,address="0.0.0.0")
tornado.ioloop.IOLoop.instance().start() | {"/new_sysinfo.py": ["/fun_sysinfo.py"], "/py_unit_test.py": ["/readconfig.py"]} |
48,340 | singlemice/e_monitor | refs/heads/master | /readconfig.py | __author__ = 'lihongchao'
import ConfigParser
class ReadConfig():
def __init__(self):
self.config=ConfigParser.ConfigParser()
self.config.read('config.cfg')
def ReadSection(self,section):
dict={}
options=self.config.options(section)
for option in options:
try:
dict[option]=self.config.get(section,option)
except:
print("exception on %s" % (option))
dict[option] = None
return dict
if __name__=="__main__":
rc=ReadConfig()
dic=rc.ReadSection('redis')
print dic
| {"/new_sysinfo.py": ["/fun_sysinfo.py"], "/py_unit_test.py": ["/readconfig.py"]} |
48,341 | singlemice/e_monitor | refs/heads/master | /monitor_web.py | # -*- coding: utf-8 -*-
__author__ = 'TaurenDruid'
import urllib
import datetime,os
from time import sleep
def writeToLog(logmsg):
try:
logfile=os.path.join(os.getcwd(),'check_status.txt')
f = open(logfile, 'a')
except Exception as e:
print "unable to open log file"
try:
f.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " | " + logmsg + "\n")
f.close()
except Exception as e:
print "unable to open log file2 "
i_200=0
i_500=0
while 1:
res=urllib.urlopen('http://www.baidu.com')
code=str(res.getcode())
writeToLog(str(res.getcode()))
if code=='200':
i_200 = i_200 + 1
sleep(1)
else:
i_500=i_500+1
pass
print ("status:200 count:%s -- status:503 count:%s" %(i_200, i_500))
| {"/new_sysinfo.py": ["/fun_sysinfo.py"], "/py_unit_test.py": ["/readconfig.py"]} |
48,342 | singlemice/e_monitor | refs/heads/master | /redis_db.py | __author__ = 'lihongchao'
import redis
from readconfig import ReadConfig
class RedisDB():
def __init__(self):
rc = ReadConfig()
redis = rc.ReadSection('redis')
self.host= redis['host']
self.port = redis['port']
self.db_index = redis['db_index']
if self.host is None:
self.host='127.0.0.1'
if self.port is None:
self.port = 6379
if self.db_index is None:
self.db_index = 12
def connect(self):
self.rs=redis.StrictRedis(host=self.host,port=self.port,db=self.db_index)
return self.rs
if __name__=="__main__":
rdb=RedisDB()
rs=rdb.connect()
rs.set("aaa","1231221")
print rs.get("aaass")
rs.save() | {"/new_sysinfo.py": ["/fun_sysinfo.py"], "/py_unit_test.py": ["/readconfig.py"]} |
48,343 | singlemice/e_monitor | refs/heads/master | /api/util/setting.py | # -*- coding: utf-8 -*-
__author__ = 'TaurenDruid'
from __future__ import with_statement
import json
def get_setting():
with open('config.conf') as config:
return json.load(config)
def get_sqlite():
config=get_setting()
return config["Sqlite"]
def get_redis():
config=get_setting()
return config['RedisServer']
def get_MySQL_server():
config=get_setting()
return config['MySQLServer'] | {"/new_sysinfo.py": ["/fun_sysinfo.py"], "/py_unit_test.py": ["/readconfig.py"]} |
48,344 | singlemice/e_monitor | refs/heads/master | /asy.py | # -*- coding: utf-8 -*-
__author__ = 'TaurenDruid'
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
import urllib
import json
import datetime
import time
from tornado.options import define, options
define("port",default=8000,help="run on the port ")
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
query=self.get_argument('q')
#client=tornado.httpclient.HTTPClient()
client=tornado.httpclient.AsyncHTTPClient()
client.fetch("http://127.0.0.1:8999/query?" + urllib.urlencode({"q": query, "result_type": "recent", "rpp": 100}), callback=self.on_response)
#print "====",response.body
#body=json.loads(response.body)
#print "================"
#print body
#result_count=len(body['result'])
#now=datetime.datetime.utcnow()
#self.write("now:%s" %(now) )
def on_response(self,response):
body=json.loads(response.body)
print "================"
print body
result_count=len(body['result'])
now=datetime.datetime.utcnow()
self.write("now:%s" %(now) )
self.finish()
if __name__ =="__main__":
tornado.options.parse_command_line()
app=tornado.web.Application(handlers=[
(r"/query",IndexHandler)
])
http_server=tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start() | {"/new_sysinfo.py": ["/fun_sysinfo.py"], "/py_unit_test.py": ["/readconfig.py"]} |
48,345 | singlemice/e_monitor | refs/heads/master | /testnumpy.py | # -*- coding: utf-8 -*-
__author__ = 'TaurenDruid'
from numpy import *
import numpy as np
#a = array([arange(2)],[arange[2]])
a = arange(5)
print a
print a.dtype
print a.shape
import urllib
query = "abc"
print(urllib.urlencode({"q": query, "result_type": "recent", "rpp": 100})) | {"/new_sysinfo.py": ["/fun_sysinfo.py"], "/py_unit_test.py": ["/readconfig.py"]} |
48,346 | singlemice/e_monitor | refs/heads/master | /py_unit_test.py | __author__ = 'lihongchao'
import unittest
import readconfig
class readconfig(unittest.TestCase):
def test_ReadSection(self):
rc=readconfig()
rc.ReadConfig('host','ip')
self.assertIsNotNone(rc.ReadConfig('host','ip'),"ok")
if __name__=="__main__":
unittest.main() | {"/new_sysinfo.py": ["/fun_sysinfo.py"], "/py_unit_test.py": ["/readconfig.py"]} |
48,347 | singlemice/e_monitor | refs/heads/master | /fun_sysinfo.py | # -*- coding: utf-8 -*-
__author__ = 'TaurenDruid'
import subprocess
def uname_func():
uname = "uname"
uname_args = "-a"
print "Gathering System information with %s command:\n" % uname
subprocess.call([uname,uname_args])
def disk_func():
diskspace = "df"
diskspace_args = "-h"
print "Gathering system information %s command:\n" % diskspace
subprocess.call([diskspace,diskspace_args])
def main():
uname_func()
disk_func()
if __name__=="__main__":
main() | {"/new_sysinfo.py": ["/fun_sysinfo.py"], "/py_unit_test.py": ["/readconfig.py"]} |
48,348 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /data_structures/linked_list.py | from __future__ import annotations
class Node:
"""
A Node in a Linked List.
Holds a data value and an optional reference to the next Node object in
the Linked List.
"""
data: any
next: Node
def __eq__(self, other: Node):
return self.data == other.data
def __str__(self):
return str(self.data)
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
"""
Implementation of a Linked List.
Offers functionality to add, find, and delete from a linked list of Nodes.
Offers functionality to traverse a linked list of Nodes.
"""
head: Node
def __init__(self):
self.head = None
def add(self, node: Node):
if self.head is None:
return self.add_first(node)
end = self.find_last()
end.next = node
def add_first(self, node: Node):
node.next = self.head
self.head = node
def traverse(self):
tmp = self.head
while tmp is not None:
yield tmp
tmp = tmp.next
def add_after(self, node: Node, to_insert: Node):
tmp = self.find(node)
if tmp is not None:
to_insert.next, tmp.next = tmp.next, to_insert
def add_before(self, node: Node, to_insert: Node):
if self.head is None:
return
if node == self.head:
self.add_first(to_insert)
return
tmp = self.find_before(node)
to_insert.next = tmp.next
tmp.next = to_insert
def find(self, node: Node):
tmp = self.head
while tmp is not None and tmp != node:
tmp = tmp.next
return tmp
def find_last(self):
node = self.head
while node.next is not None:
node = node.next
return node
def find_before(self, node: Node):
tmp = self.head
while tmp.next != node and tmp.next is not None:
tmp = tmp.next
return tmp
def delete(self, node: Node):
if self.head is None:
return
if node == self.head:
self.head = self.head.next
return
before = self.find_before(node)
before.next = node.next
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,349 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /algorithms/sort/quick_sort.py | import random
def quick_sort(arr: list, start: int = None, end: int = None):
"""
Implementation of the Quick Sort algorithm. Sorts a list with time
complexity of O(n log n) and space complexity of O(log n).
:param arr: The list to be sorted
:param start: The start index of from where the list should be sorted
:param end: The end index until which the list should be sorted.
"""
start = 0 if start is None else start
end = len(arr) - 1 if end is None else end
if start < end:
piv_idx = random.randint(start, end)
arr[piv_idx], arr[start] = arr[start], arr[piv_idx]
piv = arr[start]
pos = start
for j in range(start + 1, end + 1):
if arr[j] < piv:
pos += 1
arr[j], arr[pos] = arr[pos], arr[j]
arr[start], arr[pos] = arr[pos], arr[start]
quick_sort(arr, start, pos - 1)
quick_sort(arr, pos + 1, end)
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,350 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /data_structures/trie.py | from __future__ import annotations
from collections import deque
from typing import List, Optional, Tuple
class Node:
"""
Node implementation for a Trie data structure.
Attributes:
char single character of a word
children list of children nodes
final indicates whether the node ends a word (i.e. holds the
last character of a word)
"""
char: Optional[str]
children: dict
final: bool
def __init__(self, char: Optional[str]):
self.char = char
self.children = {}
self.final = False
class Trie:
"""
Implementation of a Trie data structure which holds strings
Attributes:
root root node of the trie. Holds None as a character
"""
root: Node
def __init__(self, root: Node):
self.root = root
def insert(self, key: str):
"""
Insert a string into the Trie.
Iterates over every character of the string and adds new nodes if
nodes holding the characters are not present.
:param key: string to be stored in the trie
"""
end_node, _ = self.find(key, True)
end_node.final = True
def is_member(self, key: str) -> bool:
"""
Searches for a string in the Trie
:param key: string to be searched for in the Trie
:return: True if word was found. False otherwise.
"""
found, _ = self.find(key)
return found is not None
def find(self, key: str, create: bool = False) \
-> Tuple[Optional[Node], List[Node]]:
"""
Finds a string in the Trie.
Note that the returned trace does NOT include the end node.
:param key: string to be found
:param create: whether to create nodes for characters that weren't
found
:return: End node of word and trace of nodes to that end node
"""
q = deque([c for c in key])
trace = []
node = self.root
while len(q) > 0:
trace.append(node)
char = q.popleft()
child = node.children.get(char, None)
if child is None:
if create:
child = Node(char)
node.children[char] = child
else:
return None, trace
node = child
return node, trace
def remove(self, key: str) -> bool:
"""
Removes a string from the Trie.
:param key: string to be removed
:return: True if string could be removed. False otherwise.
:raises: KeyError if the string could not be found in the Trie
"""
end_node, trace = self.find(key)
if end_node is None:
raise KeyError(f'{key} does not exist in Trie')
if len(end_node.children) > 0:
return False
while len(trace) > 1:
node = trace.pop()
if len(node.children) > 1:
break
node.children = {}
if node.final:
break
return True
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,351 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /tests/test_trie.py | import random
from typing import List
from unittest import TestCase
from faker import Faker
from data_structures.trie import Node, Trie
class TestTrie(TestCase):
faker = Faker()
trie: Trie
words: List[str]
def setUp(self):
self.trie = Trie(Node(None))
self.words = self._populate_trie()
def test_insert(self):
word = self.faker.word()
self.trie.insert(word)
self.assertTrue(
self.trie.find(word)[0],
f'Word {word} could not be found in Trie.'
)
def test_insert_multiple(self):
for word in self.words:
self.assertTrue(
self.trie.find(word)[0],
f'Word {word} could not be found in Trie.'
)
def test_is_member(self):
for word in self.words:
self.assertTrue(
self.trie.is_member(word),
f'Word {word} is not a member in Trie, but should be.'
)
def test_find_non_existent(self):
non_existent_word = self.faker.word()
while non_existent_word in self.words:
non_existent_word = self.faker.word()
found, trace = self.trie.find(non_existent_word)
self.assertIsNone(
found,
f'Result {found}:{trace} is not None as expected.'
)
def test_remove(self):
long_word = self.faker.word() * 2
self.trie.insert(long_word)
self.assertTrue(
self.trie.remove(long_word),
f'Word {long_word} could not be removed.'
)
def test_remove_non_existent(self):
long_word = self.faker.word() * 2
while self.trie.is_member(long_word):
long_word = self.faker.word() * 2
self.assertRaises(
KeyError,
self.trie.remove,
long_word
)
def _populate_trie(self):
num_words = random.randint(3, 10)
words = [self.faker.word() for _ in range(0, num_words)]
[self.trie.insert(word) for word in words]
return words
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,352 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /data_structures/stack.py | from typing import List
class Stack:
stack: List[any]
def __init__(self):
self.stack = []
def append(self, obj):
self.stack.append(obj)
def pop(self):
self.stack.pop()
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,353 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /algorithms/sort/merge_sort.py | def merge_sort(arr: list):
"""
Implementation of the Merge Sort algorithm. Sorts a list of integers in
O(N log N) time complexity with O(N) space complexity.
Note that this algorithm performs changes "in place", meaning that the
given array object is edited.
:param arr: The list to be sorted
"""
if len(arr) > 1:
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
merge_sort(left)
merge_sort(right)
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,354 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /tests/test_depth_first_search.py | import random
from unittest import TestCase
import igraph
from algorithms.search.depth_first_search import depth_first_search
from util.graph import create_random_graph
class TestDepthFirstSearch(TestCase):
graph: igraph.Graph
def setUp(self):
self.graph = create_random_graph()
def test_find_vertex(self):
start = 0
find = random.randint(1, self.graph.vcount() - 1)
found = depth_first_search(self.graph, start, find)
self.assertEqual(
find,
found,
f'Could not find vertex {find} in graph. Result: {found}'
)
def test_find_non_existent(self):
start = 0
find = self.graph.vcount() + 1
found = depth_first_search(self.graph, start, find)
self.assertIsNone(
found,
f'Result is not None as expected. Result: {found}'
)
def test_start_and_find_vertex_are_equal(self):
start = random.randint(0, self.graph.vcount())
find = start
found = depth_first_search(self.graph, start, find)
self.assertEqual(
find,
found,
f'Result is not equal to expected outcome: {find}. Result: {found}'
)
def test_find_vertex_with_negative_id(self):
start = 0
find = random.randint(1, self.graph.vcount()) * -1
self.assertRaises(
ValueError,
depth_first_search,
self.graph,
start,
find
)
def test_start_vertex_has_negative_id(self):
start = random.randint(1, self.graph.vcount()) * -1
find = random.randint(1, self.graph.vcount())
self.assertRaises(
ValueError,
depth_first_search,
self.graph,
start,
find
)
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,355 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /data_structures/binary_search_tree.py | from __future__ import annotations
from typing import Optional
class Node:
"""
Node class for a Binary Search Tree. Holds one data value and
optional references to left and right child nodes
"""
data: any
left: Optional[Node]
right: Optional[Node]
def __init__(self, data: any):
self.data = data
self.left = None
self.right = None
class BinarySearchTree:
"""
Implementation of basic functions of a Binary Search Tree.
Supports insertion and finding Nodes in a Binary Search Tree.
"""
root: Optional[Node]
def __init__(self, root: Node):
self.root = root
def insert(self, data: any, node: Optional[Node] = None):
"""
Insert data into the Binary Search Tree.
Gets called recursively until a suitable place for the data value
is found.
:param data: Any object implementing the greater/smaller/equal
functionality
:param node: A node in the Binary Search Tree that gets passed on by
recursive calls
"""
node = self.root if node is None else node
if data < node.data:
if node.left is None:
node.left = Node(data)
else:
self.insert(data, node.left)
elif data > node.data:
if node.right is None:
node.right = Node(data)
else:
self.insert(data, node.right)
else:
node.data = data
def find(self, data: any, node: Optional[Node] = None):
"""
Finds a Node in the Binary Search Tree with a given data value.
This function gets called recursively until either a node is found
that contains the searched for data or the bottom layer of the tree
is reached.
:param data: The data of the Node that is searched for
:param node: A Node in the Binary Search Tree that is passed on by
recursive calls.
:return: Optional[Node]
"""
node = self.root if node is None else node
if data == node.data:
return node
elif data < node.data:
if node.left is None:
return None
return self.find(data, node.left)
else:
if node.right is None:
return None
return self.find(data, node.right)
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,356 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /main.py | import random
import time
from igraph import plot
from algorithms.breadth_first_search import breadth_first_search
from algorithms.depth_first_search import depth_first_search
from util.graph import create_random_graph
if __name__ == "__main__":
graph = create_random_graph()
plot(graph)
source = random.randint(0, graph.vcount())
key = random.randint(0, graph.vcount())
t0 = time.time()
key = depth_first_search(graph, source, key)
t1 = time.time()
print(f'Found: {key is not None}. Time: {t1 - t0}s')
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,357 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /util/array.py | import random
def create_random_array(length=100):
return [random.randint(0, 1000) for _ in range(length)]
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,358 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /tests/test_binary_search_tree.py | import random
from unittest import TestCase
from data_structures.binary_search_tree import BinarySearchTree, Node
class TestBinarySearchTree(TestCase):
tree: BinarySearchTree
def setUp(self):
random_node = Node(random.randint(0, 100))
self.tree = BinarySearchTree(random_node)
def test_insert_root(self):
random_node = Node(random.randint(0, 100))
tree = BinarySearchTree(random_node)
self.assertEqual(
tree.root.data,
random_node.data,
f'Root node data {tree.root.data} '
f'does not equal {random_node.data}'
)
def test_insert_multiple(self):
for n in range(0, random.randint(5, 10)):
self.tree.insert(n)
self._check_binary_search_tree(self.tree.root)
def test_find_root(self):
node_found = self.tree.find(self.tree.root.data)
self.assertEqual(
self.tree.root.data,
node_found.data,
f'Root data {self.tree.root.data} '
f'is not equal to {node_found.data}'
)
def test_find(self):
num_nodes = random.randint(5, 10)
for n in range(0, num_nodes):
self.tree.insert(n)
random_node_data = random.randint(0, num_nodes - 1)
found_node = self.tree.find(random_node_data)
self.assertEqual(
found_node.data,
random_node_data,
f'Found node data {found_node.data} '
f'does not equal {random_node_data}'
)
def test_find_non_existent(self):
num_nodes = random.randint(5, 10)
for n in range(0, num_nodes):
self.tree.insert(n)
random_node_data = random.randint(num_nodes, 100)
res_should_be_none = self.tree.find(random_node_data)
self.assertIsNone(
res_should_be_none,
f'{res_should_be_none} should be None.'
)
def _check_binary_search_tree(self, node: Node):
if node.left is not None:
self.assertLess(
node.left.data,
node.data,
f'Left node data {node.left.data} '
f'is greater than or equal to parent node data {node.data}'
)
self._check_binary_search_tree(node.left)
if node.right is not None:
self.assertGreater(
node.right.data,
node.data,
f'Right node data {node.right.data} is equal or less than '
f'parent node data {node.data}'
)
self._check_binary_search_tree(node.right)
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,359 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /tests/test_linked_list.py | import random
from unittest import TestCase
from faker import Faker
from data_structures.linked_list import LinkedList, Node
class TestLinkedList(TestCase):
faker = Faker()
list: LinkedList
num_nodes = 5
def setUp(self):
nodes = [Node(x) for x in range(0, self.num_nodes)]
self.list = LinkedList()
for node in nodes:
self.list.add(node)
def test_add_node(self):
random_node = Node(self.faker.sentence())
self.list.add(random_node)
last_node = self.list.find_last()
self.assertEqual(
last_node,
random_node,
f'Last node: {last_node} does not equal {random_node}.'
)
def test_add_first_node(self):
random_node = Node(self.faker.sentence())
self.list.add_first(random_node)
self.assertEqual(
self.list.head,
random_node,
f'Head node of list: {self.list.head} does not equal {random_node}'
)
def test_traverse(self):
counter = 0
for node in self.list.traverse():
self.assertEqual(
node.data,
counter,
f'Node data {node.data} does not equal {counter}.'
)
counter += 1
def test_add_after(self):
random_index = random.randint(0, self.num_nodes - 1)
node = self.list.find(Node(random_index))
random_node = Node(random.randint(self.num_nodes + 1, 100))
self.list.add_after(node, random_node)
self.assertEqual(
node.next,
random_node,
f'Next node of {node} does not equal {random_node}'
)
def test_add_before(self):
random_index = random.randint(0, self.num_nodes - 1)
node = self.list.find(Node(random_index))
random_node = Node(random.randint(self.num_nodes + 1, 100))
self.list.add_before(node, random_node)
self.assertEqual(
random_node.next.data,
node.data,
f'Next node of {random_node}: {random_node.next} '
f'does not equal {node}'
)
def test_find(self):
random_index = random.randint(0, self.num_nodes - 1)
random_node_to_find = Node(random_index)
found_node = self.list.find(random_node_to_find)
self.assertEqual(
random_node_to_find.data,
found_node.data,
f'Found Node {found_node.data} is not equal '
f'to {random_node_to_find.data}'
)
def test_find_non_existent(self):
random_non_existent_index = random.randint(self.num_nodes + 1, 1000)
res_should_be_none = self.list.find(Node(random_non_existent_index))
self.assertIsNone(
res_should_be_none,
f'Result: {res_should_be_none} is not None as expected.'
)
def test_find_last(self):
last_node = Node(self.num_nodes - 1)
found_node = self.list.find_last()
self.assertEqual(
last_node.data,
found_node.data,
f'Last node {found_node} not equal to expected {last_node}'
)
def test_find_before(self):
random_index_not_head = random.randint(1, self.num_nodes - 1)
random_node = Node(random_index_not_head)
node_before = self.list.find_before(random_node)
self.assertEqual(
node_before.data,
random_index_not_head - 1,
f'Node before {node_before.data} is not equal '
f'to {random_index_not_head - 1}'
)
def test_delete(self):
random_node = Node(random.randint(0, self.num_nodes - 1))
self.list.delete(random_node)
should_be_none = self.list.find(random_node)
self.assertIsNone(
should_be_none,
f'{should_be_none} is not None as expected.'
)
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,360 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /tests/test_binary_search.py | import random
from unittest import TestCase
from algorithms.search.binary_search import binary_search
class TestBinarySearch(TestCase):
arr: list
def setUp(self):
length = random.randint(10, 1000)
self.arr = range(0, length)
def test_find_value_in_array(self):
val = random.randint(0, len(self.arr) - 1)
pos = binary_search(self.arr, val)
self.assertEqual(
val,
pos,
f'Result {pos} not equal to expected {val}'
)
def test_find_non_existent(self):
val = random.randint(1, 100) * -1
result = binary_search(self.arr, val)
self.assertIsNone(
result,
f'Result {result} not None as expected'
)
def test_find_first_element(self):
val = 0
result = binary_search(self.arr, val)
self.assertEqual(
result,
0,
f'Result {result} is not 0 as expected'
)
def test_find_last_item(self):
val = len(self.arr) - 1
result = binary_search(self.arr, val)
self.assertEqual(
result,
val,
f'Result {result} is not {val} as expected'
)
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,361 | ArturMalkov/Algorithms-in-Python | refs/heads/master | /util/graph.py | import igraph
def create_random_graph(n=15, p=0.3):
return igraph.Graph.Erdos_Renyi(n, p)
| {"/tests/test_trie.py": ["/data_structures/trie.py"], "/tests/test_depth_first_search.py": ["/util/graph.py"], "/main.py": ["/util/graph.py"], "/tests/test_binary_search_tree.py": ["/data_structures/binary_search_tree.py"], "/tests/test_linked_list.py": ["/data_structures/linked_list.py"]} |
48,362 | ladrua/django-oscar-api-vue-storefront | refs/heads/master | /oscar_vue_api/signals.py | from django.db.models.signals import post_save
from django.dispatch import receiver
from oscar.core.loading import get_model
from .search import obj_indexing_product
ProductModel = get_model('catalogue', 'product')
@receiver(post_save, sender=ProductModel)
def index_post(sender, instance, **kwargs):
obj_indexing_product(instance)
| {"/oscar_vue_api/signals.py": ["/oscar_vue_api/search.py"], "/oscar_vue_api/apps.py": ["/oscar_vue_api/signals.py"], "/oscar_vue_api/management/commands/oav_export.py": ["/oscar_vue_api/__init__.py"], "/oscar_vue_api/app.py": ["/oscar_vue_api/authtoken.py", "/oscar_vue_api/__init__.py"], "/oscar_vue_api/authtoken.py": ["/oscar_vue_api/renderers.py"], "/oscar_vue_api/views.py": ["/oscar_vue_api/serializers.py", "/oscar_vue_api/services.py", "/oscar_vue_api/renderers.py"]} |
48,363 | ladrua/django-oscar-api-vue-storefront | refs/heads/master | /oscar_vue_api/apps.py | from django.apps import AppConfig
class OscarVueApiConfig(AppConfig):
name = 'oscar_vue_api'
def ready(self):
import oscar_vue_api.signals
| {"/oscar_vue_api/signals.py": ["/oscar_vue_api/search.py"], "/oscar_vue_api/apps.py": ["/oscar_vue_api/signals.py"], "/oscar_vue_api/management/commands/oav_export.py": ["/oscar_vue_api/__init__.py"], "/oscar_vue_api/app.py": ["/oscar_vue_api/authtoken.py", "/oscar_vue_api/__init__.py"], "/oscar_vue_api/authtoken.py": ["/oscar_vue_api/renderers.py"], "/oscar_vue_api/views.py": ["/oscar_vue_api/serializers.py", "/oscar_vue_api/services.py", "/oscar_vue_api/renderers.py"]} |
48,364 | ladrua/django-oscar-api-vue-storefront | refs/heads/master | /oscar_vue_api/search.py | from elasticsearch_dsl.connections import connections
from elasticsearch_dsl import DocType, Text, Date, Integer, Float, Boolean, Object, Nested, Keyword, Long, InnerDoc
from elasticsearch.helpers import bulk
from elasticsearch import Elasticsearch
from oscar.core.loading import get_model, get_class
connections.create_connection(hosts=['elastic:changeme@db.local'], timeout=20)
class TaxRulesIndex(DocType):
id = Integer()
code = Text()
priority = Integer()
position = Integer()
customer_tax_class_ids = Long()
product_tax_class_ids = Long()
tax_rate_ids = Long()
calculate_subtotal = Boolean()
rates = Object(
properties = {
'id': Integer(),
'tax_country_id': Text(),
'tax_region_id': Integer(),
'tax_postcode': Text(),
'rate': Integer(),
'code': Text(),
}
)
class Index:
name = 'vue_storefront_catalog'
doc_type = 'taxrule'
class Meta:
doc_type = 'taxrule'
def bulk_indexing_taxrules():
TaxRulesIndex().init()
es = connections.get_connection()
all_taxrules = [1]
bulk(client=es, actions=(obj_indexing_taxrule() for b in all_taxrules ))
def obj_indexing_taxrule():
obj = TaxRulesIndex(
meta={
'id': 2,
},
id = 2,
code = "Norway",
priority = 0,
position = 0,
customer_tax_class_ids = [3],
product_tax_class_ids = [2],
tax_rate_ids = [4],
calculate_subtotal = False,
rates = [{
'id': 2,
'tax_country_id': 'NO',
'tax_region_id': 0,
'tax_postcode': '*',
'rate': 25,
'code': 'VAT25%',
}]
)
obj.save()
return obj.to_dict(include_meta=True, skip_empty=False)
class CategoriesIndex(DocType):
id = Integer()
parent_id = Integer()
name = Text()
is_active = Boolean()
position = Integer()
level = Integer()
product_count = Integer()
include_in_menu = Integer()
children_data = Nested(include_in_parent=True)
tsk = Long()
sgn = Text()
class Index:
name = 'vue_storefront_catalog'
doc_type = 'category'
class Meta:
doc_type = 'category'
class InnerCategoriesIndex(InnerDoc):
id = Integer()
parent_id = Integer()
name = Text()
is_active = Boolean()
position = Integer()
level = Integer()
product_count = Integer()
include_in_menu = Integer()
children_data = Nested(include_in_parent=True)
tsk = Long()
sgn = Text()
class Index:
name = 'vue_storefront_catalog'
doc_type = 'category'
class Meta:
doc_type = 'category'
def bulk_indexing_categories():
CategoriesIndex().init()
es = connections.get_connection()
Category = get_model('catalogue', 'category')
bulk(client=es, actions=(obj_indexing_category(b) for b in Category.get_root_nodes().iterator()))
def category_subs(category, parent):
depth = category.get_depth()
sub_categories = []
obj = InnerCategoriesIndex(
id = category.id,
parent_id = parent.id,
name = category.name,
is_active = True,
position = 2,
level = depth + 1,
product_count = 1,
children_data = {},
tsk = 0,
include_in_menu = 0,
sgn = "",
)
obj.children_data
return obj.to_dict(skip_empty=False)
def obj_indexing_category(category):
rootpage = category.get_root()
depth = category.get_depth()
children_data = []
if category.get_children():
for child in category.get_children():
obj_child = category_subs(child, category)
children_data.append(obj_child)
depth = category.get_depth()
obj = CategoriesIndex(
meta={
'id': category.id,
},
id = category.id,
parent_id = 0,
name = category.name,
is_active = True,
position = 2,
level = depth + 1,
product_count = 1,
children_data = children_data,
tsk = 0,
include_in_menu = 0,
sgn = "",
)
obj.save(skip_empty=False)
return obj.to_dict(include_meta=True, skip_empty=False)
class ProductsIndex(DocType):
id = Integer()
sku = Keyword()
name = Text()
attribute_set_id = Integer()
price = Integer()
status = Integer()
visibility = Integer()
type_id = Text()
created_at = Date()
updated_at = Date()
extension_attributes = Long()
product_links = Long()
tier_prices= Long()
custom_attributes = Long()
category = Object(
properties = {
'category_id': Long(),
'name': Text(),
}
)
description = Text()
image = Text()
small_image = Text()
thumbnail = Text()
options_container = Text()
required_options = Integer()
has_options = Integer()
url_key = Text()
tax_class_id = Integer()
children_data = Nested()
configurable_options = Object()
configurable_children = Object()
category_ids = Long()
stock = Object(properties={'is_in_stock': Boolean()})
special_price = Float()
new = Integer()
sale = Integer()
special_from_date = Date()
special_to_date = Date()
priceInclTax = Float()
originalPriceInclTax = Float()
originalPrice = Float()
specialPriceInclTax = Float()
sgn = Text()
class Index:
name = 'vue_storefront_catalog'
doc_type = 'product'
class Meta:
doc_type = 'product'
def bulk_indexing_products():
ProductsIndex().init()
es = connections.get_connection()
Product = get_model('catalogue', 'product')
bulk(client=es, actions=(obj_indexing_product(b) for b in Product.objects.all().iterator()))
def obj_indexing_product(product):
Selector = get_class('partner.strategy', 'Selector')
if product.images.first():
image=product.images.first().original.path
else:
image=""
all_categories = []
category_ids = []
for category in product.categories.all():
category_mapping = [{
'category_id': category.id,
'name': category.name
}]
#category_ids += str(category.id)
all_categories += category_mapping
category_ids.append(category.id)
strategy = Selector().strategy()
price = strategy.fetch_for_product(product).price
obj = ProductsIndex(
meta={
'id': product.id,
},
id = product.id,
sku=product.upc,
name=product.title,
attribute_set_id=None,
price=price.incl_tax,
priceInclTax=price.incl_tax,
status=1,
visibility=4,
type_id="simple",
created_at=product.date_created,
updated_at=product.date_updated,
extension_attributes=[],
product_links = [],
tier_prices = [],
custom_attributes = None,
category=all_categories,
description=product.description,
image=image,
small_image="",
thumbnail="",
options_container="container2",
required_options=0,
has_options=0,
url_key=product.slug,
tax_class_id=2,
children_data={},
configurable_options=[],
configurable_children=[],
category_ids=category_ids,
stock={
'is_in_stock': True,
},
sgn = "",
)
obj.save()
return obj.to_dict(include_meta=True)
| {"/oscar_vue_api/signals.py": ["/oscar_vue_api/search.py"], "/oscar_vue_api/apps.py": ["/oscar_vue_api/signals.py"], "/oscar_vue_api/management/commands/oav_export.py": ["/oscar_vue_api/__init__.py"], "/oscar_vue_api/app.py": ["/oscar_vue_api/authtoken.py", "/oscar_vue_api/__init__.py"], "/oscar_vue_api/authtoken.py": ["/oscar_vue_api/renderers.py"], "/oscar_vue_api/views.py": ["/oscar_vue_api/serializers.py", "/oscar_vue_api/services.py", "/oscar_vue_api/renderers.py"]} |
48,365 | ladrua/django-oscar-api-vue-storefront | refs/heads/master | /oscar_vue_api/__init__.py | default_app_config = 'oscar_vue_api.apps.OscarVueApiConfig'
| {"/oscar_vue_api/signals.py": ["/oscar_vue_api/search.py"], "/oscar_vue_api/apps.py": ["/oscar_vue_api/signals.py"], "/oscar_vue_api/management/commands/oav_export.py": ["/oscar_vue_api/__init__.py"], "/oscar_vue_api/app.py": ["/oscar_vue_api/authtoken.py", "/oscar_vue_api/__init__.py"], "/oscar_vue_api/authtoken.py": ["/oscar_vue_api/renderers.py"], "/oscar_vue_api/views.py": ["/oscar_vue_api/serializers.py", "/oscar_vue_api/services.py", "/oscar_vue_api/renderers.py"]} |
48,366 | ladrua/django-oscar-api-vue-storefront | refs/heads/master | /oscar_vue_api/management/commands/oav_export.py | from django.core.management.base import BaseCommand, CommandError
from oscar_vue_api import search
class Command(BaseCommand):
help = "Export products to ElasticSearch"
def handle(self, *args, **kwargs):
bulk_products = search.bulk_indexing_products()
bulk_categories = search.bulk_indexing_categories()
bulk_taxrules = search.bulk_indexing_taxrules()
self.stdout.write("Just finished indexing")
| {"/oscar_vue_api/signals.py": ["/oscar_vue_api/search.py"], "/oscar_vue_api/apps.py": ["/oscar_vue_api/signals.py"], "/oscar_vue_api/management/commands/oav_export.py": ["/oscar_vue_api/__init__.py"], "/oscar_vue_api/app.py": ["/oscar_vue_api/authtoken.py", "/oscar_vue_api/__init__.py"], "/oscar_vue_api/authtoken.py": ["/oscar_vue_api/renderers.py"], "/oscar_vue_api/views.py": ["/oscar_vue_api/serializers.py", "/oscar_vue_api/services.py", "/oscar_vue_api/renderers.py"]} |
48,367 | ladrua/django-oscar-api-vue-storefront | refs/heads/master | /oscar_vue_api/services.py | import requests
import json
from rest_framework.response import Response
def elastic_result(self, request):
path = request.META['PATH_INFO'].partition("catalog")[2]
fullpath = 'http://db.local:9200' + path
if request.method == "POST":
requestdata = json.loads(request.body)
r = requests.post(fullpath, json=requestdata)
if request.method == "GET":
r = requests.get(fullpath)
items = r.json()
return Response(items)
| {"/oscar_vue_api/signals.py": ["/oscar_vue_api/search.py"], "/oscar_vue_api/apps.py": ["/oscar_vue_api/signals.py"], "/oscar_vue_api/management/commands/oav_export.py": ["/oscar_vue_api/__init__.py"], "/oscar_vue_api/app.py": ["/oscar_vue_api/authtoken.py", "/oscar_vue_api/__init__.py"], "/oscar_vue_api/authtoken.py": ["/oscar_vue_api/renderers.py"], "/oscar_vue_api/views.py": ["/oscar_vue_api/serializers.py", "/oscar_vue_api/services.py", "/oscar_vue_api/renderers.py"]} |
48,368 | ladrua/django-oscar-api-vue-storefront | refs/heads/master | /oscar_vue_api/app.py | from django.conf.urls import url
from oscarapi.app import RESTApiApplication
from oscar_vue_api.authtoken import obtain_auth_token
from . import views
class MyRESTApiApplication(RESTApiApplication):
def get_urls(self):
urls = [
url(r'^user/login', obtain_auth_token),
url(r'^user/me', views.CurrentUserView.as_view()),
url(r'^cart/create', views.CreateBasketView.as_view()),
url(r'^cart/pull', views.PullBasketView.as_view()),
url(r'^cart/update', views.UpdateBasketItemView.as_view()),
url(r'^cart/delete', views.DeleteBasketItemView.as_view()),
url(r'^cart/totals', views.BasketTotalsView.as_view()),
url(r'^cart/shipping-information', views.BasketTotalsView.as_view()),
#url(r'^products/index', views.ProductList.as_view(), name='product-list'),
url(r'^catalog', views.ElasticView.as_view()),
]
return urls + super(MyRESTApiApplication, self).get_urls()
application = MyRESTApiApplication()
| {"/oscar_vue_api/signals.py": ["/oscar_vue_api/search.py"], "/oscar_vue_api/apps.py": ["/oscar_vue_api/signals.py"], "/oscar_vue_api/management/commands/oav_export.py": ["/oscar_vue_api/__init__.py"], "/oscar_vue_api/app.py": ["/oscar_vue_api/authtoken.py", "/oscar_vue_api/__init__.py"], "/oscar_vue_api/authtoken.py": ["/oscar_vue_api/renderers.py"], "/oscar_vue_api/views.py": ["/oscar_vue_api/serializers.py", "/oscar_vue_api/services.py", "/oscar_vue_api/renderers.py"]} |
48,369 | ladrua/django-oscar-api-vue-storefront | refs/heads/master | /oscar_vue_api/authtoken.py | from rest_framework.authtoken.views import ObtainAuthToken
from oscar_vue_api.renderers import CustomJSONRenderer
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class CustomAuthTokenSerializer(serializers.Serializer):
username = serializers.CharField(label=_("Username"))
password = serializers.CharField(
label=_("Password"),
style={'input_type': 'password'},
trim_whitespace=False
)
def validate(self, attrs):
username = attrs.get('username')
password = attrs.get('password')
if username and password:
user = authenticate(request=self.context.get('request'),
email=username, password=password)
# The authenticate call simply returns None for is_active=False
# users. (Assuming the default ModelBackend authentication
# backend.)
if not user:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg, code='authorization')
else:
msg = _('Must include "username" and "password".')
raise serializers.ValidationError(msg, code='authorization')
attrs['user'] = user
return attrs
class CustomObtainAuthToken(ObtainAuthToken):
renderer_classes = (CustomJSONRenderer,)
serializer_class = CustomAuthTokenSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response(token.key)
obtain_auth_token = CustomObtainAuthToken.as_view()
| {"/oscar_vue_api/signals.py": ["/oscar_vue_api/search.py"], "/oscar_vue_api/apps.py": ["/oscar_vue_api/signals.py"], "/oscar_vue_api/management/commands/oav_export.py": ["/oscar_vue_api/__init__.py"], "/oscar_vue_api/app.py": ["/oscar_vue_api/authtoken.py", "/oscar_vue_api/__init__.py"], "/oscar_vue_api/authtoken.py": ["/oscar_vue_api/renderers.py"], "/oscar_vue_api/views.py": ["/oscar_vue_api/serializers.py", "/oscar_vue_api/services.py", "/oscar_vue_api/renderers.py"]} |
48,370 | ladrua/django-oscar-api-vue-storefront | refs/heads/master | /oscar_vue_api/serializers.py | from oscar.core.loading import get_class
from rest_framework import serializers
from oscarapi.serializers import checkout, product
Selector = get_class('partner.strategy', 'Selector')
class TotalSegmentSerializer(serializers.Serializer):
code = serializers.CharField()
title = serializers.CharField()
value = serializers.DecimalField(decimal_places=2, max_digits=12)
class Meta:
fields = '__all__'
class FullBasketItemSerializer(serializers.Serializer):
item_id = serializers.IntegerField(source='id')
price = serializers.IntegerField(source='price_incl_tax')
base_price = serializers.IntegerField(source='price_excl_tax')
qty = serializers.IntegerField(source='quantity')
row_total = serializers.IntegerField(source='price_incl_tax')
base_row_total = serializers.IntegerField(source='price_excl_tax')
row_total_with_discount = serializers.IntegerField(source='price_incl_tax')
tax_amount = serializers.IntegerField(default=0)
base_tax_amount = serializers.IntegerField(default=0)
tax_percent = serializers.IntegerField(default=0)
discount_amount = serializers.IntegerField(default=0)
base_discount_amount = serializers.IntegerField(default=0)
discount_percent = serializers.IntegerField(default=0)
options = serializers.ListField(default=None)
wee_tax_applied_amount = serializers.IntegerField(default=0)
wee_tax_applied = serializers.IntegerField(default=0)
name = serializers.CharField(source='product.title')
product_option = serializers.ListField(default=None)
class Meta:
fields = '__all__'
class FullBasketSerializer(serializers.Serializer):
grand_total = serializers.IntegerField(source='total_incl_tax_excl_discounts')
weee_tax_applied_amount = serializers.IntegerField(default=0)
base_currency_code = serializers.CharField(source='currency')
quote_currency_code = serializers.CharField(source='currency')
items_qty = serializers.IntegerField(source='num_items')
items = FullBasketItemSerializer(many=True, source='lines')
total_segments = serializers.SerializerMethodField()
def get_total_segments(self, obj):
segments = TotalSegmentSerializer(many=True, data=self.context['total_segments'])
segments.is_valid()
return segments.data
class Meta:
fields = '__all__'
class BasketItemSerializer(serializers.Serializer):
sku = serializers.CharField(source='product.upc')
qty = serializers.IntegerField(source='quantity')
item_id = serializers.IntegerField(source='id')
price = serializers.IntegerField(source='price_incl_tax')
name = serializers.CharField(source='product.title')
product_type = serializers.CharField(default='simple')
quote_id = serializers.CharField(source='basket.id')
product_option = serializers.DictField(default={})
class Meta:
fields = '__all__'
class WrapperBasketItemSerializer(serializers.Serializer):
cartItem = serializers.SerializerMethodField()
def get_cartItem(self, obj):
sub_data = SubSerializer(obj)
return sub_data.data
class Meta:
fields = '__all__'
class BasketUpdateResponseSerializer(serializers.Serializer):
item_id = serializers.CharField()
sku = serializers.CharField()
qty = serializers.IntegerField()
name = serializers.CharField()
price = serializers.IntegerField()
product_type = serializers.CharField(default="simple")
quote_id = serializers.IntegerField()
class Meta:
fields = '__all_'
class UserSerializer(serializers.Serializer):
group_id = serializers.ReadOnlyField(default=1)
created_at = serializers.DateTimeField(source='date_joined')
updated_at = serializers.DateTimeField(source='date_joined')
created_in =serializers.ReadOnlyField(default="Default")
email = serializers.EmailField()
firstname = serializers.CharField(source='first_name')
lastname = serializers.CharField(source='last_name')
class Meta():
fields = (
'id',
'group_id',
'created_at',
'updated_at',
'created_in',
'email',
'firstname',
'lastname',
)
class MyProductLinkSerializer(product.ProductLinkSerializer):
images = product.ProductImageSerializer(many=True, required=False)
price = serializers.SerializerMethodField()
name = serializers.CharField(source='title')
created_at = serializers.DateTimeField(source='date_created')
updated_at = serializers.DateTimeField(source='date_updated')
has_options = serializers.ReadOnlyField(default=0)
type_id = serializers.ReadOnlyField(default="simple")
class Meta(product.ProductLinkSerializer.Meta):
fields = (
'id',
'name',
'images',
'price',
'created_at',
'updated_at',
'description',
'sku',
'has_options',
'type_id'
)
def get_price(self, obj):
request = self.context.get("request")
strategy = Selector().strategy(
request=request, user=request.user)
ser = checkout.PriceSerializer(
strategy.fetch_for_product(obj).price,
context={'request': request})
return float(ser.data['incl_tax'])
| {"/oscar_vue_api/signals.py": ["/oscar_vue_api/search.py"], "/oscar_vue_api/apps.py": ["/oscar_vue_api/signals.py"], "/oscar_vue_api/management/commands/oav_export.py": ["/oscar_vue_api/__init__.py"], "/oscar_vue_api/app.py": ["/oscar_vue_api/authtoken.py", "/oscar_vue_api/__init__.py"], "/oscar_vue_api/authtoken.py": ["/oscar_vue_api/renderers.py"], "/oscar_vue_api/views.py": ["/oscar_vue_api/serializers.py", "/oscar_vue_api/services.py", "/oscar_vue_api/renderers.py"]} |
48,371 | ladrua/django-oscar-api-vue-storefront | refs/heads/master | /oscar_vue_api/renderers.py | from rest_framework import renderers
from rest_framework import status
class CustomJSONRenderer(renderers.JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
response_data = {}
response_data['code'] = renderer_context['response'].status_code
response_data['result'] = data
response = super(CustomJSONRenderer, self).render(response_data, accepted_media_type, renderer_context)
return response
| {"/oscar_vue_api/signals.py": ["/oscar_vue_api/search.py"], "/oscar_vue_api/apps.py": ["/oscar_vue_api/signals.py"], "/oscar_vue_api/management/commands/oav_export.py": ["/oscar_vue_api/__init__.py"], "/oscar_vue_api/app.py": ["/oscar_vue_api/authtoken.py", "/oscar_vue_api/__init__.py"], "/oscar_vue_api/authtoken.py": ["/oscar_vue_api/renderers.py"], "/oscar_vue_api/views.py": ["/oscar_vue_api/serializers.py", "/oscar_vue_api/services.py", "/oscar_vue_api/renderers.py"]} |
48,372 | ladrua/django-oscar-api-vue-storefront | refs/heads/master | /oscar_vue_api/views.py | from django.shortcuts import render
from oscarapi.views import product, basket
from .serializers import *
from .services import elastic_result
from .renderers import CustomJSONRenderer
from rest_framework.views import APIView
from rest_framework.response import Response
from oscarapi.basket import operations
from rest_framework.renderers import JSONRenderer
from oscar.core.loading import get_model
from rest_framework import status
BasketModel = get_model('basket', 'Basket')
ProductModel = get_model('catalogue', 'Product')
LineModel = get_model('basket', 'Line')
Selector = get_class('partner.strategy', 'Selector')
selector = Selector()
#class ProductList(product.ProductList):
# serializer_class = MyProductLinkSerializer
class CurrentUserView(APIView):
renderer_classes = (CustomJSONRenderer, )
def get(self, request):
serializer = UserSerializer(request.user)
return Response(serializer.data)
class CreateBasketView(APIView):
"""
Api for retrieving a user's basket id.
GET:
Retrieve your basket id.
"""
renderer_classes = (CustomJSONRenderer, )
def post(self, request, format=None):
basket = operations.get_basket(request)
return Response(basket.id)
class PullBasketView(APIView):
renderer_classes = (CustomJSONRenderer, )
def get(self, request, format=None):
basket_id = request.query_params.get('cartId')
basket = BasketModel.objects.filter(pk=basket_id).first()
serializer = BasketItemSerializer(data=basket.lines, many=True)
serializer.is_valid()
print(serializer.data)
return Response(serializer.data)
class UpdateBasketItemView(APIView):
renderer_classes = (CustomJSONRenderer, )
def validate(self, basket, product, quantity, options):
availability = basket.strategy.fetch_for_product(
product).availability
# check if product is available at all
if not availability.is_available_to_buy:
return False, availability.message
# check if we can buy this quantity
allowed, message = availability.is_purchase_permitted(quantity)
if not allowed:
return False, message
# check if there is a limit on amount
allowed, message = basket.is_quantity_allowed(quantity)
if not allowed:
return False, message
return True, None
def post(self, request, format=None):
quantity = int(request.data['cartItem']['qty'])
product_sku = request.data['cartItem']['sku']
quote_id = request.data['cartItem']['quoteId']
product = ProductModel.objects.filter(upc=product_sku).first()
if 'item_id' in request.data['cartItem']:
line_id = request.data['cartItem']['item_id']
current_line = LineModel.objects.filter(pk=line_id).first()
current_line.quantity = quantity
current_line.save()
else:
basket_id = request.query_params.get('cartId')
basket = BasketModel.objects.filter(pk=basket_id).first()
basket._set_strategy(selector.strategy(request=request, user=request.user))
basket_valid, message = self.validate(
basket, product, int(quantity), options=None)
if not basket_valid:
return Response(
message,
status=status.HTTP_406_NOT_ACCEPTABLE)
line = basket.add_product(product, quantity, options=None)
line_id = line[0].id
response_item = {}
response_item['item_id'] = line_id
response_item['sku'] = product_sku
response_item['qty'] = quantity
response_item['name'] = product.title
response_item['price'] = 200
response_item['product_type'] = 'simple'
response_item['quote_id'] = quote_id
response = BasketUpdateResponseSerializer(data=response_item)
response.is_valid()
print(response.data)
return Response(response.data)
class DeleteBasketItemView(APIView):
renderer_classes = (CustomJSONRenderer, )
def post(self, request):
line_id = request.data['cartItem']['item_id']
line = LineModel.objects.filter(pk=line_id).first()
response = line.delete()
return Response(response)
class BasketTotalsView(APIView):
renderer_classes = (CustomJSONRenderer, )
def post(self, request, format=None):
return self.do_it(request)
def get(self, request, format=None):
return self.do_it(request)
def do_it(self, request, format=None):
basket_id = request.query_params.get('cartId')
basket = BasketModel.objects.filter(pk=basket_id).first()
basket._set_strategy(selector.strategy(request=request, user=request.user))
total_segments = []
total_segments.append({ 'code': 'subtotal', 'title': 'Subtotal', 'value': basket.total_excl_tax})
total_segments.append({ 'code': 'tax', 'title': 'Tax', 'value': basket.total_tax })
total_segments.append({ 'code': 'grand_total', 'title': 'Grand Total', 'value': basket.total_incl_tax })
serializer = FullBasketSerializer(basket, context={'total_segments': total_segments})
return Response(serializer.data)
class ElasticView(APIView):
permission_classes=[]
renderer_classes = (JSONRenderer, )
def get(self, request, format=None):
_search = elastic_result(self, request)
return _search
pass
def post(self, request):
_search = elastic_result(self, request)
return _search
pass
| {"/oscar_vue_api/signals.py": ["/oscar_vue_api/search.py"], "/oscar_vue_api/apps.py": ["/oscar_vue_api/signals.py"], "/oscar_vue_api/management/commands/oav_export.py": ["/oscar_vue_api/__init__.py"], "/oscar_vue_api/app.py": ["/oscar_vue_api/authtoken.py", "/oscar_vue_api/__init__.py"], "/oscar_vue_api/authtoken.py": ["/oscar_vue_api/renderers.py"], "/oscar_vue_api/views.py": ["/oscar_vue_api/serializers.py", "/oscar_vue_api/services.py", "/oscar_vue_api/renderers.py"]} |
48,396 | ashih42/ComputorV2 | refs/heads/master | /function.py | from colorama import Fore, Back, Style
from exceptions import ComputorException
class Function:
def __init__(self, name, local_vars, expr):
self.name = name
self.local_vars = local_vars
if len(self.local_vars) != len(set(self.local_vars)):
raise ComputorException('Function local variables repeated')
self.expr = expr
def __str__(self):
return Style.BRIGHT + Fore.BLUE + self.name + \
'(' + ', '.join(self.local_vars) + ')' + Fore.RESET + Style.RESET_ALL +\
' = ' + self.expr
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,397 | ashih42/ComputorV2 | refs/heads/master | /simplifier.py | from lark import Lark, Transformer, v_args
from colorama import Fore, Back, Style
from matrix import Matrix
from file_to_string import file_to_string
import computor
class Simplifier:
@v_args(inline=True) # Affects the signatures of the methods
class MyTransformer(Transformer):
def __init__(self):
pass
# TOP LEVEL STATEMENTS ------------------------------------
def expr_to_str(self, expr):
if isinstance(expr, str):
return expr
else:
return computor.Computor.instance.compact_str(expr)
# OPERATORS ------------------------------------
def add(self, a, b):
if (not isinstance(a, str)) and (not isinstance(b, str)):
return computor.Computor.instance.add(a, b)
else:
return computor.Computor.instance.compact_str(a) + ' + ' + computor.Computor.instance.compact_str(b)
def sub(self, a, b):
if (not isinstance(a, str)) and (not isinstance(b, str)):
return computor.Computor.instance.sub(a, b)
else:
return computor.Computor.instance.compact_str(a) + ' - ' + computor.Computor.instance.compact_str(b)
def mat_mul(self, a, b):
if (not isinstance(a, str)) and (not isinstance(b, str)):
return computor.Computor.instance.mat_mul(a, b)
else:
return computor.Computor.instance.compact_str(a) + ' ** ' + computor.Computor.instance.compact_str(b)
def mul(self, a, b):
if (not isinstance(a, str)) and (not isinstance(b, str)):
return computor.Computor.instance.mul(a, b)
else:
return computor.Computor.instance.compact_str(a) + ' * ' + computor.Computor.instance.compact_str(b)
def div(self, a, b):
if (not isinstance(a, str)) and (not isinstance(b, str)):
return computor.Computor.instance.div(a, b)
else:
return computor.Computor.instance.compact_str(a) + ' / ' + computor.Computor.instance.compact_str(b)
def mod(self, a, b):
if (not isinstance(a, str)) and (not isinstance(b, str)):
return computor.Computor.instance.mod(a, b)
else:
return computor.Computor.instance.compact_str(a) + ' % ' + computor.Computor.instance.compact_str(b)
def pow(self, base, power):
if (not isinstance(base, str)) and (not isinstance(power, str)):
return computor.Computor.instance.pow(base, power)
else:
return computor.Computor.instance.compact_str(base) + '^' + computor.Computor.instance.compact_str(power)
def neg(self, a):
if not isinstance(a, str):
return computor.Computor.instance.neg(a)
else:
return '-' + computor.Computor.instance.compact_str(a)
# PARSE FOR VALUE ------------------------------------
def parse_number(self, token):
return float(token.value)
def parse_neg_number(self, token):
return -float(token.value)
def resolve_var(self, var_name):
return computor.Computor.instance.resolve_var(var_name)
def imag(self):
return computor.Computor.imag
def pi(self):
return computor.Computor.pi
def parentheses_expr(self, expr):
if isinstance(expr, str):
return '(' + expr + ')'
else:
return expr
def eval_func(self, func_name, *args):
# check if this func_name with this many args exists
computor.Computor.instance.validate_func(func_name, len(args))
# if any arg is string
if any(map(lambda x: isinstance(x, str), args)):
return func_name + '(' + ', '.join(map(lambda x: computor.Computor.instance.compact_str(x), args)) + ')'
else:
return computor.Computor.instance.eval_function(func_name, args)
# BUILT-IN FUNCTIONS ------------------------------------
def eval_built_in(self, func_tuple, arg):
func = func_tuple[0]
func_str = func_tuple[1]
if isinstance(arg, str):
return func_str + '(' + arg + ')'
else:
return func(arg)
def inv(self):
return computor.Computor.instance.inv, 'inv'
def transp(self):
return computor.Computor.instance.transp, 'transp'
def sqrt(self):
return computor.Computor.instance.sqrt, 'sqrt'
def sin(self):
return computor.Computor.instance.sin, 'sin'
def cos(self):
return computor.Computor.instance.cos, 'cos'
def tan(self):
return computor.Computor.instance.tan, 'tan'
def deg(self):
return computor.Computor.instance.deg, 'deg'
def rad(self):
return computor.Computor.instance.rad, 'rad'
# MATRIX CONSTRUCTION ------------------------------------
def get_matrix(self, *rows):
return Matrix(rows)
def get_mat_rows(self, *elements):
return elements
def __init__(self):
grammar = file_to_string('grammars/simplifier.lark')
self.__lark_parser = Lark(grammar, parser='lalr', transformer=Simplifier.MyTransformer())
def simplify(self, statement):
return self.__lark_parser.parse(statement)
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,398 | ashih42/ComputorV2 | refs/heads/master | /variable.py | from colorama import Fore, Back, Style
class Variable:
def __init__(self, name, value):
self.name = name
self.value = value
def __str__(self):
return Style.BRIGHT + Fore.BLUE + self.name + Fore.RESET + Style.RESET_ALL + ' = ' + str(self.value)
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,399 | ashih42/ComputorV2 | refs/heads/master | /main.py | from colorama import Fore, Back, Style
from sys import argv
from os import path, getenv
import readline
from computor import Computor
def terminate_with_usage():
print(Style.BRIGHT + 'usage: ' + Style.RESET_ALL)
print ('python3 ' + Fore.BLUE + 'main.py ' + Fore.RESET + '-h \t\t\t (usage)')
print ('python3 ' + Fore.BLUE + 'main.py ' + Fore.RESET + '\t\t\t (interactive mode)')
print ('python3 ' + Fore.BLUE + 'main.py ' + Fore.RESET + 'statement' + '\t\t (process one statement)')
print ('python3 ' + Fore.BLUE + 'main.py ' + Fore.RESET + '-f ' + Fore.CYAN + 'filename' + Fore.RESET +
'\t\t (process all statements in file)')
print('\nexport ' + Fore.BLUE + 'COMPUTOR_PROMPT' + Fore.RESET + '=' + \
Fore.GREEN + 'value' + Fore.RESET + ' to set prompt in interactive mode')
print(Style.BRIGHT + '\n[Built-in Commands]' + Style.RESET_ALL)
print(Fore.BLUE + '@VARS' + Fore.RESET + '\t\t List all variables')
print(Fore.BLUE + '@FUNCS' + Fore.RESET + '\t\t List all functions')
print(Fore.BLUE + '@DANCE' + Fore.RESET + '\t\t ¯\\_(ツ)_/¯')
print(Fore.BLUE + '@DOGE' + Fore.RESET + '\t\t ¯\\_(ツ)_/¯')
print(Style.BRIGHT + '\n[Built-in Constants]' + Style.RESET_ALL)
print(Fore.BLUE + 'i' + Fore.RESET + '\t\t imaginary number')
print(Fore.BLUE + 'pi' + Fore.RESET + '\t\t natural number')
print(Style.BRIGHT + '\n[Built-in Functions]' + Style.RESET_ALL)
print(Fore.BLUE + 'inv(x)' + Fore.RESET + '\t\t multicative inverse')
print(Fore.BLUE + 'transp(x)' + Fore.RESET + '\t matrix transpose')
print(Fore.BLUE + 'sqrt(x)' + Fore.RESET + '\t\t square root')
print(Fore.BLUE + 'sin(radians)' + Fore.RESET + '\t sine')
print(Fore.BLUE + 'cos(radians)' + Fore.RESET + '\t cosine')
print(Fore.BLUE + 'tan(radians)' + Fore.RESET + '\t tangent')
print(Fore.BLUE + 'deg(radians)' + Fore.RESET + '\t convert radians to degrees')
print(Fore.BLUE + 'rad(degrees)' + Fore.RESET + '\t convert degrees to radians')
quit()
def interactive_loop(computor):
prompt = getenv('COMPUTOR_PROMPT')
if prompt is None or prompt == '':
prompt = '🍔 Enter statement: '
while True:
print()
statement = input(prompt)
if statement.strip().upper() == 'EXIT':
break
if statement == '' or statement[0] == '#':
continue
computor.process_statement(statement)
def process_file(computor, filename):
base_path = path.dirname(__file__)
file_path = path.join(base_path, filename)
with open(file_path, 'r') as file:
for line in file:
statement = line.strip()
if statement == '' or statement[0] == '#':
print(Fore.MAGENTA + statement + Fore.RESET)
else:
computor.process_statement(statement)
def main():
try:
computor = Computor()
# Interactive mode
if len(argv) == 1:
interactive_loop(computor)
# Usage mode
elif argv[1] == '-h':
terminate_with_usage()
# File-processing mode
elif argv[1] == '-f':
if len(argv) != 3:
terminate_with_usage()
filename = argv[2]
process_file(computor, filename)
# Single statement-processing mode
elif len(argv) == 2:
statement = argv[1]
computor.process_statement(statement)
# Nope mode
else:
terminate_with_usage()
except IOError as e:
print(Style.BRIGHT + Fore.RED + 'I/O Error: ' + Style.RESET_ALL + Fore.RESET + str(e))
if __name__ == '__main__':
main()
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,400 | ashih42/ComputorV2 | refs/heads/master | /parser.py | from lark import Lark, Transformer, v_args
from lark.exceptions import LarkError
from colorama import Fore, Back, Style
from exceptions import ParserException
from file_to_string import file_to_string
import computor
class Parser:
@v_args(inline=True) # Affects the signatures of the methods
class MyTransformer(Transformer):
def __init__(self):
pass
# TOP LEVEL STATEMENTS ------------------------------------
def eval_expr(self, expr, _=None):
return computor.Computor.instance.eval(expr)
def show_func(self, func_name, *args):
if '?' in args[-1]:
args = args[:-1]
computor.Computor.instance.show_func(func_name, args)
def define_var(self, var_name, expr):
value = computor.Computor.instance.eval(expr)
computor.Computor.instance.set_var(var_name, value)
def define_func(self, func_name, *args):
local_vars = args[0:-1]
expr = args[-1]
computor.Computor.instance.set_func(func_name, local_vars, expr)
def show_vars(self):
computor.Computor.instance.show_vars()
def show_funcs(self):
computor.Computor.instance.show_funcs()
def dance(self):
computor.Computor.instance.dance()
def doge(self):
computor.Computor.instance.doge()
# OPERATORS ------------------------------------
def add(self, a, b):
return a + ' + ' + b
def sub(self, a, b):
return a + ' - ' + b
def mat_mul(self, a, b):
return a + ' ** ' + b
def mul(self, a, b):
return a + ' * ' + b
def div(self, a, b):
return a + ' / ' + b
def mod(self, a, b):
return a + ' % ' + b
def pow(self, base, power):
return base + '^' + power
def neg(self, a):
return '-' + a
# PARSE FOR VALUE ------------------------------------
def parse_number(self, token):
return str(token.value)
def parse_neg_number(self, token):
return '-' + str(token.value)
# [number] thing -> 1 or 2 args
def parse_number_mul_with_thing(self, *args):
# case: thing
if len(args) == 1:
thing = args[0]
return thing
# case: number thing
elif len(args) == 2:
number = str(args[0].value)
thing = args[1]
return number + ' * ' + thing
def imag(self):
return 'i'
def pi(self):
return 'pi'
def parentheses_expr(self, expr):
return '(' + expr + ')'
def eval_func(self, func_name, *args):
return func_name + '(' + ','.join(args) + ')'
# BUILT-IN FUNCTIONS ------------------------------------
def eval_built_in(self, func_name, arg):
return func_name + '(' + arg + ')'
def inv(self):
return 'inv'
def transp(self):
return 'transp'
def sqrt(self):
return 'sqrt'
def sin(self):
return 'sin'
def cos(self):
return 'cos'
def tan(self):
return 'tan'
def deg(self):
return 'deg'
def rad(self):
return 'rad'
# MATRIX CONSTRUCTION ------------------------------------
def get_matrix(self, *rows):
return '[' + ';'.join(rows) + ']'
def get_mat_rows(self, *elements):
return '[' + ','.join(map(str, elements)) + ']'
# NAME VALIDATION ------------------------------------
def parse_name(self, token):
reserved = ['i', 'pi', 'inv', 'transp', 'sqrt', 'sin', 'cos', 'tan']
name = token.value
if name.lower() in reserved:
raise ParserException('Cannot use \'' + Fore.BLUE + name + Fore.RESET + '\' as variable or function name')
return name
def __init__(self):
grammar = file_to_string('grammars/parser.lark')
self.__lark_parser = Lark(grammar, parser='lalr', transformer=Parser.MyTransformer())
def parse(self, statement):
try:
statement = self.__preprocess(statement)
return self.__lark_parser.parse(statement)
except LarkError as e:
raise ParserException(e)
# Prepend 'def' in a function definition statement, to help LALR(1) parser distinguish this statement
def __preprocess(self, statement):
if '=' in statement and not '?' in statement:
lhs = statement.split('=')[0]
if '(' in lhs and ')' in lhs:
statement = 'def ' + statement
return statement
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,401 | ashih42/ComputorV2 | refs/heads/master | /computor.py | from colorama import Fore, Back, Style
from math import sin, cos, tan, pi
from os import system
from function import Function
from variable import Variable
from complex import Complex
from matrix import Matrix
from parser import Parser
from simplifier import Simplifier
# from evaluator import Evaluator
import evaluator
from solver import Solver
from exceptions import ParserException, ComputorException
class Computor:
instance = None
imag = Complex(0.0, 1.0)
pi = pi # Computor.pi = math.pi
def __init__(self):
if Computor.instance is None:
Computor.instance = self
self.__parser = Parser()
self.__simplifier = Simplifier()
self.__evaluator = evaluator.Evaluator()
self.__solver = Solver()
self.__vars = {}
self.__funcs = {}
self.__local_vars = [] # list of tuple (name, value), to be used as stack
else:
raise ComputorException('Computor.instance already instantiated')
# TOP LEVEL OPERATIONS ------------------------------------
def process_statement(self, statement):
try:
if '@SOLVE' in statement:
self.__solver.solve(statement)
else:
result = self.__parser.parse(statement)
if result is not None:
print(result)
except OverflowError as e:
print(Style.BRIGHT + Fore.RED + 'OverflowError: ' + Style.RESET_ALL + Fore.RESET + str(e))
except RecursionError as e:
print(Style.BRIGHT + Fore.RED + 'RecursionError: ' + Style.RESET_ALL + Fore.RESET + str(e))
except ParserException as e:
print(Style.BRIGHT + Fore.RED + 'ParserException: ' + Style.RESET_ALL + Fore.RESET + str(e))
except ComputorException as e:
print(Style.BRIGHT + Fore.RED + 'ComputorException: ' + Style.RESET_ALL + Fore.RESET + str(e))
finally:
self.__local_vars.clear()
def eval(self, expr):
return self.__evaluator.eval(expr)
def compact_str(self, value):
if isinstance(value, Matrix):
return value.get_compact_str()
else:
return str(value)
def set_var(self, var_name, value):
var_name_lc = var_name.lower()
self.__vars[var_name_lc] = Variable(var_name, value)
print(value)
def get_var(self, var_name):
var_name_lc = var_name.lower()
# Search in stack of local variables
for local_var in reversed(self.__local_vars):
if local_var[0].lower() == var_name_lc:
return local_var[1]
# Search in dictionary of global variables
if var_name_lc in self.__vars:
return self.__vars[var_name_lc].value
raise ComputorException('Variable \'' + Fore.BLUE + var_name + Fore.RESET + '\' is not defined')
def resolve_var(self, var_name):
var_name_lc = var_name.lower()
# Search in stack of local variables
# if found, return the variable name as string
for local_var in reversed(self.__local_vars):
if local_var[0].lower() == var_name_lc:
return var_name
# Search in dictionary of global variables
# if found, return the variable's value
if var_name_lc in self.__vars:
return self.__vars[var_name_lc].value
raise ComputorException('Variable \'' + Fore.BLUE + var_name + Fore.RESET + '\' is not defined')
def set_func(self, func_name, local_vars, expr):
func_name_lc = func_name.lower()
function = Function(func_name, local_vars, expr)
# push local variables on stack
for var_name in function.local_vars:
self.__local_vars.append((var_name, None))
# simplify the function
function.expr = self.__simplifier.simplify(function.expr)
# pop local variables from stack
for _ in self.__local_vars:
self.__local_vars.pop()
self.__funcs[func_name_lc] = function
print(function)
def get_func(self, func_name):
func_name_lc = func_name.lower()
if func_name_lc in self.__funcs:
return (self.__funcs[func_name_lc])
else:
raise ComputorException('Function \'' + Fore.GREEN + func_name + Fore.RESET + '\' is not defined')
def validate_func(self, func_name, num_args):
func_name_lc = func_name.lower()
# check name matches
if func_name_lc in self.__funcs:
function = self.__funcs[func_name_lc]
# check number of args match
if len(function.local_vars) == num_args:
return
raise ComputorException('No such function: ' + Fore.BLUE + func_name + Fore.RESET)
def show_func(self, func_name, args):
func_name = func_name.lower()
# check if func_name matches
if func_name in self.__funcs:
function = self.__funcs[func_name]
# check if args match
if len(function.local_vars) == len(args) and \
all([ x.lower() == y.lower() for x, y in zip(function.local_vars, args) ]):
print(function)
return
raise ComputorException('No such function: ' + Fore.BLUE + func_name + '(' + ', '.join(args) + ')' + Fore.RESET)
def eval_function(self, func_name, args):
function = self.get_func(func_name)
if len(function.local_vars) != len(args):
raise ComputorException('Invalid parameters for ' + str(function))
# push local variables on stack
for var_name, value in zip(function.local_vars, args):
self.__local_vars.append((var_name, value))
# evaluate
# result = self.__parser.parse(function.expr)
result = self.__evaluator.eval(function.expr)
# pop local variables from stack
for _ in self.__local_vars:
self.__local_vars.pop()
return result
def show_vars(self):
print(Style.BRIGHT + '[VARIABLES]' + Style.RESET_ALL)
for _, value in self.__vars.items():
print(value)
def show_funcs(self):
print(Style.BRIGHT + '[FUNCTIONS]' + Style.RESET_ALL)
for _, value in self.__funcs.items():
print(value)
def dance(self):
dance_str = r'''(_\ヽ
\\ .Λ_Λ.
\( ˇωˇ)
> ⌒ヽ
/ へ\
/ / \\
レ ノ ヽ_つ
/ /
/ /|
( (ヽ
| |、\
| 丿 \ ⌒)
| | ) /
`ノ ) Lノ
(_/'''
print(dance_str)
# Source: https://github.com/thiderman/doge
def doge(self):
system('doge')
# OPERATORS ------------------------------------
def add(self, a, b):
if isinstance(a, float):
if isinstance(b, float):
return a + b
elif isinstance(b, Complex):
return Complex.add(Complex(a), b)
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Rational + Matrix')
elif isinstance(a, Complex):
if isinstance(b, float):
return Complex.add(a, Complex(b))
elif isinstance(b, Complex):
return Complex.add(a, b)
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Complex + Matrix')
elif isinstance(a, Matrix):
if isinstance(b, float):
raise ComputorException('Illegal operation: Matrix + Rational')
elif isinstance(b, Complex):
raise ComputorException('Illegal operation: Matrix + Complex')
elif isinstance(b, Matrix):
return Matrix.add(a, b)
raise ComputorException('Computor.add(): something bad happened 🤷')
def sub(self, a, b):
if isinstance(a, float):
if isinstance(b, float):
return a - b
elif isinstance(b, Complex):
return Complex.sub(Complex(a), b)
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Rational - Matrix')
elif isinstance(a, Complex):
if isinstance(b, float):
return Complex.sub(a, Complex(b))
elif isinstance(b, Complex):
return Complex.sub(a, b)
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Complex - Matrix')
elif isinstance(a, Matrix):
if isinstance(b, float):
raise ComputorException('Illegal operation: Matrix - Rational')
elif isinstance(b, Complex):
raise ComputorException('Illegal operation: Matrix - Complex')
elif isinstance(b, Matrix):
return Matrix.sub(a, b)
raise ComputorException('Computor.sub(): something bad happened 🤷')
def mat_mul(self, a, b):
if isinstance(a, Matrix) and isinstance(b, Matrix):
return Matrix.mat_mul(a, b)
else:
raise ComputorException('**: both operands must be Matrix')
def mat_mul(self, a, b):
if isinstance(a, float):
if isinstance(b, float):
raise ComputorException('Illegal operation: Rational ** Rational')
elif isinstance(b, Complex):
raise ComputorException('Illegal operation: Rational ** Complex')
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Rational ** Matrix')
elif isinstance(a, Complex):
if isinstance(b, float):
raise ComputorException('Illegal operation: Complex ** Rational')
elif isinstance(b, Complex):
raise ComputorException('Illegal operation: Complex ** Complex')
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Complex ** Matrix')
elif isinstance(a, Matrix):
if isinstance(b, float):
raise ComputorException('Illegal operation: Matrix ** Rational')
elif isinstance(b, Complex):
raise ComputorException('Illegal operation: Matrix ** Complex')
elif isinstance(b, Matrix):
return Matrix.mat_mul(a, b)
raise ComputorException('Computor.mat_mul(): something bad happened 🤷')
def mul(self, a, b):
if isinstance(a, float):
if isinstance(b, float):
return a * b
elif isinstance(b, Complex):
return Complex.mul(Complex(a), b)
elif isinstance(b, Matrix):
return Matrix.scalar_mul(a, b)
elif isinstance(a, Complex):
if isinstance(b, float):
return Complex.mul(a, Complex(b))
elif isinstance(b, Complex):
return Complex.mul(a, b)
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Complex * Matrix')
elif isinstance(a, Matrix):
if isinstance(b, float):
return Matrix.scalar_mul(b, a)
elif isinstance(b, Complex):
raise ComputorException('Illegal operation: Matrix * Complex')
elif isinstance(b, Matrix):
return Matrix.element_mul(a, b)
raise ComputorException('Computor.mul(): something bad happened 🤷')
def div(self, a, b):
if isinstance(a, float):
if isinstance(b, float):
if b == 0:
raise ComputorException('Division by zero')
return a / b
elif isinstance(b, Complex):
return Complex.div(Complex(a), b)
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Rational / Matrix')
elif isinstance(a, Complex):
if isinstance(b, float):
return Complex.div(a, Complex(b))
elif isinstance(b, Complex):
return Complex.div(a, b)
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Complex / Matrix')
elif isinstance(a, Matrix):
if isinstance(b, float):
if b == 0:
raise ComputorException('Division by zero')
return Matrix.scalar_mul(1 / b, a)
elif isinstance(b, Complex):
raise ComputorException('Illegal operation: Matrix / Complex')
elif isinstance(b, Matrix):
return Matrix.mat_mul(a, b.get_inverse())
raise ComputorException('Computor.div(): something bad happened 🤷')
def mod(self, a, b):
if isinstance(a, float):
if isinstance(b, float):
if not (a.is_integer() and b.is_integer()):
raise ComputorException('Illegal operation: ' + str(a) + ' % ' + str(b))
return a % b
elif isinstance(b, Complex):
raise ComputorException('Illegal operation: Rational % Complex')
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Rational % Matrix')
elif isinstance(a, Complex):
if isinstance(b, float):
raise ComputorException('Illegal operation: Complex % Rational')
elif isinstance(b, Complex):
raise ComputorException('Illegal operation: Complex % Complex')
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Complex % Matrix')
elif isinstance(a, Matrix):
if isinstance(b, float):
raise ComputorException('Illegal operation: Matrix % Rational')
elif isinstance(b, Complex):
raise ComputorException('Illegal operation: Matrix % Complex')
elif isinstance(b, Matrix):
raise ComputorException('Illegal operation: Matrix % Matrix')
raise ComputorException('Computor.mul(): something bad happened 🤷')
def pow(self, base, power):
if not (isinstance(power, float) and power.is_integer() and int(power) >= 0):
raise ComputorException('Exponent ' + Fore.RED + str(power) + Fore.RESET + ' must be a non-negative integer')
power = int(power)
if isinstance(base, float):
return base ** power
elif isinstance(base, Complex):
return Complex.pow(base, power)
elif isinstance(base, Matrix):
return Matrix.pow(base, power)
raise ComputorException('Computor.pow(): something bad happened 🤷')
def neg(self, a):
if isinstance(a, float):
return -a
elif isinstance(a, Complex):
return Complex.neg(a)
elif isinstance(a, Matrix):
return Matrix.neg(a)
raise ComputorException('Computor.neg(): something bad happened 🤷')
# BUILT-IN FUNCTIONS ------------------------------------
def inv(self, a):
if isinstance(a, float):
return self.div(1.0, a)
elif isinstance(a, Complex):
return self.div(1.0, a)
elif isinstance(a, Matrix):
return a.get_inverse()
raise ComputorException('Computor.inv(): something bad happened 🤷')
def transp(self, a):
if isinstance(a, float):
raise ComputorException('Illegal operation: transp(Rational)')
elif isinstance(a, Complex):
raise ComputorException('Illegal operation: transp(Complex)')
elif isinstance(a, Matrix):
return a.get_transpose()
raise ComputorException('Computor.inv(): something bad happened 🤷')
def sqrt(self, a):
if isinstance(a, float):
if a >= 0:
return a ** 0.5
else:
return Complex(0, (-a) ** 0.5)
elif isinstance(a, Complex):
raise ComputorException('Illegal operation: sqrt(Complex)')
elif isinstance(a, Matrix):
raise ComputorException('Illegal operation: sqrt(Matrix)')
raise ComputorException('Computor.sqrt(): something bad happened 🤷')
def sin(self, radians):
if isinstance(radians, float):
return sin(radians)
elif isinstance(radians, Complex):
raise ComputorException('Illegal operation: sin(Complex)')
elif isinstance(radians, Matrix):
raise ComputorException('Illegal operation: sin(Matrix)')
raise ComputorException('Computor.sin(): something bad happened 🤷')
def cos(self, radians):
if isinstance(radians, float):
return cos(radians)
elif isinstance(radians, Complex):
raise ComputorException('Illegal operation: cos(Complex)')
elif isinstance(radians, Matrix):
raise ComputorException('Illegal operation: cos(Matrix)')
raise ComputorException('Computor.cos(): something bad happened 🤷')
def tan(self, radians):
if isinstance(radians, float):
return tan(radians)
elif isinstance(radians, Complex):
raise ComputorException('Illegal operation: tan(Complex)')
elif isinstance(radians, Matrix):
raise ComputorException('Illegal operation: tan(Matrix)')
raise ComputorException('Computor.tan(): something bad happened 🤷')
def deg(self, radians):
if isinstance(radians, float):
return radians * 180 / Computor.pi
elif isinstance(radians, Complex):
raise ComputorException('Illegal operation: deg(Complex)')
elif isinstance(radians, Matrix):
raise ComputorException('Illegal operation: deg(Matrix)')
raise ComputorException('Computor.deg(): something bad happened 🤷')
def rad(self, degrees):
if isinstance(degrees, float):
return degrees * Computor.pi / 180
elif isinstance(degrees, Complex):
raise ComputorException('Illegal operation: rad(Complex)')
elif isinstance(degrees, Matrix):
raise ComputorException('Illegal operation: rad(Matrix)')
raise ComputorException('Computor.rad(): something bad happened 🤷')
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,402 | ashih42/ComputorV2 | refs/heads/master | /term.py | from colorama import Fore, Back, Style
class Term:
def __init__(self, coef, degree):
self.coef = coef
self.degree = degree
def __str__(self):
buffer = ''
if self.degree == 0:
buffer += Fore.RED
elif self.degree == 1:
buffer += Fore.GREEN
elif self.degree == 2:
buffer += Fore.BLUE
else:
buffer += Fore.MAGENTA
buffer += str(self.coef) + ' * X^' + str(self.degree)
buffer += Fore.RESET
return buffer
# X^0 X^1 X^2
# coef = 0 '' '' ''
# coef = 1 1.0 X X^2
# coef = c c c * X c * X^2
def get_super_reduced_str(self):
if self.coef == 0:
return ''
buffer = ''
if self.degree == 0:
buffer += Fore.RED
elif self.degree == 1:
buffer += Fore.GREEN
elif self.degree == 2:
buffer += Fore.BLUE
else:
buffer += Fore.CYAN
if self.coef == 1.0:
if self.degree == 0:
buffer += '1.0'
elif self.degree == 1:
buffer += 'X'
else:
buffer += 'X^2'
else:
if self.degree == 0:
buffer += str(self.coef)
elif self.degree == 1:
buffer += str(self.coef) + ' * X'
else:
buffer += str(self.coef) + ' * X^2'
buffer += Fore.RESET
return buffer
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,403 | ashih42/ComputorV2 | refs/heads/master | /matrix.py | from exceptions import ComputorException
class Matrix:
@staticmethod
def add(a, b):
if a.shape != b.shape:
raise ComputorException('Invalid Matrix shapes: M' + str(a.shape) + ' + M' + str(b.shape))
data = []
for i in range(a.shape[0]):
data.append(list(map(lambda x, y: x + y, a.data[i], b.data[i])))
return Matrix(data)
@staticmethod
def sub(a, b):
if a.shape != b.shape:
raise ComputorException('Invalid Matrix shapes: M' + str(a.shape) + ' - M' + str(b.shape))
data = []
for i in range(a.shape[0]):
data.append(list(map(lambda x, y: x - y, a.data[i], b.data[i])))
return Matrix(data)
@staticmethod
def mat_mul(a, b):
if a.shape[1] != b.shape[0]:
raise ComputorException('Invalid Matrix shapes: M' + str(a.shape) + ' ** M' + str(b.shape))
data = []
for i in range(a.shape[0]):
data.append( [None] * b.shape[1] )
for j in range(b.shape[1]):
data[i][j] = sum([ a.data[i][k] * b.data[k][j] for k in range(a.shape[1]) ])
return Matrix(data)
@staticmethod
def element_mul(a, b):
if a.shape != b.shape:
raise ComputorException('Invalid Matrix shapes: M' + str(a.shape) + ' * M' + str(b.shape))
data = []
for i in range(a.shape[0]):
data.append(list(map(lambda x, y: x * y, a.data[i], b.data[i])))
return Matrix(data)
@staticmethod
def scalar_mul(scalar, matrix):
data = []
for i in range(matrix.shape[0]):
data.append(list(map(lambda x: scalar * x, matrix.data[i])))
return Matrix(data)
@staticmethod
def div(a, b):
b_inv = b.get_inverse()
return Matrix.mat_mul(a, b_inv)
# Pre-condition: power is a non-negative integer
@staticmethod
def pow(base, power):
if base.shape[0] != base.shape[1]:
raise ComputorException('Invalid Matrix shape: M' + str(base.shape) + ' ^ ' + str(power))
product = Matrix.__identity(base.shape[0])
for _ in range(power):
product = Matrix.mat_mul(product, base)
return product
@staticmethod
def neg(a):
return Matrix.scalar_mul(-1, a)
@staticmethod
def __identity(width):
data = []
for i in range(width):
data.append([ 1.0 if j == i else 0.0 for j in range(width) ])
return Matrix(data)
# data is tuple of tuples, or list of lists, where each element is a float
# Precondition: grammar/parser guarantees at least 1 element in each container
def __init__(self, data):
rows = len(data)
cols = len(data[0])
self.shape = (rows, cols)
self.data = data
for row in self.data:
if len(row) != cols:
raise ComputorException('Invalid matrix shape')
def __str__(self):
row_strs = [ '[ ' + ' , '.join(map(str, row)) + ' ]' for row in self.data ]
return '\n'.join(row_strs)
def get_compact_str(self):
row_strs = [ '[' + ','.join(map(str, row)) + ']' for row in self.data ]
return '[' + ';'.join(row_strs) + ']'
def get_transpose(self):
data = list(map(list,zip(*self.data)))
return Matrix(data)
def get_inverse(self):
# Check if it is square matrix
if self.shape[0] != self.shape[1]:
raise ComputorException('M' + str(self.shape) + ' is not invertible')
# 1 x 1 Matrix
if self.shape[0] == 1:
if self.data[0][0] == 0:
raise ComputorException('Matrix is singular')
else:
data = [[ 1 / self.data[0][0] ]]
return Matrix(data)
# Check determinant
determinant = self.__get_determinant()
if determinant == 0:
raise ComputorException('Matrix is singular')
# 2 x 2 Matrix
# inv = 1/determinant * [[d, -b], [-c, a]]
if self.shape[0] == 2:
data = [[ 1 / determinant * self.data[1][1], -1 / determinant * self.data[0][1] ],
[ -1 / determinant * self.data[1][0], 1 / determinant * self.data[0][0] ]]
return Matrix(data)
# 3 x 3 or Bigger Matrix
cofactors = []
for r in range(self.shape[0]):
cofactor_row = []
for c in range(self.shape[0]):
minor = self.__get_minor(r, c)
cofactor_row.append( ((-1)**(r+c)) * minor.__get_determinant() )
cofactors.append(cofactor_row)
inv = Matrix(cofactors).get_transpose()
for r in range(inv.shape[0]):
for c in range(inv.shape[0]):
inv.data[r][c] /= determinant
return inv
def __get_minor(self, r, c):
data = [ row[:c] + row[c+1:] for row in (self.data[:r] + self.data[r+1:]) ]
return Matrix(data)
def __get_determinant(self):
# Base case: 2 x 2 Matrix
# determinant = ad - bc
if self.shape[0] == 2:
return self.data[0][0] * self.data[1][1] - self.data[0][1] * self.data[1][0]
# Recursive case:
determinant = 0
for c in range(self.shape[0]):
minor = self.__get_minor(0, c)
determinant += ((-1) ** c) * self.data[0][c] * minor.__get_determinant()
return determinant
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,404 | ashih42/ComputorV2 | refs/heads/master | /evaluator.py | from lark import Lark, Transformer, v_args
from colorama import Fore, Back, Style
from matrix import Matrix
from file_to_string import file_to_string
import computor
class Evaluator:
@v_args(inline=True) # Affects the signatures of the methods
class MyTransformer(Transformer):
def __init__(self):
pass
# OPERATORS ------------------------------------
def add(self, a, b):
return computor.Computor.instance.add(a, b)
def sub(self, a, b):
return computor.Computor.instance.sub(a, b)
def mat_mul(self, a, b):
return computor.Computor.instance.mat_mul(a, b)
def mul(self, a, b):
return computor.Computor.instance.mul(a, b)
def div(self, a, b):
return computor.Computor.instance.div(a, b)
def mod(self, a, b):
return computor.Computor.instance.mod(a, b)
def pow(self, base, power):
return computor.Computor.instance.pow(base, power)
def neg(self, a):
return computor.Computor.instance.neg(a)
# PARSE FOR VALUE ------------------------------------
def parse_number(self, token):
return float(token.value)
def parse_neg_number(self, token):
return -float(token.value)
def get_var_value(self, var_name):
return computor.Computor.instance.get_var(var_name)
def parse_number_imag(self, number_token=None):
if number_token is None:
return computor.Computor.imag
else:
number = float(number_token.value)
return computor.Computor.instance.mul(number, computor.Computor.imag)
def pi(self):
return computor.Computor.pi
def eval_func(self, func_name, *args):
return computor.Computor.instance.eval_function(func_name, args)
# BUILT-IN FUNCTIONS ------------------------------------
def eval_built_in(self, func, arg):
return func(arg)
def inv(self):
return computor.Computor.instance.inv
def transp(self):
return computor.Computor.instance.transp
def sqrt(self):
return computor.Computor.instance.sqrt
def sin(self):
return computor.Computor.instance.sin
def cos(self):
return computor.Computor.instance.cos
def tan(self):
return computor.Computor.instance.tan
def deg(self):
return computor.Computor.instance.deg
def rad(self):
return computor.Computor.instance.rad
# MATRIX CONSTRUCTION ------------------------------------
def get_matrix(self, *rows):
return Matrix(rows)
def get_mat_rows(self, *elements):
return elements
def __init__(self):
grammar = file_to_string('grammars/evaluator.lark')
self.__lark_parser = Lark(grammar, parser='lalr', transformer=Evaluator.MyTransformer())
def eval(self, statement):
return self.__lark_parser.parse(statement)
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,405 | ashih42/ComputorV2 | refs/heads/master | /exceptions.py | class ParserException(Exception):
pass
class ComputorException(Exception):
pass
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,406 | ashih42/ComputorV2 | refs/heads/master | /complex.py | from exceptions import ComputorException
class Complex:
@staticmethod
def add(a, b):
return Complex(a.real + b.real, a.imag + b.imag)
@staticmethod
def sub(a, b):
return Complex(a.real - b.real, a.imag - b.imag)
# (a + bi) * (c + di) = (ac - bd, (ad + bc)i)
@staticmethod
def mul(a, b):
return Complex(a.real * b.real - a.imag * b.imag, a.real * b.imag + a.imag * b.real)
# (a + bi) / (c + di) = (a + bi) / (c + di) * (c - di) / (c - di)
@staticmethod
def div(a, b):
if b.__is_zero():
raise ComputorException('Division by zero')
conjugate = b.__get_conjugate()
numerator = Complex.mul(a, conjugate)
denominator = Complex.mul(b, conjugate)
assert denominator.imag == 0.0
return Complex(numerator.real / denominator.real, numerator.imag / denominator.real)
# Pre-condition: power is a non-negative integer
@staticmethod
def pow(base, power):
product = Complex(1.0, 0.0)
for _ in range(power):
product = Complex.mul(product, base)
return product
@staticmethod
def neg(a):
return Complex(-a.real, -a.imag)
def __init__(self, real, imag=0.0):
self.real = real
self.imag = imag
def __str__(self):
if self.real == 0.0:
return str(self.imag) + "i"
else:
return str(self.real) + " + " + str(self.imag) + "i"
def __is_zero(self):
return self.real == 0.0 and self.imag == 0.0
def __get_conjugate(self):
return Complex(self.real, -self.imag)
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,407 | ashih42/ComputorV2 | refs/heads/master | /solver.py | from lark import Lark, Transformer, v_args
from lark.exceptions import LarkError
from colorama import Fore, Back, Style
from function import Function
from term import Term
from file_to_string import file_to_string
from exceptions import ParserException, ComputorException
import computor
class Solver:
@v_args(inline=True) # Affects the signatures of the methods
class MyTransformer(Transformer):
def __init__(self, solver):
self.__solver = solver
def get_lhs_rhs(self, lhs, rhs):
return lhs, rhs
# build a term from var
def build_term_var(self, var_name):
value = computor.Computor.instance.get_var(var_name)
if not isinstance(value, float):
raise ComputorException('Variables must be rational')
return [ Term(value, 0) ]
# build terms from a function
def build_terms_from_func_expr(self, func, _):
return self.__solver.parse_func(func.expr)
def add(self, a, b):
return a + b
def sub(self, a, b):
b[0].coef = -b[0].coef
return a + b
def neg(self, terms):
terms[0].coef *= -1
return terms
# coef only -> c * X^0
def build_term_c_0(self, number_token):
coef = float(number_token.value)
return [ Term(coef, 0) ]
def mul_number_thing(self, number_token, terms):
number = float(number_token.value)
terms[0].coef *= number
return terms
def build_term_deg(self, _, degree=None):
if degree is None:
return [ Term(1.0, 1) ]
else:
return [ Term(1.0, degree) ]
def parse_degree(self, token):
value = float(token.value)
if value.is_integer():
value = int(value)
if 0 <= value <= 2:
return value
raise ParserException('Exponent ' + Fore.RED + str(value) + Fore.RESET + ' must be 0, 1, or 2')
def parse_var(self, token):
return token.value
def parse_func(self, token):
func_name = token.value
function = computor.Computor.instance.get_func(func_name)
if not (len(function.local_vars) == 1 and function.local_vars[0].upper() == 'X'):
raise ComputorException('Invalid function: ' + str(function))
return function
def __init__(self):
grammar = file_to_string('grammars/solver.lark')
self.__lark_parser = Lark(grammar, parser='lalr', transformer=Solver.MyTransformer(self))
self.__func_parser = Lark(grammar, parser='lalr', transformer=Solver.MyTransformer(self), start='expr')
def parse_func(self, expr):
return self.__func_parser.parse(expr)
def solve(self, statement):
lhs, rhs = self.__parse(statement)
print(Style.BRIGHT + 'Given:' + Style.RESET_ALL)
self.__print_equation(lhs, rhs)
print(Style.BRIGHT + 'Group terms by degree:' + Style.RESET_ALL)
self.__group_terms(lhs, rhs)
self.__print_equation(lhs, rhs)
print(Style.BRIGHT + 'Merge terms by degree:' + Style.RESET_ALL)
lhs = self.__merge_terms(lhs)
rhs = self.__merge_terms(rhs)
self.__print_equation(lhs, rhs)
print(Style.BRIGHT + 'Reduced form:' + Style.RESET_ALL)
reduced_form = self.__get_reduced_form(lhs,rhs)
self.__print_reduced_form(reduced_form)
a = reduced_form[0].coef
b = reduced_form[1].coef
c = reduced_form[2].coef
self.__solve_equation(a, b, c)
def __parse(self, statement):
try:
lhs, rhs = self.__lark_parser.parse(statement)
return lhs, rhs
except LarkError as e:
raise ParserException(e)
def __group_terms(self, lhs, rhs):
lhs.sort(key=lambda x: x.degree, reverse=True)
rhs.sort(key=lambda x: x.degree, reverse=True)
def __merge_terms(self, terms):
merged_expr = [Term(0.0, 2), Term(0.0, 1), Term(0.0, 0)]
for term in terms:
if term.degree == 2:
merged_expr[0].coef += term.coef
if term.degree == 1:
merged_expr[1].coef += term.coef
if term.degree == 0:
merged_expr[2].coef += term.coef
return merged_expr
def __get_reduced_form(self, lhs, rhs):
lhs[0].coef -= rhs[0].coef
lhs[1].coef -= rhs[1].coef
lhs[2].coef -= rhs[2].coef
return lhs
def __print_equation(self, lhs, rhs):
lhs_str = ' + '.join(map(str, lhs))
rhs_str = ' + '.join(map(str, rhs))
print(lhs_str + ' = ' + rhs_str)
def __print_reduced_form(self, terms):
reduced_str = ' + '.join(map(str, terms))
print(reduced_str + ' = 0')
# Print an even more reduced form
super_reduced_form = [ term.get_super_reduced_str() for term in terms ]
super_reduced_form = filter(lambda x: x != '', super_reduced_form)
super_reduced_str = ' + '.join(map(str, super_reduced_form))
if super_reduced_str == '':
super_reduced_str = '0'
print(super_reduced_str + ' = 0')
def __solve_equation(self, a, b, c):
if a == 0 and b == 0:
print(Style.BRIGHT + 'Polynomial degree: 0' + Style.RESET_ALL)
print(Style.BRIGHT + 'Solving equation with no X...' + Style.RESET_ALL)
self.__solve_constant(a, b, c)
elif a == 0:
print(Style.BRIGHT + 'Polynomial degree: 1' + Style.RESET_ALL)
print(Style.BRIGHT + 'Solving linear equation...' + Style.RESET_ALL)
self.__solve_linear(a, b, c)
else:
print(Style.BRIGHT + 'Polynomial degree: 2' + Style.RESET_ALL)
print(Style.BRIGHT + 'Solving quadratic equation...' + Style.RESET_ALL)
self.__solve_quadratic(a, b, c)
def __solve_constant(self, a, b, c):
if c == 0:
print(Style.BRIGHT + ' X =' + Style.RESET_ALL, 'All numbers!')
else:
print(Style.BRIGHT + ' X =' + Style.RESET_ALL, 'No solution!')
def __solve_linear(self, a, b, c):
x = -c / b
print(Style.BRIGHT + ' X =' + Style.RESET_ALL, x)
def __solve_quadratic(self, a, b, c):
discriminant = b ** 2 - 4 * a * c
print('Discriminant =', discriminant)
# x0 = (-b + sqrt(discriminant)) / (2 * a)
# x1 = (-b - sqrt(discriminant)) / (2 * a)
x0 = computor.Computor.instance.div(computor.Computor.instance.add(-b, computor.Computor.instance.sqrt(discriminant)), 2 * a)
x1 = computor.Computor.instance.div(computor.Computor.instance.sub(-b, computor.Computor.instance.sqrt(discriminant)), 2 * a)
if discriminant < 0:
print(' Discriminant < 0 : 2 complex solutions:')
print(Style.BRIGHT + ' X0 =' + Style.RESET_ALL, x0)
print(Style.BRIGHT + ' X1 =' + Style.RESET_ALL, x1)
elif discriminant == 0:
print(' Discriminant = 0 : 1 real solution:')
print(Style.BRIGHT + ' X =' + Style.RESET_ALL, x0)
else:
print(' Discriminant > 0 : 2 real solutions:')
print(Style.BRIGHT + ' X0 =' + Style.RESET_ALL, x0)
print(Style.BRIGHT + ' X1 =' + Style.RESET_ALL, x1)
| {"/function.py": ["/exceptions.py"], "/simplifier.py": ["/matrix.py", "/computor.py"], "/main.py": ["/computor.py"], "/parser.py": ["/exceptions.py", "/computor.py"], "/computor.py": ["/function.py", "/variable.py", "/complex.py", "/matrix.py", "/parser.py", "/simplifier.py", "/evaluator.py", "/solver.py", "/exceptions.py"], "/matrix.py": ["/exceptions.py"], "/evaluator.py": ["/matrix.py", "/computor.py"], "/complex.py": ["/exceptions.py"], "/solver.py": ["/function.py", "/term.py", "/exceptions.py", "/computor.py"]} |
48,422 | qiulongquan/test_celery | refs/heads/master | /tools/tasks.py | from __future__ import absolute_import
from celery import shared_task
import time
@shared_task(track_started=True)
# 你很可能在可重用的 Django APP 中编写了一些任务,
# 但是 Django APP 不能依赖于具体的 Django 项目,
# 所以你无法直接导入 Celery 实例。
# @shared_task 装饰器能让你在没有具体的 Celery 实例时创建任务:
def add(x, y):
time.sleep(30)
return x + y
| {"/test_celery/views/add.py": ["/tools/tasks.py", "/test_celery/models.py", "/tools/db.py"]} |
48,423 | qiulongquan/test_celery | refs/heads/master | /test_celery/models.py | from django.db import models
class Add(models.Model):
task_id = models.CharField(max_length=128)
first = models.IntegerField()
second = models.IntegerField()
log_date = models.DateTimeField()
| {"/test_celery/views/add.py": ["/tools/tasks.py", "/test_celery/models.py", "/tools/db.py"]} |
48,424 | qiulongquan/test_celery | refs/heads/master | /test_celery/views/add.py | #__*__coding:utf-8__*__
from celery.result import AsyncResult
from django.shortcuts import render_to_response
from tools.tasks import add
from test_celery.models import Add
from tools.db import Db
import datetime
def index(request):
return render_to_response('index.html')
def add_1(request):
first = int(request.GET.get('first'))
second = int(request.GET.get('second'))
result = add.delay(first,second)
dd = Add(task_id=result.id,first=first,second=second,log_date=datetime.datetime.now())
dd.save()
return render_to_response('index.html')
# 任务结果
def results(request):
#查询所有的任务信息
db = Db()
rows = db.get_tasksinfo()
return render_to_response('result.html',{'rows':rows}) | {"/test_celery/views/add.py": ["/tools/tasks.py", "/test_celery/models.py", "/tools/db.py"]} |
48,425 | qiulongquan/test_celery | refs/heads/master | /tools/db.py | import datetime
import MySQLdb
from MySQLdb.cursors import DictCursor
from test_celery.settings import DATABASES
class Db:
def __init__(self):
self.database = DATABASES['default']
self.database_name = self.database['NAME']
self.user = self.database['USER']
self.password = self.database['PASSWORD']
self.host = self.database['HOST']
self.port = int(self.database['PORT'])
self.con = MySQLdb.connect(self.host, self.user, self.password, self.database_name, self.port, charset='utf8')
self.con.autocommit(True)
def close_connect(self):
self.con.close()
def get_tasksinfo(self):
cur = self.con.cursor(DictCursor)
query_str = "select " \
"b.id as id," \
"b.task_id as task_id," \
"b.first as first," \
"b.second as second," \
"b.log_date as logdate," \
"a.status as status," \
"a.result as result," \
"a.traceback as traceback " \
"from celery_taskmeta a inner join test_celery_add b " \
"on a.task_id=b.task_id;"
cur.execute(query_str)
rows = cur.fetchall()
cur.close()
return rows
| {"/test_celery/views/add.py": ["/tools/tasks.py", "/test_celery/models.py", "/tools/db.py"]} |
48,432 | lu-cq/my_flask | refs/heads/master | /manage.py | # coding: utf-8
from __future__ import absolute_import
from src.cli import main
if __name__ == '__main__':
main()
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,433 | lu-cq/my_flask | refs/heads/master | /libs/logger/rsyslog.py | # coding=utf-8
from .filelogger import get_file_logger
__all__ = ['rsyslog']
class RsysLogger(object):
"""重写 rsyslog 日志写本地"""
@classmethod
def send(cls, message, tag=None):
logger = get_file_logger(tag)
if not tag:
tag = 'notag'
logger.info(message)
rsyslog = RsysLogger
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,434 | lu-cq/my_flask | refs/heads/master | /src/views/schema/fields.py | # coding: utf-8
"""
API Schema Fields
~~~~~~~~~~~~~~~~~
This module includes a numbers of fields which is compatible with schema
classes defined in :class:`marshmallow.Schema`.
"""
from __future__ import absolute_import, unicode_literals
from marshmallow.fields import DateTime
from dateutil.tz import tzlocal
class LocalDateTimeField(DateTime):
localtime = True
def _serialize(self, value, *args, **kwargs):
if value is not None and value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return super(LocalDateTimeField, self)._serialize(
value, *args, **kwargs)
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,435 | lu-cq/my_flask | refs/heads/master | /src/cli.py | # coding: utf-8
from __future__ import absolute_import
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from gunicorn.app.wsgiapp import WSGIApplication
from src.ext import db
from src.wsgi import app
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
@manager.shell
def make_shell_context():
return {'db': db, 'app': app}
@manager.command
def runserver(host=None, port=None, workers=None):
"""Runs the app within Gunicorn."""
host = host or app.config.get('HTTP_HOST') or '0.0.0.0'
port = port or app.config.get('HTTP_PORT') or 5000
workers = workers or app.config.get('HTTP_WORKERS') or 1
use_evalex = app.config.get('USE_EVALEX', app.debug)
if app.debug:
app.run(host, int(port), use_evalex=use_evalex)
else:
gunicorn = WSGIApplication()
gunicorn.load_wsgiapp = lambda: app
gunicorn.cfg.set('bind', '%s:%s' % (host, port))
gunicorn.cfg.set('workers', workers)
gunicorn.cfg.set('pidfile', None)
gunicorn.cfg.set('accesslog', '-')
gunicorn.cfg.set('errorlog', '-')
gunicorn.chdir()
gunicorn.run()
def main():
manager.run()
if __name__ == '__main__':
main()
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,436 | lu-cq/my_flask | refs/heads/master | /libs/logger/filelogger.py | # coding=utf-8
import logging
import os
from datetime import date
from logging import Formatter, handlers
def get_file_logger(name):
logger = logging.getLogger(name)
# 单例模式,如果已经注册了filehandler,直接返回logger
if logger.handlers:
return logger
formatter = Formatter('%(asctime)s\t%(message)s', '%Y-%m-%d %H:%M:%S')
log_dir = os.path.join('/var/log/flask', name)
if not os.path.isdir(log_dir):
os.makedirs(log_dir)
filename = os.path.join(log_dir, '{}.log'.format(str(date.today())))
handler = handlers.TimedRotatingFileHandler(
filename, when='D', backupCount=7, delay=False, encoding='utf-8')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
event_logger = get_file_logger('event')
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,437 | lu-cq/my_flask | refs/heads/master | /src/wsgi.py | # -*- coding: UTF-8 -*-
# from envcfg.json.cms import DEBUG
# if not DEBUG:
# from gevent import monkey
# monkey.patch_all(thread=False)
from werkzeug.middleware.proxy_fix import ProxyFix
from werkzeug.middleware.profiler import ProfilerMiddleware
# from werkzeug.contrib.profiler import ProfilerMiddleware
from .app import create_app
__all__ = ['app']
#: WSGI endpoint
app = create_app()
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1)
if app.config.get('PROFILING', False):
app.wsgi_app = ProfilerMiddleware(
app.wsgi_app, profile_dir=app.config['PROFILING_DIR'])
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,438 | lu-cq/my_flask | refs/heads/master | /src/views/schema/order.py | # coding: utf-8
from marshmallow import Schema, fields, validates, validate, ValidationError
from src.views.schema.fields import LocalDateTimeField
from .user import UserSchema
fields.Field.default_error_messages = {
'required': u'缺少必填数据.',
'type': u'数据类型不合法.',
'null': u'数据不能为空.',
'validator_failed': u'非法数据.'
}
class OrderSchema(Schema):
"""订单"""
id = fields.Integer()
user_id = fields.Int()
create_time = LocalDateTimeField()
user = fields.Nested(UserSchema)
order_schema_data = OrderSchema(strict=True)
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,439 | lu-cq/my_flask | refs/heads/master | /ipython_config.py | # Configuration file for ipython.
c = get_config()
c.InteractiveShellApp.exec_lines = [
'%load_ext autoreload',
'%autoreload 2',
'from source.app import create_app',
'create_app().app_context().push()',
]
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,440 | lu-cq/my_flask | refs/heads/master | /src/models/order.py | # coding: utf-8
from werkzeug.utils import cached_property
from sqlalchemy import func, text, Index
from src.ext import db
from src.models.base import BaseModel
from src.models.user import User
class Order(db.Model, BaseModel):
__tablename__ = 'order'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(
db.Integer, nullable=False, server_default='0', index=True, comment='user_id')
create_time = db.Column(db.TIMESTAMP, nullable=False, server_default=func.now())
update_time = db.Column(
db.TIMESTAMP, nullable=False,
server_default=text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
)
def __getattr__(self, item):
return getattr(self.user, item)
@property
def user(self):
return User.get(self.user_id)
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,441 | lu-cq/my_flask | refs/heads/master | /src/ext.py | # coding: utf-8
from __future__ import absolute_import
from flask_sqlalchemy import SQLAlchemy
from itsdangerous import TimedJSONWebSignatureSerializer
from envcfg.json.flask import SECRET_KEY, TOKEN_EXPIRES_IN
token_object = TimedJSONWebSignatureSerializer(SECRET_KEY, TOKEN_EXPIRES_IN)
db = SQLAlchemy()
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,442 | lu-cq/my_flask | refs/heads/master | /src/views/blueprint_factory.py | # coding: utf-8
from __future__ import absolute_import
from flask import Blueprint, jsonify, request, g
from werkzeug.exceptions import HTTPException
from marshmallow import ValidationError
from src.errors import GBaseError
from src.utils.request_log import log_request
class BlueprintFactory(object):
def __init__(self, blueprint_class, url_package='api'):
self.blueprint_class = blueprint_class
self.url_package = url_package
def __call__(self, name, version, package_name, **kwargs):
"""Creates blueprint to sort the API views.
:param name: The endpoint name.
:param version: The API version.
:param package_name: Always be ``__name__``.
:param url_prefix: The prefix of relative URL.
"""
blueprint = self.make_blueprint(name, version, package_name, **kwargs)
blueprint = self.init_blueprint(blueprint)
return blueprint
def make_blueprint(self, name, version, package_name, **kwargs):
url_prefix = kwargs.pop('url_prefix', '')
url_prefix = '/{url_package}{url_api_version}{url_prefix}'.format(
url_package=self.url_package, url_api_version='/' + version if version else '',
url_prefix=url_prefix)
blueprint_name = '{url_package}-{version}.{name}'.format(
url_package=self.url_package, name=name, version=version)
return Blueprint(
blueprint_name, package_name, url_prefix=url_prefix, **kwargs)
def init_blueprint(self, blueprint):
blueprint.errorhandler(GBaseError)(self.handle_base_error)
blueprint.errorhandler(ValidationError)(self.handle_validation_error)
# blueprint.errorhandler(Exception)(self.handle_exception)
blueprint.errorhandler(400)(self.handle_http_exception)
blueprint.errorhandler(401)(self.handle_http_exception)
blueprint.errorhandler(403)(self.handle_http_exception)
blueprint.errorhandler(404)(self.handle_http_exception)
blueprint.errorhandler(405)(self.handle_http_exception)
blueprint.errorhandler(410)(self.handle_http_exception)
blueprint.errorhandler(503)(self.handle_http_exception)
blueprint.after_request(self.after_request)
return blueprint
def handle_base_error(self, e):
return jsonify(status='error', message=e.message, code=e.errno), 200
def handle_validation_error(self, e):
return jsonify(status='error', message=e.message, code=400), 400
def handle_http_exception(self, error):
messages = (error.description).decode('utf-8')
return jsonify(status='error', message=messages), error.code
def after_request(self, response):
log_request(request, response, self.url_package)
return response
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,443 | lu-cq/my_flask | refs/heads/master | /src/views/schema/user.py | # coding: utf-8
from marshmallow import Schema, fields, validates, validate, ValidationError
from src.views.schema.fields import LocalDateTimeField
fields.Field.default_error_messages = {
'required': u'缺少必填数据.',
'type': u'数据类型不合法.',
'null': u'数据不能为空.',
'validator_failed': u'非法数据.'
}
class UserSchema(Schema):
"""用户"""
id = fields.Integer()
name = fields.String()
create_time = LocalDateTimeField()
order_schema_data = UserSchema(strict=True, many=True)
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,444 | lu-cq/my_flask | refs/heads/master | /src/app.py | # coding: utf-8
import sys
import logging
from flask import Flask
from werkzeug.utils import import_string
from libs.logger.filelogger import get_file_logger
from tasks import make_celery
blueprints = [
'src.middlewares.auto_commit:bp',
'src.views.api.v1.order:bp',
]
extensions = [
'src.ext:db',
]
collected_loggers = [
('libs.ali_id_card.client', logging.INFO),
]
celery_tasks = [
'tasks.order',
]
CELERY = None
def create_app(config=None):
"""Create application cmstance."""
app = Flask(__name__)
app.config.from_object('envcfg.json.flask')
app.config.from_object(config)
global CELERY
CELERY = make_celery(app)
for extension_qualname in extensions:
extension = import_string(extension_qualname)
extension.init_app(app)
for blueprint_qualname in blueprints:
blueprint = import_string(blueprint_qualname)
app.register_blueprint(blueprint)
for logger_name, logger_level in collected_loggers:
get_file_logger(logger_name)
for task in celery_tasks:
import_string(task)
return app
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,445 | lu-cq/my_flask | refs/heads/master | /src/models/user.py | # coding: utf-8
from sqlalchemy import func, text, Index
from src.ext import db
from src.models.base import BaseModel
class User(db.Model, BaseModel):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50), nullable=False, server_default='', comment='姓名')
create_time = db.Column(db.TIMESTAMP, nullable=False, server_default=func.now())
update_time = db.Column(
db.TIMESTAMP, nullable=False,
server_default=text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
)
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,446 | lu-cq/my_flask | refs/heads/master | /src/middlewares/auto_commit.py | # -*- coding: utf-8 -*-
'''
本地支持跨域
'''
from flask import Blueprint, current_app
from sqlalchemy.exc import SQLAlchemyError
from src.ext import db
bp = Blueprint('middlewares.auto_commit', __name__)
@bp.after_app_request
def auto_commit(response):
# add for develop mode
try:
db.session.commit()
except SQLAlchemyError as e:
db.session.rollback()
raise e
return response
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,447 | lu-cq/my_flask | refs/heads/master | /src/errors/__init__.py | # coding: utf-8
from __future__ import unicode_literals, absolute_import
class GBaseError(Exception):
errno = 2000
code = 0
class GNetworkTimeout(GBaseError):
errno = 5001
class TokenExpiresError(GBaseError):
errno = 4001
class UserNoExistError(GBaseError):
errno = 4004
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,448 | lu-cq/my_flask | refs/heads/master | /src/views/api/blueprint.py | # coding: utf-8
from __future__ import absolute_import, unicode_literals
from flask import Blueprint
from src.views.blueprint_factory import BlueprintFactory
__all__ = ['create_blueprint']
create_blueprint = BlueprintFactory(
blueprint_class=Blueprint, url_package='api')
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,449 | lu-cq/my_flask | refs/heads/master | /src/utils/request_log.py | # coding: utf-8
from uuid import uuid4
from libs.logger.rsyslog import rsyslog
__all__ = ['log_request']
hidden_fields = ['password']
def log_request(request, response, module_name):
"""Record request log"""
try:
req_id = uuid4().hex
req_remote_addr = request.remote_addr
req_host = request.host
req_url = request.path
req_args = request.args.to_dict().__str__()
body_args = request.form.to_dict()
body_json = request.get_json()
if body_json:
body_args = dict(body_args, **request.get_json())
for k in body_args:
if k in hidden_fields:
body_args[k] = '***'
req_body = body_args.__str__()
req_head = request.headers.items().__str__()
request_log_format = ('req_id={0}, req_remote_addr={1},, host={2}, url={3}, head={4},'
'args={5}, req_body={6}, resp_status={7}, resp_body={8}')
response_body = response.data if response.status_code not in [200, 201] else ''
response_body = str(response_body).replace('\n', '').replace(' ', '')
log_content = request_log_format.format(
req_id, req_remote_addr, req_host, req_url, req_head, req_args, req_body,
response.status_code, response_body)
rsyslog.send(log_content, tag=module_name)
except Exception as e:
rsyslog.send(str(e), tag='log_request')
pass
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,450 | lu-cq/my_flask | refs/heads/master | /src/views/api/v1/order.py | # coding: utf-8
from __future__ import absolute_import, unicode_literals
from flask import jsonify, request, abort, g
from src.views.api.blueprint import create_blueprint
from src.views.schema.order import order_schema_data
from src.models.order import Order
bp = create_blueprint('order', 'v1', package_name=__name__, url_prefix='/order')
@bp.route('/plan')
def get_service_type_label():
"""
**薪资支付计划**
"""
order_id = request.args.get('order_id', None)
if not order_id:
abort(400, "请求参数不完整")
order = Order.get(order_id)
return jsonify(status='success', code=1, data=order_schema_data.dump(order).data)
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,451 | lu-cq/my_flask | refs/heads/master | /tasks/order.py | # coding=utf8
from src.app import CELERY
@CELERY.task
def test(m, n):
"""celery test
"""
print('m+n=', m+n)
return None
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,452 | lu-cq/my_flask | refs/heads/master | /celery_worker.py | # coding: utf-8
from src.app import create_app
current_app = create_app()
current_app.app_context().push()
from src.app import CELERY
| {"/manage.py": ["/src/cli.py"], "/libs/logger/rsyslog.py": ["/libs/logger/filelogger.py"], "/src/cli.py": ["/src/ext.py", "/src/wsgi.py"], "/src/wsgi.py": ["/src/app.py"], "/src/views/schema/order.py": ["/src/views/schema/fields.py", "/src/views/schema/user.py"], "/src/models/order.py": ["/src/ext.py", "/src/models/user.py"], "/src/views/blueprint_factory.py": ["/src/errors/__init__.py", "/src/utils/request_log.py"], "/src/views/schema/user.py": ["/src/views/schema/fields.py"], "/src/app.py": ["/libs/logger/filelogger.py"], "/src/models/user.py": ["/src/ext.py"], "/src/middlewares/auto_commit.py": ["/src/ext.py"], "/src/views/api/blueprint.py": ["/src/views/blueprint_factory.py"], "/src/utils/request_log.py": ["/libs/logger/rsyslog.py"], "/src/views/api/v1/order.py": ["/src/views/api/blueprint.py", "/src/views/schema/order.py", "/src/models/order.py"], "/tasks/order.py": ["/src/app.py"], "/celery_worker.py": ["/src/app.py"]} |
48,516 | eik4862/TinyCalculator | refs/heads/master | /Function/Exponential.py | from typing import final
from Function import Function
class ExpFun(Function.Fun):
"""
Exponential and logarithm function toolbox.
:cvar __sign: Signatures of exponential and logarithm functions.
"""
def __new__(cls) -> None:
raise NotImplementedError
# @classmethod
# def __exp(cls, x: float) -> float:
# """
# Exponential function.
#
# Exponential function with parameter x has following computation rules.
# 1. If x is nan, the result is nan.
# 2. If x if -inf, the result is 0.
# 3. If x is +inf, the result is +inf.
# 4. If x is finite, the result is ``math.exp(x)``.
#
# This method is private and called internally as a helper of ``Exp.simplify``.
# For detailed description for simplification, refer to the comments of ``Exp.simplify``.
#
# :param x: Point where exponential function is to be computed.
# :type x: float
#
# :return: Computed value of exponential function.
# :rtype: float
# """
# try:
# return math.exp(x)
# except OverflowError:
# return math.inf
#
# @classmethod
# def __log(cls, x: float, y: float = None) -> float:
# """
# Log function.
#
# Log function with exponent x has following computation rules.
# 1. If x is nan or -inf, the result is nan.
# 2. If x is +inf, the result is +inf.
# 3. If x is finite negative, the result if nan.
# 4. If x is 0, the result is -inf.
# 5. If x is finite positive, the result is ``math.log2(x)``.
#
# Log function with exponent x and base y has following computation rules.
# 1. If x or y is nan or -inf, the result is nan.
# 2. If x or y is finite negative, the result is nan.
# 3. If y is 1, the result is nan.
# 4. If x and y is inf, the result is nan.
# 5. If x is inf and y is 0, the result is nan.
# 6. If x is inf and y is finite which is in (0, 1), the result is -inf.
# 7. If x is inf and y is finite which is greater than 1, the result is inf.
# 8. If x is 0 and y is inf, the result is nan.
# 9. If x is finite positive and y is inf, the result is 0.
# 10. If x and y is 0, the result is nan.
# 11. If x is 0 and y is finite which is in (0, 1), the result is inf.
# 12. If x is 0 and y is finite which is greater than 1, the result is -inf.
# 13. If x is finite positive and y is 0, the result is 0.
# 14. If x is finite positive and y is finite positive which is not 1, the result is ``math.log(x, y)``.
#
# This method is private and called internally as a helper of ``Exp.simplify``.
# For detailed description for simplification, refer to the comments of ``Exp.simplify``.
#
# :param x: Exponent where log function is to be computed.
# :type x: float
# :param y: Base where log function is to be computed.
# :type y: float
#
# :return: Computed value of log function.
# :rtype: float
# """
# if y is None:
# return math.nan if x < 0 else -math.inf if x == 0 else math.log(x)
# else:
# if math.isnan(x + y) or x < 0 or y < 0 or y == 1:
# return math.nan
# elif y == 0 or math.isinf(y):
# return math.nan if x == 0 or math.isinf(x) else 0
# else:
# return math.inf if x == 0 and y < 1 else -math.inf if x == 0 and y > 1 else math.log(x, y)
#
# @classmethod
# def __pow(cls, x: float, y: float) -> float:
# """
# Power function.
#
# Power function with base x and exponent y has following computation rules.
# 1. If x or y is nan, the result is nan.
# 2. If x is +-inf and y is -inf, the result is 0.
# 3. If x and y is inf, the result is inf.
# 4. If x is -inf and y is inf, the result is nan.
# 5. If x is inf and y is 0, the result is nan.
# 6. If x is inf and y is finite positive, the result is inf.
# 7. If x is inf and y is finite negative, the result is 0.
# 8. If x is -inf and y is 0 or finite noninteger, the result is nan.
# 9. If x is -inf and y is finite negative integer, the result is 0.
# 10. If x is -inf and y is finite even positive integer, the result is inf.
# 11. If x is -inf and y is finite odd positive integer, the result is -inf.
# 12. If x is 1 or y is 0, the result is 1.
# 13. If x is finite which is in [-1, 0] and y is -inf, the result is nan.
# 14. If x is finite which is in (0, 1) and y is -inf, the result is inf.
# 15. If x is finite which is not in [-1, 1] and y is -inf, the result is 0.
# 16. If x is finite which is less than or equal to -1 and y is inf, the result is nan.
# 17. If x is finite which is in (-1, 1) and y is inf, the result is 0.
# 18. If x is finite which is in greater than 1 and y is inf, the result is inf.
# 19. If x is finite negative and y is finite noninteger, the result is nan.
# 20. If x is finite positive and y is finite, the result is ``math.pow(x, y)``.
# 21. If x is finite negative and y is finite integer, the result is ``math.pow(x, y)``.
#
# This method is private and called internally as a helper of ``Exp.simplify``.
# For detailed description for simplification, refer to the comments of ``Exp.simplify``.
#
# :param x: Base where power function is to be computed.
# :type x: float
# :param y: Exponent where power function is to be computed.
# :type y: float
#
# :return: Computed value of power function.
# :rtype: float
# """
# if math.isnan(x + y) or (x < 0 and not is_int(y)):
# return math.nan
# elif (x <= -1 and y == math.inf) or (-1 <= x <= 0 and y == -math.inf) or (x == 0 and y < 0):
# return math.nan
# elif y == 0:
# return math.nan if math.isinf(x) else 1
# else:
# try:
# return math.pow(x, y)
# except OverflowError:
# return -math.inf if x < 0 and y % 2 == 1 else math.inf
#
# @classmethod
# def __sqrt(cls, x: float) -> float:
# """
# Square root function.
#
# Square root function with parameter x has following computation rules.
# 1. If x is nan or -inf, the result is nan.
# 2. If x is +inf, the result is +inf.
# 3. If x is finite negative, the result if nan.
# 4. If x is finite nonnegative, the result is ``math.sqrt(x)``.
#
# This method is private and called internally as a helper of ``Exp.simplify``.
# For detailed description for simplification, refer to the comments of ``Exp.simplify``.
#
# :param x: Point where square root function is to be computed.
# :type x: float
#
# :return: Computed value of square root function.
# :rtype: float
# """
# return math.nan if x < 0 else math.sqrt(x)
#
# @classmethod
# def __log2(cls, x: float) -> float:
# """
# Log function with base 2.
#
# Log function with base 2 with parameter x has following computation rules.
# 1. If x is nan or -inf, the result is nan.
# 2. If x is +inf, the result is +inf.
# 3. If x is finite negative, the result if nan.
# 4. If x is 0, the result is -inf.
# 5. If x is finite positive, the result is ``math.log2(x)``.
#
# This method is private and called internally as a helper of ``Exp.simplify``.
# For detailed description for simplification, refer to the comments of ``Exp.simplify``.
#
# :param x: Point where log function with base 2 is to be computed.
# :type x: float
#
# :return: Computed value of log function with base 2.
# :rtype: float
# """
# return math.nan if x < 0 else -math.inf if x == 0 else math.log2(x)
#
# @classmethod
# def __log10(cls, x: float) -> float:
# """
# Log function with base 10.
#
# Log function with base 10 with parameter x has following computation rules.
# 1. If x is nan or -inf, the result is nan.
# 2. If x is +inf, the result is +inf.
# 3. If x is finite negative, the result if nan.
# 4. If x is 0, the result is -inf.
# 5. If x is finite positive, the result is ``math.log10(x)``.
#
# This method is private and called internally as a helper of ``Exp.simplify``.
# For detailed description for simplification, refer to the comments of ``Exp.simplify``.
#
# :param x: Point where log function with base 10 is to be computed.
# :type x: float
#
# :return: Computed value of log function with base 10.
# :rtype: float
# """
# return math.nan if x < 0 else -math.inf if x == 0 else math.log10(x)
#
# @classmethod
# def chk_t(cls, rt: Token.Fun) -> Optional[List[Type.Sign]]:
# """
# Type checker for exponential and logarithm functions.
# It checks type of input function token and assigns return type as type information of the token.
#
# :param rt: Token to be type checked.
# :type rt: Token.Fun
#
# :return: None if type check is successful. Candidate signatures if not.
# :rtype: Optional[List[Type.Signature]]
# """
# cand: List[Type.Sign] = cls.__sign.get(rt.v) # Candidate signatures
# infer: Type.Sign = Type.Sign([tok.t for tok in rt.chd], Type.T.REAL, rt.v) # Inferred signature
#
# # Inferred signature must be one of candidates and return type is NUM type.
# if infer in cand:
# rt.t = Type.T.REAL
#
# return None
# else:
# return cand
#
# @classmethod
# def simplify(cls, rt: Token.Fun) -> Tuple[Token.Tok, List[Warning.InterpWarn]]:
# """
# Simplifier for exponential and logarithm functions.
#
# It does following simplifications.
# 1. Constant folding.
# 2. Dead expression stripping.
# 3. Sign propagation.
# For details and detailed explanation of these optimization tricks, refer to the comments of
# ``Operator.simplify`` and references therein.
#
# :param rt: Root of AST to be simplified.
# :type rt: Token.Fun
#
# :return: Root of simplified AST and list of generated warnings.
# :rtype: Tuple[Token.Tok, List[Warning.InterpWarn]]
#
# :raise NAN_DETECT: If nan is detected as a given parameter.
# :raise IFN_DETECT: If inf is detected as a given parameter.
# :raise DOMAIN_OUT: If given parameter is not in domain.
# :raise POLE_DETECT: If mathematical pole is detected.
# :raise BIG_INT: If given parameter exceeds floating point max.
# :raise SMALL_INT: If given parameter exceeds floating point min.
# """
# warn: List[Warning.InterpWarn] = [] # List of generated warnings.
#
# if rt.v == Type.FunT.Exp:
# # Check for warnings.
# # Exponential function with parameter x generates warning for followings cases.
# # 1. x exceeds floating point max/min size. (BIG_INT/SMALL_INT, resp.)
# # 2. x is nan. (NAN_DETECT)
# # 3. x is +-inf. (INF_DETECT)
# # The following logic is an implementation of these rules.
# if rt.chd[0].tok_t == Type.TokT.NUM:
# if is_bigint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.BIG_INT, 15, arg_pos=1, handle="Exp"))
# rt.chd[0].v = math.inf
# elif is_smallint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.SMALL_INT, 16, arg_pos=1, handle="Exp"))
# rt.chd[0].v = -math.inf
# elif math.isnan(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.NAN_DETECT, 1, arg_pos=1, handle="Exp"))
# elif math.isinf(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.INF_DETECT, 2, arg_pos=1, handle="Exp"))
#
# # Constant folding.
# # For detailed computation rule, refer to the comment in ``Exp.__exp``.
# if rt.chd[0].tok_t == Type.TokT.NUM:
# rt.chd[0].v = cls.__exp(rt.chd[0].v)
#
# return rt.chd[0], warn
#
# return rt, warn
# elif rt.v == Type.FunT.Log:
# # Check for warnings.
# # Log function with parameter x generates warning for followings cases.
# # 1. x exceeds floating point max/min size. (BIG_INT/SMALL_INT, resp.)
# # 2. x is nan. (NAN_DETECT)
# # 3. x is +-inf. (INF_DETECT)
# # 2. x is 0. (POLE_DETECT)
# # 3. x is finite negative. (DOMAIN_OUT)
# # Log function with parameter x and y generates warning for following cases.
# # 1. x exceeds floating point max/min size. (BIG_INT/SMALL_INT, resp.)
# # 2. x is nan. (NAN_DETECT)
# # 3. x is +-inf. (INF_DETECT)
# # 4. y exceeds floating point max/min size. (BIG_INT/SMALL_INT, resp.)
# # 5. y is nan. (NAN_DETECT)
# # 6. y is +-inf. (INF_DETECT)
# # 7. x and y are finite but at least one of them is negative. (DOMAIN_OUT)
# # 8. x is 0 and y is finite nonnegative. (POLE_DETECT)
# # 9. x is finite positive and y is 0 or 1. (POLE_DETECT)
# # The following logic is an implementation of these rules.
# if rt.argc == 1:
# if rt.chd[0].tok_t == Type.TokT.NUM:
# if is_bigint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.BIG_INT, 15, arg_pos=1, handle="Log"))
# rt.chd[0].v = math.inf
# elif is_smallint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.SMALL_INT, 16, arg_pos=1, handle="Log"))
# rt.chd[0].v = -math.inf
# elif math.isnan(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.NAN_DETECT, 1, arg_pos=1, handle="Log"))
# elif math.isinf(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.INF_DETECT, 2, arg_pos=1, handle="Log"))
# elif rt.chd[0].v == 0:
# warn.append(Warning.InterpWarn(Type.InterpWarnT.POLE_DETECT, 48))
# elif rt.chd[0].v < 0:
# warn.append(Warning.InterpWarn(Type.InterpWarnT.DOMAIN_OUT, 49))
# elif rt.chd[0].tok_t == rt.chd[0].tok_t == Type.TokT.NUM:
# if is_bigint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.BIG_INT, 15, arg_pos=1, handle="Log"))
# rt.chd[0].v = math.inf
# elif is_smallint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.SMALL_INT, 16, arg_pos=1, handle="Log"))
# rt.chd[0].v = -math.inf
# elif math.isnan(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.NAN_DETECT, 1, arg_pos=1, handle="Log"))
# elif math.isinf(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.INF_DETECT, 2, arg_pos=1, handle="Log"))
#
# if is_bigint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.BIG_INT, 15, arg_pos=2, handle="Log"))
# rt.chd[0].v = math.inf
# elif is_smallint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.SMALL_INT, 16, arg_pos=2, handle="Log"))
# rt.chd[0].v = -math.inf
# elif math.isnan(rt.chd[1].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.NAN_DETECT, 1, arg_pos=2, handle="Log"))
# elif math.isinf(rt.chd[1].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.INF_DETECT, 2, arg_pos=2, handle="Log"))
#
# if math.isfinite(rt.chd[0].v + rt.chd[1].v):
# if rt.chd[0].v < 0 or rt.chd[0].v < 0:
# warn.append(Warning.InterpWarn(Type.InterpWarnT.DOMAIN_OUT, 50))
# elif rt.chd[0].v == 0:
# warn.append(Warning.InterpWarn(Type.InterpWarnT.POLE_DETECT, 48))
# elif rt.chd[1].v in [0, 1]:
# warn.append(Warning.InterpWarn(Type.InterpWarnT.POLE_DETECT, 51))
#
# # Constant folding.
# # For detailed computation rule, refer to the comment in ``Exp.__log``.
# if rt.argc == 1:
# if rt.chd[0].tok_t == Type.TokT.NUM:
# rt.chd[0].v = cls.__log(rt.chd[0].v)
#
# return rt.chd[0], warn
# else:
# if rt.chd[0].tok_t == rt.chd[1].tok_t == Type.TokT.NUM:
# rt.chd[0].v = cls.__log(rt.chd[0].v, rt.chd[1].v)
#
# return rt.chd[0], warn
#
# # Dead expr stripping.
# # For dead expr stripping, it uses following rules.
# # 1. Log[nan, y] = nan
# # 2. Log[-inf, y] = nan
# # 3. Log[z, y] = nan
# # 4. Log[x, nan] = nan
# # 5. Log[x, -inf] = nan
# # 6. Log[x, z] = nan
# # where z is finite negative.
# # The following logic is an implementation of these rules.
# if rt.chd[0].tok_t == Type.TokT.NUM and not is_bigint(rt.chd[0].v):
# if rt.chd[0].v < 0 or math.isnan(rt.chd[0].v):
# rt.chd[0].v = math.nan
#
# return rt.chd[0], warn
# elif rt.chd[1].tok_t == Type.TokT.NUM and not is_bigint(rt.chd[1].v):
# if rt.chd[1].v < 0 or math.isnan(rt.chd[1].v):
# rt.chd[1].v = math.nan
#
# return rt.chd[1], warn
#
# return rt, warn
# elif rt.v == Type.FunT.Pow:
# # Check for warnings.
# # Power function with parameter x and y generates warning for following cases.
# # 1. x exceeds floating point max/min size. (BIG_INT/SMALL_INT, resp.)
# # 2. x is nan. (NAN_DETECT)
# # 3. x is +-inf. (INF_DETECT)
# # 4. y exceeds floating point max/min size. (BIG_INT/SMALL_INT, resp.)
# # 5. y is nan. (NAN_DETECT)
# # 6. y is +-inf. (INF_DETECT)
# # 7. x is finite negative and y is finite noninteger. (DOMAIN_OUT)
# # 8. x is 0 and y is finite nonpositive. (POLE_DETECT)
# # The following logic is an implementation of these rules.
# if rt.chd[0].tok_t == rt.chd[0].tok_t == Type.TokT.NUM:
# if is_bigint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.BIG_INT, 15, arg_pos=1, handle="Pow"))
# rt.chd[0].v = math.inf
# elif is_smallint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.SMALL_INT, 16, arg_pos=1, handle="Pow"))
# rt.chd[0].v = -math.inf
# elif math.isnan(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.NAN_DETECT, 1, arg_pos=1, handle="Pow"))
# elif math.isinf(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.INF_DETECT, 2, arg_pos=1, handle="Pow"))
#
# if is_bigint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.BIG_INT, 15, arg_pos=2, handle="Pow"))
# rt.chd[0].v = math.inf
# elif is_smallint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.SMALL_INT, 16, arg_pos=2, handle="Pow"))
# rt.chd[0].v = -math.inf
# elif math.isnan(rt.chd[1].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.NAN_DETECT, 1, arg_pos=2, handle="Pow"))
# elif math.isinf(rt.chd[1].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.INF_DETECT, 2, arg_pos=2, handle="Pow"))
#
# if math.isfinite(rt.chd[0].v + rt.chd[1].v):
# if rt.chd[0].v < 0 or not is_int(rt.chd[1].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.DOMAIN_OUT, 52))
# elif rt.chd[0].v == 0 and rt.chd[1].v <= 0:
# warn.append(Warning.InterpWarn(Type.InterpWarnT.POLE_DETECT, 53))
#
# # Constant folding.
# # For detailed computation rule, refer to the comment in ``Exp.__pow``.
# if rt.chd[0].tok_t == rt.chd[1].tok_t == Type.TokT.NUM:
# rt.chd[0].v = cls.__pow(rt.chd[0].v, rt.chd[1].v)
#
# return rt.chd[0], warn
#
# # Dead expr stripping.
# # For dead expr stripping, it uses following rules.
# # 1. Pow[nan, y] = nan
# # 2. Pow[x, nan] = nan
# # 3. Pow[-x, n] = Pow[x, n]
# # where n is finite even integer.
# # The following logic is an implementation of these rules.
# if rt.chd[0].tok_t == Type.TokT.NUM and not (is_bigint(rt.chd[0].v) or is_smallint(rt.chd[1].v)):
# if math.isnan(rt.chd[0].v):
# return rt.chd[0], warn
# elif rt.chd[1].tok_t == Type.TokT.NUM and not (is_bigint(rt.chd[1].v) or is_smallint(rt.chd[1].v)):
# if math.isnan(rt.chd[1].v):
# return rt.chd[1], warn
# if rt.chd[1].v % 2 == 0 and rt.chd[0].v == Type.OpT.MINUS:
# rt.swap_chd(rt.chd[0].chd[0], 0)
#
# return rt, warn
#
# # Sign propagation.
# # For sign propagation, it uses following rule.
# # 1. Pow[-x, n] = -Pow[x, n]
# # where n is finite odd integer.
# # The following logic is an implementation of this rule.
# if rt.chd[1].tok_t == Type.TokT.NUM and not (is_bigint(rt.chd[1].v) or is_smallint(rt.chd[1].v)):
# if rt.chd[0].v == Type.OpT.MINUS and rt.chd[1].v % 2 == 1:
# tmp = rt.chd[0]
# rt.swap_chd(rt.chd[0].chd[0], 0)
# tmp.swap_chd(rt, 0)
#
# return tmp, warn
#
# return rt, warn
# elif rt.v == Type.FunT.Sqrt:
# # Check for warnings.
# # Square root function with parameter x generates warning for followings cases.
# # 1. x exceeds floating point max/min size. (BIG_INT/SMALL_INT, resp.)
# # 2. x is nan. (NAN_DETECT)
# # 3. x is +-inf. (INF_DETECT)
# # 4. x is finite negative. (DOMAIN_OUT)
# # The following logic is an implementation of these rules.
# if rt.chd[0].tok_t == Type.TokT.NUM:
# if is_bigint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.BIG_INT, 15, arg_pos=1, handle="Sqrt"))
# rt.chd[0].v = math.inf
# elif is_smallint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.SMALL_INT, 16, arg_pos=1, handle="Sqrt"))
# rt.chd[0].v = -math.inf
# elif math.isnan(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.NAN_DETECT, 1, arg_pos=1, handle="Sqrt"))
# elif math.isinf(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.INF_DETECT, 2, arg_pos=1, handle="Sqrt"))
# elif rt.chd[0].v < 0:
# warn.append(Warning.InterpWarn(Type.InterpWarnT.DOMAIN_OUT, 25))
#
# # Constant folding.
# # For detailed computation rule, refer to the comment in ``Exp.__sqrt``.
# if rt.chd[0].tok_t == Type.TokT.NUM:
# rt.chd[0].v = cls.__sqrt(rt.chd[0].v)
#
# return rt.chd[0], warn
#
# return rt, warn
# elif rt.v == Type.FunT.Log2:
# # Check for warnings.
# # Log function with base 2 and parameter x generates warning for followings cases.
# # 1. x exceeds floating point max/min size. (BIG_INT/SMALL_INT, resp.)
# # 2. x is nan. (NAN_DETECT)
# # 3. x is +-inf. (INF_DETECT)
# # 4. x is 0. (POLE_DETECT)
# # 5. x is finite negative. (DOMAIN_OUT)
# # The following logic is an implementation of these rules.
# if rt.chd[0].tok_t == Type.TokT.NUM:
# if is_bigint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.BIG_INT, 15, arg_pos=1, handle="Log2"))
# rt.chd[0].v = math.inf
# elif is_smallint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.SMALL_INT, 16, arg_pos=1, handle="Log2"))
# rt.chd[0].v = -math.inf
# elif math.isnan(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.NAN_DETECT, 1, arg_pos=1, handle="Log2"))
# elif math.isinf(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.INF_DETECT, 2, arg_pos=1, handle="Log2"))
# elif rt.chd[0].v == 0:
# warn.append(Warning.InterpWarn(Type.InterpWarnT.POLE_DETECT, 54))
# elif rt.chd[0].v < 0:
# warn.append(Warning.InterpWarn(Type.InterpWarnT.DOMAIN_OUT, 55))
#
# # Constant folding.
# # For detailed computation rule, refer to the comment in ``Exp.__log2``.
# if rt.chd[0].tok_t == Type.TokT.NUM:
# rt.chd[0].v = cls.__log2(rt.chd[0].v)
#
# return rt.chd[0], warn
#
# return rt, warn
# else:
# # Check for warnings.
# # Log function with base 10 and parameter x generates warning for followings cases.
# # 1. x exceeds floating point max/min size. (BIG_INT/SMALL_INT, resp.)
# # 2. x is nan. (NAN_DETECT)
# # 3. x is +-inf. (INF_DETECT)
# # 4. x is 0. (POLE_DETECT)
# # 5. x is finite negative. (DOMAIN_OUT)
# # The following logic is an implementation of these rules.
# if rt.chd[0].tok_t == Type.TokT.NUM:
# if is_bigint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.BIG_INT, 15, arg_pos=1, handle="Log10"))
# rt.chd[0].v = math.inf
# elif is_smallint(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.SMALL_INT, 16, arg_pos=1, handle="Log10"))
# rt.chd[0].v = -math.inf
# elif math.isnan(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.NAN_DETECT, 1, arg_pos=1, handle="Log10"))
# elif math.isinf(rt.chd[0].v):
# warn.append(Warning.InterpWarn(Type.InterpWarnT.INF_DETECT, 2, arg_pos=1, handle="Log10"))
# elif rt.chd[0].v == 0:
# warn.append(Warning.InterpWarn(Type.InterpWarnT.POLE_DETECT, 56))
# elif rt.chd[0].v < 0:
# warn.append(Warning.InterpWarn(Type.InterpWarnT.DOMAIN_OUT, 57))
#
# # Constant folding.
# # For detailed computation rule, refer to the comment in ``Exp.__log10``.
# if rt.chd[0].tok_t == Type.TokT.NUM:
# rt.chd[0].v = cls.__log10(rt.chd[0].v)
#
# return rt.chd[0], warn
#
# return rt, warn
#
# @classmethod
# def test(cls, fun: Type.FunT, test_in: List[List[Decimal]]) -> List[Decimal]:
# """
# Test function for exponential and logarithm function.
#
# It just call corresponding target function anc evaluate it at test input points.
#
# :param fun: Function to be tested.
# :type fun: Type.FunT
# :param test_in: Test input.
# :type test_in: List[List[Decimal]]
#
# :return: Test output.
# :rtype: List[Decimal]
# """
# if fun == Type.FunT.Exp:
# return list(map(lambda x: Decimal(cls.__exp(*list(map(float, x)))), test_in))
# elif fun == Type.FunT.Log:
# return list(map(lambda x: Decimal(cls.__log(*list(map(float, x)))), test_in))
# elif fun == Type.FunT.Pow:
# return list(map(lambda x: Decimal(cls.__pow(*list(map(float, x)))), test_in))
# elif fun == Type.FunT.Sqrt:
# return list(map(lambda x: Decimal(cls.__sqrt(*list(map(float, x)))), test_in))
# elif fun == Type.FunT.Log2:
# return list(map(lambda x: Decimal(cls.__log2(*list(map(float, x)))), test_in))
# else:
# return list(map(lambda x: Decimal(cls.__log10(*list(map(float, x)))), test_in))
@final
class Log(ExpFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class Log2(ExpFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class Log10(ExpFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class Power(ExpFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class Exp(ExpFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class Sqrt(ExpFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class CubeRoot(ExpFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class Surd(ExpFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
| {"/Function/Exponential.py": ["/Function/__init__.py"], "/Core/WarningManager.py": ["/Warning/__init__.py"], "/Function/Error.py": ["/Function/__init__.py"], "/Core/DB.py": ["/Error/__init__.py", "/Util/Macro.py"], "/Function/Signal.py": ["/Function/__init__.py"], "/Function/Combination.py": ["/Function/__init__.py"], "/Function/Division.py": ["/Function/__init__.py"], "/Core/Interpreter.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Operator/Delimiter.py": ["/Operator/__init__.py"], "/Operator/Bool.py": ["/Operator/__init__.py"], "/Error/InterpreterError.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Function/Trigonometric.py": ["/Function/__init__.py"], "/Function/Link.py": ["/Function/__init__.py"], "/Function/Hyperbolic.py": ["/Function/__init__.py"], "/Operator/Assign.py": ["/Operator/__init__.py"], "/Core/SystemManager.py": ["/Error/__init__.py"], "/Core/Main.py": ["/Error/__init__.py"], "/Core/AST.py": ["/Operator/__init__.py"], "/Core/Parser.py": ["/Error/__init__.py", "/Warning/__init__.py", "/Operator/__init__.py", "/Function/__init__.py", "/Util/Macro.py"], "/Core/Token.py": ["/Function/__init__.py", "/Operator/__init__.py"], "/Error/ParserError.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Function/General.py": ["/Function/__init__.py"], "/Test/TestManager.py": ["/Function/__init__.py"], "/Warning/ParserWarning.py": ["/Warning/__init__.py"], "/Core/TypeChecker.py": ["/Operator/__init__.py"], "/Function/Gamma.py": ["/Function/__init__.py"], "/Operator/Binary.py": ["/Operator/__init__.py"], "/Function/Integer.py": ["/Function/__init__.py"], "/Operator/Compare.py": ["/Operator/__init__.py"], "/Core/ErrorManager.py": ["/Error/__init__.py"], "/Operator/Unary.py": ["/Operator/__init__.py"]} |
48,517 | eik4862/TinyCalculator | refs/heads/master | /Core/WarningManager.py | from typing import List, final
from Core import Type, DB
from Warning import Warning
from Util import Printer
from Warning import *
@final
class WarnManager:
"""
Handle warning by generating proper warning messages in consistent form.
This class is implemented as singleton.
For the concept of singleton pattern, consult the references below.
**Reference**
* https://en.wikipedia.org/wiki/Singleton_pattern
:cvar __inst: Singleton object.
:ivar __q: Queue where generated warnings are queued.
:ivar __cnt: Internal counter for buffering warning messages.
"""
__inst = None
def __init__(self) -> None:
self.__q: List[Warning.Warn] = []
self.__cnt: int = 0
def __del__(self) -> None:
pass
def __handle_parser_warn(self, warn: Warning.ParserWarn) -> None:
"""
Handler for warning from parser module.
It handles following warnings according to following forms.
* BIG_INT
[Parser] WARNING: {warning message} (It contains the position of parsed integer which is too big)
* OVERFLOW
[Parser] WARNING: {warning message} (It contains the position of parsed float which caused overflow)
For detailed information of each warning, refer to the comments of ``ParserWarnT``.
This method is private and called internally as a helper of ``WarnManager.handle_warn``.
For detailed description for warning handling, refer to the comments of ``WarnManager.handle_warn``.
:param warn: Parser warning to be handled.
:type warn: Warning.ParserWarn
"""
buf: Type.BufT = Type.BufT.STDWARN # Target buffer.
mark = Printer.Printer.inst().f_col('WARNING', Type.Col.BLUE) # Warning mark.
if warn.warnno in [58, 59]:
msg: str = DB.DB.inst().get_warn_msg(warn.warnno - 1).replace('$1', str(warn.pos)) # Warning message.
Printer.Printer.inst().buf(f'[{self.__cnt}] [Parser] {mark}: {msg}', buf)
Printer.Printer.inst().buf_newline(buf)
self.__cnt += 1
def __handle_interp_warn(self, warn: Warning.InterpWarn) -> None:
"""
Handler for warning from interpreter module.
It handles following warnings according to following forms.
* NAN_DETECT
[Interpreter] WARNING: {warning message} (It contains the position of operand or parameter where NAN is
detected)
* INF_DETECT
[Interpreter] WARNING: {warning message} (It contains the position of operand or parameter where INF is
detected)
* POLE_DETECT
[Interpreter] WARNING: {warning message} (Detailed reason why pole is encountered)
* DOMAIN_OUT
[Interpreter] WARNING: {warning message} (Detailed reason why input parameter is not in domain)
For detailed information of each warning, refer to the comments of ``InterpWarnT``.
This method is private and called internally as a helper of ``WarnManager.handle_warn``.
For detailed description for warning handling, refer to the comments of ``WarnManager.handle_warn``.
:param warn: Interpreter warning to be handled.
:type warn: Warning.InterpWarn
"""
buf: Type.BufT = Type.BufT.STDWARN # Target buffer.
mark = Printer.Printer.inst().f_col('WARNING', Type.Col.BLUE) # Warning mark.
if warn.warn_no in [1, 2, 7, 8, 15, 16, 18, 19]:
arg_pos: str = Printer.Printer.inst().f_ord(warn.arg_pos) # Position of operand caused warning.
msg: str = DB.DB.inst().get_warn_msg(warn.warn_no - 1).replace('$1', arg_pos) # Warning message.
msg = msg.replace('$2', warn.handle)
else:
msg: str = DB.DB.inst().get_warn_msg(warn.warn_no - 1) # Warning message.
if self.__cnt > 0:
Printer.Printer.inst().pop(buf)
Printer.Printer.inst().buf(f'[{self.__cnt}] [Interpreter] {mark}: {msg}', buf)
Printer.Printer.inst().buf_newline(buf)
self.__cnt += 1
def __handle_util_warn(self, warn: Warning.UtilWarn) -> None:
buf: Type.BufT = Type.BufT.STDWARN # Target buffer.
mark = Printer.Printer.inst().f_col('WARNING', Type.Col.BLUE) # Warning mark.
msg: str = DB.DB.inst().get_warn_msg(warn.warn_no - 1) # Warning message.
if self.__cnt > 0:
Printer.Printer.inst().pop(buf)
Printer.Printer.inst().buf(f'[{self.__cnt}] [Cmd.Utility] {mark}: {msg}', buf)
Printer.Printer.inst().buf_newline(buf)
self.__cnt += 1
@classmethod
def inst(cls):
"""
Getter for singleton object.
If it is the first time calling this, it initializes the singleton objects.
This automatically supports so called lazy initialization.
:return: Singleton object.
:rtype: WarnManager
"""
if not cls.__inst:
cls.__inst = WarnManager()
return cls.__inst
@property
def q(self) -> List[Warning.Warn]:
"""
Getter for warning queue.
:return: Warning queue.
:rtype: List[Warning.Warn]
"""
return self.__q
def push(self, warn: Warning.Warn) -> None:
"""
Push warning into the internal queue.
:param warn: Warning to be queued.
:type warn: Warning.Warn
"""
self.__q.append(warn)
def is_warn(self) -> bool:
"""
Check warning queue is empty.
:return: True if warning queue is not empty. False otherwise.
"""
return len(self.__q) != 0
def clr(self) -> None:
"""
Clear warning queue.
"""
self.__q = []
self.__cnt = 0
def handle_warn(self, warn: Warning.Warn) -> None:
"""
Handle error by generating proper error messages.
Warning messages have following general form with slight difference depending on specific warning type and
warning code.
[{Warning source}] WARNING: {Brief description}
:param warn: Warning to be handled.
:type warn: Warning.Warn
"""
warn_t: type = type(warn).__base__
if warn_t == Warning.ParserWarn:
self.__handle_parser_warn(warn)
elif isinstance(warn, Warning.InterpWarn):
self.__handle_interp_warn(warn)
else:
self.__handle_util_warn(warn)
| {"/Function/Exponential.py": ["/Function/__init__.py"], "/Core/WarningManager.py": ["/Warning/__init__.py"], "/Function/Error.py": ["/Function/__init__.py"], "/Core/DB.py": ["/Error/__init__.py", "/Util/Macro.py"], "/Function/Signal.py": ["/Function/__init__.py"], "/Function/Combination.py": ["/Function/__init__.py"], "/Function/Division.py": ["/Function/__init__.py"], "/Core/Interpreter.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Operator/Delimiter.py": ["/Operator/__init__.py"], "/Operator/Bool.py": ["/Operator/__init__.py"], "/Error/InterpreterError.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Function/Trigonometric.py": ["/Function/__init__.py"], "/Function/Link.py": ["/Function/__init__.py"], "/Function/Hyperbolic.py": ["/Function/__init__.py"], "/Operator/Assign.py": ["/Operator/__init__.py"], "/Core/SystemManager.py": ["/Error/__init__.py"], "/Core/Main.py": ["/Error/__init__.py"], "/Core/AST.py": ["/Operator/__init__.py"], "/Core/Parser.py": ["/Error/__init__.py", "/Warning/__init__.py", "/Operator/__init__.py", "/Function/__init__.py", "/Util/Macro.py"], "/Core/Token.py": ["/Function/__init__.py", "/Operator/__init__.py"], "/Error/ParserError.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Function/General.py": ["/Function/__init__.py"], "/Test/TestManager.py": ["/Function/__init__.py"], "/Warning/ParserWarning.py": ["/Warning/__init__.py"], "/Core/TypeChecker.py": ["/Operator/__init__.py"], "/Function/Gamma.py": ["/Function/__init__.py"], "/Operator/Binary.py": ["/Operator/__init__.py"], "/Function/Integer.py": ["/Function/__init__.py"], "/Operator/Compare.py": ["/Operator/__init__.py"], "/Core/ErrorManager.py": ["/Error/__init__.py"], "/Operator/Unary.py": ["/Operator/__init__.py"]} |
48,518 | eik4862/TinyCalculator | refs/heads/master | /Function/Error.py | from typing import final
from Function import Function
class ErrorFun(Function.Fun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class Erf(ErrorFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class Erfc(ErrorFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
| {"/Function/Exponential.py": ["/Function/__init__.py"], "/Core/WarningManager.py": ["/Warning/__init__.py"], "/Function/Error.py": ["/Function/__init__.py"], "/Core/DB.py": ["/Error/__init__.py", "/Util/Macro.py"], "/Function/Signal.py": ["/Function/__init__.py"], "/Function/Combination.py": ["/Function/__init__.py"], "/Function/Division.py": ["/Function/__init__.py"], "/Core/Interpreter.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Operator/Delimiter.py": ["/Operator/__init__.py"], "/Operator/Bool.py": ["/Operator/__init__.py"], "/Error/InterpreterError.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Function/Trigonometric.py": ["/Function/__init__.py"], "/Function/Link.py": ["/Function/__init__.py"], "/Function/Hyperbolic.py": ["/Function/__init__.py"], "/Operator/Assign.py": ["/Operator/__init__.py"], "/Core/SystemManager.py": ["/Error/__init__.py"], "/Core/Main.py": ["/Error/__init__.py"], "/Core/AST.py": ["/Operator/__init__.py"], "/Core/Parser.py": ["/Error/__init__.py", "/Warning/__init__.py", "/Operator/__init__.py", "/Function/__init__.py", "/Util/Macro.py"], "/Core/Token.py": ["/Function/__init__.py", "/Operator/__init__.py"], "/Error/ParserError.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Function/General.py": ["/Function/__init__.py"], "/Test/TestManager.py": ["/Function/__init__.py"], "/Warning/ParserWarning.py": ["/Warning/__init__.py"], "/Core/TypeChecker.py": ["/Operator/__init__.py"], "/Function/Gamma.py": ["/Function/__init__.py"], "/Operator/Binary.py": ["/Operator/__init__.py"], "/Function/Integer.py": ["/Function/__init__.py"], "/Operator/Compare.py": ["/Operator/__init__.py"], "/Core/ErrorManager.py": ["/Error/__init__.py"], "/Operator/Unary.py": ["/Operator/__init__.py"]} |
48,519 | eik4862/TinyCalculator | refs/heads/master | /Core/DB.py | from decimal import Decimal
from typing import Dict, List, TextIO, final, Final, Union
from Core import Type
from Error import Error
from Util import Printer
from Util.Macro import is_comment, is_newline, is_tag
# from Function import *
@final
class DB:
"""
Load database from source file and manage them.
This class is implemented as singleton.
For the concept of singleton pattern, consult the references below.
**Reference**
* https://en.wikipedia.org/wiki/Singleton_pattern
:cvar __HANDLE_SRC: Handles to be registered.
:cvar __FILE_SRC: DB source files to be loaded.
:cvar __TEST_SRC: DB source files for test to be loaded.
:cvar __inst: Singleton object.
:ivar __handle_tb: Hash table for function/command/constant handles.
:ivar __storage: Storage for DB.
"""
__FILE_SRC: Final[Dict[str, Type.FileSrc]] = {
'err_msg': Type.FileSrc('../Data/ErrorMassage.data', 'error messages', False),
'warn_msg': Type.FileSrc('../Data/WarningMessage.data', 'warning messages', False),
'greet_msg': Type.FileSrc('../Data/GreetingMessage.data', 'greeting messages', True),
'debug_in': Type.FileSrc('../Data/Debug.in', 'debug input', False),
'debug_out': Type.FileSrc('../Data/Debug.out', 'debug output', True)
}
# __TEST_IDX_OFFSET: Final[int] = len(__FILE_SRC)
# __TEST_SRC: Final[Dict[str, Type.FileSrc]] = {
# 'custom_in': Type.FileSrc('../Test/In/Test.in', 'Custom test input', False),
# # 'sin_small_in': Type.FileSrc('../Test/In/Test_Sin_Small.in', 'Sin test input', False),
# # 'sin_medium_in': Type.FileSrc('../Test/In/Test_Sin_Medium.in', 'Sin test input', False),
# # 'sin_large_in': Type.FileSrc('../Test/In/Test_Sin_Large.in', 'Sin test input', False),
# # 'cos_small_in': Type.FileSrc('../Test/In/Test_Cos_Small.in', 'Cos test input', False),
# # 'cos_medium_in': Type.FileSrc('../Test/In/Test_Cos_Medium.in', 'Cos test input', False),
# # 'cos_large_in': Type.FileSrc('../Test/In/Test_Cos_Large.in', 'Cos test input', False),
# # 'tan_small_in': Type.FileSrc('../Test/In/Test_Tan_Small.in', 'Tan test input', False),
# # 'tan_medium_in': Type.FileSrc('../Test/In/Test_Tan_Medium.in', 'Tan test input', False),
# # 'tan_large_in': Type.FileSrc('../Test/In/Test_Tan_Large.in', 'Tan test input', False),
# # 'csc_small_in': Type.FileSrc('../Test/In/Test_Csc_Small.in', 'Csc test input', False),
# # 'csc_medium_in': Type.FileSrc('../Test/In/Test_Csc_Medium.in', 'Csc test input', False),
# # 'csc_large_in': Type.FileSrc('../Test/In/Test_Csc_Large.in', 'Csc test input', False),
# # 'sec_small_in': Type.FileSrc('../Test/In/Test_Sec_Small.in', 'Sec test input', False),
# # 'sec_medium_in': Type.FileSrc('../Test/In/Test_Sec_Medium.in', 'Sec test input', False),
# # 'sec_large_in': Type.FileSrc('../Test/In/Test_Sec_Large.in', 'Sec test input', False),
# # 'cot_small_in': Type.FileSrc('../Test/In/Test_Cot_Small.in', 'Cot test input', False),
# # 'cot_medium_in': Type.FileSrc('../Test/In/Test_Cot_Medium.in', 'Cot test input', False),
# # 'cot_large_in': Type.FileSrc('../Test/In/Test_Cot_Large.in', 'Cot test input', False),
# # 'asin_small_in': Type.FileSrc('../Test/In/Test_Asin_Small.in', 'Asin test input', False),
# # 'acos_small_in': Type.FileSrc('../Test/In/Test_Acos_Small.in', 'Acos test input', False),
# # 'atan_small_in': Type.FileSrc('../Test/In/Test_Atan_Small.in', 'Atan test input', False),
# # 'atan_medium_in': Type.FileSrc('../Test/In/Test_Atan_Medium.in', 'Atan test input', False),
# # 'atan_large_in': Type.FileSrc('../Test/In/Test_Atan_Large.in', 'Atan test input', False),
# # 'acsc_small_in': Type.FileSrc('../Test/In/Test_Acsc_Small.in', 'Acsc test input', False),
# # 'acsc_medium_in': Type.FileSrc('../Test/In/Test_Acsc_Medium.in', 'Acsc test input', False),
# # 'acsc_large_in': Type.FileSrc('../Test/In/Test_Acsc_Large.in', 'Acsc test input', False),
# # 'asec_small_in': Type.FileSrc('../Test/In/Test_Asec_Small.in', 'Asec test input', False),
# # 'asec_medium_in': Type.FileSrc('../Test/In/Test_Asec_Medium.in', 'Asec test input', False),
# # 'asec_large_in': Type.FileSrc('../Test/In/Test_Asec_Large.in', 'Asec test input', False),
# # 'acot_small_in': Type.FileSrc('../Test/In/Test_Acot_Small.in', 'Acot test input', False),
# # 'acot_medium_in': Type.FileSrc('../Test/In/Test_Acot_Medium.in', 'Acot test input', False),
# # 'acot_large_in': Type.FileSrc('../Test/In/Test_Acot_Large.in', 'Acot test input', False),
# # 'sinh_small_in': Type.FileSrc('../Test/In/Test_Sinh_Small.in', 'Sinh test input', False),
# # 'sinh_medium_in': Type.FileSrc('../Test/In/Test_Sinh_Medium.in', 'Sinh test input', False),
# # 'sinh_large_in': Type.FileSrc('../Test/In/Test_Sinh_Large.in', 'Sinh test input', False),
# # 'cosh_small_in': Type.FileSrc('../Test/In/Test_Cosh_Small.in', 'Cosh test input', False),
# # 'cosh_medium_in': Type.FileSrc('../Test/In/Test_Cosh_Medium.in', 'Cosh test input', False),
# # 'cosh_large_in': Type.FileSrc('../Test/In/Test_Cosh_Large.in', 'Cosh test input', False),
# # 'tanh_small_in': Type.FileSrc('../Test/In/Test_Tanh_Small.in', 'Tanh test input', False),
# # 'tanh_medium_in': Type.FileSrc('../Test/In/Test_Tanh_Medium.in', 'Tanh test input', False),
# # 'tanh_large_in': Type.FileSrc('../Test/In/Test_Tanh_Large.in', 'Tanh test input', False),
# # 'csch_small_in': Type.FileSrc('../Test/In/Test_Csch_Small.in', 'Csch test input', False),
# # 'csch_medium_in': Type.FileSrc('../Test/In/Test_Csch_Medium.in', 'Csch test input', False),
# # 'csch_large_in': Type.FileSrc('../Test/In/Test_Csch_Large.in', 'Csch test input', False),
# # 'sech_small_in': Type.FileSrc('../Test/In/Test_Sech_Small.in', 'Sech test input', False),
# # 'sech_medium_in': Type.FileSrc('../Test/In/Test_Sech_Medium.in', 'Sech test input', False),
# # 'sech_large_in': Type.FileSrc('../Test/In/Test_Sech_Large.in', 'Sech test input', False),
# # 'coth_small_in': Type.FileSrc('../Test/In/Test_Coth_Small.in', 'Coth test input', False),
# # 'coth_medium_in': Type.FileSrc('../Test/In/Test_Coth_Medium.in', 'Coth test input', False),
# # 'coth_large_in': Type.FileSrc('../Test/In/Test_Coth_Large.in', 'Coth test input', False),
# # 'asinh_small_in': Type.FileSrc('../Test/In/Test_Asinh_Small.in', 'Asinh test input', False),
# # 'asinh_medium_in': Type.FileSrc('../Test/In/Test_Asinh_Medium.in', 'Asinh test input', False),
# # 'asinh_large_in': Type.FileSrc('../Test/In/Test_Asinh_Large.in', 'Asinh test input', False),
# # 'acosh_small_in': Type.FileSrc('../Test/In/Test_Acosh_Small.in', 'Acosh test input', False),
# # 'acosh_medium_in': Type.FileSrc('../Test/In/Test_Acosh_Medium.in', 'Acosh test input', False),
# # 'acosh_large_in': Type.FileSrc('../Test/In/Test_Acosh_Large.in', 'Acosh test input', False),
# # 'atanh_small_in': Type.FileSrc('../Test/In/Test_Atanh_Small.in', 'Atanh test input', False),
# # 'acsch_small_in': Type.FileSrc('../Test/In/Test_Acsch_Small.in', 'Acsch test input', False),
# # 'acsch_medium_in': Type.FileSrc('../Test/In/Test_Acsch_Medium.in', 'Acsch test input', False),
# # 'acsch_large_in': Type.FileSrc('../Test/In/Test_Acsch_Large.in', 'Acsch test input', False),
# # 'asech_small_in': Type.FileSrc('../Test/In/Test_Asech_Small.in', 'Asech test input', False),
# # 'acoth_small_in': Type.FileSrc('../Test/In/Test_Acoth_Small.in', 'Acoth test input', False),
# # 'acoth_medium_in': Type.FileSrc('../Test/In/Test_Acoth_Medium.in', 'Acoth test input', False),
# # 'acoth_large_in': Type.FileSrc('../Test/In/Test_Acoth_Large.in', 'Acoth test input', False),
# # 'erf_small_in': Type.FileSrc('../Test/In/Test_Erf_Small.in', 'Erf test input', False),
# # 'erf_medium_in': Type.FileSrc('../Test/In/Test_Erf_Medium.in', 'Erf test input', False),
# # 'erf_large_in': Type.FileSrc('../Test/In/Test_Erf_Large.in', 'Erf test input', False),
# # 'erfc_small_in': Type.FileSrc('../Test/In/Test_Erfc_Small.in', 'Erfc test input', False),
# # 'erfc_medium_in': Type.FileSrc('../Test/In/Test_Erfc_Medium.in', 'Erfc test input', False),
# # 'erfc_large_in': Type.FileSrc('../Test/In/Test_Erfc_Large.in', 'Erfc test input', False),
# # 'gamma_small_in': Type.FileSrc('../Test/In/Test_Gamma_Small.in', 'Gamma test input', False),
# # 'gamma_medium_in': Type.FileSrc('../Test/In/Test_Gamma_Medium.in', 'Gamma test input', False),
# # 'gamma_large_in': Type.FileSrc('../Test/In/Test_Gamma_Large.in', 'Gamma test input', False),
# # 'lgamma_small_in': Type.FileSrc('../Test/In/Test_Lgamma_Small.in', 'Lgamma test input', False),
# # 'lgamma_medium_in': Type.FileSrc('../Test/In/Test_Lgamma_Medium.in', 'Lgamma test input', False),
# # 'lgamma_large_in': Type.FileSrc('../Test/In/Test_Lgamma_Large.in', 'Lgamma test input', False),
# # 'recigamma_small_in': Type.FileSrc('../Test/In/Test_Recigamma_Small.in', 'Recigamma test input', False),
# # 'recigamma_medium_in': Type.FileSrc('../Test/In/Test_Recigamma_Medium.in', 'Recigamma test input', False),
# # 'recigamma_large_in': Type.FileSrc('../Test/In/Test_Recigamma_Large.in', 'Recigamma test input', False),
# # 'besselclifford_small_in': Type.FileSrc('../Test/In/Test_Besselclifford_Small.in', 'Besselclifford test input',
# # False),
# # 'besselclifford_medium_in': Type.FileSrc('../Test/In/Test_Besselclifford_Medium.in',
# # 'Besselclifford test input', False),
# # 'besselclifford_large_in': Type.FileSrc('../Test/In/Test_Besselclifford_Large.in', 'Besselclifford test input',
# # False),
# # 'beta_small_in': Type.FileSrc('../Test/In/Test_Beta_Small.in', 'Beta test input', False),
# # 'beta_medium_in': Type.FileSrc('../Test/In/Test_Beta_Medium.in', 'Beta test input', False),
# # 'beta_large_in': Type.FileSrc('../Test/In/Test_Beta_Large.in', 'Beta test input', False),
# # 'centralbeta_small_in': Type.FileSrc('../Test/In/Test_Centralbeta_Small.in', 'Centralbeta test input', False),
# # 'centralbeta_medium_in': Type.FileSrc('../Test/In/Test_Centralbeta_Medium.in', 'Centralbeta test input', False),
# # 'centralbeta_large_in': Type.FileSrc('../Test/In/Test_Centralbeta_Large.in', 'Centralbeta test input', False),
# # 'sinc_small_in': Type.FileSrc('../Test/In/Test_Sinc_Small.in', 'Sinc test input', False),
# # 'sinc_medium_in': Type.FileSrc('../Test/In/Test_Sinc_Medium.in', 'Sinc test input', False),
# # 'sinc_large_in': Type.FileSrc('../Test/In/Test_Sinc_Large.in', 'Sinc test input', False),
# # 'tanc_small_in': Type.FileSrc('../Test/In/Test_Tanc_Small.in', 'Tanc test input', False),
# # 'tanc_medium_in': Type.FileSrc('../Test/In/Test_Tanc_Medium.in', 'Tanc test input', False),
# # 'tanc_large_in': Type.FileSrc('../Test/In/Test_Tanc_Large.in', 'Tanc test input', False),
# # 'sinhc_small_in': Type.FileSrc('../Test/In/Test_Sinhc_Small.in', 'Sinhc test input', False),
# # 'sinhc_medium_in': Type.FileSrc('../Test/In/Test_Sinhc_Medium.in', 'Sinhc test input', False),
# # 'sinhc_large_in': Type.FileSrc('../Test/In/Test_Sinhc_Large.in', 'Sinhc test input', False),
# # 'coshc_small_in': Type.FileSrc('../Test/In/Test_Coshc_Small.in', 'Coshc test input', False),
# # 'coshc_medium_in': Type.FileSrc('../Test/In/Test_Coshc_Medium.in', 'Coshc test input', False),
# # 'coshc_large_in': Type.FileSrc('../Test/In/Test_Coshc_Large.in', 'Coshc test input', False),
# # 'tanhc_small_in': Type.FileSrc('../Test/In/Test_Tanhc_Small.in', 'Tanhc test input', False),
# # 'tanhc_medium_in': Type.FileSrc('../Test/In/Test_Tanhc_Medium.in', 'Tanhc test input', False),
# # 'tanhc_large_in': Type.FileSrc('../Test/In/Test_Tanhc_Large.in', 'Tanhc test input', False),
# # 'dirichletkernel_small_in': Type.FileSrc('../Test/In/Test_Dirichletkernel_Small.in',
# # 'Dirichletkernel test input', False),
# # 'dirichletkernel_medium_in': Type.FileSrc('../Test/In/Test_Dirichletkernel_Medium.in',
# # 'Dirichletkernel test input', False),
# # 'dirichletkernel_large_in': Type.FileSrc('../Test/In/Test_Dirichletkernel_Large.in',
# # 'Dirichletkernel test input', False),
# # 'fejerkernel_small_in': Type.FileSrc('../Test/In/Test_Fejerkernel_Small.in', 'Fejerkernel test input', False),
# # 'fejerkernel_medium_in': Type.FileSrc('../Test/In/Test_Fejerkernel_Medium.in', 'Fejerkernel test input', False),
# # 'fejerkernel_large_in': Type.FileSrc('../Test/In/Test_Fejerkernel_Large.in', 'Fejerkernel test input', False),
# # 'topologistsin_small_in': Type.FileSrc('../Test/In/Test_Topologistsin_Small.in', 'Topologistsin test input',
# # False),
# # 'topologistsin_medium_in': Type.FileSrc('../Test/In/Test_Topologistsin_Medium.in', 'Topologistsin test input',
# # False),
# # 'topologistsin_large_in': Type.FileSrc('../Test/In/Test_Topologistsin_Large.in', 'Topologistsin test input',
# # False),
# # 'exp_small_in': Type.FileSrc('../Test/In/Test_Exp_Small.in', 'Exp test input', False),
# # 'exp_medium_in': Type.FileSrc('../Test/In/Test_Exp_Medium.in', 'Exp test input', False),
# # 'exp_large_in': Type.FileSrc('../Test/In/Test_Exp_Large.in', 'Exp test input', False),
# # 'log_small_in': Type.FileSrc('../Test/In/Test_Log_Small.in', 'Log test input', False),
# # 'log_medium_in': Type.FileSrc('../Test/In/Test_Log_Medium.in', 'Log test input', False),
# # 'log_large_in': Type.FileSrc('../Test/In/Test_Log_Large.in', 'Log test input', False),
# # 'sqrt_small_in': Type.FileSrc('../Test/In/Test_Sqrt_Small.in', 'Sqrt test input', False),
# # 'sqrt_medium_in': Type.FileSrc('../Test/In/Test_Sqrt_Medium.in', 'Sqrt test input', False),
# # 'sqrt_large_in': Type.FileSrc('../Test/In/Test_Sqrt_Large.in', 'Sqrt test input', False),
# # 'log2_small_in': Type.FileSrc('../Test/In/Test_Log2_Small.in', 'Log2 test input', False),
# # 'log2_medium_in': Type.FileSrc('../Test/In/Test_Log2_Medium.in', 'Log2 test input', False),
# # 'log2_large_in': Type.FileSrc('../Test/In/Test_Log2_Large.in', 'Log2 test input', False),
# # 'log10_small_in': Type.FileSrc('../Test/In/Test_Log10_Small.in', 'Log10 test input', False),
# # 'log10_medium_in': Type.FileSrc('../Test/In/Test_Log10_Medium.in', 'Log10 test input', False),
# # 'log10_large_in': Type.FileSrc('../Test/In/Test_Log10_Large.in', 'Log10 test input', False),
# 'pow_small_in': Type.FileSrc('../Test/In/Test_Pow_Small.in', 'Pow test input', False),
# 'pow_medium_in': Type.FileSrc('../Test/In/Test_Pow_Medium.in', 'Pow test input', False),
# 'pow_large_in': Type.FileSrc('../Test/In/Test_Pow_Large.in', 'Pow test input', False),
# 'custom_ref': Type.FileSrc('../Test/Ref/Test.ref', 'Custom ref output', False),
# # 'sin_small_ref': Type.FileSrc('../Test/Ref/Test_Sin_Small.ref', 'Sin ref output', False),
# # 'sin_medium_ref': Type.FileSrc('../Test/Ref/Test_Sin_Medium.ref', 'Sin ref output', False),
# # 'sin_large_ref': Type.FileSrc('../Test/Ref/Test_Sin_Large.ref', 'Sin ref output', False),
# # 'cos_small_ref': Type.FileSrc('../Test/Ref/Test_Cos_Small.ref', 'Cos ref output', False),
# # 'cos_medium_ref': Type.FileSrc('../Test/Ref/Test_Cos_Medium.ref', 'Cos ref output', False),
# # 'cos_large_ref': Type.FileSrc('../Test/Ref/Test_Cos_Large.ref', 'Cos ref output', False),
# # 'tan_small_ref': Type.FileSrc('../Test/Ref/Test_Tan_Small.ref', 'Tan ref output', False),
# # 'tan_medium_ref': Type.FileSrc('../Test/Ref/Test_Tan_Medium.ref', 'Tan ref output', False),
# # 'tan_large_ref': Type.FileSrc('../Test/Ref/Test_Tan_Large.ref', 'Tan ref output', False),
# # 'csc_small_ref': Type.FileSrc('../Test/Ref/Test_Csc_Small.ref', 'Csc ref output', False),
# # 'csc_medium_ref': Type.FileSrc('../Test/Ref/Test_Csc_Medium.ref', 'Csc ref output', False),
# # 'csc_large_ref': Type.FileSrc('../Test/Ref/Test_Csc_Large.ref', 'Csc ref output', False),
# # 'sec_small_ref': Type.FileSrc('../Test/Ref/Test_Sec_Small.ref', 'Sec ref output', False),
# # 'sec_medium_ref': Type.FileSrc('../Test/Ref/Test_Sec_Medium.ref', 'Sec ref output', False),
# # 'sec_large_ref': Type.FileSrc('../Test/Ref/Test_Sec_Large.ref', 'Sec ref output', False),
# # 'cot_small_ref': Type.FileSrc('../Test/Ref/Test_Cot_Small.ref', 'Cot ref output', False),
# # 'cot_medium_ref': Type.FileSrc('../Test/Ref/Test_Cot_Medium.ref', 'Cot ref output', False),
# # 'cot_large_ref': Type.FileSrc('../Test/Ref/Test_Cot_Large.ref', 'Cot ref output', False),
# # 'asin_small_ref': Type.FileSrc('../Test/Ref/Test_Asin_Small.ref', 'Asin ref output', False),
# # 'acos_small_ref': Type.FileSrc('../Test/Ref/Test_Acos_Small.ref', 'Acos ref output', False),
# # 'atan_small_ref': Type.FileSrc('../Test/Ref/Test_Atan_Small.ref', 'Atan ref output', False),
# # 'atan_medium_ref': Type.FileSrc('../Test/Ref/Test_Atan_Medium.ref', 'Atan ref output', False),
# # 'atan_large_ref': Type.FileSrc('../Test/Ref/Test_Atan_Large.ref', 'Atan ref output', False),
# # 'acsc_small_ref': Type.FileSrc('../Test/Ref/Test_Acsc_Small.ref', 'Acsc ref output', False),
# # 'acsc_medium_ref': Type.FileSrc('../Test/Ref/Test_Acsc_Medium.ref', 'Acsc ref output', False),
# # 'acsc_large_ref': Type.FileSrc('../Test/Ref/Test_Acsc_Large.ref', 'Acsc ref output', False),
# # 'asec_small_ref': Type.FileSrc('../Test/Ref/Test_Asec_Small.ref', 'Asec ref output', False),
# # 'asec_medium_ref': Type.FileSrc('../Test/Ref/Test_Asec_Medium.ref', 'Asec ref output', False),
# # 'asec_large_ref': Type.FileSrc('../Test/Ref/Test_Asec_Large.ref', 'Asec ref output', False),
# # 'acot_small_ref': Type.FileSrc('../Test/Ref/Test_Acot_Small.ref', 'Acot ref output', False),
# # 'acot_medium_ref': Type.FileSrc('../Test/Ref/Test_Acot_Medium.ref', 'Acot ref output', False),
# # 'acot_large_ref': Type.FileSrc('../Test/Ref/Test_Acot_Large.ref', 'Acot ref output', False),
# # 'sinh_small_ref': Type.FileSrc('../Test/Ref/Test_Sinh_Small.ref', 'Sinh ref output', False),
# # 'sinh_medium_ref': Type.FileSrc('../Test/Ref/Test_Sinh_Medium.ref', 'Sinh ref output', False),
# # 'sinh_large_ref': Type.FileSrc('../Test/Ref/Test_Sinh_Large.ref', 'Sinh ref output', False),
# # 'cosh_small_ref': Type.FileSrc('../Test/Ref/Test_Cosh_Small.ref', 'Cosh ref output', False),
# # 'cosh_medium_ref': Type.FileSrc('../Test/Ref/Test_Cosh_Medium.ref', 'Cosh ref output', False),
# # 'cosh_large_ref': Type.FileSrc('../Test/Ref/Test_Cosh_Large.ref', 'Cosh ref output', False),
# # 'tanh_small_ref': Type.FileSrc('../Test/Ref/Test_Tanh_Small.ref', 'Tanh ref output', False),
# # 'tanh_medium_ref': Type.FileSrc('../Test/Ref/Test_Tanh_Medium.ref', 'Tanh ref output', False),
# # 'tanh_large_ref': Type.FileSrc('../Test/Ref/Test_Tanh_Large.ref', 'Tanh ref output', False),
# # 'csch_small_ref': Type.FileSrc('../Test/Ref/Test_Csch_Small.ref', 'Csch ref output', False),
# # 'csch_medium_ref': Type.FileSrc('../Test/Ref/Test_Csch_Medium.ref', 'Csch ref output', False),
# # 'csch_large_ref': Type.FileSrc('../Test/Ref/Test_Csch_Large.ref', 'Csch ref output', False),
# # 'sech_small_ref': Type.FileSrc('../Test/Ref/Test_Sech_Small.ref', 'Sech ref output', False),
# # 'sech_medium_ref': Type.FileSrc('../Test/Ref/Test_Sech_Medium.ref', 'Sech ref output', False),
# # 'sech_large_ref': Type.FileSrc('../Test/Ref/Test_Sech_Large.ref', 'Sech ref output', False),
# # 'coth_small_ref': Type.FileSrc('../Test/Ref/Test_Coth_Small.ref', 'Coth ref output', False),
# # 'coth_medium_ref': Type.FileSrc('../Test/Ref/Test_Coth_Medium.ref', 'Coth ref output', False),
# # 'coth_large_ref': Type.FileSrc('../Test/Ref/Test_Coth_Large.ref', 'Coth ref output', False),
# # 'asinh_small_ref': Type.FileSrc('../Test/Ref/Test_Asinh_Small.ref', 'Asinh ref output', False),
# # 'asinh_medium_ref': Type.FileSrc('../Test/Ref/Test_Asinh_Medium.ref', 'Asinh ref output', False),
# # 'asinh_large_ref': Type.FileSrc('../Test/Ref/Test_Asinh_Large.ref', 'Asinh ref output', False),
# # 'acosh_small_ref': Type.FileSrc('../Test/Ref/Test_Acosh_Small.ref', 'Acosh ref output', False),
# # 'acosh_medium_ref': Type.FileSrc('../Test/Ref/Test_Acosh_Medium.ref', 'Acosh ref output', False),
# # 'acosh_large_ref': Type.FileSrc('../Test/Ref/Test_Acosh_Large.ref', 'Acosh ref output', False),
# # 'atanh_small_ref': Type.FileSrc('../Test/Ref/Test_Atanh_Small.ref', 'Atanh ref output', False),
# # 'acsch_small_ref': Type.FileSrc('../Test/Ref/Test_Acsch_Small.ref', 'Acsch ref output', False),
# # 'acsch_medium_ref': Type.FileSrc('../Test/Ref/Test_Acsch_Medium.ref', 'Acsch ref output', False),
# # 'acsch_large_ref': Type.FileSrc('../Test/Ref/Test_Acsch_Large.ref', 'Acsch ref output', False),
# # 'asech_small_ref': Type.FileSrc('../Test/Ref/Test_Asech_Small.ref', 'Asech ref output', False),
# # 'acoth_small_ref': Type.FileSrc('../Test/Ref/Test_Acoth_Small.ref', 'Acoth ref output', False),
# # 'acoth_medium_ref': Type.FileSrc('../Test/Ref/Test_Acoth_Medium.ref', 'Acoth ref output', False),
# # 'acoth_large_ref': Type.FileSrc('../Test/Ref/Test_Acoth_Large.ref', 'Acoth ref output', False),
# # 'erf_small_ref': Type.FileSrc('../Test/Ref/Test_Erf_Small.ref', 'Erf ref output', False),
# # 'erf_medium_ref': Type.FileSrc('../Test/Ref/Test_Erf_Medium.ref', 'Erf ref output', False),
# # 'erf_large_ref': Type.FileSrc('../Test/Ref/Test_Erf_Large.ref', 'Erf ref output', False),
# # 'erfc_small_ref': Type.FileSrc('../Test/Ref/Test_Erfc_Small.ref', 'Erfc ref output', False),
# # 'erfc_medium_ref': Type.FileSrc('../Test/Ref/Test_Erfc_Medium.ref', 'Erfc ref output', False),
# # 'erfc_large_ref': Type.FileSrc('../Test/Ref/Test_Erfc_Large.ref', 'Erfc ref output', False),
# # 'gamma_small_ref': Type.FileSrc('../Test/Ref/Test_Gamma_Small.ref', 'Gamma ref output', False),
# # 'gamma_medium_ref': Type.FileSrc('../Test/Ref/Test_Gamma_Medium.ref', 'Gamma ref output', False),
# # 'gamma_large_ref': Type.FileSrc('../Test/Ref/Test_Gamma_Large.ref', 'Gamma ref output', False),
# # 'lgamma_small_ref': Type.FileSrc('../Test/Ref/Test_Lgamma_Small.ref', 'Lgamma ref output', False),
# # 'lgamma_medium_ref': Type.FileSrc('../Test/Ref/Test_Lgamma_Medium.ref', 'Lgamma ref output', False),
# # 'lgamma_large_ref': Type.FileSrc('../Test/Ref/Test_Lgamma_Large.ref', 'Lgamma ref output', False),
# # 'recigamma_small_ref': Type.FileSrc('../Test/Ref/Test_Recigamma_Small.ref', 'Recigamma ref output', False),
# # 'recigamma_medium_ref': Type.FileSrc('../Test/Ref/Test_Recigamma_Medium.ref', 'Recigamma ref output', False),
# # 'recigamma_large_ref': Type.FileSrc('../Test/Ref/Test_Recigamma_Large.ref', 'Recigamma ref output', False),
# # 'besselclifford_small_ref': Type.FileSrc('../Test/Ref/Test_Besselclifford_Small.ref',
# # 'Besselclifford ref output', False),
# # 'besselclifford_medium_ref': Type.FileSrc('../Test/Ref/Test_Besselclifford_Medium.ref',
# # 'Besselclifford ref output', False),
# # 'besselclifford_large_ref': Type.FileSrc('../Test/Ref/Test_Besselclifford_Large.ref',
# # 'Besselclifford ref output', False),
# # 'beta_small_ref': Type.FileSrc('../Test/Ref/Test_Beta_Small.ref', 'Beta ref output', False),
# # 'beta_medium_ref': Type.FileSrc('../Test/Ref/Test_Beta_Medium.ref', 'Beta ref output', False),
# # 'beta_large_ref': Type.FileSrc('../Test/Ref/Test_Beta_Large.ref', 'Beta ref output', False),
# # 'centralbeta_small_ref': Type.FileSrc('../Test/Ref/Test_Centralbeta_Small.ref', 'Centralbeta ref output',
# # False),
# # 'centralbeta_medium_ref': Type.FileSrc('../Test/Ref/Test_Centralbeta_Medium.ref', 'Centralbeta ref output',
# # False),
# # 'centralbeta_large_ref': Type.FileSrc('../Test/Ref/Test_Centralbeta_Large.ref', 'Centralbeta ref output',
# # False),
# # 'sinc_small_ref': Type.FileSrc('../Test/Ref/Test_Sinc_Small.ref', 'Sinc ref output', False),
# # 'sinc_medium_ref': Type.FileSrc('../Test/Ref/Test_Sinc_Medium.ref', 'Sinc ref output', False),
# # 'sinc_large_ref': Type.FileSrc('../Test/Ref/Test_Sinc_Large.ref', 'Sinc ref output', False),
# # 'tanc_small_ref': Type.FileSrc('../Test/Ref/Test_Tanc_Small.ref', 'Tanc ref output', False),
# # 'tanc_medium_ref': Type.FileSrc('../Test/Ref/Test_Tanc_Medium.ref', 'Tanc ref output', False),
# # 'tanc_large_ref': Type.FileSrc('../Test/Ref/Test_Tanc_Large.ref', 'Tanc ref output', False),
# # 'sinhc_small_ref': Type.FileSrc('../Test/Ref/Test_Sinhc_Small.ref', 'Sinhc ref output', False),
# # 'sinhc_medium_ref': Type.FileSrc('../Test/Ref/Test_Sinhc_Medium.ref', 'Sinhc ref output', False),
# # 'sinhc_large_ref': Type.FileSrc('../Test/Ref/Test_Sinhc_Large.ref', 'Sinhc ref output', False),
# # 'coshc_small_ref': Type.FileSrc('../Test/Ref/Test_Coshc_Small.ref', 'Coshc ref output', False),
# # 'coshc_medium_ref': Type.FileSrc('../Test/Ref/Test_Coshc_Medium.ref', 'Coshc ref output', False),
# # 'coshc_large_ref': Type.FileSrc('../Test/Ref/Test_Coshc_Large.ref', 'Coshc ref output', False),
# # 'tanhc_small_ref': Type.FileSrc('../Test/Ref/Test_Tanhc_Small.ref', 'Tanhc ref output', False),
# # 'tanhc_medium_ref': Type.FileSrc('../Test/Ref/Test_Tanhc_Medium.ref', 'Tanhc ref output', False),
# # 'tanhc_large_ref': Type.FileSrc('../Test/Ref/Test_Tanhc_Large.ref', 'Tanhc ref output', False),
# # 'dirichletkernel_small_ref': Type.FileSrc('../Test/Ref/Test_Dirichletkernel_Small.ref',
# # 'Dirichletkernel ref output', False),
# # 'dirichletkernel_medium_ref': Type.FileSrc('../Test/Ref/Test_Dirichletkernel_Medium.ref',
# # 'Dirichletkernel ref output', False),
# # 'dirichletkernel_large_ref': Type.FileSrc('../Test/Ref/Test_Dirichletkernel_Large.ref',
# # 'Dirichletkernel ref output', False),
# # 'fejerkernel_small_ref': Type.FileSrc('../Test/Ref/Test_Fejerkernel_Small.ref', 'Fejerkernel ref output',
# # False),
# # 'fejerkernel_medium_ref': Type.FileSrc('../Test/Ref/Test_Fejerkernel_Medium.ref', 'Fejerkernel ref output',
# # False),
# # 'fejerkernel_large_ref': Type.FileSrc('../Test/Ref/Test_Fejerkernel_Large.ref', 'Fejerkernel ref output',
# # False),
# # 'topologistsin_small_ref': Type.FileSrc('../Test/Ref/Test_Topologistsin_Small.ref', 'Topologistsin ref output',
# # False),
# # 'topologistsin_medium_ref': Type.FileSrc('../Test/Ref/Test_Topologistsin_Medium.ref',
# # 'Topologistsin ref output', False),
# # 'topologistsin_large_ref': Type.FileSrc('../Test/Ref/Test_Topologistsin_Large.ref', 'Topologistsin ref output',
# # False),
# # 'exp_small_ref': Type.FileSrc('../Test/Ref/Test_Exp_Small.ref', 'Exp ref output', False),
# # 'exp_medium_ref': Type.FileSrc('../Test/Ref/Test_Exp_Medium.ref', 'Exp ref output', False),
# # 'exp_large_ref': Type.FileSrc('../Test/Ref/Test_Exp_Large.ref', 'Exp ref output', False),
# # 'log_small_ref': Type.FileSrc('../Test/Ref/Test_Log_Small.ref', 'Log ref output', False),
# # 'log_medium_ref': Type.FileSrc('../Test/Ref/Test_Log_Medium.ref', 'Log ref output', False),
# # 'log_large_ref': Type.FileSrc('../Test/Ref/Test_Log_Large.ref', 'Log ref output', False),
# # 'sqrt_small_ref': Type.FileSrc('../Test/Ref/Test_Sqrt_Small.ref', 'Sqrt ref output', False),
# # 'sqrt_medium_ref': Type.FileSrc('../Test/Ref/Test_Sqrt_Medium.ref', 'Sqrt ref output', False),
# # 'sqrt_large_ref': Type.FileSrc('../Test/Ref/Test_Sqrt_Large.ref', 'Sqrt ref output', False),
# # 'log2_small_ref': Type.FileSrc('../Test/Ref/Test_Log2_Small.ref', 'Log2 ref output', False),
# # 'log2_medium_ref': Type.FileSrc('../Test/Ref/Test_Log2_Medium.ref', 'Log2 ref output', False),
# # 'log2_large_ref': Type.FileSrc('../Test/Ref/Test_Log2_Large.ref', 'Log2 ref output', False),
# # 'log10_small_ref': Type.FileSrc('../Test/Ref/Test_Log10_Small.ref', 'Log10 ref output', False),
# # 'log10_medium_ref': Type.FileSrc('../Test/Ref/Test_Log10_Medium.ref', 'Log10 ref output', False),
# # 'log10_large_ref': Type.FileSrc('../Test/Ref/Test_Log10_Large.ref', 'Log10 ref output', False),
# 'pow_small_ref': Type.FileSrc('../Test/Ref/Test_Pow_Small.ref', 'Pow ref output', False),
# 'pow_medium_ref': Type.FileSrc('../Test/Ref/Test_Pow_Medium.ref', 'Pow ref output', False),
# 'pow_large_ref': Type.FileSrc('../Test/Ref/Test_Pow_Large.ref', 'Pow ref output', False)
# }
__inst = None
def __init__(self) -> None:
self.__storage: List[Union[Dict[str, str], List[str]]] = []
self.__storage_test: List[List[Decimal]] = []
def __del__(self) -> None:
pass
def __load_hlpr(self, path: str, tag: bool = False) -> None:
"""
Load DB from source file.
There are two modes of parsing.
1. Plain mode.
This mode is used for no tagged DB source file.
One line which is not empty in the source file is considered as one item.
The parsed item is stored sequentially.
2. Tag mode.
This mode is used for tagged DB source file.
Each item consists of one tag and one content.
Here, content can span multiple lines whereas tag cannot.
Tag starts with special delimiter character $ and there should be no leading whitespaces.
Also, # in tag will not be considered as a start of comment.
In both mode, any character after # will be considered as commend and will not be parsed.
Note that the grammar for DB source is strict.
In case of violation (two adjacent tags, for example), it will show unexpected behavior.
This method is private and called internally as a helper of ``DB.load``.
For detailed description for DB loading chain, refer to the comments of ``DB.load``.
:param path: Path of source file.
:type path: str
:param tag: Flag for tagged DB source. (Default: False)
:type tag: bool
"""
# Open source file.
try:
src: TextIO = open(path) # Source file.
except OSError as os_err:
raise Error.DBErr(Type.DBErrT.OPEN_ERR, path, os_err.strerror)
if tag:
# Tagged mode.
# Parsing tagged DB source file comprises of two steps.
# 1. Parse tag.
# If it finds tag delimiter $, then the whole line except for trailing newline character is tag.
# 2. Parse item.
# If there is no tag delimiter, the whole line excluding any character after comment delimiter # is a
# part of item.
# In tagged mode, even the trailing newline character is a part of item.
# Note that if it detects tag, it must store previously parsed item with previously parsed tag.
# Also, do not forget to store the last parsed item with last parsed tag.
# The following logic is an implementation of these steps.
storage: Dict[str, str] = {} # Storage of tagged DB.
tag: str = '' # Parsed tag.
it: str = '' # Parsed item.
self.__storage.append(storage)
while True:
line: str = src.readline() # Current parsing line in the source file.
if not line:
break
pos: int = 0 # Current parsing position.
while pos < len(line):
# Parse tag.
if is_tag(line[pos]):
# Store previously parsed item with previously parsed tag.
if it:
storage[tag] = it
it = ''
tag = line[pos + 1:-1]
break
# Parse item with comment.
elif is_comment(line[pos]):
it += line[:pos]
break
pos += 1
# Parse item w/o comment.
if pos == len(line):
it += line
# Store last item with last tag.
storage[tag] = it
else:
# Plain mode.
# Parsing not tagged DB source file is simple.
# For each line, which is not empty, the whole line excluding any character after comment delimiter # is one
# item.
# In no tag mode, trailing newline character will be dropped.
# The following logic is an implementation of these steps.
storage: List[str] = [] # Storage of not tagged DB.
self.__storage.append(storage)
while True:
line: str = src.readline() # Current parsing line in the source file.
if not line:
break
pos: int = 0 # Current parsing position.
# Parse item with comment.
while pos < len(line):
if is_comment(line[pos]):
if line[:pos]:
storage.append(line[:pos])
break
pos += 1
# Parse item w/o comment.
if pos == len(line) and not is_newline(line[0]):
if is_newline(line[-1]):
storage.append(line[:-1])
else:
storage.append(line)
# Close source file.
try:
src.close()
except OSError as os_err:
raise Error.DBErr(Type.DBErrT.CLOSE_ERR, path, os_err.strerror)
# def __load_test_hlpr(self, path: str) -> None:
# """
# Load test DB from source file.
#
# DB source file for test has very strict (more than usual tagged or not tagged source files) grammar, which is
# inevitable for fast parsing.
# Each line must represent (arbitrary precision) numeric value.
# There must be to tag, empty lines, comments and even characters besides ``e`` for exponential.
# The parsed item is stored sequentially as Decimal class which preserves the test input's precision.
# In case of violation (existence of comment, for example), it will show unexpected behavior.
#
# This method is private and called internally as a helper of ``DB.load_test``.
# For detailed description for test DB loading, refer to the comments of ``DB.load_test``.
#
# :param path: Path of source file.
# :type path: str
# """
# # Open source file.
# try:
# src: TextIO = open(path) # Source file.
# except OSError as os_err:
# raise Error.DBErr(Type.DBErrT.OPEN_ERR, path, os_err.strerror)
#
# # Parsing test source file is trivial.
# # Each line is one numeric value.
# # The following logic is an implementation of these steps.
# storage: List[Decimal] = [] # Storage of test DB.
#
# self.__storage_test.append(storage)
#
# while True:
# line: str = src.readline() # Current parsing line in the source file.
#
# if not line:
# break
#
# storage.append(Decimal(line))
#
# # Close source file.
# try:
# src.close()
# except OSError as os_err:
# raise Error.DBErr(Type.DBErrT.CLOSE_ERR, path, os_err.strerror)
@classmethod
def inst(cls):
"""
Getter for singleton object.
If it is the first time calling this, it initializes the singleton objects.
This automatically supports so called lazy initialization.
:return: Singleton object.
:rtype: DB
"""
if not cls.__inst:
cls.__inst = DB()
return cls.__inst
def load(self, debug: bool = False) -> None:
"""
Load DB sources.
DB loading consists of two steps.
1. Register handles.
At this step, it registers function/command/constant handles.
For fast search, key is hashed value of string.
2. Load source files.
At this step, it open source files, parse it and store it properly.
This method supports brief summary outputs which can be used for debugging.
:param debug: Flag for debug mode. (Default: False)
:type debug: bool
"""
if debug:
from sys import getsizeof
from os import getcwd
import time
buf: Type.BufT = Type.BufT.DEBUG # Debug buffer.
# Print out loading target.
Printer.Printer.inst().buf(Printer.Printer.inst().f_title('database info'), buf)
Printer.Printer.inst().buf(f'@pwd : {getcwd()}', buf, indent=2)
Printer.Printer.inst().buf('@path:', buf, indent=2)
for _, src in self.__FILE_SRC.items():
tag: str = 'tag' if src.tag else 'plain' # Type of source file.
Printer.Printer.inst().buf(f'[{src.idx}] {src.path:28} ({tag})', buf, indent=4)
Printer.Printer.inst().buf_newline(buf)
Printer.Printer.inst().buf(Printer.Printer.inst().f_title('start database loading'), buf)
# Register function/constant/boolean handles.
start: float = time.process_time() # Start time stamp for elapsed time measure.
cnt: int = 0 # DB load counter.
tot_cnt: int = 0 # Total # of DB items.
tot_sz: int = 0 # Total size of DB.
# Load DB source files.
for _, src in self.__FILE_SRC.items():
Printer.Printer.inst().buf(Printer.Printer.inst().f_prog(f'[{cnt}] Loading {src.brief}'), buf, False, 2)
try:
self.__load_hlpr(src.path, src.tag)
except Error.DBErr as DB_err:
Printer.Printer.inst().buf(Printer.Printer.inst().f_col('fail', Type.Col.RED), buf)
Printer.Printer.inst().buf_newline(buf)
raise DB_err
else:
Printer.Printer.inst().buf(Printer.Printer.inst().f_col('done', Type.Col.BLUE), buf)
Printer.Printer.inst().buf(f'@size: {len(self.__storage[-1])} ({getsizeof(self.__storage[-1])} bytes)',
buf, indent=4)
Printer.Printer.inst().buf_newline(buf)
cnt += 1
tot_cnt += len(self.__storage[-1])
tot_sz += getsizeof(self.__storage[-1])
elapsed: float = time.process_time() - start # Elapsed time.
Printer.Printer.inst().buf(Printer.Printer.inst().f_title('database loading finished'), buf)
Printer.Printer.inst().buf(f'@total size: {tot_cnt} ({tot_sz} bytes)', buf, indent=2)
Printer.Printer.inst().buf(f'@elapsed : {elapsed * 1000:.2f}ms', buf, indent=2)
Printer.Printer.inst().buf_newline(buf)
else:
for _, src in self.__FILE_SRC.items():
self.__load_hlpr(src.path, src.tag)
# def load_test(self) -> None:
# """
# Load test DB sources.
#
# It just open and load two source files, one is test input and the other is test reference output generated by
# MATLAB.
# These two source files are plain DB sources with strict format.
# That is, there must be no comments and each line is comprised of one numeric value.
#
# Unlike ``DB.load``, it clears storage for test DB before loading.
# Thus there is always at most one loaded test DB.
# This is because the size of test input and reference output can be quite large, exceeding 1MB.
#
# This method always shows brief summary outputs which can be used for debugging.
# """
#
# from sys import getsizeof
# from os import getcwd
# import time
#
# buf: Type.BufT = Type.BufT.DEBUG # Debug buffer.
#
# # Print out loading target.
# Printer.Printer.inst().buf(Printer.Printer.inst().f_title('database info'), buf)
# Printer.Printer.inst().buf(f'@pwd : {getcwd()}', buf, indent=2)
# Printer.Printer.inst().buf('@path:', buf, indent=2)
#
# for _, src in self.__TEST_SRC.items():
# Printer.Printer.inst().buf(f'[{src.idx - self.__TEST_IDX_OFFSET:02d}] {src.path}', buf, indent=4)
#
# Printer.Printer.inst().buf_newline(buf)
#
# # Load DB source files.
# Printer.Printer.inst().buf(Printer.Printer.inst().f_title('start database loading'), buf)
#
# # Register function/constant handles.
# start: float = time.process_time() # Start time stamp for elapsed time measure.
# cnt: int = 0 # DB load counter.
# tot_cnt: int = 0 # Total # of DB items.
# tot_sz: int = 0 # Total size of DB.
#
# # Load inputs and references.
# for k, src in self.__TEST_SRC.items():
# src_t: str = 'custom' if 'custom' in k else k[(k.find('_') + 1):k.find('_', k.find('_') + 1)]
# Printer.Printer.inst().buf(Printer.Printer.inst().f_prog(f'[{cnt}] Loading {src.brief}'), buf, False, 2)
#
# try:
# self.__load_test_hlpr(src.path)
# except Error.DBErr as DB_err:
# Printer.Printer.inst().buf(Printer.Printer.inst().f_col('fail', Type.Col.RED), buf)
# Printer.Printer.inst().buf_newline(buf)
#
# raise DB_err
# else:
# Printer.Printer.inst().buf(Printer.Printer.inst().f_col('done', Type.Col.BLUE), buf)
#
# Printer.Printer.inst().buf(
# f'@size: {len(self.__storage_test[-1])} ({getsizeof(self.__storage_test[-1])} bytes)', buf, indent=4)
# Printer.Printer.inst().buf(f'@type: {src_t}', buf, indent=4)
# Printer.Printer.inst().buf_newline(buf)
# tot_cnt += len(self.__storage_test[-1])
# tot_sz += getsizeof(self.__storage_test[-1])
# cnt += 1
#
# elapsed: float = time.process_time() - start # Elapsed time.
# tot_cnt += len(self.__storage_test[1])
# tot_sz += getsizeof(self.__storage_test[1])
#
# Printer.Printer.inst().buf(Printer.Printer.inst().f_title('database loading finished'), buf)
# Printer.Printer.inst().buf(f'@total size: {tot_cnt} ({tot_sz} bytes)', buf, indent=2)
# Printer.Printer.inst().buf(f'@elapsed : {elapsed * 1000:.2f}ms', buf, indent=2)
# Printer.Printer.inst().buf_newline(buf)
def get_greet_msg(self, k: str) -> str:
"""
Getter for greeting messages.
:param k: Tag of greeting message to get.
:type k: str
:return: Meta information with corresponding tag.
:rtype: str
"""
return self.__storage[self.__FILE_SRC.get('greet_msg').idx].get(k)
def get_err_msg(self, idx: int) -> str:
"""
Getter for error message.
:param idx: Index of error message to get.
:type idx: int
:return: Error message with corresponding index.
:rtype: str
"""
return self.__storage[self.__FILE_SRC.get('err_msg').idx][idx]
def get_warn_msg(self, idx: int) -> str:
"""
Getter for warning message.
:param idx: Index of warning message to get.
:type idx: int
:return: Warning message with corresponding index.
:rtype: str
"""
return self.__storage[self.__FILE_SRC.get('warn_msg').idx][idx]
def get_debug_in(self, idx: int) -> str:
"""
Getter for debug input.
:param idx: Index of debug input to get.
:type idx: int
:return: Debug input with corresponding index.
:rtype: str
"""
return self.__storage[self.__FILE_SRC.get('debug_in').idx][idx]
def get_debug_out(self, k: str) -> str:
"""
Getter for debug output.
:param k: Tag of debug output to get.
:type k: str
:return: Debug output with corresponding tag
:rtype: str
"""
return self.__storage[self.__FILE_SRC.get('debug_out').idx].get(k)
def get_sz(self, storage: str) -> int:
"""
Get the # of DB items.
:return: The # of DB items.
:rtype: int
"""
return len(self.__storage[self.__FILE_SRC.get(storage).idx])
# def get_test_in(self, fun: Type.FunT = None, sz: Type.TestSzT = None) -> List[Decimal]:
# """
# Getter for test input.
#
# :return: Test input.
# :rtype: List[Decimal]
# """
# storage = f'{fun.name.lower()}_{sz.name.lower()}_in' if fun else 'custom_in'
#
# return self.__storage_test[self.__TEST_SRC.get(storage).idx - self.__TEST_IDX_OFFSET]
#
# def get_test_ref(self, fun: Type.FunT = None, sz: Type.TestSzT = None) -> List[Decimal]:
# """
# Getter for test reference output.
#
# :return: Test reference output.
# :rtype: List[Decimal]
# """
# storage = f'{fun.name.lower()}_{sz.name.lower()}_ref' if fun else 'custom_ref'
#
# return self.__storage_test[self.__TEST_SRC.get(storage).idx - self.__TEST_IDX_OFFSET]
#
# def get_test_target(self) -> List[Tuple[Type.FunT, Type.TestSzT]]:
# keys: List[List[str]] = [k.split('_') for k in [k[:-3] for k in list(self.__TEST_SRC.keys())]]
# keys = keys[1:int(len(keys) / 2)]
# target: List[Tuple[Type.FunT, Type.TestSzT]] = []
#
# for k in keys:
# if k[1] == 'small':
# target.append((self.get_handle(k[0].capitalize()), Type.TestSzT.SMALL))
# elif k[1] == 'medium':
# target.append((self.get_handle(k[0].capitalize()), Type.TestSzT.MEDIUM))
# else:
# target.append((self.get_handle(k[0].capitalize()), Type.TestSzT.LARGE))
#
# return target
| {"/Function/Exponential.py": ["/Function/__init__.py"], "/Core/WarningManager.py": ["/Warning/__init__.py"], "/Function/Error.py": ["/Function/__init__.py"], "/Core/DB.py": ["/Error/__init__.py", "/Util/Macro.py"], "/Function/Signal.py": ["/Function/__init__.py"], "/Function/Combination.py": ["/Function/__init__.py"], "/Function/Division.py": ["/Function/__init__.py"], "/Core/Interpreter.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Operator/Delimiter.py": ["/Operator/__init__.py"], "/Operator/Bool.py": ["/Operator/__init__.py"], "/Error/InterpreterError.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Function/Trigonometric.py": ["/Function/__init__.py"], "/Function/Link.py": ["/Function/__init__.py"], "/Function/Hyperbolic.py": ["/Function/__init__.py"], "/Operator/Assign.py": ["/Operator/__init__.py"], "/Core/SystemManager.py": ["/Error/__init__.py"], "/Core/Main.py": ["/Error/__init__.py"], "/Core/AST.py": ["/Operator/__init__.py"], "/Core/Parser.py": ["/Error/__init__.py", "/Warning/__init__.py", "/Operator/__init__.py", "/Function/__init__.py", "/Util/Macro.py"], "/Core/Token.py": ["/Function/__init__.py", "/Operator/__init__.py"], "/Error/ParserError.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Function/General.py": ["/Function/__init__.py"], "/Test/TestManager.py": ["/Function/__init__.py"], "/Warning/ParserWarning.py": ["/Warning/__init__.py"], "/Core/TypeChecker.py": ["/Operator/__init__.py"], "/Function/Gamma.py": ["/Function/__init__.py"], "/Operator/Binary.py": ["/Operator/__init__.py"], "/Function/Integer.py": ["/Function/__init__.py"], "/Operator/Compare.py": ["/Operator/__init__.py"], "/Core/ErrorManager.py": ["/Error/__init__.py"], "/Operator/Unary.py": ["/Operator/__init__.py"]} |
48,520 | eik4862/TinyCalculator | refs/heads/master | /Function/Signal.py | from typing import final, Final, List
from Function import Function
class SigFun(Function.Fun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class Ramp(SigFun):
__SGN: Final[List[str]] = ['Ramp[Real] -> Real', 'Ramp[Sym] -> Sym']
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class Unitize(SigFun):
__SGN: Final[List[str]] = ['Unitize[Real] -> Real',
'Unitize[Sym] -> Sym',
'Unitize[Real, Real] -> Real',
'Unitize[Sym, Sym] -> Sym']
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class Logistic(SigFun):
__SGN: Final[List[str]] = ['Logistic[Real] -> Real', 'Logistic[Sym] -> Sym']
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class SquareWave(SigFun):
__SGN: Final[List[str]] = ['SquareWave[Real, Real (Optional), Real (Optional)] -> Real',
'SquareWave[Sym, Sym (Optional), Sym (Optional)] -> Sym']
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class TriangleWave(SigFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
@final
class SawtoothWave(SigFun):
def __new__(cls, *args, **kwargs) -> None:
raise NotImplementedError
| {"/Function/Exponential.py": ["/Function/__init__.py"], "/Core/WarningManager.py": ["/Warning/__init__.py"], "/Function/Error.py": ["/Function/__init__.py"], "/Core/DB.py": ["/Error/__init__.py", "/Util/Macro.py"], "/Function/Signal.py": ["/Function/__init__.py"], "/Function/Combination.py": ["/Function/__init__.py"], "/Function/Division.py": ["/Function/__init__.py"], "/Core/Interpreter.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Operator/Delimiter.py": ["/Operator/__init__.py"], "/Operator/Bool.py": ["/Operator/__init__.py"], "/Error/InterpreterError.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Function/Trigonometric.py": ["/Function/__init__.py"], "/Function/Link.py": ["/Function/__init__.py"], "/Function/Hyperbolic.py": ["/Function/__init__.py"], "/Operator/Assign.py": ["/Operator/__init__.py"], "/Core/SystemManager.py": ["/Error/__init__.py"], "/Core/Main.py": ["/Error/__init__.py"], "/Core/AST.py": ["/Operator/__init__.py"], "/Core/Parser.py": ["/Error/__init__.py", "/Warning/__init__.py", "/Operator/__init__.py", "/Function/__init__.py", "/Util/Macro.py"], "/Core/Token.py": ["/Function/__init__.py", "/Operator/__init__.py"], "/Error/ParserError.py": ["/Error/__init__.py", "/Operator/__init__.py"], "/Function/General.py": ["/Function/__init__.py"], "/Test/TestManager.py": ["/Function/__init__.py"], "/Warning/ParserWarning.py": ["/Warning/__init__.py"], "/Core/TypeChecker.py": ["/Operator/__init__.py"], "/Function/Gamma.py": ["/Function/__init__.py"], "/Operator/Binary.py": ["/Operator/__init__.py"], "/Function/Integer.py": ["/Function/__init__.py"], "/Operator/Compare.py": ["/Operator/__init__.py"], "/Core/ErrorManager.py": ["/Error/__init__.py"], "/Operator/Unary.py": ["/Operator/__init__.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.