def savePaths(request, paths, strokeWidth, strokeColor, object_type, fillColor=None):
	# if not request.user.is_authenticated():
	# 	return simplejson.dumps({'state': 'not_logged_in'})
	
	print "hih"
	print request.user.username

	pIDs = []
	pks = []

	for path in paths:
		pID = path['pID']
		points = path['points']
		planet = str(path['planet']['x'])+','+str(path['planet']['y'])

		lockedAreas = Box.objects(planet=planet, box__geo_intersects={"type": "LineString", "coordinates": points } )
		if lockedAreas.count()>0:
			return simplejson.dumps( {'state': 'error', 'message': 'Your drawing intersects with a locked area'} )

		p = Path(planet=planet, points=points, owner=request.user.username, strokeColor=strokeColor, fillColor=fillColor, strokeWidth=strokeWidth, object_type=object_type, pID=pID )
		p.save()

		pIDs.append(pID)
		pks.append(p.pk)

	return simplejson.dumps( {'state': 'success', 'pIDs': pIDs, 'pk': pks} )
Exemple #2
0
def _export_sheet(data, sheet_scheme, scheme, ws):
    for i, field in enumerate(_get_headers_for_sheetscheme(sheet_scheme, scheme)):
        ws.write(0, i, field, HEADER_STYLE)


    for row, item_data in enumerate(Path.from_string(sheet_scheme["Path"]).get(data).values()):
        ws.write(row+1,0, item_data.name)
        for col, field in enumerate(sheet_scheme["Fields"]):
            field_path = _get_field_option(field, "Path") or field
            cell_data = Path.from_string(field_path).get(item_data)
            ws.write(row+1,col+1, cell_data.get())
Exemple #3
0
 def get(self):
     drawing_id = self.request.get("drawing_id", default_value=None)
     if drawing_id is None:
         q = Path.all().order("play_count")
         if q.count():
             path = q.fetch(1)[0]
         else:
             path = Path(key_name="initial", json="{}")
     else:
         path = Path.get(db.Key(drawing_id))
     path.play_count += 1
     path.put()
     self.response.out.write('[{"paths":%s,"success":true}]' % path.json)
Exemple #4
0
def fromtrackpath(path, job, start, stop):
    newpath = Path(job = job)
    frames = sorted(path.boxes.keys())
    laststored = None
    blowradius = job.segment.video.blowradius
    for frame in frames:
        if frame != start and frame != stop:
            box = path.boxes[frame]
            if laststored is None or frame - laststored > blowradius:
                newpath.boxes.append(tovaticbox(newpath, box))
                laststored = frame
            elif box.lost or box.occluded:
                newpath.boxes[-1] = tovaticbox(newpath, box)
                laststored = frame
    return newpath
Exemple #5
0
def fromtrackpath(path, job, start, stop):
    newpath = Path(job=job)
    frames = sorted(path.boxes.keys())
    laststored = None
    blowradius = job.segment.video.blowradius
    for frame in frames:
        if frame != start and frame != stop:
            box = path.boxes[frame]
            if laststored is None or frame - laststored > blowradius:
                newpath.boxes.append(tovaticbox(newpath, box))
                laststored = frame
            elif box.lost or box.occluded:
                newpath.boxes[-1] = tovaticbox(newpath, box)
                laststored = frame
    return newpath
Exemple #6
0
def navigate_user():
    """ display a map with basic pins of each route """
    route_id = request.form.get('route_details')

    route = Route.query.filter(Route.route_id == route_id).first()
    route_waypoints = route.waypoints

    start_point = route_waypoints[0]
    end_point = route_waypoints[-1]


    path = Path(start_point=start_point,
                end_point=end_point,
                )
    db.session.add(path)
    db.session.commit()

    path_id_tup = db.session.query(func.max(Path.path_id)).first()
    path_id = path_id_tup[0]

    step_start = start_point
    # step_end = route_waypoints[1]
    step = Step(path_id=path_id,
                start_point=step_start,
                # end_point=step_end,
                )
    db.session.add(step)
    db.session.commit()

    return render_template('navigation.html', route_id=route_id,
                                              path_id=path_id)
Exemple #7
0
def add_path(request):
    if request.method == "POST":
        path  = Path(smoothness = request.POST['smoothness'],surface = request.POST['surface'],
                        width = request.POST['width'],
                        slope = request.POST['slope'],
                        way = request.POST['way'],
                        wheelchair = request.POST['wheelchair'],
                        rating = request.POST['rating'],
                        improvement = request.POST['improvement'],
                        longitude = request.POST['longitude'],
                        latitude = request.POST['latitude'])

        path.save()
        data = {"result":SUCCESS}
    else:
        data = {"result":FAIL,"error":"Invalid request","meta":"use POST method" }
    return HttpResponse(json.dumps(data), content_type="application/json")
Exemple #8
0
	def get(self):
		"""
		Delete a drawing
		"""
		drawing_id = self.request.get('drawing_id')
		path = Path.get(db.Key(drawing_id))
		path.delete()
		self.redirect('/admin/')
Exemple #9
0
	def get(self):
		"""
		Render the thumbnail of a drawing and render a PNG
		"""
		drawing_id = self.request.get('drawing_id')
		path = Path.get(db.Key(drawing_id))
		self.response.headers['Content-Type'] = 'image/png'
		self.response.out.write(path.generate_preview_png())
Exemple #10
0
def _get_headers_for_sheetscheme(sheet_scheme, scheme):
    result = ["id"]
    for field in sheet_scheme["Fields"]:
        field_path = _get_field_option(field, "Path") or field
        field_path = field_path.replace("/", "/SubElements/")

        result.append(_get_field_option(field, "Name") or Path.from_string(sheet_scheme["Path"]+"/*/"+field_path).get(scheme)["Description"].get())
    return result
Exemple #11
0
def create_path():
    new_path = Path(request.form['id'], request.form['name'])
    db_session.add(new_path)
    db_session.commit()
    for point in json.loads(request.form['points']):
        db_session.add(
            Point(new_path.id, float(point['lat']), float(point['lng'])))
    db_session.commit()
    return 'ok'
Exemple #12
0
def add_path():
    body = request.get_json()
    pth = Path(svg=body['svg'],
               zoom=body['zoom'],
               lat=body['lat'],
               lng=body['lng'])
    db.session.add(pth)
    db.session.commit()
    return "Path added with id {}".format(pth.id)
def main():
    path = Path()
    menu = Menu()
    menu.instructions()
    while True:
        # menu.de_entrada()
        try:
            excel_filename = input("Ingresa el nombre del archivo de excel: ")
            excel_exists = path.check_existence(excel_filename)
            if excel_exists:

                # File found notification for the user.
                menu.file_found()

                # Tras haber verificado que el archivo existe, se crea el path para cargar el libro con openpyxl.
                excel_file_path = path.book_path(excel_filename)

                # Book settings
                book = Book(excel_file_path)
                book_headers = book.get_headers()
                book_rows = book.get_list_of_rows()

                app_name = input(
                    "Ingresa el nombre del app de tu proyecto Django: ")
                model_name = input("Ingresa el nombre del modelo de tu app: ")

                fx = Fixture(
                    app=app_name,
                    model=model_name,
                    headers=book_headers,
                    list_of_fields=book_rows,
                )
                fx.create_objects()
                fx.create_json_file(path.json_dir)

                menu.task_completed()
                break
            else:
                menu.file_not_found()

        except ValueError:
            print("Ingresa el nombre del archivo.")
            print("")
            pass
Exemple #14
0
def panda_pathB():
    global born_opt
    panda_key = Character.query(Character.species == "Panda").get()
    panda_path = Path.query(Path.owner == panda_key.key).get()
    if born_opt == 1:
        return panda_path.p_1b
    elif born_opt == 2:
        return panda_path.p_2b
    elif born_opt == 3:
        return panda_path.p_3b
Exemple #15
0
	def get(self):
		"""
		Directory of all drawings stored in the data store
		"""
		q = Path.all()
		q.order("-date_created")
		template_values = {
			'drawings': q,
		}
		path = os.path.join(os.path.dirname(__file__), 'templates/admin.html')
		self.response.out.write(template.render(path, template_values))
Exemple #16
0
def insert_path(nex_session, fw, path, source_id):

    x = Path(source_id=source_id,
             path=path,
             description='TBD',
             created_by=CREATED_BY)

    nex_session.add(x)
    nex_session.commit()

    fw.write("insert path for path=" + path + "\n")

    return x.path_id
Exemple #17
0
def import_from_excel(scheme, filename):
    export_scheme = scheme.get_meta().dump()["ExcelScheme"]
    rb = xlrd.open_workbook(filename)
    result = StructuredNode({})
    for sheet_name, sheet_scheme in export_scheme["Sheets"].iteritems():
        sheet = _get_sheet_by_name(rb, sheet_name)
        for rownum in range(1,sheet.nrows):
            row = sheet.row_values(rownum)
            current_id = None
            for field, cell_data in zip([ID_FIELD] + sheet_scheme["Fields"], row):
                if field==ID_FIELD:
                    current_id = cell_data
                else:
                    field_path = _get_field_option(field, "Path") or field
                    full_field_path = "/{}/{}/{}".format(sheet_scheme["Path"], current_id, field_path)
                    full_scheme_field_path = "/{}/{}/{}".format(sheet_scheme["Path"], current_id, field_path.replace("/", "/SubElements/"))
                    path = Path.from_string(full_field_path)
                    field_scheme = Path.from_string(full_scheme_field_path).get(scheme)
                    path.set(result, NodeWidget.get_data_class(field_scheme)(cell_data))
    pprint(result)
    return result.dump()
            
            
Exemple #18
0
    def setUp(self):
        self.h1 = [
            '192.168.0.1', '192.168.0.36', '192.168.0.28', '192.168.0.34',
            '192.168.0.42', '192.168.0.3'
        ]
        self.h2 = [
            '192.168.0.2', '192.168.0.136', '192.168.0.8', '192.168.0.16',
            '192.168.0.39', '192.168.0.146', '192.168.0.3'
        ]
        self.h3 = [
            '192.168.0.1', '192.168.0.136', '192.168.0.8', '192.168.0.18'
            '192.168.0.16', '192.168.0.39', '192.168.0.146', '192.168.0.4'
        ]

        self.p1 = p.Path(hops=self.h1, id=1)
        self.p2 = p.Path(hops=self.h2, id=2)
        self.p3 = p.Path(hops=self.h3, id=3)
        self.p4 = p.Path(hops=self.h1, id=4)

        self.m1 = m.Measurement(66, 1476351846113)
        self.m2 = m.Measurement(69, 1476351876762)
        self.m3 = m.Measurement(62, 1476351898901)
        self.m4 = m.Measurement(66, 1476351846113)
Exemple #19
0
def list_path( path, dirs,files,file_url_prefix,dir_url_prefix):
    for fname in os.listdir(path):
        p = Path()
        p.name = fname
        fname = os.path.join(path,fname)
        #p.physical = os.path.normpath(fname)
        p.lastmodified = datetime.fromtimestamp(os.path.getmtime(fname))
        if os.path.isdir(fname):
            p.url = url_join(dir_url_prefix,p.name)
            p.is_dir = True
            dirs.append(p)            
        elif os.path.isfile(fname):
            p.url = url_join(file_url_prefix,p.name,True)
            p.size = os.path.getsize(fname)
            
            files.append(p)
Exemple #20
0
def convert_to_db(paths, job, label):
    paths = clean_paths(paths)
    paths_db = []
    for path in paths:
        path_db = Path(job=job, label=label)
        for box in path:
            box_db = Box(path=path_db)
            box_db.xtl = box['rect'][0]
            box_db.ytl = box['rect'][1]
            box_db.xbr = box['rect'][0] + box['rect'][2]
            box_db.ybr = box['rect'][1] + box['rect'][3]
            box_db.frame = box['frame']
            box_db.outside = 0 if box['visible'] else 1
            box_db.occluded = 0
            path_db.boxes.append(box_db)

        paths_db.append(path_db)
    return paths_db
Exemple #21
0
def load(request, areasToLoad):

	paths = []
	boxes = []

	for area in areasToLoad:
				
		tlX = area['pos']['x']
		tlY = area['pos']['y']

		planet = str(area['planet']['x'])+','+str(area['planet']['y'])

		p = Path.objects(planet=planet, points__geo_intersects=makeBox(tlX, tlY, tlX+1, tlY+1) )
		b = Box.objects(planet=planet, box__geo_intersects=makeBox(tlX, tlY, tlX+1, tlY+1) )

		paths.append(p.to_json())
		boxes.append(b.to_json())

	return simplejson.dumps( {'paths': paths, 'boxes': boxes, 'user': request.user.username} )
Exemple #22
0
    def put(self, user, path_id):
        path_obj = (Path.select().where(Path.user == user,
                                        Path.id == path_id).get())

        path_obj.last_ship_date = date.today()

        move = Move(
            value=path_obj.total,
            type=0,
            obs=f"GERADO DA VENDA DA ROTA {path_obj.id}",
            user=user,
        )

        path_obj.save()
        move.save()

        result = {"msg": "sucesso"}

        return json_response(result, 200)
Exemple #23
0
def doggo_pathB():
    global post_born_opt
    doggo_key = Character.query(Character.species == "Dog").get()
    doggo_pathB = Path.query(Path.owner == doggo_key.key).get()
    why = randrange(1,3)
    if born_opt == 1:
        if why == 1:
            return doggo_pathB.p_1b[0]
        elif why == 2:
            return doggo_pathB.p_1b[1]
    elif born_opt == 2:
        if why == 1:
            return doggo_pathB.p_2b[0]
        elif why == 2:
            return doggo_pathB.p_2b[1]
    elif born_opt == 3:
        if why == 1:
            return doggo_pathB.p_3b[0]
        elif why == 2:
            return doggo_pathB.p_3b[1]
Exemple #24
0
    def get(self, user):
        routes = Path.select().where(Path.user == user)

        def parse(item):
            next_ship_date = item.last_ship_date + timedelta(
                days=item.step_days)
            now_date = date.today()
            result = next_ship_date - now_date
            days = result.days
            status = "atrasado"

            if days <= 0:
                status = "atrasado"
            if days > item.warning_sub_day:
                status = "no prazo"
            else:
                status = "atenção"

            return {
                "path_id": item.id,
                "client_id": item.client.id,
                "until_days": days,
                "status": status,
            }

        result = list(map(parse, routes))
        atrasado = list(filter(lambda x: x["status"] == "atrasado", result))
        atencao = list(filter(lambda x: x["status"] == "atenção", result))
        no_prazo = list(filter(lambda x: x["status"] == "no_prazo", result))

        header = {
            "qtd_atrasado": len(atrasado),
            "qtd_atencao": len(atencao),
            "qtd_no_prazo": len(no_prazo),
            "results": result,
        }

        return json_response(header, 200)
 def add_new_path(self, pathname, the_path):
     try:
         Path(name=pathname, path=the_path)
     except:
         return False
     return True
Exemple #26
0
def seed_data():
    kitty_key = Character(species="Cat").put()
    panda_key = Character(species="Panda").put()
    doggo_key = Character(species="Dog").put()

    kitty_born = Born(
        born_1=
        "You are a ratty streetcat born in a litter of four. Your mom abandoned you",
        born_2=
        "You are a cute kitty cat born in a litter of six. You are super healthy!",
        born_3=
        "You are a tiny teacup kitty born in a litter of nine. You are the runt of the bunch",
        owner=kitty_key).put()

    kitty_post_born = PB2(
        pb_1=
        "Congrats! A streetboy found you and took you home. Do you stay with him or run away",
        pb_2=
        "Congrats! A rich person saw you and just had to have you. Do you stay with this rich person or run",
        pb_3=
        "An old man saw you and took you home with him. Do you stay with him or run",
        owner=kitty_key).put()

    kitty_loop = Looper(
        loop_1="Ouch! The kid was a s****t, and tortured you until you died.",
        loop_2=
        "You have a new home! However, that rich person is cat obsessive and dresses you in tight clothing. Do you run or stay?",
        loop_3=
        "Noice! The old man wanted  a support animal, so you now live your day to day life well fed and happy. However, the old man died of some unknown illness. The old man left you to his nephew. Do you stay with him or run away?",
        run="You ran away.",
        owner=kitty_key).put()

    kitty_Path = KPath(
        p_2a=
        "You live your life miserably until you die from being strangled by an overly tight kitty outfit.",
        p_2b=
        "After you run away, you fell asleep in a damp alley. When you awaken, you are in a warm animal shelter. You are soon adopted by a nice person.",
        p_3a=
        "Awesomeness apparently runs in the family. The nephew is great and you live a long and happy life with him.",
        p_3b=
        "Because you have been domesticated, you do not know how to survive without human help. You come in contact with a dead mouse and begin to eat it. However, the mouse had leptospirosis, so you die of kidney failure.",
        owner=kitty_key).put()

    panda_born = Born(
        born_1=
        "For your whole life you have been on the run from hunters. Your mother and father fell victim to the vicous fur trade in China",
        born_2=
        "You were born in the San Diego Zoo where you spend your time posing for selfies with little kids and playing with your siblings",
        born_3=
        "The circus means everything to you. It has been your home for the last ten years.",
        owner=panda_key).put()

    panda_post_born = PB2(
        pb_1=
        "You become stuck in a trap! OH NO! Should you A) escape or B) stay?",
        pb_2=
        "A little kid wanders into the zoo and manages to sneak into the cage. Do you A) call for attention or B) keep quiet?",
        pb_3=
        "Oh no! Your circus has been disbanded by PETA! Do you A) start a new life or B) join a new circus?",
        owner=panda_key).put()

    panda_path = Path(
        p_1a=[
            "Your attempt to escape fails and you end up cutting your foot off. You lose too much blood and your vision is dimming fast. You panic because you do not want your life to end so soon! But your eyes close anyway as you slowly bleed out painfully.",
            ""
        ],
        p_1b=[
            "Luckily, you were found by a group of tourists who help free you.",
            ""
        ],
        p_2a=[
            "Your brother suddenly comes out of nowhere and is inches from trampling the kid. But since the zookeeper heard your cries, he shows up and saves the kid. Your good behavior is rewarded and the zookeeper buys you new toys! Yay!",
            ""
        ],
        p_2b=[
            "You end up playing with the kid and have a lot of fun. However, the kid’s mother spots you both playing and threatens to sue the zoo. The zoo decides to free you into the wild and you become separated from your family. You slowly grow apart from them, and after 2 years you have totally forgotten about them. Sad.",
            ""
        ],
        p_3a=[
            "You are unable to cope with the stress of living by yourself and end up joining a new circus.",
            ""
        ],
        p_3b=[
            "You are doing great at the new circus and were even offered a new job from Larry the Lion. Should you A) take the job or B) don't take the job?",
            ""
        ],
        owner=panda_key).put()

    panda_post_path = PPath(
        PP_1=
        "Unfortunately your new job requires for you to jump into a pool of sharks. Your attempt to jump fails and you end up getting eaten by the sharks.",
        PP_2=
        "You realize that you like your current job. In fact, the tricks that you partake in end up making you rich and famous. You live out the rest of your life swimming in your own fortune and enjoying your life. Yay.",
        owner=panda_key).put()

    doggo_born = Born(
        born_1=
        "You wake up in a dark ravine without any family. You are starving. You scavenge for food but cannot find anything.",
        born_2=
        "You were born into a rich family, but they are never home. Your food is overflowing because your owners do not know how much to feed you. The food looks old now.",
        born_3=
        "Your owner pats your head with affection. He gazes into your eyes and rubs you behind your ears, just the way you like. Your tail wags. You almost forget you both have no house to live in",
        owner=doggo_key).put()

    doggo_post_born = PB2(
        pb_1=
        "You see food on the dirty floor. One is a seemingly moldy dog buscuit and a dead mouse lies next to it. Which do you eat? Press A for the mouse and B for the buiscuit ",
        pb_2=
        "You do not want to have such a boring, empty life. You want more, so you run away. DO you A) follow the music playing from a dirty car or B) run aimlessly?",
        pb_3=
        "You see that there is no food for you both tonight. There is only enough for one of you. Do you A) take the food, or B) let the human have it?",
        owner=doggo_key).put()

    doggo_pre_path = PPath(
        PP_1=
        "You regain your strength and decide to take a chance. You go beyond your ravine and ...",
        PP_2="The dog buiscuit had salmonella and you become extremely sick.",
        owner=doggo_key).put()

    doggo_path = Path(
        p_1a=[
            "You get run over by a car. You are dead.",
            "You find a pack of dogs. You are happy with your newfound life."
        ],
        p_1b=[
            "A child finds you and takes you home. The child's family treats you and you feel better",
            "You die from being sick."
        ],
        p_2a=[
            "The owner of the car is a travelling musician. He wants a companion for the road so he takes you. You ride off into the sunset excited for what lies ahead.",
            "The driver doe not stop. You chase on for hours and get tired. You die of exhaustion in an unknown place"
        ],
        p_2b=[
            "Your owner sees you running away and catches you. You are taken back to your life of solitude."
        ],
        p_3a=[
            "He yells and tries to grab the bread but you eat it. You run away and the man dies.",
            "You nudge the bread with your nose toward the man. He places the bread infront of you and finds another piece of bread. You go to bed happy"
        ],
        p_3b=[
            "He breaks the bread in half and shares it. You rest you muzzle on him and dze off somewhat hungry.",
            "He kicks you and runs off. You bite his finger off and run away with the bread. The man's finger becomes infected and he dies. You  eat the bread and live for another day."
        ],
        owner=doggo_key).put()
Exemple #27
0
 def bind(self):
     for path in self.paths:
         self.boxes = Path.bindattributes(path.attributes, self.boxes)
Exemple #28
0
 def _get_options_from_scheme(cls, scheme, data):
     path = Path.from_string(scheme["OptionPath"].get())
     return [Node.create_node(name) for name in path.get(data).keys()]
Exemple #29
0
 def bind(self):
     for path in self.paths:
         self.boxes = Path.bindattributes(path.attributes, self.boxes)
def floodFill(img, seed, target_color, replace_color):
    print 'floodFill begin'
    q_pixel_list = []
    path = Path(replace_color)

    if img.getpixel(seed) == target_color:
        q_pixel_list.append(seed)
        while q_pixel_list:
            pixel_list = []
            for ele in q_pixel_list:

                if img.getpixel(ele) == target_color:
                    path.setMinHoriz(ele[0])
                    path.setMaxHoriz(ele[0])
                    path.setMinVert(ele[1])
                    path.setMaxVert(ele[1])
                    img.putpixel(ele, replace_color)
                    path.incArea()

                    westAndEastAnalysis(img, ele, pixel_list, target_color)
                    w = e = ele
                    while (w[0] > 0):
                        if img.getpixel((w[0]-1, w[1])) == target_color:
                            path.setMinHoriz(w[0]-1)
                            img.putpixel((w[0]-1, w[1]), replace_color)
                            path.incArea()

                            if (w[1]-1 >= 0):
                                if img.getpixel((w[0]-1,w[1]-1)) == target_color:
                                    path.setMinVert(w[1]-1)
                                    pixel_list.append((w[0]-1, w[1]-1))

                            if (w[1]+1 < img.size[1]-1):
                                if img.getpixel((w[0]-1,w[1]+1)) == target_color:
                                    path.setMaxVert(w[1]+1)
                                    pixel_list.append((w[0]-1, w[1]+1))

                            w = (w[0]-1, w[1])
                        else:
                             break

                    while (e[0] < img.size[0]-1):
                        if img.getpixel((e[0]+1, e[1])) == target_color:
                            img.putpixel((e[0]+1, e[1]), replace_color)
                            path.incArea()
                            path.setMaxHoriz(e[0]+1)

                            if (e[1]-1 >= 0):
                                if img.getpixel((e[0]+1,e[1]-1)) == target_color:
                                    pixel_list.append((e[0]+1, e[1]-1))
                                    path.setMinVert(e[1]-1)

                            if (e[1]+1 < img.size[1]-1):
                                if img.getpixel((e[0]+1,e[1]+1)) == target_color:
                                    pixel_list.append((e[0]+1, e[1]+1))
                                    path.setMaxVert(e[1]+1)

                            e = (e[0]+1, e[1])
                        else:
                             break
            q_pixel_list = pixel_list

    print 'floodFill end'
    return path