Example #1
0
 def __init__(self, config):
     super(OS2OSFerry, self).__init__(config)
     resources = {
         'identity': keystone.KeystoneIdentity,
         'image': glance_image.GlanceImage,
         'storage': cinder_storage.CinderStorage,
         'network': neutron.NeutronNetwork,
         'compute': nova_compute.NovaCompute,
         'objstorage': swift_storage.SwiftStorage
     }
     self.src_cloud = cloud.Cloud(resources, cloud.SRC, config)
     self.dst_cloud = cloud.Cloud(resources, cloud.DST, config)
     self.src_cloud.migration = {
         resource: migration.Migration(self.src_cloud, self.dst_cloud,
                                       resource)
         for resource in resources
     }
     self.dst_cloud.migration = {
         resource: migration.Migration(self.src_cloud, self.dst_cloud,
                                       resource)
         for resource in resources
     }
     self.init = {
         'src_cloud': self.src_cloud,
         'dst_cloud': self.dst_cloud,
         'cfg': self.config,
     }
     self.scenario = None
Example #2
0
def next_level():
    global flowers, bullets, level, level_text_brightness, clouds, bees, num_bees, baske, ba

    level += 1

    player1.level_up(level)

    ba = basket.Basket()
    baske = []

    clouds = []
    for i in range(random.randint(4,8)):
        clouds.append(cloud.Cloud(screen_size))

    flowers = []
    for i in range(2*level):
        flowers.append(flower.Flower([
            random.randint(0,screen_size[0]),
            random.randint(0,screen_size[1])
        ]))

    bees = []
    for i in range(num_bees):
        bees.append(bee.Bee(screen_size))
    if level%7 == 0:
        num_bees += 1

    level_text_brightness = 1.0
Example #3
0
    def test_not_allowed(self):
        """Does the auth module prevent access in the correct circumstances?"""
        self.db.rename('fancy')

        table = self.db.create_table('owner', [{
            'name': 'boffo',
            'datatype': Text
        }])
        table2 = self.db.create_table('gungy', [{
            'name': 'boffo',
            'datatype': Text
        }])
        view = self.db.create_view('stinky', {'objid': table})

        table.rename('frango')
        view.rename('spangy')
        col = self.db.Column(table2.columns()[0])
        col.modify({'datatype': 'Float'})

        if target == 'rest':
            bad_cloud = cc.connect("http://localhost:5000", cfg.b)
        elif target == 'local':
            bad_cloud = cc.Cloud(cfg.b)

        bad_db = bad_cloud.Database(self.db)
        with self.assertRaises(cc.NotAuthorized):
            bad_db.rename('gorgo')

        with self.assertRaises(cc.NotAuthorized):
            bad_db.create_table('gorgo', [])

        with self.assertRaises(cc.NotAuthorized):
            bad_db.drop()

        bad_table = bad_cloud.Table(table)
        with self.assertRaises(cc.NotAuthorized):
            bad_table.rename('boofkins')

        with self.assertRaises(cc.NotAuthorized):
            bad_table.add_columns([{'name': 'boofkins', 'datatype': 'Text'}])

        with self.assertRaises(cc.NotAuthorized):
            bad_table.drop()

        bad_view = bad_cloud.View(view)
        with self.assertRaises(cc.NotAuthorized):
            bad_view.rename('lily')

        with self.assertRaises(cc.NotAuthorized):
            bad_view.drop()

        bad_col = bad_cloud.Column(col)
        with self.assertRaises(cc.NotAuthorized):
            bad_col.rename('lacdulac')

        with self.assertRaises(cc.NotAuthorized):
            bad_col.modify('Integer')

        with self.assertRaises(cc.NotAuthorized):
            bad_col.drop()
Example #4
0
 def __init__(self, config):
     super(OS2OSFerry, self).__init__(config)
     resources = {
         'identity': keystone.KeystoneIdentity,
         'image': glance_image.GlanceImage,
         'storage': cinder_storage.CinderStorage,
         'network': neutron.NeutronNetwork,
         'compute': nova_compute.NovaCompute
     }
     self.src_cloud = cloud.Cloud(resources, cloud.SRC, config)
     self.dst_cloud = cloud.Cloud(resources, cloud.DST, config)
     self.init = {
         'src_cloud': self.src_cloud,
         'dst_cloud': self.dst_cloud,
         'cfg': self.config
     }
Example #5
0
    def tearDown(self):
        """Drop the database."""

        if target == 'rest':
            cloud = cc.connect("http://localhost:5000", cfg.user)
        elif target == 'local':
            cloud = cc.Cloud(cfg.user)

        cloud.Database(self.db).drop()
Example #6
0
 def __init__(self, width, height):
     self.mWidth = width
     self.mHeight = height
     self.mBlueSky = sky.Sky(self.mWidth, self.mHeight)
     self.mGround = ground.Ground(self.mWidth, self.mHeight)
     self.mMountain = mountain.Mountain(self.mWidth, self.mHeight)
     self.mMoon = moon.Moon(self.mWidth, self.mHeight)
     self.mWater = water.Water(self.mWidth, self.mHeight)
     self.mHouse = house.House(self.mWidth, self.mHeight)
     self.mCloud = cloud.Cloud(self.mWidth, self.mHeight)
     self.mBird = bird.Bird(self.mWidth, self.mHeight)
Example #7
0
def upload_file_cloud(f, username, password):
    if not 'CloudApp' in PROTO_LIST:
        print 'Error: CloudApp not supported'
    try:
        mycloud = cloud.Cloud()
        mycloud.auth(username, password)
        result = mycloud.upload_file(f)
        data = {'original_image': result['url']}
        return True, data
    except cloud.CloudException as e:
        return False, e.message
Example #8
0
 def populateBackground(self):
     while len(self.clouds) < 15:
         self.clouds.append(
             cloud.Cloud(
                 pygame.image.load("images/cloud{}.png".format(
                     random.randrange(1, 9))),
                 (random.randrange(0,
                                   self.surface.get_rect().width),
                  random.randrange(0,
                                   self.surface.get_rect().height)),
                 random.randrange(1, 4)))
Example #9
0
	def __init__(self, width, height):
		self.mWidth = width
		self.mHeight = height

		self.mSun = sun.Sun( (247, 238, 101), 175, 125, 50)
		self.mSky = rect.Rect((101, 233, 247), 0, 0, 900, 450)
		self.mGrass = rect.Rect((86, 219, 110), 0, 450, 900, 350)
		self.mTree1 = tree.Tree((143, 102, 26), (71, 153, 17), 650, 325, 75, 125)
		self.mTree2 = tree.Tree((168, 141, 50), (168, 50, 100), 800, 375, 50, 75)
		adult = 'adult'
		child = 'child'
		self.mParent1 = person.Person(adult, 225, 300 )
		self.mParent2 = person.Person(adult, 100, 300)
		self.mChild1 = person.Person(child, 350, 350)
		self.mChild2 = person.Person(child, 450, 350)
		self.mChild3 = person.Person(child, 550, 350)
		self.mCloud1 = cloud.Cloud(400, 50, 150, 100)
		self.mCloud2 = cloud.Cloud(650, 70, 200, 100)
		self.mBlanket = blanket.Blanket((219, 50, 107), 100, 500, 350, 150)
		return
Example #10
0
 def add_cloud(self):
     temp = random.randint(1, 100)
     if temp > 96 or len(self.clouds) == 0:
         if temp > 99:
             front_back = 'front'
         else:
             front_back = 'back'
         cloud_type = random.choice(self.cloud_types)
         self.clouds.append(
             cloud.Cloud(self.screen_width, self.screen_height, cloud_type,
                         front_back))
Example #11
0
 def __init__(self, config):
     super(OS2OSFerry, self).__init__(config)
     resources = {
         'identity': keystone.KeystoneIdentity,
         'image': glance_image.GlanceImage,
         'storage': cinder_storage.CinderStorage,
         'network': neutron.NeutronNetwork,
         'compute': nova_compute.NovaCompute,
         'objstorage': swift_storage.SwiftStorage
     }
     self.src_cloud = cloud.Cloud(resources, cloud.SRC, config)
     self.dst_cloud = cloud.Cloud(resources, cloud.DST, config)
     self.init = {
         'src_cloud': self.src_cloud,
         'dst_cloud': self.dst_cloud,
         'cfg': self.config,
         'SSHCephToCeph': ssh_ceph_to_ceph.SSHCephToCeph,
         'SSHCephToFile': ssh_ceph_to_file.SSHCephToFile,
         'SSHFileToFile': ssh_file_to_file.SSHFileToFile,
         'SSHFileToCeph': ssh_file_to_ceph.SSHFileToCeph
     }
Example #12
0
 def __init__(self, config):
     super(OS2OSFerry, self). __init__(config)
     resources = {'identity': keystone.KeystoneIdentity,
                  'image': glance_image.GlanceImage,
                  'storage': utl.import_class_by_string(
                      config.migrate.cinder_migration_strategy),
                  'network': neutron.NeutronNetwork,
                  'compute': nova_compute.NovaCompute,
                  'objstorage': swift_storage.SwiftStorage}
     self.src_cloud = cloud.Cloud(resources, cloud.SRC, config)
     self.dst_cloud = cloud.Cloud(resources, cloud.DST, config)
     self.init = {
         'src_cloud': self.src_cloud,
         'dst_cloud': self.dst_cloud,
         'cfg': self.config,
         'SSHCephToCeph': ssh_ceph_to_ceph.SSHCephToCeph,
         'SSHCephToFile': ssh_ceph_to_file.SSHCephToFile,
         'SSHFileToFile': ssh_file_to_file.SSHFileToFile,
         'SSHFileToCeph': ssh_file_to_ceph.SSHFileToCeph,
         'CopyFilesBetweenComputeHosts':
             ssh_chunks.CopyFilesBetweenComputeHosts,
     }
    def __init__(self):
        # create game objects
        self.block = blocky.Block(50, 400, 38)
        self.cactusSprites = pygame.sprite.Group()
        self.cloudSprites = pygame.sprite.Group()
        self.allsprites = pygame.sprite.Group([self.block])

        self.cactus1 = cactus.Cactus(randrange(800, 1600), 370)
        self.cactus2 = cactus.Cactus(randrange(800, 1600), 370)
        self.cactus3 = cactus.Cactus(randrange(800, 1600), 370)
        self.cactusSprites.add(self.cactus1, self.cactus2, self.cactus3)

        # create 2 clouds
        # cloud1 will lag behind cloud2 in a set pattern
        self.cloud1 = cloud.Cloud(1900, 200)
        self.cloud2 = cloud.Cloud(1800, 250)
        self.cloudSprites.add(self.cloud1, self.cloud2)

        # set initial score to 0
        self.score = 0

        # set gameOver to False intially
        self.gameOver = False
Example #14
0
def run_on_startup():
    logging.basicConfig(filename="attack_surface.log",
                        level=logging.INFO,
                        format='%(asctime)s %(levelname)s %(name)s %('
                        'threadName)s : %(message)s')
    arg_parse = argparse.ArgumentParser()
    arg_parse.add_argument("-ce",
                           "--cloud",
                           required=True,
                           help="JSON of the cloud environment")
    args = vars(arg_parse.parse_args())
    cloud_env_cfg = args["cloud"]
    cloud.Cloud(cloud_env_cfg)
    data_monitor.DataMonitor()
Example #15
0
    def wmGetCloud(self):
        try:
            sID = uiCommon.getAjaxArg("sID")
            c = cloud.Cloud()
            if c:
                c.FromID(sID)
                if c.ID:
                    return c.AsJSON()

            #should not get here if all is well
            return "{\"result\":\"fail\",\"error\":\"Failed to get Cloud details for Cloud ID [" + sID + "].\"}"
        except Exception:
            uiCommon.log_nouser(traceback.format_exc(), 0)
            return traceback.format_exc()
Example #16
0
    def GetCloudObjectsAsXML(self,
                             account_id,
                             cloud_id,
                             cloud_object_type,
                             additional_args={}):
        try:
            sXML = ""

            ca = cloud.CloudAccount()
            ca.FromID(account_id)
            if ca.ID is None:
                msg = "Failed to get Cloud Account details for Cloud Account ID [" + account_id + "]."
                print msg
                return None, msg

            if cloud_object_type is not None:
                # many reasons why we'd bail here.  Rather than a bunch of testing below, let's just crash
                # if a key field is missing.
                if not cloud_object_type.ID:
                    msg = "Cannot find definition for requested object type [" + cloud_object_type.ID + "]"
                    print msg
                    return None, msg

            else:
                msg = "GetCloudObjectType failed for [" + cloud_object_type.ID + "]"
                print msg
                return None, msg

            # get the cloud object
            c = cloud.Cloud()
            c.FromID(cloud_id)
            if c.ID is None:
                msg = "Failed to get Cloud details for Cloud ID [" + cloud_id + "]."
                return None, msg

            sURL, err = self.BuildURL(ca, c, cloud_object_type,
                                      additional_args)
            if err:
                return None, err

            # print sURL

            sXML, err = HTTPGet(sURL, 30)
            if err:
                return None, err

            return sXML, None
        except Exception, ex:
            raise Exception(ex)
Example #17
0
    def wmTestCloudConnection(self):
        try:
            sAccountID = uiCommon.getAjaxArg("sAccountID")
            sCloudID = uiCommon.getAjaxArg("sCloudID")

            c = cloud.Cloud()
            c.FromID(sCloudID)
            if c.ID is None:
                return "{\"result\":\"fail\",\"error\":\"Failed to get Cloud details for Cloud ID [" + sCloudID + "].\"}"

            ca = cloud.CloudAccount()
            ca.FromID(sAccountID)
            if ca.ID is None:
                return "{\"result\":\"fail\",\"error\":\"Failed to get Cloud Account details for Cloud Account ID [" + sAccountID + "].\"}"

            # get the test cloud object type for this provider
            cot = c.Provider.GetObjectTypeByName(c.Provider.TestObject)
            if cot is not None:
                if not cot.ID:
                    return "{\"result\":\"fail\",\"error\":\"Cannot find definition for requested object type [" + c.Provider.TestObject + "].\"}"
            else:
                return "{\"result\":\"fail\",\"error\":\"GetCloudObjectType failed for [" + c.Provider.TestObject + "].\"}"

            # different providers libs have different methods for building a url
            url = ""
            if c.Provider.Name.lower() == "openstack":
                """not yet implemented"""
                #ACWebMethods.openstackMethods acOS = new ACWebMethods.openstackMethods()
                #sXML = acOS.GetCloudObjectsAsXML(c.ID, cot, 0000BYREF_ARG0000sErr, null)
            else:  #Amazon aws, Eucalyptus, and OpenStackAws
                import aws
                awsi = aws.awsInterface()
                url, err = awsi.BuildURL(ca, c, cot)
                if err:
                    return "{\"result\":\"fail\",\"error\":\"" + uiCommon.packJSON(
                        err) + "\"}"

            if not url:
                return "{\"result\":\"fail\",\"error\":\"Unable to build API URL.\"}"
            result, err = uiCommon.HTTPGet(url, 30)
            if err:
                return "{\"result\":\"fail\",\"error\":\"" + uiCommon.packJSON(
                    err) + "\"}"

            return "{\"result\":\"success\",\"response\":\"" + uiCommon.packJSON(
                result) + "\"}"
        except Exception:
            uiCommon.log_nouser(traceback.format_exc(), 0)
            return traceback.format_exc()
Example #18
0
 def __init__(self, width, height):
     self.mWidth = width
     self.mHeight = height
     self.mSky = sky.Sky(self.mWidth, self.mHeight)
     self.mSun = sun.Sun(0.67 * self.mWidth, 0.47 * self.mHeight,
                         (1. / 8.) * self.mHeight)
     outline = [(int(0 * self.mWidth), int(1 * self.mHeight)),
                (int(0 * self.mWidth), int((2 / 3) * self.mHeight)),
                (int(0.25 * self.mWidth), int((5 / 9) * self.mHeight)),
                (int(0.5 * self.mWidth), int((2 / 3) * self.mHeight)),
                (int((5 / 6) * self.mWidth), int((4 / 9) * self.mHeight)),
                (int(1 * self.mWidth), int((7 / 9) * self.mHeight)),
                (int(1 * self.mWidth), int(1 * self.mHeight))]
     self.mMountain = mountain.Mountain(outline)
     self.mCloud1 = cloud.Cloud(0.1 * self.mWidth, .43 * self.mHeight,
                                0.31 * self.mWidth, 0.20 * self.mHeight)
     self.mCloud1.darken()
     self.mCloud2 = cloud.Cloud(0.70 * self.mWidth, .10 * self.mHeight,
                                0.16 * self.mWidth, 0.10 * self.mHeight)
     self.mCloud3 = cloud.Cloud(0.55 * self.mWidth, .40 * self.mHeight,
                                0.40 * self.mWidth, 0.10 * self.mHeight)
     self.mCloud3.lighten()
     self.mSmallBird1 = small_bird.SmallBird(0.25 * self.mWidth,
                                             0.25 * self.mHeight,
                                             0.07 * self.mWidth,
                                             0.04 * self.mHeight)
     self.mSmallBird2 = small_bird.SmallBird(0.22 * self.mWidth,
                                             0.28 * self.mHeight,
                                             0.07 * self.mWidth,
                                             0.04 * self.mHeight)
     self.mSmallBird2.thicken()
     self.mSmallBird3 = small_bird.SmallBird(0.15 * self.mWidth,
                                             0.30 * self.mHeight,
                                             0.07 * self.mWidth,
                                             0.04 * self.mHeight)
     return
def attack():
    """Return the VM ids that can potentially attack 'vm_id'"""
    start = timer()
    monitor = data_monitor.DataMonitor()

    vm_id = request.args.get('vm_id')
    if not vm_id:
        raise ValueError('Query parameter vm_id was not provided')
    app.logger.info(f'New attack request for VM: {vm_id}')

    cloud_env = cloud.Cloud()
    vm_list = cloud_env.vulnerable_to(vm_id)

    end = timer()
    monitor.log_new_request(start, end)
    return make_response(jsonify(list(vm_list)), 200)
Example #20
0
 def updateBackground(self):
     tempclouds = []
     for x in self.clouds:
         x.update()
         if x.x < self.surface.get_rect().width:
             tempclouds.append(x)
     self.clouds = tempclouds
     if len(self.clouds) < 20:
         self.clouds.append(
             cloud.Cloud(
                 pygame.image.load("images/cloud{}.png".format(
                     random.randrange(1, 9))),
                 (-200,
                  random.randrange(0,
                                   self.surface.get_rect().height - 50)),
                 random.randrange(2, 4)))
Example #21
0
    def wmSaveCloud(self):
        sMode = uiCommon.getAjaxArg("sMode")
        sCloudID = uiCommon.getAjaxArg("sCloudID")
        sCloudName = uiCommon.getAjaxArg("sCloudName")
        sProvider = uiCommon.getAjaxArg("sProvider")
        sAPIUrl = uiCommon.getAjaxArg("sAPIUrl")
        sAPIProtocol = uiCommon.getAjaxArg("sAPIProtocol")

        c = None
        try:
            if sMode == "add":
                c, sErr = cloud.Cloud.DBCreateNew(sCloudName, sProvider,
                                                  sAPIUrl, sAPIProtocol)
                if sErr:
                    return "{\"error\" : \"" + sErr + "\"}"
                if c == None:
                    return "{\"error\" : \"Unable to create Cloud.\"}"

                uiCommon.WriteObjectAddLog(uiGlobals.CatoObjectTypes.Cloud,
                                           c.ID, c.Name, "Cloud Created")
            elif sMode == "edit":
                c = cloud.Cloud()
                c.FromID(sCloudID)
                if c == None:
                    return "{\"error\" : \"Unable to get Cloud using ID [" + sCloudID + "].\"}"
                c.Name = sCloudName
                c.APIProtocol = sAPIProtocol
                c.APIUrl = sAPIUrl

                #get a new provider by name
                c.Provider = providers.Provider.FromName(sProvider)
                result, msg = c.DBUpdate()
                if not result:
                    uiCommon.log(msg, 2)
                    return "{\"info\" : \"%s\"}" % msg

                uiCommon.WriteObjectPropertyChangeLog(
                    uiGlobals.CatoObjectTypes.Cloud, c.ID, c.Name, sCloudName,
                    c.Name)

            if c:
                return c.AsJSON()
            else:
                return "{\"error\" : \"Unable to save Cloud using mode [" + sMode + "].\"}"
        except Exception:
            uiCommon.log_nouser(traceback.format_exc(), 0)
            return traceback.format_exc()
def main():
    # for image_path in os.listdir(IMAGES_DIR):
    image = cv2.imread(OPENCV_WORKSPACE + "clouds.jpg")
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

    finds = CLOUD_CASCADE.detectMultiScale(gray,
                                           minSize=MIN_SIZE,
                                           maxSize=MAX_SIZE,
                                           scaleFactor=SCALE_FACTOR,
                                           minNeighbors=MIN_NEIGHBORS)

    clouds = []

    for x, y, w, h in finds:
        clouds.append(cloud.Cloud(x, y, w, h))

    clouds = cloud.trim_cloud_list(clouds)
    clouds = cloud.combine_clouds(clouds)
    clouds = cloud.trim_cloud_list(clouds)

    draw_rects(clouds, image)

    print(len(clouds), "clouds")

    for cloud_ in clouds:
        orb = cv2.ORB_create()
        kp1, des1 = orb.detectAndCompute(gray, None)
        kp2, des2 = orb.detectAndCompute(CIRRUS_FEATURES, None)
        bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
        matches = bf.match(des1, des2)
        matches = sorted(matches, key=lambda x: x.distance)
        subimage = gray[cloud_.y:(cloud_.y + cloud_.h),
                        cloud_.x:(cloud_.x + cloud_.w)]
        match_image = cv2.drawMatches(subimage,
                                      kp1,
                                      CIRRUS_FEATURES,
                                      kp2,
                                      matches,
                                      flags=2,
                                      outImg=None)

        print(len(matches), "matches")

        if len(matches) > 0:
            display_image(match_image)
Example #23
0
    def __init__(self, config, group_file, cloud_id):
        self.config = config
        if group_file is None:
            message = "Grouping config is not provided."
            LOG.error(message)
            raise ValueError(message)
        self.group_config = utils.read_yaml_file(group_file)
        resources = {
            'identity': keystone.KeystoneIdentity,
            'network': neutron.NeutronNetwork,
            'compute': nova_compute.NovaCompute
        }
        self.cloud = cloud.Cloud(resources, cloud_id, config)

        self.network = self.cloud.resources['network']
        self.compute = self.cloud.resources['compute']
        self.identity = self.cloud.resources['identity']

        self.groups = {}
Example #24
0
def upload():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            gcs_uploader = cloud.Cloud()
            gcs_uploader.upload_blob("sumy",'{}/{}'.format(app.config['UPLOAD_FOLDER'],filename),filename)
            return redirect(url_for('dashboard',
                                    filename=filename))
    return render_template('upload.html')
Example #25
0
    def __init__(self, ip, id):
        """
        Create a new SmartDevice instance, identified through its IP address.

        :param str ip: ip address on which the device listens
        :raises SmartPlugException: when unable to communicate with the device
        """
        self.__deactivated = False
        self._ip = ip
        self.__id = id
        self.netif = netif.Netif(self)
        self.cloud = cloud.Cloud(self)
        self.time = dtime.DTime(self)
        self.anti_theft = schedules.AntiTheft(self)
        self.count_down = schedules.Countdown(self)
        self.schedule = schedules.Schedule(self)
        self.system = system.System(self)
        self.firmware = firmware.Firmware(self)
        self.hardware = hardware.Hardware(self)
        self._polling_data = None
        self.__callbacks = []
Example #26
0
    def __init__(self, config_file):

        with open(config_file) as data_file:
            config_data = json.load(data_file)

        routes = {}
        hosts = {}
        self.objects = {}

        #Process all components
        for item in config_data:

            # Add networks to routes, they'll be added as objects later
            if (item["type"] == "network"):
                routes[item["name"]] = item["name"]

            # Add cloud
            elif (item["type"] == "cloud"):
                self.objects[item["name"]] = cloud.Cloud(
                    item["name"], item["parameters"]["network-node"])
                hosts[item["name"]] = item["parameters"]["network-node"]

            # Add device and host network node
            elif (item["type"] == "device"):
                self.objects[item["name"]] = device.Device(
                    item["type"], item["parameters"]["network-node"],
                    item["parameters"]["lumens-per-watt"],
                    item["parameters"]["max-lumens"],
                    item["parameters"]["standby-usage"],
                    item["parameters"]["default-brightness"])
                if (item["parameters"]["network-node"] != ""):
                    hosts[item["name"]] = item["parameters"]["network-node"]

        #Add network nodes
        for host in hosts:
            self.objects[hosts[host]] = network.NetworkNode(
                hosts[host], host, routes, hosts)
 def __init__(self):
     cloud_env = cloud.Cloud()
     self.vm_count = cloud_env.vm_count
     self.request_count = 0
     self.avg_request_time = -1
Example #28
0
import telas as t
import uteis as u
import cat as c
import Back as b
import mouse as m
import cloud as cl
import game as g

todas_as_sprites = pygame.sprite.Group()
cat = c.Cat()
back = b.Back()
todas_as_sprites.add(back)
todas_as_sprites.add(cat)

for i in range(3):
    cloud = cl.Cloud()
    todas_as_sprites.add(cloud)

mouse1 = m.Mouse()
mouse2 = m.Mouse()
mouse3 = m.Mouse()
mouse4 = m.Mouse()

todas_as_sprites.add(mouse1, mouse2, mouse3, mouse4)

grupo_obstaculos = pygame.sprite.Group()
grupo_obstaculos.add(mouse1, mouse2, mouse3, mouse4)

grupo_oM1 = pygame.sprite.Group()
grupo_oM1.add(mouse2, mouse3, mouse4)
Example #29
0
def GetCloudObjectsAsList(sAccountID, sCloudID, sObjectType):
    try:
        log("Querying the cloud for %s" % sObjectType, 4)

        import cloud

        # first, get the cloud
        c = cloud.Cloud()
        c.FromID(sCloudID)
        if c is None:
            return None, "Unable to get Cloud for ID [" + sCloudID + "]"

        cot = c.Provider.GetObjectTypeByName(sObjectType)
        if cot is not None:
            if not cot.ID:
                return None, "Cannot find definition for requested object type [" + sObjectType + "]"
        else:
            return None, "GetCloudObjectType failed for [" + sObjectType + "]"

        # ok, kick out if there are no properties for this type
        if not cot.Properties:
            return None, "No properties defined for type [" + sObjectType + "]"

        # All good, let's hit the API
        sXML = ""

        import aws

        if c.Provider.Name.lower() == "openstack":
            """not yet implemented"""
            #ACWebMethods.openstackMethods acOS = new ACWebMethods.openstackMethods()
            #sXML = acOS.GetCloudObjectsAsXML(c.ID, cot, 0000BYREF_ARG0000sErr, null)
        else:  #Amazon aws, Eucalyptus, and OpenStackAws
            awsi = aws.awsInterface()
            sXML, err = awsi.GetCloudObjectsAsXML(sAccountID, sCloudID, cot)

        if err:
            return None, err

        if not sXML:
            return None, "GetCloudObjectsAsXML returned an empty document."

        # Got results, objectify them.

        # OK look, all this namespace nonsense is annoying.  Every AWS result I've witnessed HAS a namespace
        #  (which messes up all our xpaths)
        #  but I've yet to see a result that actually has two namespaces
        #  which is the only scenario I know of where you'd need them at all.

        # So... to eliminate all namespace madness
        # brute force... parse this text and remove anything that looks like [ xmlns="<crud>"] and it's contents.
        sXML = RemoveDefaultNamespacesFromXML(sXML)

        xDoc = ET.fromstring(sXML)
        if xDoc is None:
            return None, "API Response XML document is invalid."

        log(sXML, 4)

        # FIRST ,we have to find which properties are the 'id' value.  That'll be the key for our dictionary.
        # an id can be a composite of several property values
        # this is just so we can kick back an error if no IsID exists.
        # we build the actual id from values near the end
        sIDColumnName = ""
        for prop in cot.Properties:
            if prop.IsID:
                sIDColumnName += prop.Name

        # no sIDColumnName means we can't continue
        if not sIDColumnName:
            return None, "ID column(s) not defined for Cloud Object Type" + cot.Name

        # for each result in the xml
        #     for each column
        xRecords = xDoc.findall(cot.XMLRecordXPath)
        if len(xRecords):
            for xRecord in xRecords:
                record_id = ""
                row = []
                for prop in cot.Properties:
                    # NOW PAY ATTENTION.
                    # the CloudObjectTypeProperty class has a 'Value' attribute.
                    # but, we obviously can't set that property of THIS instance (prop)
                    # because it's gonna get changed each time.

                    # so, we create a clone of that property here, and give that copy the actual value,
                    # then append the copy to 'row', not the one we're looping here.

                    # cosmic?  yes... it is.
                    newprop = copy.copy(prop)
                    log("looking for property [%s]" % newprop.Name, 4)

                    # ok look, the property may be an xml attribute, or it might be an element.
                    # if there is an XPath value on the column, that means it's an element.
                    # the absence of an XPath means we'll look for an attribute.
                    # NOTE: the attribute we're looking for is the 'name' of this property
                    # which is the DataColumn.name.
                    if not newprop.XPath:
                        xa = xRecord.attrib[newprop.Name]
                        if xa is not None:
                            log(" -- found (attribute) - [%s]" % xa, 4)
                            newprop.Value = xa
                            row.append(newprop)
                    else:
                        # if it's a tagset column put the tagset xml in it
                        #  for all other columns, they get a lookup
                        xeProp = xRecord.find(newprop.XPath)
                        if xeProp is not None:
                            # does this column have the extended property "ValueIsXML"?
                            bAsXML = (True if newprop.ValueIsXML else False)

                            if bAsXML:
                                newprop.Value = ET.tostring(xeProp)
                                log(
                                    " -- found (as xml) - [%s]" %
                                    newprop.Value, 4)
                            else:
                                newprop.Value = xeProp.text
                                log(" -- found - [%s]" % newprop.Value, 4)

                        # just because it's missing from the data doesn't mean we can omit the property
                        # it just has an empty value.
                        row.append(newprop)

                    if newprop.IsID:
                        if not newprop.Value:
                            return None, "A property [%s] cannot be defined as an 'ID', and have an empty value." % newprop.Name
                        else:
                            log(
                                "[%s] is part of the ID... so [%s] becomes part of the ID"
                                % (newprop.Name, newprop.Value), 4)
                            record_id += (newprop.Value
                                          if newprop.Value else "")

                    # an id is required
                    if not record_id:
                        return None, "Unable to construct an 'id' from property values."

                cot.Instances[record_id] = row

            return cot.Instances, None
        else:
            return None, ""
    except Exception:
        log_nouser(traceback.format_exc(), 4)
        return None, None
Example #30
0
import cloud
import world
import random
import car
import bouncy
import time

window = ccircle.Window('Lab 4', 800, 600)
my_world = world.World('jungle')

for i in range(400):
    x = random.randint(0, 800)
    y = random.randint(0, 150)
    size = random.randint(25, 50)
    vx = 0
    my_world.add(cloud.Cloud(x, y, size, vx))

for i in range(1):
    x = random.randint(0, 300)
    y = random.randint(0, 550)
    size = random.randint(300, 300)
    my_world.add(car.Car(x, y, size))

my_ball = bouncy.Bouncy(200, 300)
my_world.add(my_ball)
"""""
for i in range(500):
    x = random.randint(0, 800)
    y = random.randint(0, 600)
    size = random.randint(25, 150)
    my_world.add(bouncy.Bouncy(x, y, size))