コード例 #1
0
ファイル: process_pdb.py プロジェクト: Jianlong-Peng/pytools
def main(argv=sys.argv):
    if len(argv) != 4:
        print "\n  Usage: %s [option] out_dir"%argv[0]
        print "\n  [option]"
        print "    -f pdb_file"
        print "    -l file.  pdb file in each line"
        print "  out_dir: where to save extracted protein(s), ligand(s), and water(s)"
        print "\n  a file named 'names_pro_lig.log' will be generated"
        print ""
        sys.exit(1)

    
    outf_log = open("names_pro_lig.log","a")
    if argv[1] == "-f":
        tools.process(argv[2], argv[3], outf_log)
    elif argv[1] == "-l":
        inf = open(argv[2],"r")
        for line in inf:
            if line.startswith('#'):
                continue
            tools.process(line.strip(), argv[3], outf_log)
        inf.close()
    else:
        print "Error: invalid option ",argv[1]
    outf_log.close()
コード例 #2
0
ファイル: workplace.py プロジェクト: rajeshtaneja/mdk
    def checkCachedClones(self, stable=True, integration=True):
        """Clone the official repository in a local cache"""
        cacheStable = self.getCachedRemote(False)
        cacheIntegration = self.getCachedRemote(True)

        if not os.path.isdir(cacheStable) and stable:
            logging.info('Cloning stable repository into cache...')

            # For faster clone, we will copy the integration clone if it exists.
            if os.path.isdir(cacheIntegration):
                shutil.copytree(cacheIntegration, cacheStable)
                repo = git.Git(cacheStable, C.get('git'))
                repo.setRemote('origin', C.get('remotes.stable'))
                # The repository is not updated at this stage, it has to be done manually.
            else:
                logging.info('This is going to take a while...')
                process('%s clone --mirror %s %s' % (C.get('git'), C.get('remotes.stable'), cacheStable))

        if not os.path.isdir(cacheIntegration) and integration:
            logging.info('Cloning integration repository into cache...')

            # For faster clone, we will copy the integration clone if it exists.
            if os.path.isdir(cacheStable):
                shutil.copytree(cacheStable, cacheIntegration)
                repo = git.Git(cacheIntegration, C.get('git'))
                repo.setRemote('origin', C.get('remotes.integration'))
                # The repository is not updated at this stage, it has to be done manually.
            else:
                logging.info('Have a break, this operation is slow...')
                process('%s clone --mirror %s %s' % (C.get('git'), C.get('remotes.integration'), cacheIntegration))
コード例 #3
0
ファイル: scripts.py プロジェクト: rajeshtaneja/mdk
    def run(cls, script, path, arguments=None, cmdkwargs={}):
        """Executes a script at in a certain directory"""

        # Converts arguments to a string.
        arguments = '' if arguments == None else arguments
        if type(arguments) == list:
            arguments = ' '.join(arguments)
        arguments = ' ' + arguments

        cli = cls.find(script)
        if cli.endswith('.php'):
            dest = os.path.join(path, 'mdkscriptrun.php')
            logging.debug('Copying %s to %s' % (cli, dest))
            shutil.copyfile(cli, dest)

            cmd = '%s %s %s' % (C.get('php'), dest, arguments)

            result = process(cmd, cwd=path, **cmdkwargs)
            os.remove(dest)
        elif cli.endswith('.sh'):
            dest = os.path.join(path, 'mdkscriptrun.sh')
            logging.debug('Copying %s to %s' % (cli, dest))
            shutil.copyfile(cli, dest)
            os.chmod(dest, stat.S_IRUSR | stat.S_IXUSR)

            cmd = '%s %s' % (dest, arguments)
            result = process(cmd, cwd=path, **cmdkwargs)
            os.remove(dest)
        else:
            raise UnsupportedScript('Script not supported')

        return result[0]
コード例 #4
0
 def checkCachedClones(self, stable = True, integration = True):
     """Clone the official repository in a local cache"""
     cacheStable = os.path.join(self.cache, 'moodle.git')
     cacheIntegration = os.path.join(self.cache, 'integration.git')
     if not os.path.isdir(cacheStable) and stable:
         debug('Cloning stable repository into cache...')
         result = process('%s clone %s %s' % (C.get('git'), C.get('remotes.stable'), cacheStable))
         result = process('%s fetch -a' % C.get('git'), cacheStable)
     if not os.path.isdir(cacheIntegration) and integration:
         debug('Cloning integration repository into cache...')
         result = process('%s clone %s %s' % (C.get('git'), C.get('remotes.integration'), cacheIntegration))
         result = process('%s fetch -a' % C.get('git'), cacheIntegration)
コード例 #5
0
ファイル: workplace.py プロジェクト: andrewnicols/mdk
    def checkCachedClones(self, stable=True, integration=True):
        """Clone the official repository in a local cache"""
        cacheStable = self.getCachedRemote(False)
        cacheIntegration = self.getCachedRemote(True)
        if not os.path.isdir(cacheStable) and stable:
            logging.info('Cloning stable repository into cache...')
            logging.info('That\'s going to take a while...')
            process('%s clone --mirror %s %s' % (C.get('git'), C.get('remotes.stable'), cacheStable))

        if not os.path.isdir(cacheIntegration) and integration:
            logging.info('Cloning integration repository into cache...')
            logging.info('Have a break, this operation is slow...')
            process('%s clone --mirror %s %s' % (C.get('git'), C.get('remotes.integration'), cacheIntegration))
コード例 #6
0
def resolveIssueNumber(view, folders):
    """Try to find an issue number"""

    issue = None

    # Read from the content of the file.
    if view:
        for region in view.sel():
            if region.empty():
                region = view.word(region)
            word = view.substr(region)
            issue = extractIssueNumberFromText(word)
            if issue != None:
                break

    # Read from the folders.
    if not issue:
        for folder in folders:
            result = process('git symbolic-ref -q HEAD', cwd=folder)
            if result[0] == 0 and result[1] != '':
                issue = extractIssueNumberFromText(result[1])
                if issue != None:
                    break

    return issue
コード例 #7
0
ファイル: css.py プロジェクト: rajeshtaneja/mdk
    def execute(self):
        executable = C.get('lessc')
        if not executable:
            raise Exception('Could not find executable path')

        cmd = [executable]

        sourcePath = os.path.relpath(self._source, self._cwd)
        sourceDir = os.path.dirname(sourcePath)

        if self._debug:
            cmd.append('--source-map-rootpath=' + sourceDir)
            cmd.append('--source-map-map-inline')
            self.setCompress(False)

        if self._compress:
            cmd.append('--compress')

        """Append the source and destination"""
        cmd.append(sourcePath)
        cmd.append(os.path.relpath(self._dest, self._cwd))

        (code, out, err) = process(cmd, self._cwd)
        if code != 0 or len(out) != 0:
            raise CssCompileFailed('Error during compile')
コード例 #8
0
ファイル: moodle.py プロジェクト: andrewnicols/mdk
    def initBehat(self, switchcompletely=False):
        """Initialise the Behat environment"""

        if self.branch_compare(25, '<'):
            raise Exception('Behat is only available from Moodle 2.5')

        # Force switch completely for PHP < 5.4
        (none, phpVersion, none) = process('%s -r "echo version_compare(phpversion(), \'5.4\');"' % (C.get('php')))
        if int(phpVersion) <= 0:
            switchcompletely = True

        # Set Behat data root
        behat_dataroot = self.get('dataroot') + '_behat'
        self.updateConfig('behat_dataroot', behat_dataroot)

        # Set Behat DB prefix
        behat_prefix = 'zbehat_'
        self.updateConfig('behat_prefix', behat_prefix)

        # Switch completely?
        if switchcompletely:
            self.updateConfig('behat_switchcompletely', switchcompletely)
            self.updateConfig('behat_wwwroot', self.get('wwwroot'))
        else:
            self.removeConfig('behat_switchcompletely')
            self.removeConfig('behat_wwwroot')

        # Force a cache purge
        self.purge()

        # Run the init script.
        self.cli('admin/tool/behat/cli/init.php', stdout=None, stderr=None)

        # Force a cache purge
        self.purge()
コード例 #9
0
ファイル: moodle.py プロジェクト: jacano1969/mdk
    def initBehat(self, switchcompletely=False):
        """Initialise the Behat environment"""

        if self.branch_compare(25, "<"):
            raise Exception("Behat is only available from Moodle 2.5")

        # Force switch completely for PHP < 5.4
        (none, phpVersion, none) = process("%s -r \"echo version_compare(phpversion(), '5.4');\"" % (C.get("php")))
        if int(phpVersion) <= 0:
            switchcompletely = True

        # Set Behat data root
        behat_dataroot = self.get("dataroot") + "_behat"
        self.updateConfig("behat_dataroot", behat_dataroot)

        # Set Behat DB prefix
        behat_prefix = "zbehat_"
        self.updateConfig("behat_prefix", behat_prefix)

        # Switch completely?
        if switchcompletely:
            self.updateConfig("behat_switchcompletely", switchcompletely)
            self.updateConfig("behat_wwwroot", self.get("wwwroot"))
        else:
            self.removeConfig("behat_switchcompletely")
            self.removeConfig("behat_wwwroot")

        # Force a cache purge
        self.purge()

        # Run the init script.
        self.cli("admin/tool/behat/cli/init.php", stdout=None, stderr=None)

        # Force a cache purge
        self.purge()
コード例 #10
0
ファイル: moodle.py プロジェクト: rajeshtaneja/mdk
 def cli(self, cli, args='', **kwargs):
     """Executes a command line tool script"""
     cli = os.path.join(self.get('path'), cli.lstrip('/'))
     if not os.path.isfile(cli):
         raise Exception('Could not find script to call')
     if type(args) == 'list':
         args = ' '.join(args)
     cmd = '%s %s %s' % (C.get('php'), cli, args)
     return process(cmd, cwd=self.get('path'), **kwargs)
コード例 #11
0
 def cli(self, cli, args='', **kwargs):
     """Executes a command line tool script"""
     cli = os.path.join(self.get('path'), cli.lstrip('/'))
     if not os.path.isfile(cli):
         raise Exception('Could not find script to call')
     if type(args) == 'list':
         args = ' '.join(args)
     cmd = '%s %s %s' % (C.get('php'), cli, args)
     return process(cmd, cwd=self.get('path'), **kwargs)
コード例 #12
0
ファイル: moodle.py プロジェクト: jacano1969/mdk
 def cli(self, cli, args="", **kwargs):
     """Executes a command line tool script"""
     cli = os.path.join(self.get("path"), cli.lstrip("/"))
     if not os.path.isfile(cli):
         raise Exception("Could not find script to call")
     if type(args) == "list":
         args = " ".join(args)
     cmd = "%s %s %s" % (C.get("php"), cli, args)
     return process(cmd, cwd=self.get("path"), **kwargs)
コード例 #13
0
ファイル: scripts.py プロジェクト: canocampus/mdk
    def run(cls, script, path, cmdkwargs={}):
        """Executes a script at in a certain directory"""

        cli = cls.find(script)
        if cli.endswith('.php'):
            dest = os.path.join(path, 'mdkscriptrun.php')
            shutil.copyfile(cli, dest)

            cmd = '%s %s' % (C.get('php'), dest)
            result = process(cmd, cwd=path, **cmdkwargs)
            os.remove(dest)
        else:
            raise UnsupportedScript('Script not supported')

        return result[0]
コード例 #14
0
ファイル: process_pdb.py プロジェクト: Jianlong-Peng/pytools
def main(argv=sys.argv):
    if len(argv) != 4:
        print "\n  Usage: %s [option] out_dir" % argv[0]
        print "\n  [option]"
        print "    -f pdb_file"
        print "    -l file.  pdb file in each line"
        print "  out_dir: where to save extracted protein(s), ligand(s), and water(s)"
        print "\n  a file named 'names_pro_lig.log' will be generated"
        print ""
        sys.exit(1)

    outf_log = open("names_pro_lig.log", "a")
    if argv[1] == "-f":
        tools.process(argv[2], argv[3], outf_log)
    elif argv[1] == "-l":
        inf = open(argv[2], "r")
        for line in inf:
            if line.startswith('#'):
                continue
            tools.process(line.strip(), argv[3], outf_log)
        inf.close()
    else:
        print "Error: invalid option ", argv[1]
    outf_log.close()
コード例 #15
0
ファイル: moodle.py プロジェクト: rajeshtaneja/mdk
    def initBehat(self, switchcompletely=False):
        """Initialise the Behat environment"""

        if self.branch_compare(25, '<'):
            raise Exception('Behat is only available from Moodle 2.5')

        # Force switch completely for PHP < 5.4
        (none, phpVersion, none) = process('%s -r "echo version_compare(phpversion(), \'5.4\');"' % (C.get('php')))
        if int(phpVersion) <= 0:
            switchcompletely = True

        # Set Behat data root
        behat_dataroot = self.get('dataroot') + '_behat'
        self.updateConfig('behat_dataroot', behat_dataroot)

        # Set Behat DB prefix
        behat_prefix = 'zbehat_'
        self.updateConfig('behat_prefix', behat_prefix)

        # Switch completely?
        if self.branch_compare(27, '<'):
            if switchcompletely:
                self.updateConfig('behat_switchcompletely', switchcompletely)
                self.updateConfig('behat_wwwroot', self.get('wwwroot'))
            else:
                self.removeConfig('behat_switchcompletely')
                self.removeConfig('behat_wwwroot')
        else:
            # Defining wwwroot.
            wwwroot = '%s://%s/' % (C.get('scheme'), C.get('behat.host'))
            if C.get('path') != '' and C.get('path') != None:
                wwwroot = wwwroot + C.get('path') + '/'
            wwwroot = wwwroot + self.identifier
            self.updateConfig('behat_wwwroot', wwwroot)

        # Force a cache purge
        self.purge()

        # Run the init script.
        result = self.cli('admin/tool/behat/cli/init.php', stdout=None, stderr=None)
        if result[0] != 0:
            raise Exception('Error while initialising Behat. Please try manually.')

        # Force a cache purge
        self.purge()
コード例 #16
0
ファイル: css.py プロジェクト: rajeshtaneja/mdk
    def execute(self):
        executable = C.get('recess')
        if not executable:
            raise Exception('Could not find executable path')

        cmd = [executable, self._source, '--compile']

        if self._compress:
            cmd.append('--compress')


        (code, out, err) = process(cmd, self._cwd)
        if code != 0 or len(out) == 0:
            raise CssCompileFailed('Error during compile')

        # Saving to destination
        with open(self._dest, 'w') as f:
            f.write(out)
コード例 #17
0
ファイル: workplace.py プロジェクト: andrewnicols/mdk
    def create(self, name=None, version='master', integration=False, useCacheAsRemote=False):
        """Creates a new instance of Moodle.
        The parameter useCacheAsRemote has been deprecated.
        """
        if name == None:
            name = self.generateInstanceName(version, integration=integration)

        installDir = os.path.join(self.path, name)
        wwwDir = os.path.join(installDir, self.wwwDir)
        dataDir = os.path.join(installDir, self.dataDir)
        linkDir = os.path.join(self.www, name)

        if self.isMoodle(name):
            raise CreateException('The Moodle instance %s already exists' % name)
        elif os.path.isdir(installDir):
            raise CreateException('Installation path exists: %s' % installDir)

        self.checkCachedClones(not integration, integration)
        self.updateCachedClones(stable=not integration, integration=integration, verbose=False)
        mkdir(installDir, 0755)
        mkdir(wwwDir, 0755)
        mkdir(dataDir, 0777)

        repository = self.getCachedRemote(integration)

        # Clone the instances
        logging.info('Cloning repository...')
        process('%s clone %s %s' % (C.get('git'), repository, wwwDir))

        # Symbolic link
        if os.path.islink(linkDir):
            os.remove(linkDir)
        if os.path.isfile(linkDir) or os.path.isdir(linkDir):  # No elif!
            logging.warning('Could not create symbolic link. Please manually create: ln -s %s %s' % (wwwDir, linkDir))
        else:
            os.symlink(wwwDir, linkDir)

        # Symlink to dataDir in wwwDir
        if type(C.get('symlinkToData')) == str:
            linkDataDir = os.path.join(wwwDir, C.get('symlinkToData'))
            if not os.path.isfile(linkDataDir) and not os.path.isdir(linkDataDir) and not os.path.islink(linkDataDir):
                os.symlink(dataDir, linkDataDir)

        logging.info('Checking out branch...')
        repo = git.Git(wwwDir, C.get('git'))

        # Removing the default remote origin coming from the clone
        repo.delRemote('origin')

        # Setting up the correct remote names
        repo.setRemote(C.get('myRemote'), C.get('remotes.mine'))
        repo.setRemote(C.get('upstreamRemote'), repository)

        # Creating, fetch, pulling branches
        repo.fetch(C.get('upstreamRemote'))
        branch = stableBranch(version)
        track = '%s/%s' % (C.get('upstreamRemote'), branch)
        if not repo.hasBranch(branch) and not repo.createBranch(branch, track):
            logging.error('Could not create branch %s tracking %s' % (branch, track))
        else:
            repo.checkout(branch)
        repo.pull(remote=C.get('upstreamRemote'))

        # Fixing up remote URLs if need be, this is done after pulling the cache one because we
        # do not want to contact the real origin server from here, it is slow and pointless.
        if not C.get('useCacheAsUpstreamRemote'):
            realupstream = C.get('remotes.integration') if integration else C.get('remotes.stable')
            if realupstream:
                repo.setRemote(C.get('upstreamRemote'), realupstream)

        M = self.get(name)
        return M
コード例 #18
0
    def create(self, name = None, version = 'master', integration = False, useCacheAsRemote = False):
        """Creates a new instance of Moodle"""
        if name == None:
            if integration:
                name = C.get('wording.prefixIntegration') + prefixVersion
            else:
                name = C.get('wording.prefixStable') + prefixVersion

        installDir = os.path.join(self.path, name)
        wwwDir = os.path.join(installDir, self.wwwDir)
        dataDir = os.path.join(installDir, self.dataDir)
        linkDir = os.path.join(self.www, name)

        if self.isMoodle(name):
            raise Exception('The Moodle instance %s already exists' % name)
        elif os.path.isdir(installDir):
            raise Exception('Installation path exists: %s' % installDir)

        self.checkCachedClones(not integration, integration)
        os.mkdir(installDir, 0755)
        os.mkdir(wwwDir, 0755)
        os.mkdir(dataDir, 0777)

        if integration:
            repository = os.path.join(self.cache, 'integration.git')
            upstreamRepository = C.get('remotes.integration')
        else:
            repository = os.path.join(self.cache, 'moodle.git')
            upstreamRepository = C.get('remotes.stable')

        # Clone the instances
        debug('Cloning repository...')
        if useCacheAsRemote:
            result = process('%s clone %s %s' % (C.get('git'), repository, wwwDir))
            upstreamRepository = repository
        else:
            copy_tree(repository, wwwDir)

        # Symbolic link
        if os.path.islink(linkDir):
            os.remove(linkDir)
        if os.path.isfile(linkDir) or os.path.isdir(linkDir): # No elif!
            debug('Could not create symbolic link')
            debug('Please manually create: ln -s %s %s' (wwwDir, linkDir))
        else:
            os.symlink(wwwDir, linkDir)

        # Symlink to dataDir in wwwDir
        if type(C.get('symlinkToData')) == str:
            linkDataDir = os.path.join(wwwDir, C.get('symlinkToData'))
            if not os.path.isfile(linkDataDir) and not os.path.isdir(linkDataDir) and not os.path.islink(linkDataDir):
                os.symlink(dataDir, linkDataDir)

        debug('Checking out branch...')
        repo = git.Git(wwwDir, C.get('git'))

        # Setting up the correct remote names
        repo.setRemote(C.get('myRemote'), C.get('remotes.mine'))
        repo.setRemote(C.get('upstreamRemote'), upstreamRepository)

        # Creating, fetch, pulling branches
        result = repo.fetch(C.get('upstreamRemote'))
        if version == 'master':
            repo.checkout('master')
        else:
            track = '%s/MOODLE_%s_STABLE' % (C.get('upstreamRemote'), version)
            branch = 'MOODLE_%s_STABLE' % version
            if not repo.hasBranch(branch) and not repo.createBranch(branch, track):
                debug('Could not create branch %s tracking %s' % (branch, track))
            else:
                repo.checkout(branch)
        repo.pull(remote = C.get('upstreamRemote'))

        M = self.get(name)
        return M
コード例 #19
0
ファイル: workplace.py プロジェクト: canocampus/mdk
    def create(self, name=None, version='master', integration=False, useCacheAsRemote=False):
        """Creates a new instance of Moodle.
        The parameter useCacheAsRemote has been deprecated.
        """
        if name == None:
            name = self.generateInstanceName(version, integration=integration)

        installDir = os.path.join(self.path, name)
        wwwDir = os.path.join(installDir, self.wwwDir)
        dataDir = os.path.join(installDir, self.dataDir)
        linkDir = os.path.join(self.www, name)

        if self.isMoodle(name):
            raise CreateException('The Moodle instance %s already exists' % name)
        elif os.path.isdir(installDir):
            raise CreateException('Installation path exists: %s' % installDir)

        self.checkCachedClones(not integration, integration)
        self.updateCachedClones(stable=not integration, integration=integration, verbose=False)
        os.mkdir(installDir, 0755)
        os.mkdir(wwwDir, 0755)
        os.mkdir(dataDir, 0777)

        if integration:
            repository = os.path.join(self.cache, 'integration.git')
        else:
            repository = os.path.join(self.cache, 'moodle.git')

        # Clone the instances
        logging.info('Cloning repository...')
        process('%s clone %s %s' % (C.get('git'), repository, wwwDir))

        # Symbolic link
        if os.path.islink(linkDir):
            os.remove(linkDir)
        if os.path.isfile(linkDir) or os.path.isdir(linkDir):  # No elif!
            logging.warning('Could not create symbolic link. Please manually create: ln -s %s %s' (wwwDir, linkDir))
        else:
            os.symlink(wwwDir, linkDir)

        # Symlink to dataDir in wwwDir
        if type(C.get('symlinkToData')) == str:
            linkDataDir = os.path.join(wwwDir, C.get('symlinkToData'))
            if not os.path.isfile(linkDataDir) and not os.path.isdir(linkDataDir) and not os.path.islink(linkDataDir):
                os.symlink(dataDir, linkDataDir)

        logging.info('Checking out branch...')
        repo = git.Git(wwwDir, C.get('git'))

        # Setting up the correct remote names
        repo.setRemote(C.get('myRemote'), C.get('remotes.mine'))
        repo.setRemote(C.get('upstreamRemote'), repository)

        # Creating, fetch, pulling branches
        repo.fetch(C.get('upstreamRemote'))
        branch = stableBranch(version)
        track = '%s/%s' % (C.get('upstreamRemote'), branch)
        if not repo.hasBranch(branch) and not repo.createBranch(branch, track):
            logging.error('Could not create branch %s tracking %s' % (branch, track))
        else:
            repo.checkout(branch)
        repo.pull(remote=C.get('upstreamRemote'))

        M = self.get(name)
        return M
コード例 #20
0
    def initBehat(self, switchcompletely=False):
        """Initialise the Behat environment"""

        if self.branch_compare(25, '<'):
            raise Exception('Behat is only available from Moodle 2.5')

        # Force switch completely for PHP < 5.4
        (none, phpVersion, none) = process(
            '%s -r "echo version_compare(phpversion(), \'5.4\');"' %
            (C.get('php')))
        if int(phpVersion) <= 0:
            switchcompletely = True

        # Set Behat data root
        behat_dataroot = self.get('dataroot') + '_behat'
        self.updateConfig('behat_dataroot', behat_dataroot)

        # Set Behat DB prefix
        behat_prefix = 'zbehat_'
        self.updateConfig('behat_prefix', behat_prefix)

        # Switch completely?
        if switchcompletely:
            self.updateConfig('behat_switchcompletely', switchcompletely)
            self.updateConfig('behat_wwwroot', self.get('wwwroot'))
        else:
            self.removeConfig('behat_switchcompletely')
            self.removeConfig('behat_wwwroot')

        # Drop the tables
        def drop():
            result = (None, None, None)
            try:
                debug('Dropping database')
                result = self.cli('/admin/tool/behat/cli/util.php',
                                  args='--drop',
                                  stdout=None,
                                  stderr=None)
            except:
                pass
            return result

        # Enabling Behat (or updating the definitions)
        def enable():
            result = (None, None, None)
            try:
                debug('Enabling Behat')
                result = self.cli('/admin/tool/behat/cli/util.php',
                                  args='--enable')
            except:
                pass
            return result

        # Install the tables
        def install():
            result = (None, None, None)
            try:
                debug('Installing Behat tables')
                result = self.cli('/admin/tool/behat/cli/util.php',
                                  args='--install',
                                  stdout=None,
                                  stderr=None)
            except:
                pass
            return result

        # Force a cache purge
        self.purge()

        # Not really proud of this logic, but it works for now. Ideally there shouldn't be any duplicated call to enable().
        result = enable()
        if result[0] == 251:
            raise Exception(
                'Error: Behat requires PHP 5.4 or the flag --switch-completely to be set'
            )
        elif result[0] == 254:
            # Installation required
            installResult = install()
            if installResult[0] != 0:
                raise Exception(
                    'Unknown error while installing Behat. \nError code: %s\nStdout: %s\nStderr: %s'
                    % (result))
            result = enable()
        elif result[0] > 0:
            # Need to drop the tables
            drop()
            installResult = install()
            if installResult[0] != 0:
                raise Exception(
                    'Unknown error while installing Behat. \nError code: %s\nStdout: %s\nStderr: %s'
                    % (result))
            result = enable()

        # Could not enable Behat
        if result[0] != 0:
            raise Exception(
                'Unknown error while enabling Behat. \nError code: %s\nStdout: %s\nStderr: %s'
                % (result))
コード例 #21
0
target_dqn = dqn.DQN(session, height, width, num_actions, "target", None)

session.run(tf.global_variables_initializer())
target_dqn.tranfer_variables_from(main_dqn)

steps_epoch = []
reward_epoch = []
steps_to_train = training_hz
steps_to_transfer = transfer_hz
time_last_save = time.time()

for epoch in range(num_epoch):
    print "\nEpoch: ", epoch

    state, _, crashed = agent.start_game()
    state = process(state, height, width)
    step = 0
    total_reward = 0

    while step < len_epoch and not crashed:
        # keep track how many pretraining steps we still have to execute
        pretraining_steps = max(pretraining_steps - 1, 0)

        explore = rnd.rand() <= explore_prob or pretraining_steps > 0
        action = rnd.randint(num_actions) if explore else main_dqn.get_action(
            state)
        state_next, reward, crashed = agent.do_action(action)
        print "action: {}\t crashed: {}\t random action: {} (prob: {})" \
                .format(game_agent.GameAgent.actions[action], crashed, explore, round(explore_prob,2))
        state_next = process(state_next, height, width)
コード例 #22
0
    vertexBunch.append(tools.Vertex(13, 2))
    vertexBunch.append(tools.Vertex(14, 5))
    vertexBunch.append(tools.Vertex(15, 9))

    linkBunch.append(tools.Link(1, 3, 2))
    linkBunch.append(tools.Link(1, 4, 2))
    linkBunch.append(tools.Link(2, 4, 1))
    linkBunch.append(tools.Link(2, 6, 2))
    linkBunch.append(tools.Link(3, 5, 4))
    linkBunch.append(tools.Link(3, 7, 3))
    linkBunch.append(tools.Link(3, 9, 3))
    linkBunch.append(tools.Link(4, 6, 4))
    linkBunch.append(tools.Link(5, 12, 4))
    linkBunch.append(tools.Link(5, 14, 4))
    linkBunch.append(tools.Link(6, 5, 1))
    linkBunch.append(tools.Link(6, 8, 1))
    linkBunch.append(tools.Link(6, 11, 2))
    linkBunch.append(tools.Link(6, 15, 2))
    linkBunch.append(tools.Link(8, 10, 3))
    linkBunch.append(tools.Link(8, 13, 4))
    linkBunch.append(tools.Link(9, 11, 2))
    linkBunch.append(tools.Link(9, 12, 2))
    linkBunch.append(tools.Link(10, 12, 2))
    linkBunch.append(tools.Link(11, 13, 3))
    linkBunch.append(tools.Link(12, 13, 3))
    linkBunch.append(tools.Link(14, 15, 3))

    familyBunch = tools.createFamilies(vertexBunch, linkBunch)
    tasks, transmissions, coreAmount, totalTime = tools.process(familyBunch)
    tools.draw(tasks, transmissions, coreAmount, totalTime)
コード例 #23
0
ファイル: moodle.py プロジェクト: danpoltawski/mdk
    def initBehat(self, switchcompletely=False):
        """Initialise the Behat environment"""

        if self.branch_compare(25, '<'):
            raise Exception('Behat is only available from Moodle 2.5')

        # Force switch completely for PHP < 5.4
        (none, phpVersion, none) = process('%s -r "echo version_compare(phpversion(), \'5.4\');"' % (C.get('php')))
        if int(phpVersion) <= 0:
            switchcompletely = True

        # Set Behat data root
        behat_dataroot = self.get('dataroot') + '_behat'
        self.updateConfig('behat_dataroot', behat_dataroot)

        # Set Behat DB prefix
        behat_prefix = 'zbehat_'
        self.updateConfig('behat_prefix', behat_prefix)

        # Switch completely?
        if switchcompletely:
            self.updateConfig('behat_switchcompletely', switchcompletely)
            self.updateConfig('behat_wwwroot', self.get('wwwroot'))
        else:
            self.removeConfig('behat_switchcompletely')
            self.removeConfig('behat_wwwroot')

        # Drop the tables
        def drop():
            result = (None, None, None)
            try:
                debug('Dropping database')
                result = self.cli('/admin/tool/behat/cli/util.php', args='--drop', stdout=None, stderr=None)
            except:
                pass
            return result

        # Enabling Behat (or updating the definitions)
        def enable():
            result = (None, None, None)
            try:
                debug('Enabling Behat')
                result = self.cli('/admin/tool/behat/cli/util.php', args='--enable')
            except:
                pass
            return result

        # Install the tables
        def install():
            result = (None, None, None)
            try:
                debug('Installing Behat tables')
                result = self.cli('/admin/tool/behat/cli/util.php', args='--install', stdout=None, stderr=None)
            except:
                pass
            return result

        # Force a cache purge
        self.purge()

        # Not really proud of this logic, but it works for now. Ideally there shouldn't be any duplicated call to enable().
        result = enable()
        if result[0] == 251:
            raise Exception('Error: Behat requires PHP 5.4 or the flag --switch-completely to be set')
        elif result[0] == 254:
            # Installation required
            installResult = install()
            if installResult[0] != 0:
                raise Exception('Unknown error while installing Behat. \nError code: %s\nStdout: %s\nStderr: %s' % (result))
            result = enable()
        elif result[0] > 0:
            # Need to drop the tables
            drop()
            installResult = install()
            if installResult[0] != 0:
                raise Exception('Unknown error while installing Behat. \nError code: %s\nStdout: %s\nStderr: %s' % (result))
            result = enable()

        # Could not enable Behat
        if result[0] != 0:
            raise Exception('Unknown error while enabling Behat. \nError code: %s\nStdout: %s\nStderr: %s' % (result))