Esempio n. 1
0
def run():
    data = pd.read_csv('50_states.csv')
    states = data[data.columns[0]]
    print(states)
    screen = Screen()
    screen.title('U.S. States Game')
    image = "blank_states_img.gif"
    screen.addshape(image)
    turtle.shape(image)

    # def get_mouse_click_cords(x, y):
    #     print(x, y)
    # turtle.onscreenclick(get_mouse_click_cords)

    is_guessing = True
    counter = 0
    guessed_states = []

    while is_guessing:
        answer_state = screen.textinput(title=f"{counter}/50 Guess the State", prompt="What's another State name?").title().strip()
        if answer_state == "Exit":
            missing_states = [x for x in states if x not in guessed_states]
            print(f'The states that you missed guessing are:\n{missing_states}')
            # save a list with the missing states to learn:
            new_data = pd.DataFrame(missing_states)
            new_data.to_csv('states_to_learn.csv')
            break

        for st in data['state']:
            if st == answer_state:
                guessed_states.append(answer_state)
                counter += 1
                state_data = data[data.state == answer_state]   # Obtiene los datos de la fila
                state_cords = (int(state_data.x), int(state_data.y))
                print_state = Naming(st, state_cords)
            #     place_state(answer_state)
            if counter == 51:
                is_guessing = False
Esempio n. 2
0
    def get_from_db_naming(my, search_type):
        project_code = Project.get_project_code()
        if project_code in ["admin", "sthpw"]:
            return ""

        file_type = my.get_file_type()
        filename = my.file_object.get_full_file_name()

        naming = Naming.get(my.sobject, my.snapshot, file_path=filename)

        if not naming:
            return None

        if naming and my.checkin_type:
            checkin_type = naming.get_value('checkin_type')
            if checkin_type and my.checkin_type != checkin_type:
                print "mismatched checkin_type!"
                naming = None
                return None

        naming_util = NamingUtil()

        # Provide a mechanism for a custom class
        naming_class = naming.get_value("class_name", no_exception=True)
        if naming_class:
            kwargs = {
                'sobject': my.sobject,
                'snapshot': my.snapshot,
                'file_object': my.file_object,
                'ext': my.get_ext(),
                'mode': 'file'
            }
            naming = Common.create_from_class_path(naming_class, kwargs)
            filename = naming.get_file()
            if filename:
                return filename


        # provide a mechanism for a custom client side script
        script_path = naming.get_value("script_path", no_exception=True)
        if script_path:
            project_code = my.sobject.get_project_code()
            input = {
                'sobject': my.sobject,
                'snapshot': my.snapshot,
                'file_object': my.file_object,
                'ext': my.get_ext(),
                'mode': 'file',
                'project': project_code
            }
            from tactic.command import PythonCmd

            cmd = PythonCmd(script_path=script_path, input=input)
            results = cmd.execute()
            if results:
                return results




        naming_value = naming.get_value("file_naming")

        if not naming_value:
            is_versionless = naming.get_value("latest_versionless") or naming.get_value("current_versionless")
            if not is_versionless:
                return ""

            # FIXME:
            # if this is a versionless naming, then empty uses a default
            # This is put here because the check-in type is determined by the
            # naming here.  Normally, this is passed through with "naming_expr"
            # but in snapshot.py, it is not yet known that this is an "auto"
            # checkin_type because it is defined in the naming and not the
            # process

            server = Config.get_value("install", "server")
            if server:
                naming_value= "{basefile}_{snapshot.process}_%s.{ext}" % server
            else:
                naming_value = "{basefile}_{snapshot.process}.{ext}"

        
        # check for manual_version
        manual_version = naming.get_value('manual_version')
        if manual_version == True:
	    # if the file version is not the same as the snapshot version
            # then check to see if the snapshot already exists
            filename = my.file_object.get_full_file_name()
            version = my.get_version_from_file_name(filename)
            context = my.snapshot.get_context()
            if version > 0 and version != my.snapshot.get_value("version"):
                existing_snap = Snapshot.get_snapshot(\
                    my.snapshot.get_value("search_type"),\
                    my.snapshot.get_value("search_id"), context=context, \
                    version=version, show_retired=True)
                if existing_snap:
                    raise TacticException('You have chosen manual version in Naming for this SObject. A snapshot with context "%s" and version "%s" already exists.' % (context, version) )


                my.snapshot.set_value("version", version)
                my.snapshot.commit()
        
       
        file_type = my.get_file_type()

        return naming_util.naming_to_file(naming_value, my.sobject,my.snapshot,my.file_object,ext=my.get_ext(),file_type=file_type)
Esempio n. 3
0
    def get_from_db_naming(my, search_type):
        project_code = Project.get_project_code()
        if project_code in ["admin", "sthpw"]:
            return ""

        file_type = my.get_file_type()
        filename = my.file_object.get_full_file_name()

        naming = Naming.get(my.sobject, my.snapshot, file_path=filename)

        if not naming:
            return None

        if naming and my.checkin_type:
            checkin_type = naming.get_value('checkin_type')
            if checkin_type and my.checkin_type != checkin_type:
                print "mismatched checkin_type!"
                naming = None
                return None

        naming_util = NamingUtil()

        # Provide a mechanism for a custom class
        naming_class = naming.get_value("class_name", no_exception=True)
        if naming_class:
            kwargs = {
                'sobject': my.sobject,
                'snapshot': my.snapshot,
                'file_object': my.file_object,
                'ext': my.get_ext(),
                'mode': 'file'
            }
            naming = Common.create_from_class_path(naming_class, kwargs)
            filename = naming.get_file()
            if filename:
                return filename

        # provide a mechanism for a custom client side script
        script_path = naming.get_value("script_path", no_exception=True)
        if script_path:
            project_code = my.sobject.get_project_code()
            input = {
                'sobject': my.sobject,
                'snapshot': my.snapshot,
                'file_object': my.file_object,
                'ext': my.get_ext(),
                'mode': 'file',
                'project': project_code
            }
            from tactic.command import PythonCmd

            cmd = PythonCmd(script_path=script_path, input=input)
            results = cmd.execute()
            if results:
                return results

        naming_value = naming.get_value("file_naming")

        if not naming_value:
            is_versionless = naming.get_value(
                "latest_versionless") or naming.get_value(
                    "current_versionless")
            if not is_versionless:
                return ""

            # FIXME:
            # if this is a versionless naming, then empty uses a default
            # This is put here because the check-in type is determined by the
            # naming here.  Normally, this is passed through with "naming_expr"
            # but in snapshot.py, it is not yet known that this is an "auto"
            # checkin_type because it is defined in the naming and not the
            # process

            server = Config.get_value("install", "server")
            if server:
                naming_value = "{basefile}_{snapshot.process}_%s.{ext}" % server
            else:
                naming_value = "{basefile}_{snapshot.process}.{ext}"

        # check for manual_version
        manual_version = naming.get_value('manual_version')
        if manual_version == True:
            # if the file version is not the same as the snapshot version
            # then check to see if the snapshot already exists
            filename = my.file_object.get_full_file_name()
            version = my.get_version_from_file_name(filename)
            context = my.snapshot.get_context()
            if version > 0 and version != my.snapshot.get_value("version"):
                existing_snap = Snapshot.get_snapshot(\
                    my.snapshot.get_value("search_type"),\
                    my.snapshot.get_value("search_id"), context=context, \
                    version=version, show_retired=True)
                if existing_snap:
                    raise TacticException(
                        'You have chosen manual version in Naming for this SObject. A snapshot with context "%s" and version "%s" already exists.'
                        % (context, version))

                my.snapshot.set_value("version", version)
                my.snapshot.commit()

        file_type = my.get_file_type()

        return naming_util.naming_to_file(naming_value,
                                          my.sobject,
                                          my.snapshot,
                                          my.file_object,
                                          ext=my.get_ext(),
                                          file_type=file_type)
Esempio n. 4
0
        type = 'ma'
        version = -1
        virtual_versionless_snapshot = Snapshot.create_new()
        virtual_snapshot_xml = '<snapshot process=\'%s\'><file type=\'%s\'/></snapshot>' % (process, type)
        virtual_versionless_snapshot.set_value("snapshot", virtual_snapshot_xml)
        virtual_versionless_snapshot.set_value("process", process)
        virtual_versionless_snapshot.set_value("context", context)
        virtual_versionless_snapshot.set_value("snapshot_type", 'file')
        virtual_versionless_snapshot.set_sobject(sobject2)
        virtual_versionless_snapshot.set_value("version", version)

        Container.put("Naming:cache", None)
        Container.put("Naming:cache:latest", None)
        Container.put("Naming:cache:current", None)
        Container.put("Naming:namings", None)
        name = Naming.get(sobject, virtual_snapshot)
        my.assertEquals(name.get_value('dir_naming'), '{project.code}/cut/{sobject.code}')

        virtual_snapshot.set_value('context', 'light/sub2')
        name = Naming.get(sobject, virtual_snapshot)
        my.assertEquals(name.get_value('dir_naming'), '{project.code}/light')
        
        has = Naming.has_versionless(sobject, virtual_snapshot, versionless='latest')
        my.assertEquals(has, False)

        virtual_snapshot.set_value('context', 'asset/light')
        name = Naming.get(sobject, virtual_snapshot)
        my.assertEquals(name.get_value('dir_naming'), '{project.code}/cut')
        has = Naming.has_versionless(sobject, virtual_snapshot)
        has = Naming.has_versionless(sobject, virtual_snapshot, versionless='latest')
        my.assertEquals(has, False)
Esempio n. 5
0
    def get_from_db_naming(my, protocol):
        project_code = Project.get_project_code()
        if project_code in ["admin", "sthpw"]:
            return None

        # get the naming object
        naming = Naming.get(my.sobject, my.snapshot)
        if not naming:
            return None

        if protocol == 'sandbox':
            mode = 'sandbox_dir'
        else:
            mode = 'dir'

        # Provide a mechanism for a custom class
        naming_class = naming.get_value("class_name", no_exception=True)
        #naming_class = "pyasm.biz.TestFileNaming"
        if naming_class:
            kwargs = {
                'sobject': my.sobject,
                'snapshot': my.snapshot,
                'file_object': my._file_object,
                #'ext': my.get_ext(),
                'file_type': my.file_type,
                'mode': mode
            }
            naming = Common.create_from_class_path(naming_class, [], kwargs)
            dirname = naming.get_dir()
            if dirname:
                return dirname


        # provide a mechanism for a custom client side script
        script_path = naming.get_value("script_path", no_exception=True)
        if script_path:
            project_code = my.sobject.get_project_code()
            input = {
                'sobject': my.sobject,
                'snapshot': my.snapshot,
                'file_object': my._file_object,
                #'ext': my.get_ext(),
                'file_type': my.file_type,
                'mode': mode,
                'project': project_code
            }
            from tactic.command import PythonCmd

            cmd = PythonCmd(script_path=script_path, input=input)
            results = cmd.execute()
            if results:
                return results


        naming_util = NamingUtil()

        naming_expr = ''
        if protocol == 'sandbox':
            naming_expr = naming.get_value("sandbox_dir_naming")

        if not naming_expr:
            naming_expr = naming.get_value("dir_naming")

        # so it can take the default
        if not naming_expr:
            return None

        file_type = my.get_file_type()

        # build the dir name
        dir_name = naming_util.naming_to_dir(naming_expr, my.sobject, my.snapshot, file=my._file_object, file_type=file_type)

        return dir_name
Esempio n. 6
0
    def get_dir(my, protocol=None, alias=None):

        if protocol:
            my.protocol = protocol

        assert my.protocol != None
        assert my.sobject != None
        
        # this is needed first
        my._init_file_object()


        
        # get the alias from the naming, if it exists
        if not alias and my.protocol in ["file", "http"]:
            if my._file_object:
                alias = my._file_object.get_value("base_dir_alias")
            else:
                naming = Naming.get(my.sobject, my.snapshot)
                if naming and my.verify_checkin_type(naming):
                    alias = naming.get_value("base_dir_alias")

        dirs = []
        dirs.extend( my.get_base_dir(alias=alias) )
        if not my.create:
           dir_dict = my._get_recorded_dir()
           if dir_dict.get('relative_dir'):
                dirs.append(dir_dict.get('relative_dir'))
                return '/'.join(dirs)
           elif dir_dict.get('inplace_dir'):
                return dir_dict.get('inplace_dir')
        
        # Now either create is True or relative_dir has been cleared in the db
        # first check the db, so we build up the naming

        if type(my.naming_expr) == types.DictType:
            override_naming_expr = my.naming_expr.get("override")
            default_naming_expr = my.naming_expr.get("default")
        else:
            override_naming_expr = my.naming_expr
            default_naming_expr = None

        if override_naming_expr:
            dir_name = my.get_from_expression(override_naming_expr)
            if dir_name.startswith("/"):
                return dir_name
            else:
                dirs.append(dir_name)
                return '/'.join(dirs)

        # get from db
        db_dir_name = my.get_from_db_naming(my.protocol)

        if db_dir_name:
            dirs.append(db_dir_name)
            return '/'.join(dirs)
        elif db_dir_name == "":
            return '/'.join(dirs)


        # otherwise look for an overriding python method
        search_type = my.sobject.get_search_type_obj().get_base_key()
        func_name = search_type.replace("/", "_")


        # if there is no snapshot, then create a virtual one
        if not my.snapshot:
            # TODO: may have to fill this in later
            my.snapshot = SearchType.create("sthpw/snapshot")
            my.snapshot.set_value("context", "publish")
        if not my.file_type:
            my.file_type = "main"


        # check to see if the function name exists.
        try:
            dirs = eval( "my.%s(dirs)" % func_name)
            return "/".join(dirs)
        except Exception, e:
            msg = e.__str__()
            if msg.find("object has no attribute '%s'" % func_name) != -1:
                pass
            else:
                raise
Esempio n. 7
0
    def get_from_db_naming(self, protocol):

        project_code = Project.get_project_code()
        if project_code in ["admin", "sthpw"]:
            return None

        # get the naming object
        naming = Naming.get(self.sobject, self.snapshot)
        if not naming:
            return None

        if not self.verify_checkin_type(naming):
            return None

        if protocol == 'sandbox':
            mode = 'sandbox_dir'
        else:
            mode = 'dir'

        # Provide a mechanism for a custom class
        naming_class = naming.get_value("class_name", no_exception=True)
        #naming_class = "pyasm.biz.TestFileNaming"
        if naming_class:
            kwargs = {
                'sobject': self.sobject,
                'snapshot': self.snapshot,
                'file_object': self._file_object,
                #'ext': self.get_ext(),
                'file_type': self.file_type,
                'mode': mode
            }
            naming = Common.create_from_class_path(naming_class, [], kwargs)
            dirname = naming.get_dir()
            if dirname:
                return dirname


        # provide a mechanism for a custom client side script
        script_path = naming.get_value("script_path", no_exception=True)
        if script_path:
            project_code = self.sobject.get_project_code()
            input = {
                'sobject': self.sobject,
                'snapshot': self.snapshot,
                'file_object': self._file_object,
                #'ext': self.get_ext(),
                'file_type': self.file_type,
                'mode': mode,
                'project': project_code
            }
            from tactic.command import PythonCmd

            cmd = PythonCmd(script_path=script_path, input=input)
            results = cmd.execute()
            if results:
                return results


        naming_util = NamingUtil()

        naming_expr = ''
        if protocol == 'sandbox':
            naming_expr = naming.get_value("sandbox_dir_naming")

        if not naming_expr:
            naming_expr = naming.get_value("dir_naming")

        # so it can take the default
        if not naming_expr:
            return None

        file_type = self.get_file_type()

        alias = naming.get_value("base_dir_alias", no_exception=True)

        # build the dir name
        dir_name = naming_util.naming_to_dir(naming_expr, self.sobject, self.snapshot, file=self._file_object, file_type=file_type)

        return dir_name
Esempio n. 8
0
    def get_dir(self, protocol=None, alias=None):

        if protocol:
            self.protocol = protocol

        assert self.protocol != None
        assert self.sobject != None
        
        # this is needed first
        self._init_file_object()

        # get the alias from the naming, if it exists
        if not alias and self.protocol in ["file", "http"]:
            if self._file_object:
                alias = self._file_object.get_value("base_dir_alias")
            else:
                naming = Naming.get(self.sobject, self.snapshot)
                if naming and self.verify_checkin_type(naming):
                    alias = naming.get_value("base_dir_alias")

        dirs = []
        dirs.extend( self.get_base_dir(alias=alias) )
        if not self.create:
           dir_dict = self._get_recorded_dir()
           if dir_dict.get('relative_dir'):
                dirs.append(dir_dict.get('relative_dir'))
                return '/'.join(dirs)
           elif dir_dict.get('inplace_dir'):
                return dir_dict.get('inplace_dir')
        
        # Now either create is True or relative_dir has been cleared in the db
        # first check the db, so we build up the naming

        if type(self.naming_expr) == types.DictType:
            override_naming_expr = self.naming_expr.get("override")
            default_naming_expr = self.naming_expr.get("default")
        else:
            override_naming_expr = self.naming_expr
            default_naming_expr = None

        if override_naming_expr:
            dir_name = self.get_from_expression(override_naming_expr)
            if dir_name.startswith("/"):
                return dir_name
            else:
                dirs.append(dir_name)
                return '/'.join(dirs)

        # get from db
        db_dir_name = self.get_from_db_naming(self.protocol)

        if db_dir_name:
            dirs.append(db_dir_name)
            return '/'.join(dirs)
        elif db_dir_name == "":
            return '/'.join(dirs)


        # otherwise look for an overriding python method
        search_type = self.sobject.get_search_type_obj().get_base_key()
        func_name = search_type.replace("/", "_")


        # if there is no snapshot, then create a virtual one
        if not self.snapshot:
            # TODO: may have to fill this in later
            self.snapshot = SearchType.create("sthpw/snapshot")
            self.snapshot.set_value("context", "publish")
        if not self.file_type:
            self.file_type = "main"


        # check to see if the function name exists.
        try:
            dirs = eval( "self.%s(dirs)" % func_name)
            return "/".join(dirs)
        except Exception, e:
            msg = e.__str__()
            if msg.find("object has no attribute '%s'" % func_name) != -1:
                pass
            else:
                raise
Esempio n. 9
0
    async def create_containers(self, update):
        # Clean up all the containers
        if not update:
            await self.delete_containers()

        # Make sure the defined images are available and config the ports
        count, image_ports, unique_ports = await self.setup_images(
            self.config.images, update)

        addresses, subnet, gateway = self.get_available_address(
            self.config.network.hosts)

        # Do not recreate the network during an update. docker does not provide a
        # way to update the network so during an update it would need to be dropped and
        # updated. The network id for any existing containers would need to be updated
        if not update:
            # Create a network for the containers
            await self.create_network(self.config.network.hosts, subnet,
                                      gateway)

            # Apply the iptable rules required for the configured images
            rules = IPTableRules(self.config)
            rules.create(subnet, unique_ports)

        logging.info('Creating containers')

        # Create a unique list of host names
        naming = Naming()
        host_names = naming.generate_host_names(self.config.naming, count)

        scripts_dir = ''.join([os.getcwd(), SCRIPTS_DIR])
        logging.info('Using %s for script directory', scripts_dir)

        client = aiodocker.Docker()
        for image in self.config.images:

            # If the image has no exposed ports then there is no use in
            # creating a container
            if image.name not in image_ports:
                continue

            ports = [port.text for port in image_ports[image.name]]
            ports = dict.fromkeys(ports, {})
            for count in range(image.count):
                host_name = host_names.pop()
                ip = addresses.pop(0)
                mac = utility.Net.generate_mac(ip)
                config = {
                    'Hostname': host_name,
                    'Image': image.name,
                    'ExposedPorts': ports,
                    'MacAddress': mac,
                    'Env': image.env_variables,
                    'NetworkingConfig': {
                        'EndpointsConfig': {
                            'clab': {
                                'IPAMConfig': {
                                    'IPv4Address': ip,
                                },
                            }
                        }
                    }
                }

                if not image.startup_script is None and len(
                        image.startup_script) > 0:
                    config['HostConfig'] = {
                        'Binds': ['{}:{}'.format(scripts_dir, SCRIPTS_DIR)],
                    }

                logging.debug('Creating container %s:%s', host_name,
                              image.name)
                container = await client.containers.create(config,
                                                           name=host_name)

                # Persist the container info to the db with the ports
                # Ports are used to determine what listeners to create
                new_container = Container.create(
                    container_id=container.id,
                    name=host_name,
                    ip=ip,
                    mac=mac,
                    start_delay=image.start_delay,
                    start_retry_count=image.start_retry_count,
                    start_on_create=image.start_on_create,
                    sub_domain=image.sub_domain)

                # Some containers perform a lot of startup work when run for the first time
                # To mitigate this containers can be started and stopped on creation
                if image.start_on_create:
                    await self.start_container_on_create(
                        image, new_container, client)

                for port in image_ports[image.name]:
                    Port.create(container=new_container.id,
                                number=port.num,
                                protocol=port.protocol)

        await client.close()