Dataset Viewer
Auto-converted to Parquet Duplicate
repo_name
stringlengths
5
113
combined_content
stringlengths
88
120M
file_paths
listlengths
2
11.1k
0-k-1/TodoMVC2
from django.db import models #from django.contrib.auth.models import User class Todo(models.Model): title = models.CharField(max_length=50) completed = models.BooleanField(default=False) --- FILE SEPARATOR --- # from django.urls import path from django.conf.urls import url from App.views import todoMVC_view,save_view urlpatterns = [ url('', todoMVC_view), url(r'^save/', save_view, name='save') ] --- FILE SEPARATOR --- from django.shortcuts import render,redirect from App.models import Todo import json # from django.forms.models import model_to_dict def todoMVC_view(request): # list=[{"content":"任务1","completed":"True"},{"content":"任务2","completed":"False"}] # list=[ # {"completed": "false","id": "1","title": "31"}, # {"completed": "true","id": "2","title": "35"}, # {"completed": "true","id": "0","title": "32"} # ] # list_value = list.values() # list = model_to_dict(list[0]) # print(list_value) ls = Todo.objects.all() ls = list(ls.values()) print(ls) return render(request, 'VueExample.html', {"list":json.dumps(ls)}) #return render(request, 'VueExample.html', {"list":list}) def save_view(request): print(request.POST['q']) # print(request.body) # print(type(request.body)) # print(request.body.decode()) # para = json.loads(request.body.decode()) # print(para) # 直接覆盖 ls = Todo.objects.all() ls.delete() for item in json.loads(request.POST['q']): Todo.objects.create(title=item['title'], completed=item['completed']) # 删除不起作用 # try: # for k in item.keys(): # print(k,item[k]) # Todo.objects.update_or_create(id=item['id'], # defaults={'id': item['id'], 'title': item['title'], # 'completed': item['completed']}) # except: # pass #return render(request, 'VueExample.html') return redirect('/')
[ "/App/models.py", "/App/urls.py", "/App/views.py" ]
0000duck/vrep
#!python3 # -*- coding:utf-8 -*- import matplotlib.pyplot as plt import math import heapq import time try: import vrep except: print ('--------------------------------------------------------------') print ('"vrep.py" could not be imported. This means very probably that') print ('either "vrep.py" or the remoteApi library could not be found.') print ('Make sure both are in the same folder as this file,') print ('or appropriately adjust the file "vrep.py"') print ('--------------------------------------------------------------') print ('') class Entity: def __init__(self, type, name, x=0.0, y=0.0, r=0, x1=0.0, x2=0.0, y1=0.0, y2=0.0): self.type = type self.name = name if type == 'Point': self.x = x self.y = y elif type == 'Obstacle': self.x = x self.y = y self.r = r elif type == 'Gate': self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 class Record: def __init__(self, loc=-1, dis=0, gate=0, path=''): self.loc = loc self.dis = dis self.gate = gate self.path = path self.hash = str(loc) + '$' + str(self.gate) def __lt__(self, other): return self.dis < other.dis class Heap: def __init__(self): self.heap = [] self.hash = {} def push(self, record): dis = self.hash.get(record.hash, 1e+10) if dis <= record.dis + 1e-6: return else: self.hash[record.hash] = record.dis heapq.heappush(self.heap, (record.dis, record)) def top(self): dis, record = self.heap[0] return record def pop(self): dis, record = heapq.heappop(self.heap) return record class Search: def __init__(self, entities, clientID): self.entities = entities self.clientID = clientID def distance_between_points(self, p1, p2): return (p1.x - p2.x)**2 + (p1.y - p2.y)**2 def check_point_in_obstacle(self, point, obstacle): return self.distance_between_points(point, obstacle) <= obstacle.r**2 def check_insection_with_obstacle(self, point1, point2, obstacle): p1_to_o = math.sqrt(self.distance_between_points(point1, obstacle)) p2_to_o = math.sqrt(self.distance_between_points(point2, obstacle)) p1_to_p2 = math.sqrt(self.distance_between_points(point1, point2)) half = (p1_to_o + p2_to_o + p1_to_p2) / 2.0 s = math.sqrt(half * (half - p1_to_o) * (half - p2_to_o) * (half - p1_to_p2)) high = s * 2 / p1_to_p2 p1_b = math.sqrt(p1_to_o**2 - high**2) p2_b = math.sqrt(p2_to_o**2 - high**2) if abs(p1_b + p2_b - p1_to_p2) < 1e-4: dis = high else: dis = min(p1_to_o, p2_to_o) return dis < obstacle.r def draw(self, type='A'): if type == 'A': for entity in self.entities: if entity.type == 'Point': if entity.name == 'Target0': plt.scatter(entity.x, entity.y, c='r') elif entity.name == 'Target1': plt.scatter(entity.x, entity.y, c='g') elif entity.name == 'Target2': plt.scatter(entity.x, entity.y, c='b') else: print (entity.name) elif entity.type == 'Obstacle': xs = [entity.x + entity.r * math.cos(math.pi * 2.0 * i / 1000) for i in range(0, 1000)] ys = [entity.y + entity.r * math.sin(math.pi * 2.0 * i / 1000) for i in range(0, 1000)] plt.plot(xs, ys, c='k') elif entity.type == 'Gate': plt.scatter(entity.x1, entity.y1, c='k') plt.scatter(entity.x2, entity.y2, c='k') else: print (entity.type, entity.name) if type == 'B' or type == 'C': cnt = 0 for entity in self.points: if entity.name == 'Target0': plt.scatter(entity.x, entity.y, c='r') elif entity.name == 'Target1': plt.scatter(entity.x, entity.y, c='g') elif entity.name == 'Target2': plt.scatter(entity.x, entity.y, c='b') else: plt.scatter(entity.x, entity.y, c='k', label = 'P'+str(cnt)) cnt += 1 if type == 'D': for entity in self.points: if 'Gate' in entity.name: plt.scatter(entity.x, entity.y, c='k') if type == 'B' or type == 'C' or type == 'D': for entity in self.obstacles: xs = [entity.x + entity.r * math.cos(math.pi * 2.0 * i / 1000) for i in range(0, 1000)] ys = [entity.y + entity.r * math.sin(math.pi * 2.0 * i / 1000) for i in range(0, 1000)] plt.plot(xs, ys, c='k') if type == 'C' or type == 'D': xs = [item.x for item in self.answers] ys = [item.y for item in self.answers] plt.plot(xs, ys, c='y') plt.show() def build(self, divided = 10): self.obstacles = [] self.points = [] cnt = 0 for entity in self.entities: if entity.type == 'Point': self.points.append(entity) elif entity.type == 'Obstacle': self.obstacles.append(entity) elif entity.type == 'Gate': self.points.append(Entity(type='Point', name='GateA'+str(cnt), x=entity.x1, y=entity.y1)) self.points.append(Entity(type='Point', name='GateB'+str(cnt), x=entity.x2, y=entity.y2)) cnt += 1 else: print ('Error') self.minx = self.maxx = self.points[0].x self.miny = self.maxy = self.points[0].y for point in self.points: self.minx = min(self.minx, point.x) self.miny = min(self.miny, point.y) self.maxx = max(self.maxx, point.x) self.maxy = max(self.maxy, point.y) for obstacle in self.obstacles: self.minx = min(self.minx, obstacle.x - obstacle.r) self.miny = min(self.miny, obstacle.y - obstacle.r) self.maxx = max(self.maxx, obstacle.x + obstacle.r) self.maxy = max(self.maxy, obstacle.y + obstacle.r) self.minx -= 2 self.miny -= 2 self.maxx += 2 self.maxy += 2 cnt = 0 for i in range(divided+1): for j in range(divided+1): x = self.minx + (self.maxx - self.minx) * i / divided y = self.miny + (self.maxy - self.miny) * j / divided self.points.append(Entity(type='Point', name='Point'+str(cnt), x=x, y=y)) newpoints = [] for point in self.points: flag = True for obstacle in self.obstacles: if self.check_point_in_obstacle(point, obstacle): flag = False break if flag: newpoints.append(point) self.points = newpoints def search(self, targetnum=2, gatenum=4): name_to_entity = {} name_to_number = {} cnt = 0 for point in self.points: name_to_entity[point.name] = point name_to_number[point.name] = cnt cnt += 1 #print (point.name) heap = Heap() loc = name_to_number['Target0'] record = Record(loc=loc, dis=0, gate=0, path=str(loc)) heap.push(record) starttime = time.time() answer = None connect = {} for i in range(len(self.points)): for j in range(len(self.points)): flag = True if i==j: flag = False else: for obstacle in self.obstacles: if self.check_insection_with_obstacle(self.points[i], self.points[j], obstacle): flag = False break connect [str(i) + '$' + str(j)] = flag while len(heap.heap): record = heap.pop() if heap.hash.get(record.hash) < record.dis: continue old_targetnum = record.gate % 10 old_gatenum = record.gate % 100 // 10 old_gatevalue = record.gate // 100 #print ('search ', record.gate, record.dis) #print ('\t\t', record.path) if old_targetnum == targetnum and old_gatenum == gatenum: answer = record break for loc in range(len(self.points)): if loc == record.loc: continue if not connect[str(loc) + '$' + str(record.loc)]: continue new_dis = record.dis + math.sqrt(self.distance_between_points(self.points[record.loc], self.points[loc])) new_path = record.path + '$' + str(loc) if self.points[loc].name == 'Target' + str(old_targetnum + 1): new_targetnum = old_targetnum + 1 #print ('\t\t\ttarget', record.loc, loc, old_targetnum, self.points[loc].name, new_targetnum, new_dis) else: new_targetnum = old_targetnum name1 = self.points[record.loc].name name2 = self.points[loc].name new_gatenum = old_gatenum new_gatevalue = old_gatevalue if 'Gate' in name1 and 'Gate' in name2: if 'GateB' in name1: name1, name2 = name2, name1 if 'GateA' in name1 and 'GateB' in name2 and name1[5:] == name2[5:]: number = 1<<int(name1[5:]) if number & old_gatevalue == 0: new_gatenum += 1 new_gatevalue |= number new_record = Record(loc=loc, dis=new_dis, gate=new_gatevalue*100+new_gatenum*10+new_targetnum, path=new_path) heap.push(new_record) print ('Time ', time.time() - starttime) if answer is None: print ('No answer') else: print ('Answer') print (answer.dis) print (answer.path) self.answers = [self.points[int(item)] for item in answer.path.split('$')] print (len(self.answers)) count = 0 for point in self.answers: print ('\t', point.x, point.y, point.name) res, handle = vrep.simxGetObjectHandle(self.clientID, 'target'+str(count), vrep.simx_opmode_blocking) if point.name=='Target1': res = vrep.simxSetObjectPosition(self.clientID, handle, -1, [point.x, point.y, 1], vrep.simx_opmode_blocking) elif point.name=='Target2': res = vrep.simxSetObjectPosition(self.clientID, handle, -1, [point.x, point.y, 2], vrep.simx_opmode_blocking) elif point.name[0]=='G': if point.name[4]=='A': res = vrep.simxSetObjectPosition(self.clientID, handle, -1, [point.x, point.y, 3], vrep.simx_opmode_blocking) else: res = vrep.simxSetObjectPosition(self.clientID, handle, -1, [point.x, point.y, 4], vrep.simx_opmode_blocking) else: res = vrep.simxSetObjectPosition(self.clientID, handle, -1, [point.x, point.y, 0], vrep.simx_opmode_blocking) count += 1 if __name__ == '__main__': search = Search([]) point1 = Entity(type='Point', name='Tmp1', x=0, y=0) point2 = Entity(type='Point', name='Tmp2', x=10, y=0) obstacle = Entity(type='Obstacle', name='Tmp3', x=-4, y=3, r=4.9) print (search.check_insection_with_obstacle(point1, point2, obstacle)) --- FILE SEPARATOR --- #!python3 # -*- coding:utf-8 -*- # Make sure to have the server side running in V-REP: # in a child script of a V-REP scene, add following command # to be executed just once, at simulation start: # # simRemoteApi.start(19999) # # then start simulation, and run this program. # # IMPORTANT: for each successful call to simxStart, there # should be a corresponding call to simxFinish at the end! try: import vrep except: print ('--------------------------------------------------------------') print ('"vrep.py" could not be imported. This means very probably that') print ('either "vrep.py" or the remoteApi library could not be found.') print ('Make sure both are in the same folder as this file,') print ('or appropriately adjust the file "vrep.py"') print ('--------------------------------------------------------------') print ('') import time from entity import Entity, Search if __name__ == '__main__': #print ('Program started') vrep.simxFinish(-1) # just in case, close all opened connections clientID = vrep.simxStart('127.0.0.1', 19999, True, True, 5000, 5) # Connect to V-REP #print (clientID) if clientID!=-1: print ('Connected to remote API server') ########## objects = { 'Tree': 'Tree', 'Tree#0': 'Tree', 'Cylinder': 'Cylinder', 'Start_point': 'Start', 'Target': 'Target', 'End': 'End', 'UR3': 'UR', 'UR3#0': 'UR', 'GateCounter_55cmX40cm': 'Gate', 'GateCounter_55cmX40cm#0': 'Gate', 'GateCounter_55cmX40cm#1': 'Gate', 'GateCounter_80cmX190cm': 'Gate', 'GateCounter_80cmX190cm#0': 'Gate', 'GateCounter_80cmX190cm#1': 'Gate', 'GateCounter_80cmX190cm#2': 'Gate', } entities = [] for key, value in objects.items(): if value in ['Tree', 'UR', 'Cylinder']: res, handle = vrep.simxGetObjectHandle(clientID, key, vrep.simx_opmode_blocking) res, position = vrep.simxGetObjectPosition(clientID, handle, -1, vrep.simx_opmode_blocking) entity = Entity(type='Obstacle', name=key, x=position[0], y=position[1], r=2.0 if value != 'Cylinder' else 1.0) elif value == 'Start': res, handle = vrep.simxGetObjectHandle(clientID, key, vrep.simx_opmode_blocking) res, position = vrep.simxGetObjectPosition(clientID, handle, -1, vrep.simx_opmode_blocking) name ='Target0' if value == 'Start' else 'Target1' if value == 'Target' else 'Target2' if value == 'End' else 'Error' entity = Entity(type='Point', name=name, x=position[0], y=position[1]) elif value in ['Target', 'End']: function_name = "get_target_platform_pos" if value == 'Target' else "get_end_point_pos" res, _, position, _, _ = vrep.simxCallScriptFunction(clientID, "util_funcs", vrep.sim_scripttype_customizationscript,function_name, [], [], [],bytearray(), vrep.simx_opmode_blocking) name ='Target0' if value == 'Start' else 'Target1' if value == 'Target' else 'Target2' if value == 'End' else 'Error' entity = Entity(type='Point', name=name, x=position[0], y=position[1]) elif value == 'Gate': res, handle1 = vrep.simxGetObjectHandle(clientID, key, vrep.simx_opmode_blocking) res, handle2 = vrep.simxGetObjectHandle(clientID, 'Tmp', vrep.simx_opmode_blocking) res, position1 = vrep.simxGetObjectPosition(clientID, handle1, -1, vrep.simx_opmode_blocking) vrep.simxSetObjectPosition(clientID, handle2, handle1, (2,0,0), vrep.simx_opmode_blocking) res, position2 = vrep.simxGetObjectPosition(clientID, handle2, -1, vrep.simx_opmode_blocking) vrep.simxSetObjectPosition(clientID, handle2, handle1, (-2,0,0), vrep.simx_opmode_blocking) res, position3 = vrep.simxGetObjectPosition(clientID, handle2, -1, vrep.simx_opmode_blocking) entity = Entity(type='Gate', name=key, x1=position2[0], y1=position2[1], x2=position3[0], y2=position3[1]) else: print (key, value) entities.append(entity) ########## search = Search(entities, clientID) search.build(divided = 10) #search.draw(type='B') search.search() search.draw(type='D') # Before closing the connection to V-REP, make sure that the last command sent out had time to arrive. You can guarantee this with (for example): vrep.simxGetPingTime(clientID) # Now close the connection to V-REP: vrep.simxFinish(clientID) else: print ('Failed connecting to remote API server') print ('Program ended') --- FILE SEPARATOR --- function sysCall_init() -- Make sure we have version 2.4.13 or above (the particles are not supported otherwise) v=sim.getInt32Parameter(sim.intparam_program_version) if (v<20413) then sim.displayDialog('Warning','The propeller model is only fully supported from V-REP version 2.4.13 and above.&&nThis simulation will not run as expected!',sim.dlgstyle_ok,false,'',nil,{0.8,0,0,0,0,0}) end -- Detatch the manipulation sphere: targetObj=sim.getObjectHandle('Quadricopter_target') sim.setObjectParent(targetObj,-1,true) -- This control algo was quickly written and is dirty and not optimal. It just serves as a SIMPLE example d=sim.getObjectHandle('Quadricopter_base') hand_handle=sim.getObjectHandle('JacoHand') quadricopter=sim.getObjectHandle('Quadricopter') quadricopter_prop_respondable1=sim.getObjectHandle('Quadricopter_propeller_respondable1') particlesAreVisible=sim.getScriptSimulationParameter(sim.handle_self,'particlesAreVisible') sim.setScriptSimulationParameter(sim.handle_tree,'particlesAreVisible',tostring(particlesAreVisible)) simulateParticles=sim.getScriptSimulationParameter(sim.handle_self,'simulateParticles') sim.setScriptSimulationParameter(sim.handle_tree,'simulateParticles',tostring(simulateParticles)) propellerScripts={-1,-1,-1,-1} for i=1,4,1 do propellerScripts[i]=sim.getScriptHandle('Quadricopter_propeller_respondable'..i) end heli=sim.getObjectAssociatedWithScript(sim.handle_self) hand_script_handle = sim.getScriptHandle('JacoHand') print('hand_script_handle', hand_script_handle) particlesTargetVelocities={0,0,0,0} pParam=6 iParam=0.04 dParam=0.08 vParam=-2 cumul=0 lastE=0 pAlphaE=0 pBetaE=0 alphaCumul=0 betaCumul=0 rotCorrCumul=0 psp2=0 psp1=0 spCumul=0 prevEuler=0 maxCorr=0 deltax=0 deltay=0 fakeShadow=sim.getScriptSimulationParameter(sim.handle_self,'fakeShadow') if (fakeShadow) then shadowCont=sim.addDrawingObject(sim.drawing_discpoints+sim.drawing_cyclic+sim.drawing_25percenttransparency+sim.drawing_50percenttransparency+sim.drawing_itemsizes,0.2,0,-1,1) end -- Prepare 2 floating views with the zed camera views: zed_vision0 = sim.getObjectHandle('zed_vision0') zed_vision1 = sim.getObjectHandle('zed_vision1') zed_v0_View=sim.floatingViewAdd(0.9,0.9,0.2,0.2,0) zed_v1_View=sim.floatingViewAdd(0.7,0.9,0.2,0.2,0) sim.adjustView(zed_v0_View,zed_vision0,64) sim.adjustView(zed_v1_View,zed_vision1,64) end_vector = {0,0,0.14} t_sim_start = sim.getSimulationTime() grapped = false speed = -1 -- m/s hold_time = 0.5 -- s distance_hold = 0.11 start_position = sim.getObjectPosition(targetObj, -1) ----- the commented part is the decision logic to grap a 'Sphere' --hold_target_handle = sim.getObjectHandle('Sphere') --hold_target_position = sim.getObjectPosition(hold_target_handle, -1) targetPos=sim.getObjectPosition(targetObj,-1) end function sysCall_cleanup() sim.removeDrawingObject(shadowCont) sim.floatingViewRemove(zed_v0_View) sim.floatingViewRemove(zed_v1_View) end function sysCall_actuation() s=sim.getObjectSizeFactor(d) pos=sim.getObjectPosition(d,-1) target_pos = sim.getObjectPosition(targetObj, -1) -- z_distance = target_pos[3] - hold_target_position[3] -- print('z_distance', z_distance) -- if (math.abs(z_distance) < 0.21) then -- sim.setScriptSimulationParameter(hand_script_handle, 'close_hand', 'true') -- print('Closing hand') -- end -- print('simulation time', sim.getSimulationTime()) pos_z_delta = 0 -- if grapped == false then -- if (z_distance > distance_hold) then -- pos_z_delta = speed * sim.getSimulationTimeStep() -- hold_start_time = sim.getSimulationTime() -- print('start', pos_z_delta) -- elseif z_distance < distance_hold then -- hold for a while -- if (sim.getSimulationTime() - hold_start_time) > hold_time then -- grapped = true -- speed = 1 -- end -- end -- else -- end_delta = start_position[3] - target_pos[3] -- if (end_delta > 0.01) then -- pos_z_delta = speed * sim.getSimulationTimeStep() -- end -- end sim.setObjectPosition(targetObj, -1, {target_pos[1], target_pos[2], target_pos[3] + pos_z_delta}) if (fakeShadow) then itemData={pos[1],pos[2],0.002,0,0,1,0.2*s} sim.addDrawingObjectItem(shadowCont,itemData) end ------------------ Controller ------------------------------------- -- Vertical control: -- landing down: if(targetPos[3]>1)then targetPos[3] = targetPos[3] - 0.01 end pos=sim.getObjectPosition(d,-1) l=sim.getVelocity(heli) e_z=(targetPos[3]-pos[3]) cumul=cumul+e_z thrust=9+pParam*e_z+iParam*cumul+dParam*(e_z-lastE)+l[3]*vParam lastE=e_z -- Rotational control: euler=sim.getObjectOrientation(d,targetObj) linearSpeed, angularSpeed=sim.getObjectVelocity(d) alphaCorr=0 maxCorr=maxCorr-0.02 if(maxCorr < 0) then maxCorr = 0.2 ------------------ Visual ------------------------------------- imageBuffer = sim.getVisionSensorImage(zed_vision0) print(#imageBuffer) maxx=0 minx=100000 maxy=0 miny=100000 maxd=0 xlen = 1280 ylen = 2160 ylock = 0 out = {} for i=1,xlen,2 do maxy2=0 miny2=100000 for j=100,ylen-100,30 do if (imageBuffer[i*ylen+j]>0.9 and imageBuffer[i*ylen+j+1]>0.9 and imageBuffer[i*ylen+j+2]>0.9) then maxx=math.max(maxx,i) minx=math.min(minx,i) maxy2=math.max(maxy2,j) miny2=math.min(miny2,j) end end if(maxy2 - miny2 < 10000 and maxy2 - miny2 > maxd) then maxd = maxy2 - miny2; maxy = maxy2; miny = miny2; end end print(maxx,minx,maxy,miny); if(minx < 10000)then deltax = (maxx + minx)/2/xlen-0.5; end if(miny < 10000) then deltay = (maxy + miny)/2/ylen-0.5; end print(deltax,deltay); end deltax = 1 if(maxCorr > 0.15) then deltaSpeed = 0.1*deltax elseif(maxCorr > 0.05) then deltaSpeed = 0 elseif(maxCorr > 0) then deltaSpeed = -0.1*deltax else deltaSpeed = 0 end print(deltaSpeed) alphaCumul = alphaCumul + euler[1] + deltaSpeed alphaCorr=0.00323 + euler[1]*0.225 + 1.4*(euler[1]-pAlphaE)-- + 0.005 * alphaCumul pAlphaE=euler[1] + deltaSpeed betaCumul = betaCumul + euler[2] betaCorr=euler[2]*0.225 + 1.4*(euler[2]-pBetaE)-- + 0.001 * betaCumul pBetaE=euler[2] rotCorrCumul = rotCorrCumul + euler[3] rotCorr=euler[3]*4 + 1*(euler[3]-prevEuler) + 0.001 * rotCorrCumul prevEuler=euler[3] -- Decide of the motor velocities: particlesTargetVelocities[1]=thrust*(1-alphaCorr+betaCorr+rotCorr) particlesTargetVelocities[2]=thrust*(1-alphaCorr-betaCorr-rotCorr) particlesTargetVelocities[3]=thrust*(1+alphaCorr-betaCorr+rotCorr) particlesTargetVelocities[4]=thrust*(1+alphaCorr+betaCorr-rotCorr) -- Send the desired motor velocities to the 4 rotors: for i=1,4,1 do sim.setScriptSimulationParameter(propellerScripts[i],'particleVelocity',particlesTargetVelocities[i]) end end --- FILE SEPARATOR --- import numpy as np import vrep for i in range(50): try: # close any open connections vrep.simxFinish(-1) # Connect to the V-REP continuous server clientID = vrep.simxStart('127.0.0.1', 19997, True, True, 500, 5) if clientID != -1: # if we connected successfully print ('Connected to remote API server') # --------------------- Setup the simulation vrep.simxSynchronous(clientID,True) dt = .025 vrep.simxSetFloatingParameter(clientID, vrep.sim_floatparam_simulation_time_step, dt, # specify a simulation time step vrep.simx_opmode_oneshot) # start our simulation in lockstep with our code vrep.simxStartSimulation(clientID, vrep.simx_opmode_blocking) count = 0 track_hand = [] track_target = [] while count < 60: # run for 1 simulated second # move simulation ahead one time step vrep.simxSynchronousTrigger(clientID) count += dt # stop the simulation vrep.simxStopSimulation(clientID, vrep.simx_opmode_blocking) # Before closing the connection to V-REP, #make sure that the last command sent out had time to arrive. vrep.simxGetPingTime(clientID) # Now close the connection to V-REP: vrep.simxFinish(clientID) else: raise Exception('Failed connecting to remote API server') finally: # stop the simulation vrep.simxStopSimulation(clientID, vrep.simx_opmode_blocking) # Before closing the connection to V-REP, # make sure that the last command sent out had time to arrive. vrep.simxGetPingTime(clientID) # Now close the connection to V-REP: vrep.simxFinish(clientID) print('connection closed...')
[ "/entity.py", "/mission_path_planning_main.py", "/old_code/5有视觉横向调试.py", "/repeat.py" ]
000Justin000/agnav
import os import sys import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import math, copy, time import pandas as pd from transformers import AutoTokenizer import matplotlib.pyplot as plt from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from utils import * from IPython.core.debugger import set_trace os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' # we will use CUDA if it is available USE_CUDA = torch.cuda.is_available() DEVICE = torch.device('cuda:0') if USE_CUDA else torch.device("cpu") # set random seed seed = 666 np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) class EncoderDecoder(nn.Module): """ A standard Encoder-Decoder architecture. Base for this and many other models. """ def __init__(self, encoder, decoder, src_embed, trg_embed, evaluator): super(EncoderDecoder, self).__init__() self.encoder = encoder self.decoder = decoder self.src_embed = src_embed self.trg_embed = trg_embed self.evaluator = evaluator def forward(self, src, trg, src_mask, trg_mask, src_lengths, trg_lengths): """Take in and process masked src and target sequences.""" encoder_hidden, encoder_final = self.encode(src, src_mask, src_lengths) return self.decode(encoder_hidden, encoder_final, src_mask, trg, trg_mask) def encode(self, src, src_mask, src_lengths): return self.encoder(self.src_embed(src), src_mask, src_lengths) def decode(self, encoder_hidden, encoder_final, src_mask, trg, trg_mask, decoder_hidden=None): return self.decoder(self.trg_embed(trg), encoder_hidden, encoder_final, src_mask, trg_mask, hidden=decoder_hidden) class Encoder(nn.Module): """Encodes a sequence of word embeddings""" def __init__(self, input_size, hidden_size, num_layers=1, dropout=0.0): super(Encoder, self).__init__() self.num_layers = num_layers self.rnn = nn.GRU(input_size, hidden_size, num_layers, batch_first=True, bidirectional=True, dropout=dropout) def forward(self, x, mask, lengths): """ Applies a bidirectional GRU to sequence of embeddings x. The input mini-batch x needs to be sorted by length. x should have dimensions [batch, time, dim]. """ packed = pack_padded_sequence(x, lengths, batch_first=True) output, final = self.rnn(packed) output, _ = pad_packed_sequence(output, batch_first=True) # we need to manually concatenate the final states for both directions fwd_final = final[0:final.size(0):2] bwd_final = final[1:final.size(0):2] final = torch.cat([fwd_final, bwd_final], dim=2) # [num_layers, batch, 2*dim] return output, final class Decoder(nn.Module): """A conditional RNN decoder with attention.""" def __init__(self, emb_size, hidden_size, attention, num_layers=1, dropout=0.0, bridge=True): super(Decoder, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.attention = attention self.dropout = dropout self.rnn = nn.GRU(emb_size+2*hidden_size, hidden_size, num_layers, batch_first=True, dropout=dropout) # to initialize from the final encoder state self.bridge = nn.Linear(2*hidden_size, hidden_size, bias=True) if bridge else None self.dropout_layer = nn.Dropout(p=dropout) self.pre_output_layer = nn.Linear(hidden_size + 2*hidden_size + emb_size, hidden_size, bias=False) def forward_step(self, prev_embed, encoder_hidden, src_mask, proj_key, hidden): """Perform a single decoder step (1 word)""" # compute context vector using attention mechanism query = hidden[-1].unsqueeze(1) # [#layers, B, D] -> [B, 1, D] context, attn_probs = self.attention(query=query, proj_key=proj_key, value=encoder_hidden, mask=src_mask) # update rnn hidden state rnn_input = torch.cat([prev_embed, context], dim=2) output, hidden = self.rnn(rnn_input, hidden) pre_output = torch.cat([prev_embed, output, context], dim=2) pre_output = self.dropout_layer(pre_output) pre_output = self.pre_output_layer(pre_output) return output, hidden, pre_output, attn_probs def forward(self, trg_embed, encoder_hidden, encoder_final, src_mask, trg_mask, hidden=None, max_len=None): """Unroll the decoder one step at a time.""" # the maximum number of steps to unroll the RNN if max_len is None: max_len = trg_mask.size(-1) # initialize decoder hidden state if hidden is None: hidden = self.init_hidden(encoder_final) # pre-compute projected encoder hidden states # (the "keys" for the attention mechanism) # this is only done for efficiency proj_key = self.attention.key_layer(encoder_hidden) # here we store all intermediate hidden states and pre-output vectors decoder_states = [] pre_output_vectors = [] attn_probs_history = [] # unroll the decoder RNN for max_len steps for i in range(max_len): prev_embed = trg_embed[:, i].unsqueeze(1) output, hidden, pre_output, attn_probs = self.forward_step(prev_embed, encoder_hidden, src_mask, proj_key, hidden) decoder_states.append(output) pre_output_vectors.append(pre_output) attn_probs_history.append(attn_probs) decoder_states = torch.cat(decoder_states, dim=1) pre_output_vectors = torch.cat(pre_output_vectors, dim=1) return decoder_states, hidden, pre_output_vectors, attn_probs_history # [B, N, D] def init_hidden(self, encoder_final): """Returns the initial decoder state, conditioned on the final encoder state.""" if encoder_final is None: return None # start with zeros return torch.tanh(self.bridge(encoder_final)) class BahdanauAttention(nn.Module): """Implements Bahdanau (MLP) attention""" def __init__(self, hidden_size, key_size=None, query_size=None): super(BahdanauAttention, self).__init__() # We assume a bi-directional encoder so key_size is 2*hidden_size key_size = 2*hidden_size if key_size is None else key_size query_size = hidden_size if query_size is None else query_size self.key_layer = nn.Linear(key_size, hidden_size, bias=False) self.query_layer = nn.Linear(query_size, hidden_size, bias=False) self.energy_layer = nn.Linear(hidden_size, 1, bias=False) # to store attention scores self.alphas = None def forward(self, query=None, proj_key=None, value=None, mask=None): assert mask is not None, "mask is required" # We first project the query (the decoder state). # The projected keys (the encoder states) were already pre-computated. query = self.query_layer(query) # Calculate scores. scores = self.energy_layer(torch.tanh(query + proj_key)) scores = scores.squeeze(2).unsqueeze(1) # Mask out invalid positions. # The mask marks valid positions so we invert it using `mask & 0`. scores.data.masked_fill_(mask == 0, -float('inf')) # Turn scores to probabilities. alphas = F.softmax(scores, dim=-1) self.alphas = alphas # The context vector is the weighted sum of the values. context = torch.bmm(alphas, value) # context shape: [B, 1, 2D], alphas shape: [B, 1, M] return context, alphas class Evaluator(nn.Module): """Define standard linear action value function.""" def __init__(self, hidden_size, vocab_size): super(Evaluator, self).__init__() self.proj = nn.Linear(hidden_size, vocab_size, bias=False) def forward(self, x): return self.proj(x) def make_model(src_vocab, tgt_vocab, emb_size=256, hidden_size=512, num_layers=1, dropout=0.0): "Helper: Construct a model from hyperparameters." attention = BahdanauAttention(hidden_size) model = EncoderDecoder( Encoder(emb_size, hidden_size, num_layers=num_layers, dropout=dropout), Decoder(emb_size, hidden_size, attention, num_layers=num_layers, dropout=dropout), nn.Embedding(src_vocab, emb_size), nn.Embedding(tgt_vocab, emb_size), Evaluator(hidden_size, tgt_vocab)) return model class Batch: """Object for holding a batch of data with mask during training. Input is a batch from a torch text iterator. """ def __init__(self, src, trg, pad_index=0): src, src_lengths = src self.src = src self.src_lengths = src_lengths self.src_mask = (src != pad_index).unsqueeze(-2) self.nseqs = src.size(0) trg, trg_lengths = trg self.trg = trg self.trg_lengths = trg_lengths self.trg_mask = (self.trg != pad_index) self.ntokens = self.trg_mask.data.sum().item() def simulate_episode(G, qa_instance, tokenizer, model, action_to_ix, max_len, epsilon, verbose=False): question, decorated_entity, answer_set = qa_instance tokenized_inputs = tokenizer(question, max_length=50, padding=True, truncation=True, return_tensors="pt") src, src_mask = tokenized_inputs["input_ids"].to(DEVICE), tokenized_inputs["attention_mask"].unsqueeze(-2).to(DEVICE) assert decorated_entity in G.nodes kgnode = decorated_entity if verbose: print(question) print(kgnode) kgnode_chain = [] action_chain = [] reward_chain = [] encoder_hidden, encoder_final = model.encode(src, src_mask, [src_mask.sum().item()]) # pre-compute projected encoder hidden states # (the "keys" for the attention mechanism) # this is only done for efficiency proj_key = model.decoder.attention.key_layer(encoder_hidden) # initialize decoder hidden state hidden_init = model.decoder.init_hidden(encoder_final) sos_embed = model.trg_embed(torch.tensor([action_to_ix["[SOS]"]], device=DEVICE)).unsqueeze(1) _, hidden, context, _ = model.decoder.forward_step(sos_embed, encoder_hidden, src_mask, proj_key, hidden_init) for t in range(max_len): # compute the action value functions for available actions at the current node actions = unique([info["type"] for (_, _, info) in G.edges(kgnode, data=True)]) + ["terminate"] values = model.evaluator(context)[0, 0, [action_to_ix[action] for action in actions]] # select the action at the current time step with epsilon-greedy policy if random.random() < epsilon: action = random.choice(actions) else: action = actions[values.argmax()] # take the action if (action == "terminate") or (t == max_len-1): reward = torch.tensor(1.0 if ((action == "terminate") and (re.match(r".+: (.+)", kgnode).group(1) in answer_set)) else 0.0).to(DEVICE) kgnode_next = "termination" hidden_next = None context_next = None else: reward = torch.tensor(0.0).to(DEVICE) kgnode_next = random.choice(list(filter(lambda tp: tp[2]["type"] == action, G.edges(kgnode, data=True))))[1] action_embed = model.trg_embed(torch.tensor([action_to_ix[action]], device=DEVICE)).unsqueeze(1) _, hidden_next, context_next, _ = model.decoder.forward_step(action_embed, encoder_hidden, src_mask, proj_key, hidden) kgnode_chain.append(kgnode) action_chain.append(action) reward_chain.append(reward) if verbose: print(actions) print(values.data.reshape(-1).to("cpu")) print(action, " =====> ", kgnode_next) if kgnode_next == "termination": break else: kgnode = kgnode_next hidden = hidden_next context = context_next return kgnode_chain, action_chain, reward_chain def make_batch(episodes, tokenizer, action_to_ix, pad_index=0, sos_index=1): episodes = sorted(episodes, key=lambda x: (-len(tokenizer.tokenize(x.qa_instance.question)), -len(x.action_chain))) inputs = tokenizer(list(map(lambda x: x.qa_instance.question, episodes)), max_length=50, padding=True, truncation=True, return_tensors="pt", return_length=True) src = inputs["input_ids"].to(DEVICE) src_lengths = inputs["length"] max_len = max(len(x.action_chain) for x in episodes) trg = torch.cat(tuple(map(lambda x: torch.tensor([[sos_index] + [action_to_ix[action] for action in x.action_chain] + [pad_index]*(max_len-len(x.action_chain))], device=DEVICE), episodes)), dim=0) trg_lengths = list(map(lambda x: len(x.action_chain)+1, episodes)) kgnode_chains = [episode.kgnode_chain for episode in episodes] action_chains = [episode.action_chain for episode in episodes] reward_chains = [episode.reward_chain for episode in episodes] return Batch((src, src_lengths), (trg, trg_lengths), pad_index=pad_index), kgnode_chains, action_chains, reward_chains def compute_loss(episodes, tokenizer, model, action_to_ix, verbose=False): batch, kgnode_chains, action_chains, reward_chains = make_batch(episodes, tokenizer, action_to_ix) _, _, pre_output, _ = model.forward(batch.src, batch.trg, batch.src_mask, batch.trg_mask, batch.src_lengths, batch.trg_lengths) batch_values = model.evaluator(pre_output) losses = [] for (i, (kgnode_chain, action_chain, reward_chain)) in enumerate(zip(kgnode_chains, action_chains, reward_chains)): for t in range(len(kgnode_chain)): kgnode, action, reward = kgnode_chain[t], action_chain[t], reward_chain[t] if t != len(kgnode_chain)-1: kgnode_next = kgnode_chain[t+1] actions_next = unique([info["type"] for (_, _, info) in G.edges(kgnode_next, data=True)]) + ["terminate"] values_next = batch_values[i, t+1, [action_to_ix[action] for action in actions_next]] reference = reward + gamma*values_next.max().item() else: reference = reward losses.append(loss_func(batch_values[i, t, action_to_ix[action]], reference)) if verbose: print(" {:100s} {:30s} {:7.4f} {:7.4f}".format(kgnode, action, batch_values[i, t, action_to_ix[action]].data.to("cpu").item(), reference.to("cpu").item())) return sum(losses) / len(losses) def evaluate_accuracy(G, qa_instances, tokenizer, model, action_to_ix, max_len, verbose=False): num_success = 0 for qa_instance in qa_instances: with torch.no_grad(): _, _, reward_chain = simulate_episode(G, qa_instance, tokenizer, model, action_to_ix, max_len, 0.0, verbose) if verbose: print("\noutcome: {:s}\n".format("success" if (reward_chain[-1] == 1.0) else "failure")) num_success += 1 if (reward_chain[-1] == 1.0) else 0 return num_success / len(qa_instances) if __name__ == "__main__": emb_size = 256 hidden_size = 512 num_layers = 1 max_len = 4 gamma = 0.90 kappa = 0.20 epsilon_start = 1.00 epsilon_end = 0.10 decay_rate = 5.00 M = 3000000 batch_size = 32 experiment = "e{:03d}_h{:03d}_l{:02d}_g{:03d}_k{:03d}_m{:07d}".format(emb_size, hidden_size, num_layers, int(gamma*100), int(kappa*100), M) os.makedirs("checkpoints/{:s}".format(experiment), exist_ok=True) sys.stderr = sys.stdout = open("logs/{:s}".format(experiment), "w") entity_token = "[ETY]" tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased", additional_special_tokens=[entity_token]) G = read_MetaQA_KG() qa_train_1h, qa_dev_1h, qa_test_1h = read_MetaQA_Instances("1-hop", entity_token, DEVICE) qa_train_2h, qa_dev_2h, qa_test_2h = read_MetaQA_Instances("2-hop", entity_token, DEVICE) qa_train_3h, qa_dev_3h, qa_test_3h = read_MetaQA_Instances("3-hop", entity_token, DEVICE) qa_train = pd.concat([qa_train_1h, qa_train_2h, qa_train_3h]) qa_dev = pd.concat([ qa_dev_1h, qa_dev_2h, qa_dev_3h]) qa_test = pd.concat([ qa_test_1h, qa_test_2h, qa_test_3h]) possible_actions = ["[PAD]", "[SOS]"] + sorted(list(set([edge[2]["type"] for edge in G.edges(data=True)]))) + ["terminate"] action_to_ix = dict(map(reversed, enumerate(possible_actions))) model = make_model(len(tokenizer), len(possible_actions), emb_size=emb_size, hidden_size=hidden_size, num_layers=num_layers, dropout=0.2).to(DEVICE) loss_func = nn.MSELoss() optimizer = optim.AdamW(model.parameters(), lr=3.0e-4, betas=(0.9, 0.999), weight_decay=2.5e-4) memory_overall = ReplayMemory(1000) memory_success = ReplayMemory(1000) memory_failure = ReplayMemory(1000) for m in range(M): epsilon = epsilon_end + (epsilon_start - epsilon_end) * math.exp(-decay_rate * (m / M)) print("epsilon: {:5.3f}".format(epsilon)) if (len(memory_failure) > 0) and (random.random() < kappa): qa_instance = memory_failure.sample_random(1)[0].qa_instance else: qa_instance = qa_train.sample(1).values[0] with torch.no_grad(): kgnode_chain, action_chain, reward_chain = simulate_episode(G, qa_instance, tokenizer, model, action_to_ix, max_len, epsilon, verbose=True) print("\noutcome: {:s}\n".format("success" if (reward_chain[-1] == 1.0) else "failure")) if reward_chain[-1] == 1.0: memory_overall.push(Episode(qa_instance, kgnode_chain, action_chain, reward_chain)) memory_success.push(Episode(qa_instance, kgnode_chain, action_chain, reward_chain)) else: memory_overall.push(Episode(qa_instance, kgnode_chain, action_chain, reward_chain)) memory_failure.push(Episode(qa_instance, kgnode_chain, action_chain, reward_chain)) # optimize model episodes = memory_overall.sample_random(batch_size) loss = compute_loss(episodes, tokenizer, model, action_to_ix, verbose=True) optimizer.zero_grad() loss.backward() optimizer.step() print("\n") if (m+1) % 100000 == 0: model.train(False) print(" training accuracies for 1-hop, 2-hop, 3-hop questions are {:7.4f}, {:7.4f}, {:7.4f}".format(evaluate_accuracy(G, qa_train_1h, tokenizer, model, action_to_ix, max_len), evaluate_accuracy(G, qa_train_2h, tokenizer, model, action_to_ix, max_len), evaluate_accuracy(G, qa_train_3h, tokenizer, model, action_to_ix, max_len))) print("validation accuracies for 1-hop, 2-hop, 3-hop questions are {:7.4f}, {:7.4f}, {:7.4f}".format(evaluate_accuracy(G, qa_dev_1h, tokenizer, model, action_to_ix, max_len), evaluate_accuracy(G, qa_dev_2h, tokenizer, model, action_to_ix, max_len), evaluate_accuracy(G, qa_dev_3h, tokenizer, model, action_to_ix, max_len))) model.train(True) print("\n\n") torch.save({"model": model.state_dict()}, "checkpoints/{:s}/save@{:07d}.pt".format(experiment, m+1)) model.train(False) print(" testing accuracies for 1-hop, 2-hop, 3-hop questions are {:7.4f}, {:7.4f}, {:7.4f}".format(evaluate_accuracy(G, qa_test_1h, tokenizer, model, action_to_ix, max_len, True), evaluate_accuracy(G, qa_test_2h, tokenizer, model, action_to_ix, max_len, True), evaluate_accuracy(G, qa_test_3h, tokenizer, model, action_to_ix, max_len, True))) model.train(True) --- FILE SEPARATOR --- import os import torch from transformers import GPT2Tokenizer, GPT2Model os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' # tokenizer.tokenize # tokenize.encode # tokenize.forward tokenizer = GPT2Tokenizer.from_pretrained('gpt2', pad_token="[PAD]", additional_special_tokens=["[OBJ]"]) model = GPT2Model.from_pretrained('gpt2') embedding_layer = model.resize_token_embeddings(len(tokenizer)) # Update the model embeddings with the new vocabulary size inputs = tokenizer("who is the writer for [OBJ]", max_length=50, padding="max_length", truncation=True, return_tensors='pt') outputs = model(input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"]) from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased", additional_special_tokens=["[OBJ]"]) inputs = tokenizer("who is the writer for [OBJ]", max_length=10, padding="max_length", truncation=True, return_tensors='pt') --- FILE SEPARATOR --- import networkx as nx import pandas as pd import random import re import torch from collections import namedtuple from transformers import AutoTokenizer QAInstance = namedtuple("QAInstance", ["question", "decorated_entity", "answer_set"]) Episode = namedtuple("Episode", ["qa_instance", "kgnode_chain", "action_chain", "reward_chain"]) class ReplayMemory: def __init__(self, capacity): self.capacity = capacity self.memory = [] self.position = 0 def push(self, episode): if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = episode self.position = (self.position + 1) % self.capacity def sample_random(self, batch_size): batch = random.choices(self.memory, k=batch_size) return batch def sample_last(self, batch_size): pointer = self.position batch = [] for _ in range(batch_size): pointer = (pointer - 1 + len(self.memory)) % len(self.memory) batch.append(self.memory[pointer]) return batch def __len__(self): return len(self.memory) def unique(items): return sorted(list(set(items))) def read_MetaQA_KG(): def edge_to_prefix(edge): if edge == "directed_by": return "director: " elif edge == "written_by": return "writer: " elif edge == "starred_actors": return "actor: " elif edge == "release_year": return "year: " elif edge == "in_language": return "language: " elif edge == "has_tags": return "tag: " elif edge == "has_genre": return "genre: " elif edge == "has_imdb_votes": return "votes: " elif edge == "has_imdb_rating": return "rating: " else: raise Exception("unexpected edge type \"" + edge + "\"") df = pd.read_csv("datasets/MetaQA/kb.txt", delimiter='|', names=["head", "edge", "tail"]) decorated_heads = "movie: " + df["head"] decorated_tails = df["edge"].apply(edge_to_prefix) + df["tail"] fwd_edges = "fwd_"+df["edge"] rvs_edges = "rvs_"+df["edge"] G = nx.MultiDiGraph() G.add_nodes_from(zip(decorated_heads.unique(), [{"type": decorated_head.split(':')[0]} for decorated_head in decorated_heads.unique()])) G.add_nodes_from(zip(decorated_tails.unique(), [{"type": decorated_tail.split(':')[0]} for decorated_tail in decorated_tails.unique()])) G.add_edges_from(zip(decorated_heads, decorated_tails, [{"type": fwd_edge} for fwd_edge in fwd_edges])) G.add_edges_from(zip(decorated_tails, decorated_heads, [{"type": rvs_edge} for rvs_edge in rvs_edges])) return G def read_MetaQA_Instances(question_type="1-hop", entity_token="[ETY]", device="cpu"): def process_question(question): processed_question = re.sub(r"(\[.+\])", entity_token, question) entity = re.search(r"\[(.+)\]", question).group(1) return processed_question, entity def process_answers(answers): return set(answers.split('|')) def info_to_instance(info): processed_question, entity = process_question(info["question"]) decorated_entity = info["question_type"].split('_')[0] + ": " + entity answer_set = process_answers(info["answers"]) return QAInstance(processed_question, decorated_entity, answer_set) qa_text_train = pd.read_csv("datasets/MetaQA/"+question_type+"/vanilla/qa_train.txt", delimiter='\t', names=["question", "answers"]) qa_qtype_train = pd.read_csv("datasets/MetaQA/"+question_type+"/qa_train_qtype.txt", names=["question_type"]) qa_info_train = pd.concat([qa_text_train, qa_qtype_train], axis=1) qa_instance_train = qa_info_train.apply(info_to_instance, axis=1) qa_text_dev = pd.read_csv("datasets/MetaQA/"+question_type+"/vanilla/qa_dev.txt", delimiter='\t', names=["question", "answers"]) qa_qtype_dev = pd.read_csv("datasets/MetaQA/"+question_type+"/qa_dev_qtype.txt", names=["question_type"]) qa_info_dev = pd.concat([qa_text_dev, qa_qtype_dev], axis=1) qa_instance_dev = qa_info_dev.apply(info_to_instance, axis=1) qa_text_test = pd.read_csv("datasets/MetaQA/"+question_type+"/vanilla/qa_test.txt", delimiter='\t', names=["question", "answers"]) qa_qtype_test = pd.read_csv("datasets/MetaQA/"+question_type+"/qa_test_qtype.txt", names=["question_type"]) qa_info_test = pd.concat([qa_text_test, qa_qtype_test], axis=1) qa_instance_test = qa_info_test.apply(info_to_instance, axis=1) return qa_instance_train, qa_instance_dev, qa_instance_test
[ "/main.py", "/playground.py", "/utils.py" ]
007Saikat/idil_demo
from django import forms from django.contrib.auth.models import User from .models import UserDetail class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password*','class':"form-control"})) username=forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter username*','class':"form-control"})) first_name = forms.CharField(max_length=75, required=True,widget= forms.TextInput(attrs={'placeholder':'Enter your first name*','class': "form-control"})) last_name=forms.CharField(max_length=75,required=False,widget= forms.TextInput(attrs={'placeholder':'Enter your Last name','class': "form-control"})) email = forms.CharField(max_length=75, required=True,widget= forms.TextInput(attrs={'placeholder':'Enter email address*','class': "form-control"})) class Meta(): model=User fields=('username','first_name','last_name','email','password') class UserDetailForm(forms.ModelForm): profile_pic=forms.ImageField(required=False) class Meta(): model=UserDetail fields=('profile_pic',) --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-17 18:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basic_app', '0002_auto_20200817_1353'), ] operations = [ migrations.AlterField( model_name='userdetail', name='role', field=models.CharField(blank=True, default='employee', max_length=100, null=True), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-19 16:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basic_app', '0005_auto_20200819_2116'), ] operations = [ migrations.AlterField( model_name='userdetail', name='role', field=models.CharField(choices=[('A', 'admin'), ('E', 'employee')], default='E', max_length=128), ), ] --- FILE SEPARATOR --- from django.db import models from django.contrib.auth.models import User import os from uuid import uuid4 def path_and_rename(instance, filename): upload_to = 'profile_pics' ext = filename.split('.')[-1] # get filename if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: # set filename as random string filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return os.path.join(upload_to, filename) # Create your models here. class UserDetail(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) role=models.CharField(max_length=128,default='employee') profile_pic=models.ImageField(upload_to=path_and_rename,blank=True,null=True) last_login = models.DateTimeField(blank=True,null=True) def __str__(self): return self.user.username --- FILE SEPARATOR --- from django.urls import path,include from basic_app import views app_name='basic_app' urlpatterns = [ path('',views.login_register,name='login_register'), path('index/',views.index,name='index'), path('manage_acc/<username>',views.acc,name='acc'), path('upload/<username>',views.upload,name='upload'), path('save/<username>',views.save,name='save'), path('change/<username>',views.change,name='change'), path('update/<username>',views.update,name='update'), path('show/<username>',views.show,name='show'), path('apply/<username>',views.apply,name='apply'), path('logout',views.user_logout,name='user_logout'), ] --- FILE SEPARATOR --- from django.shortcuts import render,redirect from .forms import UserForm,UserDetailForm from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import login from django.utils import timezone from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,login,logout from django.urls import reverse from .models import User,UserDetail from user_admin.models import UserAdmin,Challenges,AppliedChallenges from idil import settings import os import cv2 # Create your views here. @login_required def home(request,username): context={} print(username+'sjh') user_list=User.objects.all() challenges=Challenges.objects.all() ac=AppliedChallenges.objects.all() context['challenges']=challenges appl=True p=0 for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info users=UserDetail.objects.all() for user2 in users: if str(user2)==str(username): context['usd']=user2 for c in challenges: for a in ac: if str(a.challenge)==str(c.name) and str(a.user)==str(context['usr']): p=a.points appl=False break context['a']=appl context['p']=p return render(request,'basic_app/home.html',context) @login_required def acc(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_detail_list=UserDetail.objects.all() for user2 in user_detail_list: if str(user2)==str(username): context['usd']=user2 return render(request,'basic_app/acc.html',context) @login_required def upload(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_details_list=UserDetail.objects.all() for user2 in user_details_list: if str(user2)==str(username): context['usd']=user2 if request.method=="POST": if len(request.FILES)!=0: img = request.FILES['pic'] img_extension = os.path.splitext(img.name)[1] s=settings.MEDIA_ROOT s=os.path.join(s, 'profile_pics') if context['usd'].profile_pic: c=str(context['usd'].profile_pic).split("/")[1] k=os.path.join(s,c) print("ghxc") if os.path.exists(k): os.remove(k) context['usd'].profile_pic=request.FILES['pic'] context['usd'].save() return render(request,'basic_app/acc.html',context) else: print("Image not there") context['usd'].profile_pic=request.FILES['pic'] context['usd'].save() return render(request,'basic_app/acc.html',context) @login_required def save(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_detail_list=UserDetail.objects.all() for user2 in user_detail_list: if str(user2)==str(username): context['usd']=user2 if request.method=="POST": context['usr'].email=request.POST.get('email') context['usr'].save() return render(request,'basic_app/acc.html',context) @login_required def update(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_detail_list=UserDetail.objects.all() for user2 in user_detail_list: if str(user2)==str(username): context['usd']=user2 if request.method=="POST": context['usr'].first_name=request.POST.get('fn') context['usr'].last_name=request.POST.get('ln') context['usr'].save() return render(request,'basic_app/acc.html',context) @login_required def change(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_detail_list=UserDetail.objects.all() for user2 in user_detail_list: if str(user2)==str(username): context['usd']=user2 if request.method=="POST": user1=authenticate(username=username,password=request.POST.get('op')) if user1==None: context['er']=True else: if request.POST.get('op')==request.POST.get('np'): context['dm']=True else: context['usr'].set_password(request.POST.get('np')) context['usr'].save() return render(request,'basic_app/acc.html',context) @login_required def user_logout(request): #request.session.flush() logout(request) return redirect('/') def index(request): context={} context['name']='Saikat' # user_form=UserForm(data=request.POST) # user_detail_form=UserDetailForm(data=request.POST) # context['user_form']=user_form # context['user_detail_form']=user_detail_form return render(request,'basic_app/index.html',context) def login_register(request): show_div=False print(request.method) if request.GET.get('login'): show_div=False elif request.GET.get('reg'): show_div=True context={} context['error']=False user_form=UserForm(data=request.POST) user_detail_form=UserDetailForm(data=request.POST) user_detail1=UserDetail if request.method == "POST" and show_div: print(user_form.is_valid()) print(user_detail_form.is_valid()) if user_form.is_valid() and user_detail_form.is_valid(): user = user_form.save(commit=False) user.set_password(user.password) user_detail=user_detail_form.save(commit=False) user_detail.user=user if len(request.FILES)!=0: p=request.FILES['profile_pic'] p=str(p) print(p) if p.endswith('.jpg') or p.endswith('.jpeg') or p.endswith('.png'): user_detail.profile_pic=request.FILES['profile_pic'] user.save() user_detail.save() request.session['username']=user.username login(request,user) return redirect('/basic_app/home') else: context['show_div']=True context['user_form']=user_form context['user_detail_form']=user_detail_form context['warning']=True return render(request,'basic_app/login.html',context) else: user.save() user_detail.save() request.session['username']=user.username login(request,user) return redirect('/basic_app/home') elif request.method == "POST" and not show_div: username=request.POST.get('username') password=request.POST.get('password') user1=authenticate(username=username,password=password) if user1!=None: user_detail_list=UserDetail.objects.all() ef=False for user2 in user_detail_list: if str(user2)==str(user1): ef=True break user_admin_list=UserAdmin.objects.all() af=False for user2 in user_admin_list: if str(user2)==str(user1): print(user2) af=True break request.session['username']=user1.username if af: u=str(user1) url = reverse('admin', kwargs={'username': u}) print(url) login(request,user1) return HttpResponseRedirect(url) elif ef: u=str(user1) url = reverse('user', kwargs={'username': u}) login(request,user1) return HttpResponseRedirect(url) else: context['error']=True context['user_form']=user_form context['user_detail_form']=user_detail_form context['show_div']=show_div return render(request,'basic_app/login.html',context) @login_required def show(request,username): c_name=username.split('_')[1] print(c_name) username=username.split("_")[0] challenges=Challenges.objects.all() ac=AppliedChallenges.objects.all() appl=True context={} for c in challenges: if str(c)==c_name: context['ch']=c user_list=User.objects.all() for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_detail_list=UserDetail.objects.all() for user2 in user_detail_list: if str(user2)==str(username): context['usd']=user2 for a in ac: if str(a.challenge)==str(context['ch']) and str(a.user)==str(context['usr']): appl=False break context['a']=appl return render(request,'basic_app/show.html',context) @login_required def apply(request,username): print(username) u=username.split("_")[0] c=username.split("_")[1] a=AppliedChallenges() n=0 challenges=Challenges.objects.all() for ca in challenges: if str(ca.name)==c: n=ca.applicant break n=n+1 l=AppliedChallenges.objects.filter(user=u).filter(challenge=c) if(len(l)==0): Challenges.objects.filter(pk=c).update(applicant=n) a.user=u a.challenge=c a.save() url = reverse('user', kwargs={'username': u}) return HttpResponseRedirect(url) --- FILE SEPARATOR --- from django.contrib import admin from .models import UserAdmin,Challenges # Register your models here. admin.site.register(UserAdmin) admin.site.register(Challenges) --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-19 18:28 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import user_admin.models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserAdmin', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('role', models.CharField(default='admin', max_length=128)), ('profile_pic', models.ImageField(blank=True, null=True, upload_to=user_admin.models.path_and_rename)), ('last_login', models.DateTimeField(blank=True, null=True)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-20 17:56 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0001_initial'), ] operations = [ migrations.CreateModel( name='Challenges', fields=[ ('name', models.CharField(max_length=255, primary_key=True, serialize=False)), ('technology', models.CharField(max_length=255)), ('account', models.CharField(max_length=255)), ('capability', models.CharField(max_length=255)), ('applicant_status', models.CharField(default='NOT FILLED', max_length=255)), ('date_posted', models.DateField(default=datetime.date.today)), ('expiry_date', models.DateField()), ('applicant', models.IntegerField(default=0)), ('manager', models.CharField(max_length=255)), ('owner', models.CharField(max_length=255)), ('desc', models.CharField(max_length=255)), ('points', models.IntegerField()), ('category', models.CharField(max_length=255)), ], ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-20 22:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0002_challenges'), ] operations = [ migrations.AlterField( model_name='challenges', name='applicant_status', field=models.CharField(blank=True, default='NOT_FILLED', max_length=255), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-20 22:45 from django.db import migrations, models import user_admin.models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0003_auto_20200821_0413'), ] operations = [ migrations.AlterField( model_name='challenges', name='applicant_status', field=models.CharField(default=user_admin.models.o, max_length=255), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-20 22:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0004_auto_20200821_0415'), ] operations = [ migrations.AlterField( model_name='challenges', name='applicant_status', field=models.CharField(default='0000000', editable=False, max_length=7), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-20 22:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('user_admin', '0005_auto_20200821_0418'), ] operations = [ migrations.RemoveField( model_name='challenges', name='applicant_status', ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-21 06:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0006_remove_challenges_applicant_status'), ] operations = [ migrations.AddField( model_name='challenges', name='applicant_status', field=models.CharField(default='NOT FILLED', max_length=255), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-23 08:06 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('user_admin', '0007_challenges_applicant_status'), ] operations = [ migrations.CreateModel( name='AppliedChallenges', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('completed', models.BooleanField(default=False)), ('points', models.IntegerField(default=0)), ('challenge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='user_admin.Challenges')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-23 08:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('user_admin', '0008_appliedchallenges'), ] operations = [ migrations.AlterField( model_name='appliedchallenges', name='challenge', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='user_admin.Challenges'), ), ] --- FILE SEPARATOR --- # Generated by Django 3.0.3 on 2020-08-23 08:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_admin', '0009_auto_20200823_1351'), ] operations = [ migrations.AlterField( model_name='appliedchallenges', name='challenge', field=models.CharField(max_length=255), ), migrations.AlterField( model_name='appliedchallenges', name='user', field=models.CharField(max_length=255), ), ] --- FILE SEPARATOR --- from django.db import models from django.contrib.auth.models import User import os from uuid import uuid4 import datetime def path_and_rename(instance, filename): upload_to = 'profile_pics' ext = filename.split('.')[-1] # get filename if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: # set filename as random string filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return os.path.join(upload_to, filename) # Create your models here. def o(): return "NOT FILLED" class UserAdmin(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) role=models.CharField(max_length=128,default='admin') profile_pic=models.ImageField(upload_to=path_and_rename,blank=True,null=True) last_login = models.DateTimeField(blank=True,null=True) def __str__(self): return self.user.username class Challenges(models.Model): name=models.CharField(primary_key=True,max_length=255) technology=models.CharField(max_length=255) account=models.CharField(max_length=255) capability=models.CharField(max_length=255) applicant_status=models.CharField(max_length=255,default="NOT FILLED") date_posted=models.DateField(default=datetime.date.today) expiry_date=models.DateField() applicant=models.IntegerField(default=0) manager=models.CharField(max_length=255) owner=models.CharField(max_length=255) desc=models.CharField(max_length=255) points=models.IntegerField() category=models.CharField(max_length=255) def __str__(self): return self.name class AppliedChallenges(models.Model): user=models.CharField(max_length=255) challenge=models.CharField(max_length=255) completed=models.BooleanField(default=False) points=models.IntegerField(default=0) def __str__(self): return self.user+'_'+self.challenge --- FILE SEPARATOR --- from django.urls import path,include from user_admin import views1 app_name='user_admin' urlpatterns = [ path('acc/<username>',views1.acc,name='acc'), path('upload/<username>',views1.upload,name='upload'), path('save/<username>',views1.save,name='save'), path('change/<username>',views1.change,name='change'), path('update/<username>',views1.update,name='update'), path('add/<username>',views1.add,name="add"), path('save_challenge/<username>',views1.save_challenge,name="save_challenge"), path('edit/<username>',views1.edit,name='edit'), path('show/<username>',views1.show,name='show'), path('delete/<username>',views1.delete,name='delete'), path('admin_logout/',views1.user_logout,name='admin_logout'), path('applicants/<username>',views1.applicants,name='applicants'), path('complete/<username>',views1.complete,name='complete') ] --- FILE SEPARATOR --- from django.shortcuts import render from django.shortcuts import render,redirect from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import login from django.utils import timezone from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,login,logout from django.urls import reverse from basic_app.models import User,UserDetail from user_admin.models import UserAdmin,Challenges,AppliedChallenges from idil import settings import os import cv2 # Create your views here. @login_required def index(request,username): context={} print(username+'sjh') user_list=User.objects.all() challenges=Challenges.objects.all() context['challenges']=challenges for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 return render(request,'user_admin/index.html',context) @login_required def acc(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 return render(request,'user_admin/acc.html',context) @login_required def upload(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": if len(request.FILES)!=0: img = request.FILES['pic'] img_extension = os.path.splitext(img.name)[1] s=settings.MEDIA_ROOT s=os.path.join(s, 'profile_pics') if context['uad'].profile_pic: c=str(context['uad'].profile_pic).split("/")[1] k=os.path.join(s,c) print("ghxc") if os.path.exists(k): os.remove(k) context['uad'].profile_pic=request.FILES['pic'] context['uad'].save() return render(request,'user_admin/acc.html',context) else: print("Image not there") context['uad'].profile_pic=request.FILES['pic'] context['uad'].save() return render(request,'user_admin/acc.html',context) @login_required def save(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": context['usr'].email=request.POST.get('email') context['usr'].save() return render(request,'user_admin/acc.html',context) @login_required def update(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": context['usr'].first_name=request.POST.get('fn') context['usr'].last_name=request.POST.get('ln') context['usr'].save() return render(request,'user_admin/acc.html',context) @login_required def change(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": user1=authenticate(username=username,password=request.POST.get('op')) if user1==None: context['er']=True else: if request.POST.get('op')==request.POST.get('np'): context['dm']=True else: context['usr'].set_password(request.POST.get('np')) context['usr'].save() return render(request,'user_admin/acc.html',context) @login_required def add(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 return render(request,'user_admin/add.html',context) @login_required def save_challenge(request,username): user_list=User.objects.all() context={} for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": challange=Challenges() challange.name=request.POST.get('cn') challange.technology=request.POST.get('tech') challange.account=request.POST.get('acc') challange.capability=request.POST.get('cap') challange.applicant_status=request.POST.get('astat') challange.expiry_date=request.POST.get('edate') challange.category=request.POST.get('cat') challange.manager=request.POST.get('manager') challange.owner=request.POST.get('powner') challange.points=request.POST.get('points') challange.desc=request.POST.get('desc') challange.applicant_status="NOT FILLED" challange.save() url = reverse('admin', kwargs={'username': username}) return HttpResponseRedirect(url) @login_required def edit(request,username): c_name=username.split('_')[1] username=username.split("_")[0] challenges=Challenges.objects.all() context={} k=Challenges() for c in challenges: if str(c)==c_name: context['ch']=c k=c user_list=User.objects.all() for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 if request.method=="POST": c = Challenges.objects.get(name=k.name) print("ed"+c.name) c.name=request.POST.get('cn') c.technology=request.POST.get('tech') c.account=request.POST.get('acc') c.capability=request.POST.get('cap') c.applicant_status=request.POST.get('astat') c.expiry_date=request.POST.get('edate') c.category=request.POST.get('cat') c.manager=request.POST.get('manager') c.owner=request.POST.get('powner') c.points=request.POST.get('points') c.desc=request.POST.get('desc') c.date_posted=k.date_posted c.applicant=request.POST.get('applicant') c.save() url = reverse('admin', kwargs={'username': username}) return HttpResponseRedirect(url) return render(request,'user_admin/edit.html',context) def delete(request,username): c_name=username.split('_')[1] username=username.split("_")[0] challenges=Challenges.objects.all() for c in challenges: if str(c)==c_name: c.delete() url = reverse('admin', kwargs={'username': username}) return HttpResponseRedirect(url) @login_required def show(request,username): c_name=username.split('_')[1] print(c_name) username=username.split("_")[0] challenges=Challenges.objects.all() context={} for c in challenges: if str(c)==c_name: context['ch']=c user_list=User.objects.all() for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 return render(request,'user_admin/show.html',context) @login_required def user_logout(request): #request.session.flush() logout(request) return redirect('/') @login_required def applicants(request,username): c_name=username.split('_')[1] username=username.split("_")[0] challenges=Challenges.objects.all() context={} for c in challenges: if str(c)==c_name: context['ch']=c break user_list=User.objects.all() for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 break appl=AppliedChallenges.objects.filter(challenge=str(context['ch'])) context['appls']=appl for a in appl: o=User.objects.filter(username=a.user) context['o']=o h=[] e=dict() for i in o: a=AppliedChallenges.objects.filter(challenge=str(context['ch'])).filter(user=i.username) for r in a: e[i.username]=r.completed print(e[i.username]) context['e']=e return render(request,'user_admin/applicants.html',context) @login_required def complete(request,username): c_name=username.split('_')[1] print(c_name) username=username.split("_")[0] challenges=Challenges.objects.all() context={} for c in challenges: if str(c)==c_name: context['ch']=c break user_list=User.objects.all() for u in user_list: if str(u)==str(username): user_info=u context['usr']=user_info user_admin_list=UserAdmin.objects.all() for user2 in user_admin_list: if str(user2)==str(username): context['uad']=user2 break
[ "/idil/basic_app/forms.py", "/idil/basic_app/migrations/0003_auto_20200817_2347.py", "/idil/basic_app/migrations/0006_auto_20200819_2225.py", "/idil/basic_app/models.py", "/idil/basic_app/urls.py", "/idil/basic_app/views.py", "/idil/user_admin/admin.py", "/idil/user_admin/migrations/0001_initial.py", "/idil/user_admin/migrations/0002_challenges.py", "/idil/user_admin/migrations/0003_auto_20200821_0413.py", "/idil/user_admin/migrations/0004_auto_20200821_0415.py", "/idil/user_admin/migrations/0005_auto_20200821_0418.py", "/idil/user_admin/migrations/0006_remove_challenges_applicant_status.py", "/idil/user_admin/migrations/0007_challenges_applicant_status.py", "/idil/user_admin/migrations/0008_appliedchallenges.py", "/idil/user_admin/migrations/0009_auto_20200823_1351.py", "/idil/user_admin/migrations/0010_auto_20200823_1354.py", "/idil/user_admin/models.py", "/idil/user_admin/urls.py", "/idil/user_admin/views1.py" ]
00MB/stock-simulation
line = "\n" + "_" * 50 + "\n" #globals = {"start" : start, "quit" : quit, "help" : help, "about" : about} --- FILE SEPARATOR --- #Python stock market simulator from globals import * from bs4 import BeautifulSoup import requests def set(): global portfolio global funds fileread = open("data.txt", "r") funds = fileread.readline() funds = float(funds.strip()) portfolio = fileread.readline().strip().split(",") if portfolio != [""]: for x in range(len(portfolio)): portfolio[x] = portfolio[x].split("-") portfolio[x][1] = float(portfolio[x][1]) portfolio[x][2] = int(portfolio[x][2]) fileread.close() for x in range(len(portfolio)): if portfolio[x] == "": del portfolio[x] set() print(f"""\nThis is a real time investment simulation. \n If you are new or want to reset the simulation, type !START. \n To see a list of commands, type !COMMANDS {line}""") #FUNCTIONS def about(): print(""" This stock simulator is a weekend project created by github user 00MB on 20/7/20. The simulator works by scraping live figures from yahoo finance, and saving the user into a text file. Feel free to play around and break it. """) def buy(): global funds global portfolio symbol = input("Enter stock symbol: ") url = "https://uk.finance.yahoo.com/quote/" + symbol headers = {"User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/83.0.4103.61 Chrome/83.0.4103.61 Safari/537.36"} request = requests.get(url, headers=headers) soup = BeautifulSoup(request.content, 'html.parser') try: price = soup.find("span", class_="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text() price = float(price.replace(',','')) except: print("ERROR - invalid stock symbol") return print(f"Stock price: ${price}") print(f"funds available: ${funds}") try: amount = int(input("Please insert stock amount (To cancel, insert 0): ")) except ValueError: print("\nERROR - incorrect data type") return if amount < 0 or amount > 1000: print("ERROR - unavailable amount") return elif amount == 0: return totalsum = amount * price if totalsum > funds: print("Costs exceeds available funds") return else: portfolio.append([symbol,price,amount]) funds = round((funds - totalsum),2) print("Successfully purchased stock") def sell(): global funds global portfolio try: symbol = input("Enter stock symbol to sell: ") names = [x[0] for x in portfolio] index = names.index(symbol) print(f"index:{index}") except: print(f"ERROR - no {symbol} stock is owned") return print(f"Amount owned: {portfolio[index][2]}") try: amount = int(input("Input amount of stocks to sell: ")) except ValueError: print("\nERROR - incorrect data type") return if amount > portfolio[index][2]: print("ERROR - invalid input") return url = "https://uk.finance.yahoo.com/quote/" + symbol headers = {"User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/83.0.4103.61 Chrome/83.0.4103.61 Safari/537.36"} request = requests.get(url, headers=headers) soup = BeautifulSoup(request.content, 'html.parser') price = soup.find("span", class_="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text() price = float(price.replace(',','')) print(f"Stock bought at: ${portfolio[index][1]}") print(f"Current stock price: ${price}") print(f"Profit/loss: ${amount * (float(price) - float(portfolio[index][1]))}\n") sold = input(f"Would you like to sell {symbol} stock at ${price} (type Y or N): ") if sold.lower() == "n": print("Request cancelled") return elif sold.lower() == "y": pass else: print("ERROR - invalid input") return amountnew = portfolio[index][2] - amount funds = round((funds + (float(price) * amount)),2) if amountnew == 0: del portfolio[index] else: portfolio[index][2] = amountnew print(f"Successfully sold {symbol} stock at ${price}, your funds available are ${funds}") if funds < 0: print("\nFunds available have reached less than 0, please type !START to reset") def fund(): print(f"Current funds available: ${funds}") def stocks(): print("Current stocks:") for x in portfolio: print(f"Symbol: {x[0]}, Bought at: ${x[1]}, Amount: {x[2]}") def start(): global funds global portfolio try: funds = float(input("Enter your starting amount: $")) except ValueError: print("\nERROR - incorrect data type") return print("\nSuccessfully set funds") portfolio = [] def quit(): dup = portfolio filewrite = open("data.txt", "w") filewrite.write(str(funds)+"\n") for x in range(len(dup)): dup[x][1] = str(dup[x][1]) dup[x][2] = str(dup[x][2]) dup[x] = "-".join(dup[x]) dup = ",".join(dup) filewrite.write(dup) filewrite.close() exit() def save(): dup = portfolio filewrite = open("data.txt", "w") filewrite.write(str(funds)) filewrite.write("\n") for x in range(len(dup)): dup[x][1] = str(dup[x][1]) dup[x][2] = str(dup[x][2]) dup[x] = "-".join(dup[x]) dup = ",".join(dup) filewrite.write(dup) filewrite.close() set() def commands(): print(""" !ABOUT - displays information about the program and creator\n !BUY - displays menu to buy stocks\n # !FUND - displays the current funds available\n # !PRICE {stock symbol} - displays live price of stock\n !QUIT - stops the process and closes the application\n !SAVE - saves current stocks and available funds\n !SELL - displays menu to sell your current stocks\n # !START - clears data and prompts user to enter starting funds amount\n # !STOCKS - displays the currently owned stocks\n # """) globals = {'!BUY' : buy, '!START' : start, '!QUIT' : quit, '!COMMANDS' : commands, '!STOCKS' : stocks, '!FUND' : fund, '!SELL' : sell, '!SAVE' : save, '!ABOUT' : about} while True: inp = input("Enter command: ") if inp in globals: print("\n") globals[inp]() print(line) else: print("ERROR - invalid command")
[ "/globals.py", "/stock.py" ]
00arun00/PyRate
def readGz(f): import gzip for l in gzip.open(f): yield eval(l) def amazon_purchase_review(): ''' Loads the amazon purchase review data ''' import pandas as pd import numpy as np from sklearn.model_selection import train_test_split as tts f_name=('Data/assignment1/train.json.gz') df = pd.DataFrame(readGz(f_name))[['itemID','reviewerID','rating']] data = df.values x = data[:,:2] y = data[:,2:] x_train,x_test,y_train,y_test = tts(x,y,test_size = 0.5) return x_train,y_train,x_test,y_test --- FILE SEPARATOR --- import numpy as np class Metric(object): ''' Abstarct class for evaluation metrics ''' @staticmethod def score(Y_hat,Y): ''' retruns the score based on the eval metric Args: :Y_hat (numpy.ndarray): Predicted values :Y (numpy.ndarray): Labels Returns: :error (float): Score ''' raise NotImplementedError('Abstract class') def __call__(self,Y_hat,Y): return self.score(Y_hat,Y) def __repr__(self): if hasattr(self,'eval_metric'): return f'{self.eval_metric}' else: raise NotImplementedError('pretty print not implemented') class RMSE(Metric): ''' Root Mean Square Error ''' def __init__(self): self.eval_metric = "RMSE" @staticmethod def score(Y_hat,Y): ''' retruns the score based on root mean square Args: :Y_hat (numpy.ndarray): Predicted values :Y (numpy.ndarray): Labels Returns: :error (float): Score based on RMSE ''' error = np.sqrt(np.mean((Y_hat-Y)**2)) return error class MSE(Metric): ''' Mean Square Error ''' def __init__(self): self.eval_metric = "MSE" @staticmethod def score(Y_hat,Y): ''' retruns the score based on root mean square Args: :Y_hat (numpy.ndarray): Predicted values :Y (numpy.ndarray): Labels Returns: :error (float): Score based on MSE ''' error = np.mean((Y_hat-Y)**2) return error class SSE(Metric): ''' Sum of Square Error ''' def __init__(self): self.eval_metric = "SSE" @staticmethod def score(Y_hat,Y): ''' retruns the score based on sum of squared error Args: :Y_hat (numpy.ndarray): Predicted values :Y (numpy.ndarray): Labels Returns: :error (float): Score based on SSE ''' error = np.sum((Y_hat-Y)**2) return error class MAE(Metric): ''' Mean Absolute Error ''' def __init__(self): self.eval_metric = "MAE" @staticmethod def score(Y_hat,Y): ''' retruns the score based on mean absolute error Args: :Y_hat (numpy.ndarray): Predicted values :Y (numpy.ndarray): Labels Returns: :error (float): Score based on MAE ''' error = np.mean(np.abs((Y_hat-Y)**2)) return error #aliases rmse = RMSE mse = MSE sse = SSE mae = MAE --- FILE SEPARATOR --- import numpy as np import warnings from eval_metrics import Metric class Model(object): ''' Recomender System model to be used **Note** This is a base class and cannot be used to make predictions ''' def __call__(self,X): ''' redirect to predict ''' return self.predict(X) def __repr__(self): ''' pretty print ''' if hasattr(self,'model_name'): return f'{self.model_name}' else: return 'Not implemented' def _predict_single_(self,x): ''' Predicts single ''' return np.random.uniform(0,5) def predict(self,X): ''' Predict Function Args: :X (numpy.ndarray): User, Item pairs to predict rating on Retruns: :predicted_rating (numpy.ndarray): predicted ratings ''' predicted_rating = np.array(list(map(self._predict_single_,X))).reshape(-1,1) return predicted_rating def set_eval_metric(self,metric): ''' Sets evaluation metric Args: :metric (Metric): evaluation metric used ''' assert isinstance(metric,Metric) self.eval_metric = metric def score(self,X,Y): ''' Predicts the score based on set eval metric Args: :X (numpy.ndarray): Input :Y (numpy.ndarray): Labels Retruns: :score (float): score based on the selected eval metric ''' y_pred = self.predict(X) if not hasattr(self,'eval_metric'): raise KeyError("Please add eval_metric") score = self.eval_metric(y_pred,Y) return score def fit(self,X,Y): ''' Fits model to the data ''' raise NotImplementedError('This is an abstract class') class Baseline(Model): ''' Baseline model ''' def __init__(self): self.model_name = 'Baseline' self.alpha = 0 self.fit_flag = False def __call__(self,X): ''' redirect to predict ''' return self.predict(X) def _predict_single_(self,X): if not self.fit_flag: warnings.warn(f'Model currently not fit, predicting 0 for all') return self.alpha def fit(self,X,Y): ''' Fits model to the data ''' self.alpha = np.mean(Y) self.fit_flag = True --- FILE SEPARATOR --- import data_loader import eval_metrics import models
[ "/data_loader.py", "/eval_metrics.py", "/models.py", "/pyrate.py" ]
00ba/LIST
''' Created on Sep 8, 2016 ''' class Cell: def __init__(self): self.cell = [] def get_car(self): result = self.cell.pop(0) return result def set_car(self, n): self.cell.insert(0, n) def get_cdr(self): result = self.cell.pop() return result def set_cdr(self, n): self.cell.append(n) class List(Cell): def __init__(self): self.root = Cell() def get_list(self): print self.root.cell def set_list(self, *args): for arg in args: if self.root.cell == []: self.root = cons(arg) else: self.root = cons(arg, self.root.cell) return self.root def cons(a, b = None): newcell = Cell() newcell.set_car(a) newcell.set_cdr(b) return newcell def atom(a): if isinstance(a, int): return True elif isinstance(a, str): return True else: False def eq(a, b): if a == b: return True else: return False --- FILE SEPARATOR --- from list import * if __name__ == '__main__': mylist = List() mylist.set_list(1, 2, 3) mylist.get_list() --- FILE SEPARATOR --- ''' Created on Sep 8, 2016 ''' from list import * import unittest class Test(unittest.TestCase): def test_list(self): box = List() box = box.cons(1, 2) self.assertEquals(box.root.get_car(),1) self.assertEquals(box.root.get_cdr(),2) self.assertTrue(atom(1)) self.assertTrue(atom('two')) self.assertFalse(atom([1, 2])) self.assertTrue(eq(1, 1)) self.assertFalse(eq(1, 2)) mylist = List() mylist.set_list(1, 2, 3) mylist.get_list() self.assertEquals(mylist.get_list(), [3, [2, [1, None]]]) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.test_list'] unittest.main()
[ "/list.py", "/main.py", "/test_list.py" ]
00fatal00-dev/rpg-python
import pygame,sys from player import Player screen_size = (800, 600) screen = pygame.display.set_mode(screen_size) pygame.display.set_caption("Game") running = True #Initiating player player = Player(0, 0, 32, 32, (255, 0, 0), .075, 0, 0) while running: player.x += player.move_x player.y += player.move_y for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() #Checking player movement if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: player.move_y = -player.move_speed if event.type == pygame.KEYUP: if event.key == pygame.K_w: player.move_y = 0 if event.type == pygame.KEYDOWN: if event.key == pygame.K_s: player.move_y = player.move_speed if event.type == pygame.KEYUP: if event.key == pygame.K_s: player.move_y = 0 if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: player.move_x -= player.move_speed if event.type == pygame.KEYUP: if event.key == pygame.K_a: player.move_x = 0 if event.type == pygame.KEYDOWN: if event.key == pygame.K_d: player.move_x += player.move_speed if event.type == pygame.KEYUP: if event.key == pygame.K_d: player.move_x = 0 screen.fill((0, 255, 0)) #Draw player pygame.draw.rect(screen, player.colour, (player.x, player.y, player.width, player.height), 0) pygame.display.update() --- FILE SEPARATOR --- import pygame import json class Player(): def __init__(self, x, y, width, height, colour, move_speed, move_x, move_y): self.x = x self.y = y self.width = width self.height = height self.colour = colour self.move_speed = move_speed self.move_x = move_x self.move_y = move_y self.stats = { 'health': 100 } def set_stats(self, stat_to_set, new_value): pass def get_stats(self, stat_to_get): return self.stats[stat_to_get]
[ "/main.py", "/player.py" ]
00mjk/GitManager
"#!/usr/bin/env python\n\nimport sys\nfrom GitManager import main\n\nif __name__ == '__main__':\n (...TRUNCATED)
["/GitManager/__main__.py","/GitManager/commands/__init__.py","/GitManager/commands/clone.py","/GitM(...TRUNCATED)
00mjk/NMP
"import torch\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\nimport(...TRUNCATED)
["/DataLoader.py","/eval_metrics.py","/modules.py","/preprocess/ass_fun.py","/preprocess/extract_vgg(...TRUNCATED)
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
9