Example #1
0
def test_create_hosts():
    br = Branch.get_unique(sess, 'ny-prod', compel=True)
    dns_dmn = DnsDomain.get_unique(sess, 'one-nyp.ms.com', compel=True)
    stat = Status.get_unique(sess, 'build', compel=True)
    os = sess.query(OperatingSystem).filter(Archetype.name == 'vmhost').first()
    assert os, 'No OS in %s' % func_name()

    pers = sess.query(Personality).select_from(
        join(Personality, Archetype)).filter(
        and_(Archetype.name=='vmhost', Personality.name=='generic')).one()

    sess.autoflush=False

    for i in xrange(NUM_HOSTS):
        machine = m_factory.next()
        vm_host = Host(machine=machine, name='%s%s' % (HOST_NAME, i),
                       dns_domain=dns_dmn, branch=br, personality=pers,
                       status=stat, operating_system=os)
        add(sess, vm_host)

    sess.autoflush=True

    commit(sess)

    hosts = sess.query(Host).filter(
        Host.name.like(HOST_NAME+'%')).all()
    assert len(hosts) is NUM_HOSTS
    print 'created %s hosts'% len(hosts)
Example #2
0
    def move(self, move):
        '''
        Moves according the direction vectors, if it accelerates, returns the position to put a candy on
        :param move: a (direction, norm) tuple with direction being the tuple encoding the direction
        and norm being 1 for a normal move and 2 for acceleration
        :return: None if the snake didn't accelerate, the position to put a candy on, if it did accelerate
        '''
        norm, direction = move.norm(), move.direction()
        self.on_tail = False
        if norm == 2:
            self.pop()
            before_last_tail = self.pop()
            self.add(utils.add(self.position[0], direction))
            new_head = utils.add(self.position[0], direction)
            if self.onSnake(new_head):
                self.on_tail = True
            self.add(new_head)
            self.removePoints(CANDY_VAL)
            return before_last_tail

        self.pop()
        head = utils.add(self.head(), direction)
        if not utils.isOnGrid(head, self.grid_size):
            print head
            print self.id
            print self.position
            print self.bool_pos
            print self
        if self.onSnake(head):
            self.on_tail = True
        self.add(head)
        return None
Example #3
0
def test_host_in_two_clusters():
    """
        create 2 new clusters and add a host to both. check Host.cluster.
    """
    per = sess.query(Personality).select_from(join(
        Archetype, Personality)).filter(
            and_(Archetype.name == 'windows',
                 Personality.name == 'generic')).one()

    for i in xrange(3):
        ec = EsxCluster(name='%s%s' % (CLUSTER_NAME, i), personality=per)
        add(sess, ec)
    commit(sess)

    c1 = sess.query(EsxCluster).filter_by(name='%s1' % (CLUSTER_NAME)).one()
    c2 = sess.query(EsxCluster).filter_by(name='%s2' % (CLUSTER_NAME)).one()

    assert c1
    assert c2
    print 'clusters in host in 2 cluster test are %s and %s' % (c1, c2)

    host = h_factory.next()

    sess.autoflush = False
    hcm1 = HostClusterMember(host=host, cluster=c1)
    create(sess, hcm1)
    assert host in c1.hosts
    print 'c1 hosts are %s' % (c1.hosts)

    c2.hosts.append(host)
    sess.autoflush = True
    commit(sess)
Example #4
0
def test_create_host_simple():
    for i in xrange(NUM_MACHINES):
        machine = MACHINE_FACTORY.next()
        #create an a_record for the primary name
        name = '%s%s' % (SHORT_NAME_PREFIX, i)

        #convert ip to ipaddr to int, add 1 (router) + i,
        #convert back to ip, then back to string
        #convoluted indeed (FIXME?)
        ip = str(IPAddr(int(IPAddr(NETWORK.ip)) + i +1 ))
        a_rec = FutureARecord.get_or_create(session=sess,
                                      fqdn='%s.ms.com' % name,
                                      ip=ip)

        BRANCH = sess.query(Branch).first()

        # make sure to delete them after (Or put in commit block?)
        sess.refresh(machine)
        host = Host(machine=machine, #primary_name_id=a_rec.id,
                    personality=PRSNLTY, status=STATUS, operating_system=OS,
                    branch=BRANCH)

        add(sess, host)

        pna = PrimaryNameAssociation(a_record_id=a_rec.id,
                                     hardware_entity_id=machine.machine_id)

        add(sess, pna)
        commit(sess)

    hosts = sess.query(Host).all()
    eq_(len(hosts), NUM_MACHINES)
    print 'created %s hosts'% len(hosts)
Example #5
0
    def move(self, move):
        '''
        Moves according the direction vectors, if it accelerates, returns the position to put a candy on
        :param move: a (direction, norm) tuple with direction being the tuple encoding the direction
        and norm being 1 for a normal move and 2 for acceleration
        :return: None if the snake didn't accelerate, the position to put a candy on, if it did accelerate
        '''
        norm, direction = move.norm(), move.direction()
        self.on_tail = False
        if norm == 2:
            self.last_tail = self.position[-2]
            second = utils.add(self.position[0], direction)
            head = utils.add(second, direction)
            self.position = [head, second] + self.position[:-2]
            self.removePoints(CANDY_VAL)
            if head in self.position[1:]:
                self.on_tail = True
            return self.last_tail

        self.last_tail = self.position[-1]
        head = utils.add(self.position[0], direction)
        self.position = [head] + self.position[:-1]
        if head in self.position[1:]:
            self.on_tail = True
        return None
Example #6
0
def test_create_hosts():
    br = Branch.get_unique(sess, 'ny-prod', compel=True)
    dns_dmn = DnsDomain.get_unique(sess, 'one-nyp.ms.com', compel=True)
    stat = Status.get_unique(sess, 'build', compel=True)
    os = sess.query(OperatingSystem).filter(Archetype.name == 'vmhost').first()
    assert os, 'No OS in %s' % func_name()

    pers = sess.query(Personality).select_from(join(
        Personality, Archetype)).filter(
            and_(Archetype.name == 'vmhost',
                 Personality.name == 'generic')).one()

    sess.autoflush = False

    for i in xrange(NUM_HOSTS):
        machine = m_factory.next()
        vm_host = Host(machine=machine,
                       name='%s%s' % (HOST_NAME, i),
                       dns_domain=dns_dmn,
                       branch=br,
                       personality=pers,
                       status=stat,
                       operating_system=os)
        add(sess, vm_host)

    sess.autoflush = True

    commit(sess)

    hosts = sess.query(Host).filter(Host.name.like(HOST_NAME + '%')).all()
    assert len(hosts) is NUM_HOSTS
    print 'created %s hosts' % len(hosts)
Example #7
0
def test_host_in_two_clusters():
    """
        create 2 new clusters and add a host to both. check Host.cluster.
    """
    per = sess.query(Personality).select_from(
            join(Archetype, Personality)).filter(
            and_(Archetype.name=='windows', Personality.name=='generic')).one()

    for i in xrange(3):
        ec = EsxCluster(name='%s%s'% (CLUSTER_NAME, i), personality=per)
        add(sess, ec)
    commit(sess)

    c1 = sess.query(EsxCluster).filter_by(name='%s1' % (CLUSTER_NAME)).one()
    c2 = sess.query(EsxCluster).filter_by(name='%s2' % (CLUSTER_NAME)).one()

    assert c1
    assert c2
    print 'clusters in host in 2 cluster test are %s and %s'% (c1, c2)

    host = h_factory.next()


    sess.autoflush = False
    hcm1 = HostClusterMember(host=host, cluster=c1)
    create(sess, hcm1)
    assert host in c1.hosts
    print 'c1 hosts are %s'% (c1.hosts)

    c2.hosts.append(host)
    sess.autoflush = True
    commit(sess)
Example #8
0
def test_whitespace_padding():
    a=StringTbl(name='  some eXTRa space     ')
    add(s, a)
    commit(s)

    p = StringTbl.__table__.select().execute().fetchall()[1]
    assert p['name'].startswith('s'), 'Whitespace not stripped in AqStr'
    print a
Example #9
0
def test_whitespace_padding():
    a = StringTbl(name='  some eXTRa space     ')
    add(s, a)
    commit(s)

    p = StringTbl.__table__.select().execute().fetchall()[1]
    assert p['name'].startswith('s'), 'Whitespace not stripped in AqStr'
    print a
Example #10
0
def test_valid_aqstr():
    a = StringTbl(name='Hi there')
    add(s, a)
    commit(s)

    s.expunge_all()
    rec = s.query(StringTbl).first()
    print rec.name
    assert rec.name == 'hi there', 'String not lowercase in AqStr'
Example #11
0
def test_valid_aqstr():
    a = StringTbl(name='Hi there')
    add(s, a)
    commit(s)

    s.expunge_all()
    rec = s.query(StringTbl).first()
    print rec.name
    assert rec.name == 'hi there', 'String not lowercase in AqStr'
Example #12
0
    def test_add(self):
        """Expectation: add two numbers using correct template"""
        with self.subTest("Testing add() using ints"):
            computed = utils.add(self.i3, self.i4)
            self.assertIsInstance(computed, int)
            self.assertEqual(computed, int(3 + 4))

        with self.subTest("Testing add() using floats"):
            computed = utils.add(self.f3, self.f4)
            self.assertIsInstance(computed, float)
            self.assertEqual(computed, self.f3 + self.f4)
Example #13
0
def test_no_host_threshold():
    """ ensure down_hosts_threshold must exist """
    br = Branch.get_unique(sess, 'ny-prod', compel=True)
    np = Building.get_unique(sess, name='np', compel=True)

    per = sess.query(Personality).select_from(
            join(Archetype, Personality)).filter(
            and_(Archetype.name=='windows', Personality.name=='generic')).one()

    ec = EsxCluster(name=CLUSTER_NAME,
                    location_constraint=np, personality=per, branch=br)
    add(sess, ec)
    commit(sess)
Example #14
0
def check_and_add(subdomains):
    new_subdomains = {}
    for c,j in enumerate(subdomains):
        if not utils.exists(j):
            live = checks.check_if_live(j)
            if live:
                utils.add(j, live=True, cname="")
                new_subdomains[c] = {"subdomain":j,"title":live}
            else:
                utils.add(j, live=False, cname="")
                new_subdomains[c] = {"subdomain":j,"title":""}


    return new_subdomains
Example #15
0
def test_create_local_disk():
    """ create a local disk """
    print 'setup finished'
    machine = add_machine(sess, MACHINE_NAME, MODEL)
    assert machine, "Could not create machine in %s"% (inspect.stack()[1][3])
    print machine

    disk = LocalDisk(machine=machine, capacity=180, controller_type='scsi')
    add(sess, disk)
    commit(sess)

    assert disk, 'no disk created by %s'% (inspect.stack()[1][3])
    print disk
    disk_id_cache.append(disk.id)
Example #16
0
    def make_game_state(self, rng: SeededRandomNumberGenerator) -> GameState:
        enemy_goal_center: Vector3 = Vector3(0, 5120 * self.team, 93)
        car_spawn_block: utils.Area = utils.RectPrism(Vector3(0, 0, 17), 8000,
                                                      8000, 0)
        car_loc: Vector3 = car_spawn_block.random_point_inside(rng)
        car_facing: Rotator = utils.rotator_from_dir(
            sub(enemy_goal_center, car_loc))
        relative: Vector3 = sub(enemy_goal_center, car_loc)
        #Spawn the ball halfway between us and the enemy goal
        ball_loc: Vector3 = add(
            car_loc, Vector3(relative.x / 2, relative.y / 2, relative.z / 2))
        ball_loc.z = 93

        return GameState(
            ball=BallState(physics=Physics(location=ball_loc,
                                           velocity=Vector3(0, 0, 0),
                                           angular_velocity=Vector3(0, 0, 0))),
            cars={
                0:
                CarState(physics=Physics(location=car_loc,
                                         rotation=car_facing,
                                         velocity=Vector3(0, 0, 0),
                                         angular_velocity=Vector3(0, 0, 0)),
                         boost_amount=33),
            },
            boosts={i: BoostState(0)
                    for i in range(34)},
        )
Example #17
0
def test_no_host_threshold():
    """ ensure down_hosts_threshold must exist """
    br = Branch.get_unique(sess, 'ny-prod', compel=True)
    np = Building.get_unique(sess, name='np', compel=True)

    per = sess.query(Personality).select_from(join(
        Archetype, Personality)).filter(
            and_(Archetype.name == 'windows',
                 Personality.name == 'generic')).one()

    ec = EsxCluster(name=CLUSTER_NAME,
                    location_constraint=np,
                    personality=per,
                    branch=br)
    add(sess, ec)
    commit(sess)
Example #18
0
def idcadd():
    if request.method == 'GET':
        users = utils.select_one('user', user_fields)['result']
        return render_template('idcadd.html',users=users, info=session, role=session.get('role'))
    data = {k:v[0] for k,v in dict(request.form).items()}
    if utils.add('idc',data):
        return json.dumps({'code':1,'result':'add user success'})
Example #19
0
    def startState(self):
        """
        Initialize a game with `n_snakes` snakes of size 2, randomly assigned to different locations of the grid,
        and `n_candies` candies, randomly located over the grid.
        Guarantees a valid state.
        """

        n_squares_per_row = int(math.ceil(math.sqrt(self.n_snakes))**2)
        square_size = self.grid_size / int(n_squares_per_row)
        assignment = random.sample(range(n_squares_per_row**2), self.n_snakes)

        assert self.grid_size >= 3 * n_squares_per_row

        snakes = {}
        for snake, assign in enumerate(assignment):
            head = (random.randint(1, square_size - 2) +
                    (assign / n_squares_per_row) * square_size,
                    random.randint(1, square_size - 2) +
                    (assign % n_squares_per_row) * square_size)
            snakes[snake] = newSnake(
                [head, utils.add(head,
                                 random.sample(DIRECTIONS, 1)[0])], snake)

        candies_to_put = 2 * int(self.candy_ratio) + 1
        start_state = State(snakes, {})
        start_state.addNRandomCandies(candies_to_put, self.grid_size)
        return start_state
Example #20
0
def test_add_machines():
    a = sess.query(MachineClusterMember).all()
    if a:
        print '%s machines are already in existence'

    machines = sess.query(Machine).filter(Machine.label.like(VM_NAME+'%')).all()
    ec = EsxCluster.get_unique(sess, CLUSTER_NAME)
    assert ec

    sess.autoflush=False
    for vm in machines[0:10]:
        mcm = MachineClusterMember(cluster=ec, machine=vm)
        add(sess, mcm)
    commit(sess)
    sess.autoflush=True

    assert len(ec.machines) is 10
    print 'there are %s machines in the cluster: %s'%(len(ec.machines), ec.machines)
Example #21
0
def test_create_nas_disk():
    svc = add_service(sess, NAS_SVC)
    assert svc, 'no %s service created by %s' %(NAS_SVC, inspect.stack()[1][3])

    si = add_service_instance(sess, NAS_SVC, SHARE_NAME)
    assert si, 'no instance created in %s'% (inspect.stack()[1][3])

    machine = add_machine(sess, MACHINE_NAME, MODEL)
    assert machine, "Could not create machine in %s"% (inspect.stack()[1][3])
    print machine

    disk = NasDisk(machine=machine, capacity=40, controller_type='sata',
            device_name='c_drive', address='0:1:0', service_instance=si)
    add(sess, disk)
    commit(sess)

    assert disk, 'no nas disk created in %s'% (inspect.stack()[1][3])
    print disk
    disk_id_cache.append(disk.id)
Example #22
0
    def move(self, move):
        if (not self.is_active() or not self.is_move_valid(move)):
            return False

        new_pos = utils.add(self._current_position, move)
        self._current_position = new_pos

        if (self._current_position == self._finish_position):
            self._is_solved = True
            self._is_over = True
Example #23
0
	def move( self, move):
		if( not self.is_active() or not self.is_move_valid( move)):
			return False

		new_pos = utils.add( self._current_position, move)
		self._current_position = new_pos

		if( self._current_position == self._finish_position):
			self._is_solved = True
			self._is_over = True
Example #24
0
 def cal_camera(p, p1, p2, p3, extra_height=80):
     """Calculate the position and orientation of photographing according to a center point p and other three
     points."""
     plane = plane_from_3_points(p1, p2, p3)
     intersection = intersection_of_line_and_plane(p, [0, 0, -1], p1,
                                                   plane[:-1])
     is_convex_surface = True if p[2] - intersection[2] <= 0 else False
     if is_convex_surface:
         camera_pos = add(p, [0, 0, -1 * extra_height])
     else:
         d = distance(p, intersection)
         if d < extra_height / 2:
             camera_pos = add(p, [0, 0, -1 * extra_height])
         else:
             camera_pos = add(p, [0, 0, -2 * d])
     camera = vector_to_yaw_and_pitch(
         angular_bisector(camera_pos, p1, p2, p3))
     camera.update({"position": camera_pos})
     return camera
Example #25
0
def add_machine(sess, name, model=MODEL):
    """ Shorthand to create machines created for the purposes of reuse
        among all the various tests that require them """
    mchn = sess.query(Machine).filter_by(label=name).first()
    if mchn:
        return mchn

    model = Model.get_unique(sess, name=model, compel=True)

    proc = sess.query(Cpu).first()
    assert proc, "Can't find a cpu"

    rack = sess.query(Rack).first()
    assert rack, "Can't find a rack"

    mchn = Machine(label=name, model=model, location=rack, cpu=proc)
    add(sess, mchn)
    commit(sess)

    return mchn
Example #26
0
def test_add_machines():
    a = sess.query(MachineClusterMember).all()
    if a:
        print '%s machines are already in existence'

    machines = sess.query(Machine).filter(Machine.label.like(VM_NAME +
                                                             '%')).all()
    ec = EsxCluster.get_unique(sess, CLUSTER_NAME)
    assert ec

    sess.autoflush = False
    for vm in machines[0:10]:
        mcm = MachineClusterMember(cluster=ec, machine=vm)
        add(sess, mcm)
    commit(sess)
    sess.autoflush = True

    assert len(ec.machines) is 10
    print 'there are %s machines in the cluster: %s' % (len(
        ec.machines), ec.machines)
Example #27
0
def add_machine(sess, name, model=MODEL):
    """ Shorthand to create machines created for the purposes of reuse
        among all the various tests that require them """
    mchn = sess.query(Machine).filter_by(label=name).first()
    if mchn:
        return mchn

    model = Model.get_unique(sess, name=model, compel=True)

    proc = sess.query(Cpu).first()
    assert proc, "Can't find a cpu"

    rack = sess.query(Rack).first()
    assert rack, "Can't find a rack"

    mchn = Machine(label=name, model=model, location=rack, cpu=proc)
    add(sess, mchn)
    commit(sess)

    return mchn
Example #28
0
def useradd():
    if request.method == 'GET':
        return render_template('add.html', role=session.get('role'))
    if request.method == 'POST':
        data = dict((k, v[0]) for k, v in dict(request.form).items())
        l = []
        for i in utils.list('user', fields):
            l.append(i['name'])
        if not data['name']:
            return json.dumps({'code': 1, 'errmsg': 'name can not be null'})
        elif not data['password']:
            return json.dumps({
                'code': 1,
                'errmsg': 'password can not be null'
            })
        elif data['name'] in l:
            return json.dumps({'code': 1, 'errmsg': 'username is exist'})
        else:
            conditions = ["%s='%s'" % (k, v) for k, v in data.items()]
            utils.add('user', conditions)
            return json.dumps({'code': 0, 'result': 'add user success'})
Example #29
0
    def updateW(self):
        # reset the misclass sum vector
        wnew = [0] * self.d

        # Update vector
        for d in range(self.d):
            #Δw_i = -η * ∂/∂w_i
            wnew[d] = -self.rate * self.data.ddwi(self.w, d)
        #w(t+1) = w(t) + Δw
        self.w = utils.add(self.w, wnew)
        self.updates += 1
        self.deltaError = self.getError() - self.last_error
        self.last_error += self.deltaError
Example #30
0
def test_create_clusters():
    np = sess.query(Building).filter_by(name='np').one()
    br = Branch.get_unique(sess, 'ny-prod', compel=True)

    per = sess.query(Personality).select_from(
            join(Archetype, Personality)).filter(
            and_(Archetype.name == 'windows',
                Personality.name == 'generic')).one()

    for i in xrange(NUM_CLUSTERS):
        ec = EsxCluster(name='%s%s' % (CLUSTER_NAME, i),
                        location_constraint=np, branch=br,
                        personality=per, down_hosts_threshold=2)
        add(sess, ec)
    commit(sess)

    ecs = sess.query(EsxCluster).all()
    assert len(ecs) is NUM_CLUSTERS
    print ecs[0]

    assert ecs[0].max_hosts is 8
    print 'esx cluster max hosts = %s' % (ecs[0].max_hosts)
Example #31
0
    def run(self):
        while True:
            new_subdomain = self.q.get()
            try:
                exist = utils.exists(new_subdomain)
                if not exist:
                    live = checks.check_if_live(new_subdomain)
                    if isinstance(live,str):
                        wappa = checks.analyze_wappalyzer("https://" + new_subdomain)
                        wappa_string = ', '.join(wappa)
                        takeover = checks.takeover(new_subdomain)
                        utils.add(new_subdomain, live=True, cname=takeover)
                        utils.send(new_subdomain + "\n" + live + "\n " + wappa_string + "\n" + takeover)
                    else:
                        utils.add(new_subdomain, live=False, cname="")
                        utils.send(new_subdomain)

                logger.info("Domain " + new_subdomain + " has been sucessfully added")


            except Exception as e:
                logger.exception("Subdomain found but an error occured while processing: %s " % new_subdomain)
            finally:
                self.q.task_done()
Example #32
0
    def updateW(self):
        # reset the misclass sum vector
        wnew = [0] * self.d
        self.gradient = 0

        # Update vector
        for i in range(self.d):
            # Δw_i = -η * ∂/∂w_i
            partial = self.data.ddwi(self.w, i) + (2 * self.ridge * self.w[i])
            wnew[i] = -self.rate * partial
            self.gradient += partial**2
        # w(t+1) = w(t) + Δw
        self.w = utils.add(self.w, wnew)
        self.updates += 1
        self.gradient = math.sqrt(self.gradient)
Example #33
0
def test_create_host_simple():
    for i in xrange(NUM_MACHINES):
        machine = MACHINE_FACTORY.next()
        #create an a_record for the primary name
        name = '%s%s' % (SHORT_NAME_PREFIX, i)

        #convert ip to ipaddr to int, add 1 (router) + i,
        #convert back to ip, then back to string
        #convoluted indeed (FIXME?)
        ip = str(IPAddr(int(IPAddr(NETWORK.ip)) + i + 1))
        a_rec = FutureARecord.get_or_create(session=sess,
                                            fqdn='%s.ms.com' % name,
                                            ip=ip)

        BRANCH = sess.query(Branch).first()

        # make sure to delete them after (Or put in commit block?)
        sess.refresh(machine)
        host = Host(
            machine=machine,  #primary_name_id=a_rec.id,
            personality=PRSNLTY,
            status=STATUS,
            operating_system=OS,
            branch=BRANCH)

        add(sess, host)

        pna = PrimaryNameAssociation(a_record_id=a_rec.id,
                                     hardware_entity_id=machine.machine_id)

        add(sess, pna)
        commit(sess)

    hosts = sess.query(Host).all()
    eq_(len(hosts), NUM_MACHINES)
    print 'created %s hosts' % len(hosts)
Example #34
0
    def dictExtractor(self, state, action):
        if action is None:
            return [('trapped', 1.)]

        if action.norm() == 1:
            agent = state.snakes[self.id]
            # pretend agent moves with action
            last_tail = agent.position.pop()
            agent.position.appendleft(
                utils.add(agent.head(), action.direction()))
        else:
            agent = deepcopy(state.snakes[self.id])
            agent.move(action)

        head = agent.head()
        dir_ = agent.orientation()

        def relPos(p):
            return self.relativePos(head, p, dir_)

        features = [(('candy', v, relPos(c)), 1.)
                    for c, v in state.candies.iteritems()
                    if utils.dist(head, c) < self.radius]
        features += [
            (('adv-head', relPos(s.head())), 1.)
            for k, s in state.snakes.iteritems()
            if k != self.id and utils.dist(head, s.head()) < self.radius
        ]
        features += [
            (('adv-tail', relPos(s.position[i])), 1.)
            for k, s in state.snakes.iteritems()
            for i in xrange(1, len(s.position))
            if k != self.id and utils.dist(head, s.position[i]) < self.radius
        ]
        features += [
            (('my-tail', relPos(state.snakes[self.id].position[i])), 1.)
            for i in xrange(1, len(state.snakes[self.id].position)) if
            utils.dist(head, state.snakes[self.id].position[i]) < self.radius
        ]
        features += [(('x', min(head[0], state.grid_size - 1 - head[0])), 1.),
                     (('y', min(head[1], state.grid_size - 1 - head[1])), 1.)]

        # revert changes
        if action.norm() == 1:
            agent.position.popleft()
            agent.position.append(last_tail)

        return features
Example #35
0
def register():
    if request.method=="GET":
    	return render_template("register.html", taken = False, success = False)
    if request.method=="POST":
        button = request.form['button']
        username=request.form['username']
        password=request.form['password']
        if button=="Register":
        	response = utils.add(username,password)
        	if response == "taken":
        		return render_template("register.html", taken = True, success = False)
        	elif response == "success":
        		return render_template("register.html", taken = False, success = True)
        	else:
        		return "Wrong combo"
        else:
            return "bye"
Example #36
0
def register():
    if request.method == "GET":
        return render_template("register.html", taken=False, success=False, s=session)
    if request.method == "POST":
        button = request.form["button"]
        username = request.form["username"]
        password = request.form["password"]
        if button == "Register":
            response = utils.add(username, password)
            print response
            if response == "taken":
                return render_template("register.html", taken=True, success=False, s=session)
            elif response == "success":
                return render_template("register.html", taken=False, success=True, s=session)
            else:
                return "Wrong combo"
        else:
            return "bye"
Example #37
0
def signup():
    if request.method == "GET":
        return render_template("signup.html")
    else:
        username = request.form['username']
        password = request.form['password']
        bio = request.form['bio']
        button = request.form['button']
        if button == "cancel":
            return redirect(url_for("home"))
        if utils.add(username, password):
            f = open(username + ".html", 'w')
            message = "<html> <h1> " + username + "</h1> " + bio + "</html>"
            f.write(message)
            f.flush()
            return render_template("signedup.html")
        else:
            error = "Bad username or password -> Password must be more than 4 characters"
            return render_template("signup.html", err = error)
Example #38
0
def signup():
    if request.method == "GET":
        return render_template("signup.html")
    else:
        username = request.form['username']
        password = request.form['password']
        bio = request.form['bio']
        button = request.form['button']
        if button == "cancel":
            return redirect(url_for("home"))
        if utils.add(username, password):
            f = open(username + ".html", 'w')
            message = "<html> <h1> " + username + "</h1> " + bio + "</html>"
            f.write(message)
            f.flush()
            return render_template("signedup.html")
        else:
            error = "Bad username or password -> Password must be more than 4 characters"
            return render_template("signup.html", err=error)
Example #39
0
def register():
    if request.method == "GET":
        return render_template("register.html", taken=False, success=False)
    if request.method == "POST":
        button = request.form['button']
        username = request.form['username']
        password = request.form['password']
        if button == "Register":
            response = utils.add(username, password)
            if response == "taken":
                return render_template("register.html",
                                       taken=True,
                                       success=False)
            elif response == "success":
                return render_template("register.html",
                                       taken=False,
                                       success=True)
            else:
                return "Wrong combo"
        else:
            return "bye"
Example #40
0
def main():
    print(add(2, 3))
    print(retrieve_even_number([1, 2, 3, 4, 5]))
Example #41
0
def main():
    print(add(2, 3))
    print(utils.add(2, 3))
# python import module example
import utils

print(utils.add(10,10))
print(utils.uppercase('java'))

# python import as
import utils as u

print(u.add(10,10))
print(u.uppercase('java'))

# python import from another directory
# Refer: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
# Refer: https://stackoverflow.com/questions/4383571/importing-files-from-different-folder
import importlib, importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

strutils = module_from_file("strutils", "../mymodule/strutils.py")

print(strutils.uppercase('java'))
print(strutils.lowercase('DATA'))

#python import class from another file
mc = module_from_file("myclasses", "../mymodule/myclasses.py")
Example #43
0
from webob import exc
from webob.dec import wsgify
from routes.middleware import RoutesMiddleware
from routes import Mapper
import utils


@wsgify
def add(request):
    match = request.urlvars
    try:
        a, b = int(match['a']), int(match['b'])
    except Exception, e:
        raise exc.HTTPBadRequest(str(e))

    return Response(str(utils.add(a, b)), content_type="text/plain")


resources = {}
resources['add'] = add
mapper = Mapper()

mapper.connect(None, "/add/{a},{b}", resource="add")

@wsgify
def front(request):
    match = request.urlvars
    if match:
        resource = resources[match['resource']]

        return request.get_response(resource)
Example #44
0
from utils import add

add('lib')

import httplib2
import csv

from apiclient.discovery import build as discovery_build
from GCSIterator import GCSIterator
from oauth2client.client import GoogleCredentials


def get_authenticated_service():
  credentials = GoogleCredentials.get_application_default()
  http = credentials.authorize(httplib2.Http())
  return discovery_build('storage', 'v1', http=http)


gcs_service = get_authenticated_service()
bucket_name = '<your-bucket-name>'
object_name = '<your-object-name>'

request = gcs_service.objects().get_media(bucket=bucket_name, object=object_name.encode('utf8'))
iterator = GCSIterator(request, chunksize=512)

reader = csv.DictReader(iterator, skipinitialspace=True, delimiter=',')
for row in reader:
  print row
Example #45
0
PRSNLTY = Personality.get_unique(sess, name='generic', archetype=ARCH)
assert isinstance(PRSNLTY, Personality), 'no personality @ %s' % func_name()

NETWORK = sess.query(Network).filter(Network.cidr < 31).first()
assert isinstance(NETWORK, Network), 'no network in %s' % func_name()

DNS_DOMAIN = DnsDomain.get_unique(sess, DNAME)
assert isinstance(DNS_DOMAIN, DnsDomain), 'no dns domain @ %s' % func_name()

BRANCH = sess.query(Branch).first()
if not BRANCH:
    BRANCH = Branch(branch_type='domain', name='ny-prod', is_sync_valid=1,
                    compiler='/ms/dist/elfms/PROJ/panc/prod/lib/panc.jar',
                    autosync=1, owner_id=1)
    add(sess, BRANCH)
    commit(sess)
    print BRANCH


def teardown():
    #print '%s.teardown()' % func_name()

    a_records = sess.query(FutureARecord).filter(
        FutureARecord.name.like(SHORT_NAME_PREFIX+'%')).all()

    for rec in a_records:
        # this means that deleting the PNA deletes the host table.
        # is that how we want it? Yes, we don't know what it is without it.
        pna = sess.query(PrimaryNameAssociation).filter_by(a_record=rec).first()
        if pna:
Example #46
0
def testWithExtraSpaces():
    """ test strip and lower case"""
    a = Rack(name='r3', fullname='r3', rack_row='  BaZ  ')
    add(s, a)
    commit(s)
    assert a.rack_row == 'baz'
Example #47
0
def testWithBangCharacter():
    """ test invalid characters"""
    a = Rack(name='r2', fullname='r2', rack_column='bar!!!')
    add(s, a)
    commit(s)
    assert a.name
Example #48
0
	def is_move_valid( self, move):
		new_pos = utils.add( self._current_position, move)
		if( self._grid.contains_pos( new_pos)):
			if( not self.is_obstacle( new_pos)):
				return True
		return False
Example #49
0
def testNormalInput():
    """ test valid rack characters """
    a = Rack(name='r1', fullname='r1', rack_row='FOO')
    add(s, a)
    commit(s)
    assert a.rack_row == 'foo', 'valid input lowercased'
Example #50
0
# python import module example
import utils

print(utils.add(10, 10))
print(utils.uppercase('java'))

# python import as
import utils as u

print(u.add(10, 10))
print(u.uppercase('java'))

# python import from another directory
# Refer: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
# Refer: https://stackoverflow.com/questions/4383571/importing-files-from-different-folder
import importlib, importlib.util


def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


strutils = module_from_file("strutils", "../mymodule/strutils.py")

print(strutils.uppercase('java'))
print(strutils.lowercase('DATA'))

#python import class from another file
Example #51
0
def generate_100_sums():
    for i in range(100):
        print utils.add(i, i+1)