def test_normalise_zoomout(self): self.lap.session.zoom = 0.5 result = self.lap.normalise(self.lap.last_point, math.pi / 2) self.assertTrue(result[0].equal_coords(Point(202.5, 0, 96.5))) self.assertTrue(result[1].equal_coords(Point(202.5, 0, 98))) self.assertTrue(result[2].equal_coords(Point(201, 0, 99))) self.assertTrue(result[3].equal_coords(Point(200, 0, 100)))
def test_distance(): ''' Test distance from one point to another. ''' p1 = Point(0, 1, 2) p2 = Point(1, 3, 4) assert p1.distance(p2) == math.sqrt(abs(3 - 1) ** 2 + abs(4 - 2) ** 2)
def test_point_domination(self): a = Point(1, 2) b = Point(3, 4) c = Point(2, 2) self.assertTrue(b.dominating(a)) self.assertTrue(b.dominating(c)) self.assertFalse(a.dominating(c))
def test_normalise_zoomin(self): self.lap.session.zoom = 1.4 result = self.lap.normalise(self.lap.last_point, math.pi / 2) self.assertTrue(result[0].equal_coords(Point(207, 0, 90.2))) self.assertTrue(result[1].equal_coords(Point(207, 0, 94.4))) self.assertTrue(result[2].equal_coords(Point(202.8, 0, 97.2))) self.assertTrue(result[3].equal_coords(Point(200, 0, 100)))
def test_polygon_area(self): p1 = Point(0, 0) p2 = Point(0, 100) p3 = Point(100, 100) p4 = Point(100, 0) p = Polygon((p1, p2, p3, p4)) self.assertAlmostEqual(p.area, 10000) self.assertAlmostEqual(p.area, 10000)
def setUp(self): session = Session() session.app_size_x = 400 session.app_size_y = 200 self.lap = Lap(session, 0) self.lap.points.append(Point(10, 0, 10, 100, 0.9, 0, 0.2)) self.lap.points.append(Point(13, 0, 10, 110, 1.0, 0, 0.0)) self.lap.points.append(Point(15, 0, 13, 130, 1.0, 0, 0.0)) self.lap.points.append(Point(17, 0, 15, 140, 0.1, 0.8, 0.9))
def predict_arabic_glyphs(sequential_model): arab_supplement = get_unicode_block_glyphs('Arabic Supplement') supplement = embedded_stroke_type_input(arab_supplement) #Grab the datums supplement_contours = tf.keras.preprocessing.sequence.pad_sequences( supplement[0], padding='post') supplement_types = tf.keras.preprocessing.sequence.pad_sequences( supplement[2], padding='post') supplement_contours = tf.keras.constraints.UnitNorm(axis=1)(tf.cast( supplement_contours, tf.float32)) supplement_types = tf.keras.backend.cast(supplement_types, dtype='float32') predict_supplement = concat_model([supplement_types, supplement_contours]) #Generation routine: feed in a value, then iteratively predict based on the results of the prediction routine #We don't really need to make prediction data - we just start with the Glyph Generation symbol: #new_glyph = np.array([[[5]]],[[[0.0,0.0]]],dtype='float32') #How deterministic is this? We might be able to perturb the x-y to get different glyphs. Play wid it prediction_length = 100 preds = [] #prediction = sequential_model.predict(new_glyph) prediction = sequential_model.predict( [supplement_types[0:1, 0:1, 0:1], supplement_contours[0:1, 0:1, :]]) #Part of the problem here might be a lack of context, where we are simply predicting on the last character, #rather than a sequence of the previous predictions - transfer hidden state somehow? for i in range(0, prediction_length): preds.append(prediction) prediction = sequential_model.predict( [prediction[:, 0:1, 0:1], prediction[:, 0:1, 1:]]) #Now parse predictions into a glyph format - interpret stroke type and scale back up using font metadata (short trick might be multiply by 1000) #We visualize contours separately until we're sure that the RNN can properly segment glyphs with the proper stroke type, if ever strokes = [] for pred in preds: type = pred[0][0][0] * 5 x = pred[0][0][1] * 1000 y = pred[0][0][2] * 1000 strokes.append(Stroke(type='L', point=Point(x=x, y=y))) num_contours = 5 contour_length = int(prediction_length / num_contours) predicted_contours = [] for i in range(0, num_contours): new_s = strokes[i * contour_length:(i * contour_length) + contour_length] new_s.insert(0, Stroke(type='G', point=Point(x=0, y=0))) predicted_contours.append(Contour(strokes=new_s)) predicted_glyphs = [ Glyph(contours=predicted_contours[i:i + 1]) for i in range(0, num_contours) ] prediction_font = Font(name="Predictions", glyphs=predicted_glyphs) db.session.add(prediction_font) db.session.commit()
def test_quickhull1(self): pts = [Point(3, 4), Point(0, 0), Point(7, 2)] tree = BinTree(Node([pts[1], pts[0], pts[2]])) tree.root.left = Node([pts[1], pts[0], pts[2]]) tree.root.right = Node([pts[2], pts[1]]) tree.root.left.left = Node([pts[1], pts[0]]) tree.root.left.right = Node([pts[0], pts[2]]) hull = [pts[1], pts[0], pts[2]] ans = quickhull(pts) self.assertEqual(tree, next(ans)) self.assertEqual(hull, next(ans))
def test_graph_vertex_add(self): g = Graph() v1 = Vertex(Point(1, 2)) v2 = Vertex(Point(2, 1)) g.add_vertex(v1) g.add_vertex(v2) g.add_edge(v1, v2) g.add_edge(v2, v1) self.assertEqual(len(g.edges), 1)
def parse_drawing(drawing): contours = [] for index, line in enumerate(drawing['drawing']): length = len(line[0]) lines = [] for i in range(length - 1): point = [ Point(x=line[0][i], y=line[1][i]), Point(x=line[0][i + 1], y=line[1][i + 1]) ] stroke = Stroke(type='L', point=point) lines.append(stroke) contours.append(Contour(strokes=lines)) return contours
async def payout_wager(username, team_name, wager_id, result, bot): team, user = get_team_user(team_name, username) marvn = s.query(User).filter_by(username='******').first() if result.lower() == 'true': result = True else: result = False msg = "" for wager in team.wagers: if wager.id == wager_id: msg = f"Wager: `#{wager.id}` - `CLOSED`\n" \ f'"{wager.description}"\n' \ f"{get_wager_bets(wager)}" \ f"Result: `{result}`" wager.result = result payout = False for bet in wager.bets[1:]: if bet.position != wager.bets[0].position: payout = True if payout: for bet in wager.bets: bet.result = result if bet.position is not result: points = bet.points * -1 msg += f"\nDeducting {bet.points} points from {bet.user}" p = Point(giver_id=marvn.id, receiver_id=bet.user.id, team_id=team.id, points=points, description=f"Wager: #{wager.id}") s.add(p) else: msg += f"\nPaying {bet.points} points to {bet.user}" p = Point(giver_id=marvn.id, receiver_id=bet.user.id, team_id=team.id, points=bet.points, description=f"Wager: #{wager.id}") s.add(p) wager.is_closed = True s.commit() await update_wager_msg(bot, wager, msg) s.close() return msg else: msg = f"Nobody took the Wager `#{wager_id}` so this didn't payout.\n" \ f"`{wager.description}`" wager.is_closed = True s.commit() await update_wager_msg(bot, wager, msg) s.close() return msg return f"Wager `#{wager_id}` is either already closed or non-existant."
def setUp(self): db.session.remove() db.drop_all() db.create_all() user = User('johndoe', encrypt('password'), 'John Doe') db.session.add(user) start_point = Point(10.0, 20.0) db.session.add(start_point) end_point = Point(30.0, 40.0) db.session.add(end_point) db.session.commit()
def test_point_centroid(self): p1 = Point(1, 2, 3) p2 = Point(1, 5, 6) p3 = Point(1, 2, 3) self.assertEqual(Point.centroid((p1, p2, p3)), Point(1, 3, 4)) p1 = Point(1, 2, 3) p2 = Point(1, 5, 6) p3 = Point(1, 2, 3) p4 = Point(1, 2, 3) self.assertEqual(Point.centroid((p1, p2, p3, p4)), Point(1, 2.75, 3.75))
def read_instance(filename: str) -> PDPInstance: ''' Reads a file that contains a PDP instance and returns its object. ''' filepath = get_filepath(filename) try: # if file is empty if os.stat(filepath).st_size == 0: print(' File %s is empty.' % filename) return None with open(filepath, 'r') as file: # read every line of the file and parse it to constructor's arguments of Point class points = [Point(*map(int, line.split())) for line in file] # get p from filename p = int(filename.split('_')[1]) # return an object of PDPInstance return PDPInstance(p, points) except FileNotFoundError as error: print(' ', error) return None except ValueError: print(' File %s has invalid format.' % filename) return None
def write_score(user, sender, team_name, points, description): # file_exists = os.path.isfile(f'./storage/{channel}.csv') # if not file_exists: # with open(f'./storage/{channel}.csv', mode='w') as morningreport_file: # header = ["User", "Date-time", "Points", "Sender", "Conv_id"] # score_writer = csv.writer(morningreport_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) # if not file_exists: # score_writer.writerow(header) # # with open(f'./storage/{channel}.csv', mode='a') as morningreport_file: # score_writer = csv.writer(morningreport_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) # score_writer.writerow([user, datetime.datetime.now(), points, sender, channel]) team = s.query(Team).filter(Team.name.match(team_name)).first() giver = s.query(User).filter(User.username.match(sender)).first() receiver = s.query(User).filter(User.username.match(user)).first() points = Point(giver_id=giver.id, receiver_id=receiver.id, team_id=team.id, points=points, description=description) s.add(points) s.commit() s.close() return
def point_in_polygon(polygon, point): line_left = Segment(Point(-999999999, point.y), point) line_right = Segment(point, Point(999999999, point.y)) count_left = 0 count_right = 0 for e in polygon.get_edges(): if edges_intersect(line_left, e): count_left += 1 if edges_intersect(line_right, e): count_right += 1 if count_left % 2 == 0 and count_right % 2 == 0: return False return True
def result(): from models import Point zip_code = request.form['zip'] key = 'AIzaSyCDKSQdglP_kfxPsZsDfqXxO0T193LJZfs' url = f'https://maps.googleapis.com/maps/api/geocode/json?address={zip_code}&key={key}' data = requests.get(url).json() longitude = data["results"][0]["geometry"]["location"]["lng"] latitude = data["results"][0]["geometry"]["location"]["lat"] address = data["results"][0]["formatted_address"] new_point = Point(zip_code=zip_code, longitude=longitude, latitude=latitude, address=address) db.session.add(new_point) db.session.commit() return render_template('result.html', zip_code=zip_code, longitude=longitude, latitude=latitude, address=address)
def draw_came_from_mtrx(self, visualizer): came_from_mtrx = self.came_from_mtrx for x in range(len(came_from_mtrx)): for y in range(len(came_from_mtrx[0])): if came_from_mtrx[x][y] is not None: arrow = (Point(x, y) - came_from_mtrx[x][y] ).get_direction().get_ascii_arrow() visualizer.client.draw_text(x, y, arrow)
def save_measure_in_db(session, data, point): objects = [] value = data.pop(0) my_ssid = Ssid(value[0]) my_bssid = Bssid(value[1]) my_measure = Measure(value[2]) my_channel = Channel(value[3]) my_security = Security(value[4]) my_point = Point(point) entry = session.query(Ssid).filter(Ssid.ssid_value.like(value[0])).first() if entry is None: my_ssid.measure.append(my_measure) objects.append(my_ssid) else: entry.measure.append(my_measure) entry = session.query(Bssid).filter(Bssid.bssid_value.like( value[1])).first() if entry is None: my_bssid.measure.append(my_measure) objects.append(my_bssid) else: entry.measure.append(my_measure) entry = session.query(Channel).filter(Channel.channel_number.like( value[3])).first() if entry is None: my_channel.measure.append(my_measure) objects.append(my_channel) else: entry.measure.append(my_measure) entry = session.query(Security).filter( Security.security_type.like(value[4])).first() if entry is None: my_security.measure.append(my_measure) objects.append(my_security) else: entry.measure.append(my_measure) entry = session.query(Point).filter(Point.x_location == point.x).filter( Point.y_location == point.y).first() if entry is None: my_point.measure.append(my_measure) objects.append(my_point) else: entry.measure.append(my_measure) objects.append(my_measure) session.add_all(objects) session.commit() if len(data) != 0: save_measure_in_db(session, data, point) else: return
def setUp(self): self.maxDiff = None db.session.remove() db.drop_all() db.create_all() # adding users user = User('adriangohjw', encrypt('password'), 'Adrian Goh') db.session.add(user) # add points point_1 = Point(30.0, 40.0) db.session.add(point_1) point_2 = Point(50.0, 60.0) db.session.add(point_2) # add routes route_1 = Route( user_id=1, distance=10, polyline= 'evfGin%7CwR%5Cf@%60@Zh@Vb@JfBP%60CJtHd@LgBNiCF%7D@YCXBNe@PUr@i@p@c@lDsBj@c@DKJW@Yi@cA%7B@yBg@wAa@aAWaAg@qAoCaH%5BaAWs@k@OOEO?%5DDuEpBoInDo@TMVGREVRhBPbBH~AAzEAdD?XX@nAH~AJ@UAT_BKcCMHcGAcEUkC%5D%7DCEMPGbCaA%60MuFlDaB%60CuAdJuFnAy@r@a@pDuBtEuC%60CqARIZc@%5E%7B@Py@uB%7BH%7BF_TyAcFbAFbCJnD?@GtAWrCy@jAg@xAe@lDwA%7C@i@HSBe@wBuDNGVOfCsAtAs@%60@K@u@ES%7B@wAi@d@o@%5EXh@LLFFBH?ROZGHm@%5CiAh@e@IIKKQIWAW?WGEMGGGESA%5BFg@J%5DZe@TQNGH?%5CBJEMWMU%7B@b@%5BXSXQb@Kp@@l@Pz@j@jARZbAjBx@tAVL%5EFP?vAaAlD_CrCoBzAgAl@_@l@YvBaAbD%7BAnBs@VKlAS@GtAAfCDbAHtAP~Bh@%60A%5E%60Bz@zC~ApBqD%5EaAFo@EqGImG@%7DACWU_AY_AcBj@e@Ls@N_BTw@HaBDkAC%7DJ%5Dk%5Da@cBBa@DmAXeAXsCjAuG~CiCvAi@%60@q@v@U%5EgAxBU%60@SROLWLg@L_AFkA@g@AYCs@Oq@Ye@UcAYo@C%7D@?SZQXIXPtA%60@dBrGfVtBbHhAhEfDjMd@%7CAVv@tApFx@pCsAb@mA%60@wAr@_DpBu@Xs@d@kDpBy@h@aAl@%7DFzDsDhBSl@Kf@G%7C@jA%7CCz@%60CxAdDeBbA_FpCkBhAGHMPKXI~AUdE', purpose='Casual', calories=100, ascent=1, descent=2, startPos_id=1, endPos_id=2) db.session.add(route_1) route_2 = Route( user_id=1, distance=10, polyline= 'evfGin%7CwR%5Cf@%60@Zh@Vb@JfBP%60CJtHd@LgBNiCF%7D@YCXBNe@PUr@i@p@c@lDsBj@c@DKJW@Yi@cA%7B@yBg@wAa@aAWaAg@qAoCaH%5BaAWs@k@OOEO?%5DDuEpBoInDo@TMVGREVRhBPbBH~AAzEAdD?XX@nAH~AJ@UAT_BKcCMHcGAcEUkC%5D%7DCEMPGbCaA%60MuFlDaB%60CuAdJuFnAy@r@a@pDuBtEuC%60CqARIZc@%5E%7B@Py@uB%7BH%7BF_TyAcFbAFbCJnD?@GtAWrCy@jAg@xAe@lDwA%7C@i@HSBe@wBuDNGVOfCsAtAs@%60@K@u@ES%7B@wAi@d@o@%5EXh@LLFFBH?ROZGHm@%5CiAh@e@IIKKQIWAW?WGEMGGGESA%5BFg@J%5DZe@TQNGH?%5CBJEMWMU%7B@b@%5BXSXQb@Kp@@l@Pz@j@jARZbAjBx@tAVL%5EFP?vAaAlD_CrCoBzAgAl@_@l@YvBaAbD%7BAnBs@VKlAS@GtAAfCDbAHtAP~Bh@%60A%5E%60Bz@zC~ApBqD%5EaAFo@EqGImG@%7DACWU_AY_AcBj@e@Ls@N_BTw@HaBDkAC%7DJ%5Dk%5Da@cBBa@DmAXeAXsCjAuG~CiCvAi@%60@q@v@U%5EgAxBU%60@SROLWLg@L_AFkA@g@AYCs@Oq@Ye@UcAYo@C%7D@?SZQXIXPtA%60@dBrGfVtBbHhAhEfDjMd@%7CAVv@tApFx@pCsAb@mA%60@wAr@_DpBu@Xs@d@kDpBy@h@aAl@%7DFzDsDhBSl@Kf@G%7C@jA%7CCz@%60CxAdDeBbA_FpCkBhAGHMPKXI~AUdE', purpose='Casual', calories=200, ascent=1, descent=2, startPos_id=1, endPos_id=2) db.session.add(route_2) db.session.commit()
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'
def test_pointRead(self): self.assertIsNone(pointRead(1)) point = Point(10.0, 20.0) db.session.add(point) db.session.commit() self.assertEqual(pointRead(1).latitude, 10.0)
def test_pointCreate(self): self.assertEqual(len(Point.query.all()), 0) point = Point(10.0, 20.0) # point successfully created self.assertTrue(pointCreate(point)) self.assertEqual(len(Point.query.all()), 1)
def parser(): if request.method == 'POST': longitude = float(request.form['longitude']) latitude = float(request.form['latitude']) polygons = build_polygons() point = Point(longitude, latitude) result = search(polygons, point) return result
def init_db(): # Create the fixtures point = Point(name='John Smith', latitude='0', longitud='0.1', phone='+79000000000') point.save() config = Config(version=1, allowedRadius=1000, isDayPeriodAllowed=True) config.save()
def store_data(): body = request.get_json() smell = body['key1'] taste = body['key2'] latitude = body['key3'] longitude = body['key4'] point = Point(smell = smell, taste = taste, latitude = latitude, longitude = longitude) db.session.add(point) db.session.commit() return body
def read_track(file: str) -> Track: track = Track() with open(file) as f: for i, row in enumerate(csv.DictReader(f)): point = Point(i, float(row['radius']), prev=track.points[-1] if i > 0 else None) track.points.append(point) if point.prev: point.prev.next = point return track
async def gift(session, ctx: commands.context, a: int, b: int): point = session.query(Point).filter_by(owner=str(ctx.author.id)).first() if point is None: point = Point() point.owner = str(ctx.author.id) point.point = 0 session.add(point) gift_point = randint(a, b) point.point += gift_point session.commit() await ctx.reply(f"선물 상자에서 {gift_point}P 를 받았습니다!")
def test_closest_points(self): points_test = [ Point(3, 3), Point(6, 2), Point(5, 6), Point(7, 4), Point(2, 9) ] close_pair_true = (Point(6, 2), Point(7, 4)) self.assertTupleEqual(closest_points(points_test), close_pair_true)
def incoming(request): logging.warning(request.GET) try: # p#, lat, long, timestamp message = request.GET['text'] phone_no, lat, lon, time = message.split(',') p = Point(phone_no=phone_no, lat=float(lat), lon=float(lon), time=datetime.fromtimestamp(float(time))) p.save() post(phone_no, lat, lon, time) except ValueError as err: print "Not Recorded: {}".format(err.args[0]) raise(err) return HttpResponse("RECEIVING SMS")