def UsePsyco():
    'Tries to use psyco if possible'
    try:
        import psyco
        psyco.profile()
    except:
        pass
Ejemplo n.º 2
0
def _hook(*args, **kwargs):
    try:
        import psyco
    except ImportError:
        pass
    else:
        psyco.profile()
Ejemplo n.º 3
0
def __test():
    import psyco
    psyco.profile()

    class W(object):
        def GetClientSizeTuple(self):
            return (640,480)

    class O(object):
        pass

    w = W()
    v = Viewport(w)
    v.SetCenter((50, 3000))
    objects = [ ( "a", 12555, -256 ),
                ( "b", 123, 7885 ),
                ( "c", -45645, 0 ),
                ( "d", 235, 66 ),
                ]
    for i in xrange(5):
        for name, x, y in objects:
            v.Add(name + str(i), O(), position=(x, y))
    print v._Ratio(v._Indices())
    for i in xrange(50000):
        v._ConvertPositions(v._Indices())
    print v._ConvertPositions(v._Indices())
Ejemplo n.º 4
0
 def process_request(self, request):
     try:
         import psyco
         psyco.profile()
     except ImportError:
         pass
     return None
Ejemplo n.º 5
0
def UsePsyco():
    'Tries to use psyco if possible'
    try:
        import psyco
        psyco.profile()
        print "Using psyco"
    except: pass         
Ejemplo n.º 6
0
def run_or_profile(suite):
    runner = unittest.TextTestRunner(verbosity=2)

    args = sys.argv[1:]

    if '-P' in args or '-PP' in args:
        try:
            import psyco
            if '-PP' in sys.argv[1:]:
                psyco.profile()
            else:
                psyco.full()
            print "Using Psyco."
        except:
            pass

    if '-p' in args:
        import os, hotshot, hotshot.stats
        LOG_FILE="profile.log"

        profiler = hotshot.Profile(LOG_FILE)
        profiler.runcall(runner.run, suite)
        profiler.close()

        stats = hotshot.stats.load(LOG_FILE)
        stats.strip_dirs()
        stats.sort_stats('time', 'calls')
        stats.print_stats(60)

        try:
            os.unlink(LOG_FILE)
        except:
            pass
    else:
        runner.run(suite)
Ejemplo n.º 7
0
def main(argv):
    """The main method for this module."""
    parser = _createOptionParser()
    (options, args) = parser.parse_args(argv)

    try:
        [inputFile, outputFile] = args
    except:
        parser.print_help()
        sys.exit(1)

    # Avoid psyco in debugging mode, since it merges stack frames.
    if not options.debug:
        try:
            import psyco
            psyco.profile()
        except:
            pass

    if options.escape:
        escapeUtf8(inputFile, outputFile)
    else:
        unescapeUtf8(inputFile, outputFile)
    
    return
Ejemplo n.º 8
0
def Main(args):
    """Parses arguments and does the appropriate thing."""
    util.ChangeStdoutEncoding()

    if sys.version_info < (2, 6):
        print "GRIT requires Python 2.6 or later."
        return 2
    elif not args or (len(args) == 1 and args[0] == 'help'):
        PrintUsage()
        return 0
    elif len(args) == 2 and args[0] == 'help':
        tool = args[1].lower()
        if not _GetToolInfo(tool):
            print "No such tool.  Try running 'grit help' for a list of tools."
            return 2

        print("Help for 'grit %s' (for general help, run 'grit help'):\n" %
              (tool))
        print _GetToolInfo(tool)[_FACTORY]().__doc__
        return 0
    else:
        options = Options()
        args = options.ReadOptions(args)  # args may be shorter after this
        if not args:
            print "No tool provided.  Try running 'grit help' for a list of tools."
            return 2
        tool = args[0]
        if not _GetToolInfo(tool):
            print "No such tool.  Try running 'grit help' for a list of tools."
            return 2

        try:
            if _GetToolInfo(tool)[_REQUIRES_INPUT]:
                os.stat(options.input)
        except OSError:
            print(
                'Input file %s not found.\n'
                'To specify a different input file:\n'
                '  1. Use the GRIT_INPUT environment variable.\n'
                '  2. Use the -i command-line option.  This overrides '
                'GRIT_INPUT.\n'
                '  3. Specify neither GRIT_INPUT or -i and GRIT will try to load '
                "'resource.grd'\n"
                '     from the current directory.' % options.input)
            return 2

        if options.psyco:
            # Psyco is a specializing JIT for Python.  Early tests indicate that it
            # could speed up GRIT (at the expense of more memory) for large GRIT
            # compilations.  See http://psyco.sourceforge.net/
            import psyco
            psyco.profile()

        toolobject = _GetToolInfo(tool)[_FACTORY]()
        if options.profile_dest:
            import hotshot
            prof = hotshot.Profile(options.profile_dest)
            prof.runcall(toolobject.Run, options, args[1:])
        else:
            toolobject.Run(options, args[1:])
Ejemplo n.º 9
0
def Main(args):
  """Parses arguments and does the appropriate thing."""
  util.ChangeStdoutEncoding()

  if sys.version_info < (2, 6):
    print "GRIT requires Python 2.6 or later."
    return 2
  elif not args or (len(args) == 1 and args[0] == 'help'):
    PrintUsage()
    return 0
  elif len(args) == 2 and args[0] == 'help':
    tool = args[1].lower()
    if not _GetToolInfo(tool):
      print "No such tool.  Try running 'grit help' for a list of tools."
      return 2

    print ("Help for 'grit %s' (for general help, run 'grit help'):\n"
           % (tool))
    print _GetToolInfo(tool)[_FACTORY]().__doc__
    return 0
  else:
    options = Options()
    args = options.ReadOptions(args)  # args may be shorter after this
    if not args:
      print "No tool provided.  Try running 'grit help' for a list of tools."
      return 2
    tool = args[0]
    if not _GetToolInfo(tool):
      print "No such tool.  Try running 'grit help' for a list of tools."
      return 2

    try:
      if _GetToolInfo(tool)[_REQUIRES_INPUT]:
        os.stat(options.input)
    except OSError:
      print ('Input file %s not found.\n'
             'To specify a different input file:\n'
             '  1. Use the GRIT_INPUT environment variable.\n'
             '  2. Use the -i command-line option.  This overrides '
             'GRIT_INPUT.\n'
             '  3. Specify neither GRIT_INPUT or -i and GRIT will try to load '
             "'resource.grd'\n"
             '     from the current directory.' % options.input)
      return 2

    if options.psyco:
      # Psyco is a specializing JIT for Python.  Early tests indicate that it
      # could speed up GRIT (at the expense of more memory) for large GRIT
      # compilations.  See http://psyco.sourceforge.net/
      import psyco
      psyco.profile()

    toolobject = _GetToolInfo(tool)[_FACTORY]()
    if options.profile_dest:
      import hotshot
      prof = hotshot.Profile(options.profile_dest)
      prof.runcall(toolobject.Run, options, args[1:])
    else:
      toolobject.Run(options, args[1:])
Ejemplo n.º 10
0
def UsePsyco():
    "Tries to use psyco if possible"
    try:
        import psyco

        psyco.profile()
    except:
        pass
Ejemplo n.º 11
0
def UsePsyco():
    'Tries to use psyco if possible'
    try:
        import psyco
        psyco.profile()
        print "Using psyco"
    except:
        pass
Ejemplo n.º 12
0
 def open_file(self, filename):
     try:
         import psyco
         psyco.profile()
     except ImportError:
         print "Psyco not found"
     self._start = time.clock()
     print "Export to " + filename
     self.export_scene(filename)
Ejemplo n.º 13
0
def initPsyco(psycoProfile=False):
	try:
		import psyco
		if psycoProfile:
			psyco.log()
			psyco.profile()
		else:
			psyco.full()
	except ImportError:
		pass
Ejemplo n.º 14
0
def initPsyco(psycoProfile=False):
    try:
        import psyco
        if psycoProfile:
            psyco.log()
            psyco.profile()
        else:
            psyco.full()
    except ImportError:
        pass
Ejemplo n.º 15
0
Archivo: main.py Proyecto: sabren/blaze
def run():
    try:
        import psyco
        psyco.profile()
    except ImportError:
        print 'psyco not found! If your game runs slowly try installing \
it from http://psyco.sourceforge.net.'
    e = Game(20)
    e.DEFAULT = menus.MainMenu
    e.run()
Ejemplo n.º 16
0
 def start(self):
     "Launch various sub-threads."
     #self.listener.start()
     self.reporter.start()
     if self.config.do_cleaning:
         self.cleaner.start()
     try:
         import psyco
         psyco.profile()
     except ImportError:
         log.info("The psyco package is unavailable (that's okay, but the client is more\nefficient if psyco is installed).")
Ejemplo n.º 17
0
Archivo: main.py Proyecto: sabren/blaze
    def __init__(self, fps=40):
        Engine.__init__(self, fps)
        try:
            import psyco

            psyco.profile()
        except ImportError:
            print "psyco not detected, if your game runs slowly try installing \
it from http://psyco.sourceforge.net."
        pygame.display.set_caption("Ascent of Justice")
        pygame.display.set_icon(data.icon)
Ejemplo n.º 18
0
Archivo: Miro.py Proyecto: cool-RR/Miro
def activate_psyco():
    # Get cpu type
    info = os.uname()
    cpu = info[-1]

    # Activate only if we are on an Intel Mac.
    if cpu == 'i386':
        try:
            import psyco
            psyco.profile()
        except:
            pass
Ejemplo n.º 19
0
def Main(data_dir):
    print "Now checking your Python environment:"
    Check_Version()

    # Psyco is optional, but recommended :)
    if ( True ):
        try:
            import psyco
            psyco.profile()
        except Exception, r:
            print 'Psyco not found. If the game runs too slowly, '
            print 'install Psyco from http://psyco.sf.net/'
Ejemplo n.º 20
0
 def start(self):
     "Launch various sub-threads."
     #self.listener.start()
     self.reporter.start()
     if self.config.do_cleaning:
         self.cleaner.start()
     try:
         import psyco
         psyco.profile()
     except ImportError:
         log.info(
             "The psyco package is unavailable (that's okay, but the client is more\nefficient if psyco is installed)."
         )
Ejemplo n.º 21
0
def run():
    import sys, optparse
    app = qt.QApplication(sys.argv)

    opparser = optparse.OptionParser()
    opparser.add_option('-l', '--logfile', dest='logfile',
                        help="write log to FILE", metavar='FILE')

    opparser.add_option('-d', '--loglevel', dest='loglevel',
                        help="set log level", default='ERROR')

    opparser.add_option('-L', '--language', dest='language',
                        help="set user interface language")

    opparser.add_option('-P', '--no-psyco', dest='psyco_off',
                        action='store_true', default=False,
                        help="set user interface language")

    options, args = opparser.parse_args( app.argv() )

    if not options.psyco_off:
        try:
            import psyco
            psyco.profile()
            RUNNING_PSYCO = True
        except ImportError:
            pass

    loglevel = getattr(logging, options.loglevel.upper(), logging.ERROR)
    if options.logfile:
        logging.basicConfig(level=loglevel,
                            filename=options.logfile, filemode='w')
    else:
        logging.basicConfig(level=loglevel)

    if options.language:
        translator = qt.QTranslator()
        if translator.load('gui_%s' % options.language, 'qtgui/ts'):
            app.installTranslator(translator)

    # setup GUI
    qt.QObject.connect(app, qt.SIGNAL("lastWindowClosed()"), app, qt.SLOT("quit()"))

    w = OverlayDesigner_gui()
    app.setMainWidget(w)
    w.show()

    if len(args) > 1:
        w.loadFile(args[1])

    app.exec_loop()
Ejemplo n.º 22
0
	def __init__(self, fileName = None, stream = None):
		import psyco
		psyco.profile()
		self.logger = logging.getLogger("pypsd.psdfile.PSDFile")
		self.logger.debug("__init__ method. In: fileName=%s" % fileName)

		self.stream = stream
		self.fileName = fileName

		self.header = None
		self.colorMode = None
		self.imageResources = None
		self.layerMask = None
		self.imageData = None
Ejemplo n.º 23
0
def load_psyco():
    """
    Load psyco library for speedup.
    """
    if HasPsyco:
        import psyco
        # psyco >= 1.4.0 final is needed
        if psyco.__version__ >= 0x10400f0:
            #psyco.log(logfile="psyco.log")
            psyco.profile(memory=10000, memorymax=100000)
        else:
            # warn about old psyco version
            log.warn(LOG_PROXY,
         _("Psyco is installed but not used since the version is too old.\n"
           "Psyco >= 1.4 is needed."))
Ejemplo n.º 24
0
def main(argv):
    parser = _create_option_parser()
    (options, args) = parser.parse_args(argv)

    if args:
        parser.print_help()
        sys.exit(1)

    # Avoid psyco in debugging mode, since it merges stack frames.
    if not options.debug:
        try:
            import psyco
            psyco.profile()
        except:
            pass

    check_alignments()
    return
Ejemplo n.º 25
0
def main(argv):
    parser = _create_option_parser()
    (options, args) = parser.parse_args(argv)

    if args:
        parser.print_help()
        sys.exit(1)

    # Avoid psyco in debugging mode, since it merges stack frames.
    if not options.debug:
        try:
            import psyco
            psyco.profile()
        except:
            pass

    check_alignments()
    return
Ejemplo n.º 26
0
def startPsyco ():

    import leoGlobals as g

    try:
        import psyco
        if 0:
            theFile = r"c:\prog\test\psycoLog.txt"
            g.es("psyco now logging to:",theFile,color="blue")
            psyco.log(theFile)
            psyco.profile()
        psyco.full()
        g.es("psyco now running",color="blue")
    except ImportError:
        g.app.use_psyco = False
    except:
        print "unexpected exception importing psyco"
        g.es_exception()
        g.app.use_psyco = False
Ejemplo n.º 27
0
def main():
    if options.run_shell:
        # Due to univlib init code having been moved into initthread,
        # we must duplicate (ugh!) the univlib initialization code here
        # in order to maintain easiness in shell operations
        # the code is directly copied from LobsterLoader
        # TODO: refactor this once i come up with a solution

        ### START COPY ###
        # init univlib ahead of time
        from gingerprawn.api import univlib

        # FIXED: not hardcoded anymore, can be changed via cmdline
        # default value moved there
        univlib.set_current_univ(_APP_OPTIONS.univ_sel)
        ### END OF COPY ###

        import code

        conzole = code.InteractiveConsole()
        conzole.interact()
        sys.exit(0)

    if not options.do_profiling:
        if options.run_psycoed:
            try:
                import psyco

                logdebug("running Psyco'd")
                psyco.log()
                psyco.profile()
            except ImportError:
                pass
        wxmain()
    else:
        import cProfile

        loginfo("running profiled, starting from here...")
        cProfile.run(
            "wxmain()",
            # profile result destination
            normpath(pathjoin(_PKG_TOPLEV, "launcher/gp-profile")),
        )
 def usepsyco(self, options):
     # options.psyco == None means the default, which is "full", but don't give a warning...
     # options.psyco == "none" means don't use psyco at all...
     if getattr(options, "psyco", "none") == "none":
         return
     try:
         import psyco
     except Exception:
         if options.psyco is not None:
             self.warning("psyco unavailable", options, sys.exc_info())
         return
     if options.psyco is None:
         options.psyco = "full"
     if options.psyco == "full":
         psyco.full()
     elif options.psyco == "profile":
         psyco.profile()
     # tell psyco the functions it cannot compile, to prevent warnings
     import encodings
     psyco.cannotcompile(encodings.search_function)
Ejemplo n.º 29
0
def main(argv):
    parser = _createOptionParser()
    (options, args) = parser.parse_args(argv)

    try:
        [title, message] = args
    except:
        parser.print_help()
        sys.exit(1)

    # Avoid psyco in debugging mode, since it merges stack frames.
    if not options.debug:
        try:
            import psyco
            psyco.profile()
        except:
            pass

    notify(title=title, message=message, appName="Python shell")
    
    return
Ejemplo n.º 30
0
def main(argv):
    """ The main method for this module.
    """
    parser = _createOptionParser()
    (options, args) = parser.parse_args(argv)

    if args:
        parser.print_help()
        sys.exit(1)

    # Avoid psyco in debugging mode, since it merges stack frames.
    if not options.debug:
        try:
            import psyco
            psyco.profile()
        except:
            pass

    mineAsahi()
    
    return
Ejemplo n.º 31
0
 def __init__(self, path):
     configuration.Config.__init__(self)
     self.dir = os.path.dirname(path)
     self.PID_FILE = self.PID_FILE.replace("$configdir", self.dir)
     if os.path.exists(path):
         self.load(path)
         if self.VERSION < self.__class__.VERSION.default:
             self.VERSION = self.__class__.VERSION.default
             self.save(path)
     else:
         self.save(path)
     self.set_prefix(os.path.abspath(os.path.join(os.path.dirname(__file__),
             os.pardir, os.pardir)))
     self.path = path
     socket.setdefaulttimeout(self.SOCKET_TIMEOUT/1000.0)
     if self.PSYCO:
         try:
             import psyco
             psyco.profile()
             print "Psyco JIT optimization active"
         except ImportError:
             print "Psyco enabled but not installed"
     sys.path.append(os.path.dirname(__file__))
Ejemplo n.º 32
0
    def run(self):
        # Try to load psyco module, saving this information
        # if we care to use it later (such as in a About Dialog)
        if not development_mode(default=False):
            try:
                import psyco
            except ImportError:
                log.warning(_("RUNNING WITHOUT PSYCO!"))
                log.warning(_("psyco is a module that speeds up the execution "
                    "of Python applications. It is not a requirement, and "
                    "Umit will work normally without it, but you're "
                    "encouraged to install it to have a better speed "
                    "experience. Download psyco at http://psyco.sf.net/"""))
                self.using_psyco = False
            else:
                psyco.profile()
                self.using_psyco = True

        self.diff = option_parser.get_diff()
        if self.diff:
            self.__run_text()
        else:
            self.__run_gui()
Ejemplo n.º 33
0
def open_file(filename):
    try:
        import psyco
        psyco.profile()
    except ImportError:
        print "Psyco not available to PyPRP..."
    start = time.clock()
    log = ptLog(sys.stdout, filename + ".log", "w")
    std = sys.stdout
    sys.stdout = log
    print("Importing %s ..." % filename)
    args = __script__['arg']
    print("Args are %s " % args)
    w = args.split("_")
    print w
    ext = "." + w[1]
    basepath = dirname(filename)
    if filename.find(ext, -4) == -1:
        raise RuntimeError, "Unsuported file %s, expecting an %s file" % (
            filename, ext)
    if w[1] == "age":
        agename = basename(filename[:-4])
        if w[0] == "i":
            import_age(agename, basepath)
        else:
            raise RuntimeError, "Unimplemented option %s" % (args)
    elif w[1] == "prp":
        if w[0] == "i":
            import_prp(filename, basepath)
        else:
            raise RuntimeError, "Unimplemented option %s" % (args)
    else:
        raise RuntimeError, "Unimplemented option %s" % (args)
    stop = time.clock()
    print("done in %.2f seconds" % (stop - start))
    sys.stdout = std
    log.close()
Ejemplo n.º 34
0
def open_file(filename):
    try:
        import psyco
        psyco.profile()
    except ImportError:
        print "Psyco not available to PyPRP..."
    start=time.clock()
    log=ptLog(sys.stdout,filename + ".log","w")
    std=sys.stdout
    sys.stdout=log
    print("Importing %s ..." % filename)
    args = __script__['arg']
    print("Args are %s " % args)
    w = args.split("_")
    print w
    ext="." + w[1]
    basepath = dirname(filename)
    if filename.find(ext,-4) == -1:
        raise RuntimeError,"Unsuported file %s, expecting an %s file" %(filename,ext)
    if w[1]=="age":
        agename = basename(filename[:-4])
        if w[0]=="i":
            import_age(agename,basepath)
        else:
            raise RuntimeError,"Unimplemented option %s" %(args)
    elif w[1]=="prp":
        if w[0]=="i":
            import_prp(filename,basepath)
        else:
            raise RuntimeError,"Unimplemented option %s" %(args)
    else:
        raise RuntimeError,"Unimplemented option %s" %(args)
    stop=time.clock()
    print("done in %.2f seconds" % (stop-start))
    sys.stdout=std
    log.close()
Ejemplo n.º 35
0
 def __init__(self, path):
     configuration.Config.__init__(self)
     self.dir = os.path.dirname(path)
     self.PID_FILE = self.PID_FILE.replace("$configdir", self.dir)
     if os.path.exists(path):
         self.load(path)
         if self.VERSION < self.__class__.VERSION.default:
             self.VERSION = self.__class__.VERSION.default
             self.save(path)
     else:
         self.save(path)
     self.set_prefix(
         os.path.abspath(
             os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)))
     self.path = path
     socket.setdefaulttimeout(self.SOCKET_TIMEOUT / 1000.0)
     if self.PSYCO:
         try:
             import psyco
             psyco.profile()
             print "Psyco JIT optimization active"
         except ImportError:
             print "Psyco enabled but not installed"
     sys.path.append(os.path.dirname(__file__))
Ejemplo n.º 36
0
 def process_request(self, request):
     psyco.profile()
     return None
Ejemplo n.º 37
0
import psyco
psyco.full()
psyco.log()
psyco.profile(.05)


import pygame
import eventqueue
import library
import time

from ocempgui.widgets import *
from ocempgui.widgets.Constants import *
#The purpose of this class is to hold all of the images
#This will keep the system from loading multiples of the
#same image.

#This class will also hold all of the sprites as well as
#the background.

#all sprite classes will need to add themselves to the engine on creation
#all views will need to talk to the engine in order to get the collisions
#(using the sprites group) as well as the images it should render.

#Engine might not be the best description of this class, if someone thinks
#of a better one, let me know.


#this is going to start taking care of more than just sprites.
class spawn:
	def __init__(self, sprite_engin, x, y, facing):
Ejemplo n.º 38
0
def main():
    """
    The main function of the plotting module
    """
    logging.basicConfig(level=logging.INFO,
                        format='%(levelname)s [%(funcName)s] %(message)s')
    try:
        import psyco
        psyco.full()
        psyco.profile(0.0)
    except ImportError:
        print "INFO: psyco module not available"

    parser = argparse.ArgumentParser(
        description='Plot data stored in an sqlite database')
    parser.add_argument(
        '--topo',
        required=True,
        help='name of the database where the network topology is available')
    parser.add_argument(
        '--db',
        required=True,
        help='name of the database where the results shall be stored')
    parser.add_argument('--clone',
                        default=None,
                        help='clone the scenarios from another experiment')
    parser.add_argument('--src',
                        nargs='+',
                        default=['all'],
                        help='source node sending packets')
    parser.add_argument('--gossip',
                        nargs='+',
                        default=['0'],
                        help='gossip variants')
    parser.add_argument('-m', nargs='+', default=['1'], help='m')
    parser.add_argument('-k',
                        nargs='+',
                        default=['1'],
                        help='flood on first k hops')
    parser.add_argument('--probability',
                        '-p',
                        nargs='+',
                        default=list(pylab.linspace(0.1, 1, 10)),
                        help='gossip variants')
    parser.add_argument('--outdir',
                        default='',
                        help='output directory for the plots')
    parser.add_argument('--pkg_num',
                        default=100,
                        type=int,
                        help='number of packets')
    parser.add_argument('--pkg_size',
                        nargs='+',
                        default=[0],
                        type=int,
                        help='select a particular graph')
    parser.add_argument('--no_loss',
                        nargs='?',
                        const=True,
                        default=False,
                        help='List all callable plotting functions')
    args = parser.parse_args()

    options = {}
    options['topo'] = args.topo
    options['outdir'] = args.outdir
    options['loss'] = not args.no_loss
    options['db'] = args.db
    options['nodes'] = 'all'

    gossip_params = dict()
    options['gossip_params'] = gossip_params
    gossip_params['src'] = args.src
    gossip_params['gossip'] = args.gossip
    gossip_params['m'] = args.m
    gossip_params['k'] = args.k
    gossip_params['p'] = args.probability
    gossip_params['pkg_num'] = args.pkg_num
    gossip_params['pkg_size'] = args.pkg_size

    db = options['topo']
    conn = sqlite3.connect(db)
    options['topo_conn'] = conn
    cursor = conn.cursor()

    if 'all' in args.src and not args.clone:
        logging.info('all routers selected as sources')
        cursor.execute('''SELECT host FROM addr''')
        hosts = list(pylab.flatten(cursor.fetchall()))
        options['src'] = hosts

    if args.clone:
        clone_conn = sqlite3.connect(args.clone)
        clone_cursor = clone_conn.cursor()
        clone(options, clone_cursor)

    cursor = prepare_db(options)
    graphs = create_graphs(options)

    #for helloSize, G in graphs:
    #for gossip in gossip_params['gossip']:
    #for p in gossip_params['p']:
    #t = (None, '', '', p, p2, k, n, m, timeout, gossip, 0, 0, 0, 0, T_MAX, p_min, p_max, helloSize)
    #cursor.execute('INSERT INTO tag VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', t)
    #curr_tag_key = c.lastrowid

    for node in graphs[0][1]:
        cursor.execute('INSERT INTO addr VALUES (?)', (node, ))
    options['db_conn'].commit()

    for i, pkg_size in enumerate(gossip_params['pkg_size']):
        G = None
        for helloSize, graph in graphs:
            if helloSize == pkg_size:
                G = (helloSize, graph)
                break
        if not G:
            logging.critical('no graph found for pkg_size=%d', pkg_size)
            assert (False)
        logging.info('helloSize=\"%d\" (%d/%d)', G[0], i + 1, len(graphs))
        simulate(G, options)
Ejemplo n.º 39
0
def main():
  # Disabling garbage collection saves about 1 second out of 16 on a Linux
  # z620 workstation. Since this is a short-lived process it's not a problem to
  # leak a few cyclyc references in order to spare the CPU cycles for
  # scanning the heap.
  gc.disable()

  args = sys.argv[1:]

  use_analyzer = len(args) and args[0] == '--analyzer'
  if use_analyzer:
    args.pop(0)
    os.environ['GYP_GENERATORS'] = 'analyzer'
    args.append('-Gconfig_path=' + args.pop(0))
    args.append('-Ganalyzer_output_path=' + args.pop(0))

  if int(os.environ.get('GYP_CHROMIUM_NO_ACTION', 0)):
    print 'Skipping gyp_chromium due to GYP_CHROMIUM_NO_ACTION env var.'
    sys.exit(0)

  # Use the Psyco JIT if available.
  if psyco:
    psyco.profile()
    print "Enabled Psyco JIT."

  # Fall back on hermetic python if we happen to get run under cygwin.
  # TODO(bradnelson): take this out once this issue is fixed:
  #    http://code.google.com/p/gyp/issues/detail?id=177
  if sys.platform == 'cygwin':
    import find_depot_tools
    depot_tools_path = find_depot_tools.add_depot_tools_to_path()
    python_dir = sorted(glob.glob(os.path.join(depot_tools_path,
                                               'python2*_bin')))[-1]
    env = os.environ.copy()
    env['PATH'] = python_dir + os.pathsep + env.get('PATH', '')
    cmd = [os.path.join(python_dir, 'python.exe')] + sys.argv
    sys.exit(subprocess.call(cmd, env=env))

  # This could give false positives since it doesn't actually do real option
  # parsing.  Oh well.
  gyp_file_specified = any(arg.endswith('.gyp') for arg in args)

  gyp_environment.SetEnvironment()

  # If we didn't get a file, check an env var, and then fall back to
  # assuming 'all.gyp' from the same directory as the script.
  if not gyp_file_specified:
    gyp_file = os.environ.get('CHROMIUM_GYP_FILE')
    if gyp_file:
      # Note that CHROMIUM_GYP_FILE values can't have backslashes as
      # path separators even on Windows due to the use of shlex.split().
      args.extend(shlex.split(gyp_file))
    else:
      args.append(os.path.join(script_dir, 'all.gyp'))

  supplemental_includes = GetSupplementalFiles()
  gyp_vars_dict = GetGypVars(supplemental_includes)
  # There shouldn't be a circular dependency relationship between .gyp files,
  # but in Chromium's .gyp files, on non-Mac platforms, circular relationships
  # currently exist.  The check for circular dependencies is currently
  # bypassed on other platforms, but is left enabled on iOS, where a violation
  # of the rule causes Xcode to misbehave badly.
  # TODO(mark): Find and kill remaining circular dependencies, and remove this
  # option.  http://crbug.com/35878.
  # TODO(tc): Fix circular dependencies in ChromiumOS then add linux2 to the
  # list.
  if gyp_vars_dict.get('OS') != 'ios':
    args.append('--no-circular-check')

  # libtool on Mac warns about duplicate basenames in static libraries, so
  # they're disallowed in general by gyp. We are lax on this point, so disable
  # this check other than on Mac. GN does not use static libraries as heavily,
  # so over time this restriction will mostly go away anyway, even on Mac.
  # https://code.google.com/p/gyp/issues/detail?id=384
  if sys.platform != 'darwin':
    args.append('--no-duplicate-basename-check')

  # We explicitly don't support the make gyp generator (crbug.com/348686). Be
  # nice and fail here, rather than choking in gyp.
  if re.search(r'(^|,|\s)make($|,|\s)', os.environ.get('GYP_GENERATORS', '')):
    print 'Error: make gyp generator not supported (check GYP_GENERATORS).'
    sys.exit(1)

  # We explicitly don't support the native msvs gyp generator. Be nice and
  # fail here, rather than generating broken projects.
  if re.search(r'(^|,|\s)msvs($|,|\s)', os.environ.get('GYP_GENERATORS', '')):
    print 'Error: msvs gyp generator not supported (check GYP_GENERATORS).'
    print 'Did you mean to use the `msvs-ninja` generator?'
    sys.exit(1)

  # If CHROMIUM_GYP_SYNTAX_CHECK is set to 1, it will invoke gyp with --check
  # to enfore syntax checking.
  syntax_check = os.environ.get('CHROMIUM_GYP_SYNTAX_CHECK')
  if syntax_check and int(syntax_check):
    args.append('--check')

  # TODO(dmikurube): Remove these checks and messages after a while.
  if ('linux_use_tcmalloc' in gyp_vars_dict or
      'android_use_tcmalloc' in gyp_vars_dict):
    print '*****************************************************************'
    print '"linux_use_tcmalloc" and "android_use_tcmalloc" are deprecated!'
    print '-----------------------------------------------------------------'
    print 'You specify "linux_use_tcmalloc" or "android_use_tcmalloc" in'
    print 'your GYP_DEFINES. Please switch them into "use_allocator" now.'
    print 'See http://crbug.com/345554 for the details.'
    print '*****************************************************************'

  # Automatically turn on crosscompile support for platforms that need it.
  # (The Chrome OS build sets CC_host / CC_target which implicitly enables
  # this mode.)
  if all(('ninja' in os.environ.get('GYP_GENERATORS', ''),
          gyp_vars_dict.get('OS') in ['android', 'ios'],
          'GYP_CROSSCOMPILE' not in os.environ)):
    os.environ['GYP_CROSSCOMPILE'] = '1'
  if gyp_vars_dict.get('OS') == 'android':
    args.append('--check')

  args.extend(
      ['-I' + i for i in additional_include_files(supplemental_includes, args)])

  args.extend(['-D', 'gyp_output_dir=' + GetOutputDirectory()])

  if not use_analyzer:
    print 'Updating projects from gyp files...'
    sys.stdout.flush()

  # Off we go...
  gyp_rc = gyp.main(args)

  if not use_analyzer:
    vs2013_runtime_dll_dirs = vs_toolchain.SetEnvironmentAndGetRuntimeDllDirs()
    if vs2013_runtime_dll_dirs:
      x64_runtime, x86_runtime = vs2013_runtime_dll_dirs
      vs_toolchain.CopyVsRuntimeDlls(
        os.path.join(chrome_src, GetOutputDirectory()),
        (x86_runtime, x64_runtime))

  sys.exit(gyp_rc)
Ejemplo n.º 40
0
def startup_script( main_globals):
    """
    This is the main startup script for NE1.
    It is intended to be run only once, and only by the code in main.py.
    When this function returns, the caller is intended to immediately exit
    normally.
       Parameter main_globals should be the value of globals() in __main__,
    which is needed in case .atom-debug-rc is executed, since it must be
    executed in that global namespace.
    """

    # Note: importing all of NE1's functionality can take a long time.
    # To the extent possible, we want that time to be spent after
    # something is visible to the user, but (mostly) before the main
    # window is shown to the user (since showing the main window implies
    # that NE1 is almost ready to go). So we display a splashscreen
    # before doing most imports and initializations, then set up most
    # of our data structures and UI commands (thus importing the code
    # needed to implement them), and then show the main window.
    # (Some experimental commands are initialized after that, so that
    # errors that occur then can't prevent the main window from becoming
    # visible.)

    # TODO: turn the sections of code below into named functions or methods,
    # and perhaps split before_most_imports and before_creating_app into
    # more named functions or methods. The biggest split should be between
    # functions that need to be careful to do very few or no imports,
    # and functions that are free to do any imports.
    
    # print the version information including official release candidate if it
    # is not 0 (false)
    if NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE:
        print "Version: NanoEngineer-1 v%s_RC%s" % \
              (NE1_Build_Constants.NE1_RELEASE_VERSION, \
               NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE)
    else:
        print "Version: NanoEngineer-1 v%s" % \
              NE1_Build_Constants.NE1_RELEASE_VERSION 
    
    # "Do things that should be done before most imports occur."
    
    startup_before_most_imports.before_most_imports( main_globals )


    from PyQt4.Qt import QApplication, QSplashScreen

    
    # "Do things that should be done before creating the application object."
    
    startup_before_most_imports.before_creating_app()
        ### TODO: this imports undo, env, debug, and it got moved earlier
        # in the startup process at some point. Those imports are probably not
        # too likely to pull in a lot of others, but if possible we should put up
        # the splash screen before doing most of them. Sometime try to figure out
        # how to do that. The point of this function is mostly to wrap every signal->slot
        # connection -- maybe it's sufficient to do that before creating the main
        # window rather than before creating the app? [bruce 071008 comment]
    

    # Create the application object (an instance of QApplication).
    QApplication.setColorSpec(QApplication.CustomColor)
    #russ 080505: Make it global so it can be run under debugging below.
    global app
    app = QApplication(sys.argv)

    # do some imports used for putting up splashscreen
    
    import utilities.icon_utilities as icon_utilities
    icon_utilities.initialize() 


    # Put up the splashscreen (if its image file can be found in cad/images).
    #    
    # Note for developers:
    # If you don't want the splashscreen, just rename the splash image file.

    splash_pixmap = icon_utilities.imagename_to_pixmap( "images/splash.png" )
        # splash_pixmap will be null if the image file was not found
    if not splash_pixmap.isNull():
        splash = QSplashScreen(splash_pixmap) # create the splashscreen
        splash.show()
        MINIMUM_SPLASH_TIME = 3.0 
            # I intend to add a user pref for MINIMUM_SPLASH_TIME for A7. mark 060131.
        splash_start = time.time()
    else:
        print "note: splash.png was not found"


    # connect the lastWindowClosed signal
    
    from PyQt4.Qt import SIGNAL
    app.connect(app, SIGNAL("lastWindowClosed ()"), app.quit)


    # NOTE: At this point, it is ok to do arbitrary imports as needed,
    # except of experimental code.


    # import MWsemantics.
    
    # An old comment (I don't know if it's still true -- bruce 071008):
    # this might have side effects other than defining things.

    from ne1_ui.MWsemantics import MWsemantics 


    # initialize modules and data structures

    from ne1_startup import startup_misc
        # do this here, not earlier, so it's free to do whatever toplevel imports it wants
        # [bruce 071008 change]
    
    startup_misc.call_module_init_functions()
    
    startup_misc.register_MMP_RecordParsers()
        # do this before reading any mmp files

    # create the single main window object
    
    foo = MWsemantics() # This does a lot of initialization (in MainWindow.__init__)

    import __main__
    __main__.foo = foo
        # developers often access the main window object using __main__.foo when debugging,
        # so this is explicitly supported


    # initialize CoNTubGenerator
    # TODO: move this into one of the other initialization functions   
    #Disabling the following code that initializes the ConTub plugin 
    #(in UI it is called Heterojunction.) The Heterojunction generator or 
    #ConTubGenerator was never ported to Qt4 platform. The plugin generator 
    #needs a code cleanup  -- ninad 2007-11-16
    ##import CoNTubGenerator
    ##CoNTubGenerator.initialize()


    # for developers: run a hook function that .atom-debug-rc might have defined
    # in this module's global namespace, for doing things *before* showing the
    # main window.
    
    try:
        # do this, if user asked us to by defining it in .atom-debug-rc
        func = atom_debug_pre_main_show
    except NameError:
        pass
    else:
        func()


    # Do other things that should be done just before showing the main window
    
    startup_misc.pre_main_show(foo) # this sets foo's geometry, among other things
    
    foo._init_after_geometry_is_set()
    
    if not splash_pixmap.isNull():
        # If the MINIMUM_SPLASH_TIME duration has not expired, sleep for a moment.
        while time.time() - splash_start < MINIMUM_SPLASH_TIME:
            time.sleep(0.1)
        splash.finish( foo ) # Take away the splashscreen


    # show the main window
    
    foo.show() 


    # set up the sponsors system and perhaps show the permission dialog
    
    if sys.platform != 'darwin':
        #bruce 070515 added condition to disable this on Mac, until Brian fixes the hang on Mac.
        # Note: this is enabled in the Mac released version, due to a patch during the release
        # building process, at least in A9.1.
        from sponsors.Sponsors import PermissionDialog
##        print "start sponsors startup code"
        # Show the dialog that asks permission to download the sponsor logos, then
        # launch it as a thread to download and process the logos.
        #
        permdialog = PermissionDialog(foo)
        if permdialog.needToAsk:
            permdialog.exec_()
        permdialog.start()
##        print "end sponsors startup code"


    # for developers: run a hook function that .atom-debug-rc might have defined
    # in this module's global namespace, for doing things *after* showing the
    # main window.

    try:
        # do this, if user asked us to by defining it in .atom-debug-rc
        func = atom_debug_post_main_show 
    except NameError:
        pass
    else:
        func()


    # do other things after showing the main window
    startup_misc.post_main_show(foo)


    # start psyco runtime optimizer (EXPERIMENTAL) --
    # for doc see http://psyco.sourceforge.net/
    #
    # Example: it speeds up code like this by 17 times:
    # (in my test, Intel Mac OS 10.4, Python 2.4.4)
    #   x = 17
    #   for i in range(10**7):
    #       x += i % 3 - 1
    #
    #  [bruce 080524]
    from utilities.debug_prefs import debug_pref, Choice_boolean_False
    if debug_pref("Use psyco runtime optimizer (next session)?",
                  Choice_boolean_False,
                  prefs_key = True ):
        # Import Psyco if available
        try:
            import psyco
            ## psyco.full() -- insert dna takes a lot of time, then segfaults
            # after printing "inside this what's this";
            # plan: be more conservative about what it should optimize...
            # preferably bind specific functions using psyco.bind().
            # For now, just tell it to only optimize the most important ones.
            psyco.log() # manual says: log file name looks like xxx.log-psyco
                # by default, where xxx is the name of the script you ran
                # (when I ran "python main.py" in cad/src, it wrote to main.log-psyco there)
                # (maybe we can pass our own pathname as an argument?)
            ## psyco.profile(0.2) # use profiling, optimize funcs that use
                # more than 20% of the time (not sure what that means exactly)
                # (seems safe, but from log file, i guess it doesn't do much)
            psyco.profile(0.05) # "aggressive"
            print "using psyco"
            pass
        except ImportError:
            print "not using psyco"
            pass
        pass


    # Decide whether to do profiling, and if so, with which
    # profiling command and into what file. Set local variables
    # to record the decision, which are used later when running
    # the Qt event loop.
    
    # If the user's .atom-debug-rc specifies PROFILE_WITH_HOTSHOT = True, use hotshot, otherwise
    # fall back to vanilla Python profiler.
    try:
        PROFILE_WITH_HOTSHOT
    except NameError:
        PROFILE_WITH_HOTSHOT = False
    
    try:
        # user can set this to a filename in .atom-debug-rc,
        # to enable profiling into that file
        atom_debug_profile_filename = main_globals['atom_debug_profile_filename']
        if atom_debug_profile_filename:
            print ("\nUser's .atom-debug-rc requests profiling into file %r" %
                   (atom_debug_profile_filename,))
            if not type(atom_debug_profile_filename) in [type("x"), type(u"x")]:
                print ("error: atom_debug_profile_filename must be a string;" +
                       "running without profiling")
                assert 0 # caught and ignored, turns off profiling
            if PROFILE_WITH_HOTSHOT:
                try:
                    import hotshot
                except:
                    print "error during 'import hotshot'; running without profiling"
                    raise # caught and ignored, turns off profiling
            else:
                try:
                    import cProfile
                except:
                    print "error during 'import profile'; running without profiling"
                    raise # caught and ignored, turns off profiling
    except:
        atom_debug_profile_filename = None


    # Create a fake "current exception", to help with debugging
    # (in case it's shown inappropriately in a later traceback).
    # One time this is seen is if a developer inserts a call to print_compact_traceback
    # when no exception is being handled (instead of the intended print_compact_stack).
    try:
        assert 0, "if you see this exception in a traceback, it is from the" \
            " startup script called by main.py, not the code that printed the traceback"
    except:
        pass


    # Handle a mmp file passed to it via the command line.  The mmp file
    # must be the first argument (after the program name) found on the 
    # command line.  All other arguments are currently ignored and only
    # one mmp file can be loaded from the command line.
    # old revision with --initial-file is at: svn rev 12759
    # Derrick 20080520
    if ((len(sys.argv) >= 2) and sys.argv[1].endswith(".mmp")):
        foo.fileOpen(sys.argv[1])
            
    # Finally, run the main Qt event loop --
    # perhaps with profiling, depending on local variables set above.
    # This does not normally return until the user asks NE1 to exit.
    
    # Note that there are three copies of the statement which runs that loop,
    # two inside string literals, all of which presumably should be the same.

    if atom_debug_profile_filename:
        if PROFILE_WITH_HOTSHOT:
            profile = hotshot.Profile(atom_debug_profile_filename)
            profile.run('app.exec_()')
        else:
            cProfile.run('from ne1_startup.main_startup import app; app.exec_()',
                         atom_debug_profile_filename)
        print ("\nProfile data was presumably saved into %r" %
               (atom_debug_profile_filename,))
    else:
        # if you change this code, also change the string literals just above
        app.exec_() 


    # Now return to the caller in order to do a normal immediate exit of NE1.
    
    return # from startup_script
Ejemplo n.º 41
0
def run(fileName=None, *args, **keywords):
    """Initialize and run Leo"""
    if not isValidPython(): return
    # Import leoGlobals, but do NOT set g.
    import leoGlobals
    # Create the application object.
    import leoApp
    leoGlobals.app = leoApp.LeoApp()
    g = leoGlobals
    assert (g.app)  # NOW we can set g.
    g.app.loadDir = computeLoadDir(
    )  # Depends on g.app.tkEncoding: uses utf-8 for now.
    import leoConfig
    g.app.config = leoConfig.config()
    g.app.setEncoding()  # 10/20/03: do this earlier
    script = getBatchScript()
    if script:
        createNullGuiWithScript(script)
        fileName = None
    else:
        #@        << print encoding info >>
        #@+node:orkman.20050213172746.3:<< print encoding info >>
        g.es("leoConfig.txt encoding: " + g.app.config.config_encoding,
             color="blue")

        if 0:  # This is just confusing for users.
            g.es("Text encoding: " + g.app.tkEncoding, color="blue")
        #@nonl
        #@-node:orkman.20050213172746.3:<< print encoding info >>
        #@nl
    # Load plugins. Plugins may create g.app.gui.
    g.doHook("start1")
    if g.app.killed: return  # Support for g.app.forceShutdown.
    # Create the default gui if needed.
    #if g.app.gui == "swing" :
    #    g.app.createSwingGui()
    if g.app.gui == None:
        #g.app.createTkGui()
        g.app.createSwingGui()
    if g.app.use_gnx:
        if not g.app.leoID:
            g.app.setLeoID()  # Forces the user to set g.app.leoID.
        import leoNodes
        g.app.nodeIndices = leoNodes.nodeIndices()
    # Initialize tracing and statistics.
    g.init_sherlock(args)
    g.clear_stats()
    #@    << start psycho >>
    #@+node:orkman.20050213172746.4:<< start psycho >>
    if g.app.config.use_psyco:
        try:
            import psyco
            if 0:
                file = r"c:\prog\test\psycoLog.txt"
                g.es("psyco now logging to", file, color="blue")
                psyco.log(file)
                psyco.profile()
            psyco.full()
            g.es("psyco now running", color="blue")
        except ImportError:
            pass
        except:
            print "unexpected exception importing psyco"
            g.es_exception()
    #@nonl
    #@-node:orkman.20050213172746.4:<< start psycho >>
    #@nl
    # Create the main frame.  Show it and all queued messages.
    c, frame = createFrame(fileName)
    if not frame: return
    if g.app.disableSave:
        g.es("disabling save commands", color="red")
    g.app.writeWaitingLog()
    v = c.currentVnode()
    #g.doHook("start2",c=c,v=v,fileName=fileName)
    g.enableIdleTimeHook()
    frame.tree.redraw()
    frame.body.setFocus()
    g.app.initing = False  # "idle" hooks may now call g.app.forceShutdown.
    g.app.gui.runMainLoop()
Ejemplo n.º 42
0
    def _Execute(self, object):
        '''Execute instructions stored inside Vector or Macro layers.\n\
"object" is the name of a LatterMonster layer that containins instructions.\n\
All vector instructions are : Rotate90Right, Rotate90Left, FlipH, FlipV, Reverse, StripRightSpace, StripLeftSpace,\n\
AlignRight, AlignLeft, Center, Crop, Border, RightBorder, LeftBorder.\n\
All macro instructions are : hideall, unhideall, lockall, unlockall, new, del, ren, change.\n\
'''
        #
        try: psyco.profile() # Psyco boost.
        except: pass
        #
        try:
            vElem = self.body[object]
            vInstructions = vElem.instructions
        except: print( 'Letter-Monster snarls: "`%s` is not an object from my body, or it doesn\'t have valid instructions! I refuse to execute!"' % object ) ; return
        #
        if not vInstructions:
            print( 'Letter-Monster growls: "`%s` has NULL instructions! I have nothing to execute!"' % object ) ; return
        #
        #ti = clock()
        if str(vElem)=='vector': # Execute vector instructions.
            for vInstr in vInstructions: # For each instruction in vector instructions list.
                vFunc = vInstr['f']      # Save function name, then delete this mapping.
                del vInstr['f']          # All vector function-calls are backpack functions.
                #
                f = getattr(self.VA, vFunc, 'Error') # Save the function call.
                #
                if f!='Error': # If function is not Error, means it's valid.
                    #
                    # Overwrite the Name of the vector with the Data of the vector.
                    try: vInstr['Input'] = self.body[vInstr['Input']].data
                    except: print( 'Letter-Monster growls: "Vector Execute - Vector `%s` doesn\'t have valid data! Canceling."' % object ) ; return
                    #
                    # Try to call the function with parameters and catch the errors.
                    try: vData = f( **vInstr )
                    except TypeError: print( 'Letter-Monster growls: "Vector Execute - Incorrect arguments for function `%s`! Canceling."' % vFunc ) ; return
                    except: print( 'Letter-Monster growls: "Vector Execute - Unknown error occured in `%s` function call! Canceling."' % vFunc ) ; return
                    #
                    # Save data in LetterMonster body -> object.
                    if vData is not None: self.body[object].data = vData
                    else: self.body[object].data = np.zeros((1,1),'U')
                    #
                else:
                    print( 'Letter-Monster growls: "Vector Execute - I don\'t know any `%s` function! Canceling."' % (object,vFunc) ) ; return
                #
            #
        #
        elif str(vElem)=='macro':
            for vInstr in vInstructions: # For each instruction in macro instructions list.
                #
                # A few mass instructions...
                #
                if vInstr['f']=='hideall': # Make all Vector and Raster layers invisible, then break.
                    for key in self.body:
                        if str(self.body[key])=='raster' or str(self.body[key])=='vector':
                            if not self.body[key].lock: # If it's Raster of Vector and it's not Locked.
                                self.body[key].visible = False
                    continue
                #
                elif vInstr['f']=='unhideall': # Make all layers visible, then break.
                    for key in self.body:
                        if str(self.body[key])=='raster' or str(self.body[key])=='vector':
                            if not self.body[key].lock: # If it's Raster of Vector and it's not Locked.
                                self.body[key].visible = True
                    continue
                #
                elif vInstr['f']=='lockall': # Lock all layers, then break.
                    for key in self.body:
                        if str(self.body[key])=='Raster' or 'Vector':
                            self.body[key].lock = True
                    continue
                #
                elif vInstr['f']=='unlockall': # Unlock all layers, then break.
                    for key in self.body:
                        if str(self.body[key])=='Raster' or 'Vector':
                            self.body[key].lock = False
                    continue
                #
                # It's not a mass instruction, so it affects only 1 layer. Save the name of that layer.
                try: exec('vName = ' + vInstr['name'])
                except: print( 'Letter-Monster growls: "Macro Execute - Can\'t access `name` attribute in Macro `%s` instruction! Canceling."' % object ) ; return
                #
                if vInstr['f']=='new':   # Instruction to create new layer.
                    vNew = vInstr['layer'].title()
                    if self.body.has_key( vName ):
                        print( 'Letter-Monster growls: "Macro Execute - Layer `%s` already exists! Canceling."' % vName ) ; return
                    # Create new instance.
                    if vNew=='Raster':
                        self.body[vName] = Raster()
                        self.body[vName].name = vName
                    elif vNew=='Vector':
                        self.body[vName] = Vector()
                        self.body[vName].name = vName
                    elif vNew=='Macro':
                        self.body[vName] = Macro()
                        self.body[vName].name = vName
                    elif vNew=='Event':
                        self.body[vName] = Event()
                        self.body[vName].name = vName
                    else: print( 'Letter-Monster growls: "Macro Execute - `%s` is not a layer type! Canceling."' % vNew ) ; return
                #
                elif vInstr['f']=='del': # Instruction to delete a layer.
                    try: del self.body[vName]
                    except: print( 'Letter-Monster growls: "Macro Execute - Layer `%s` doesn\'t exist! Canceling."' % vName ) ; return
                #
                elif vInstr['f']=='ren': # Instruction to rename a layer.
                    vNewname = vInstr['newname']
                    if self.body.has_key( vNewname ):
                        print( 'Letter-Monster growls: "Macro Execute - Layer `%s` already exists! Canceling."' % vName ) ; return
                    # Copy the old element into a new key, change new elements name, delete the old element.
                    self.body[vNewname] = self.body[vName]
                    self.body[vNewname].name = vNewname
                    del self.body[vName]
                #
                elif vInstr['f']=='change': # Instruction to change attributes of a layer.
                    for key in vInstr:      # For each key in change instruction.
                        #
                        if key=='f' or key=='name': pass # This keys must be ignored.
                        #
                        else: # This is either a new value, OR a string to execute.
                            #
                            if type(vInstr[key])==type(''): # It's probably a string to execute.
                                try: exec( 'val=' + vInstr[key] )
                                except: print( 'Letter-Monster growls: "Macro Execute - Cannot execute string instruct `%s` layer! Canceling."' % vName ) ; return
                                self.body[vName].__dict__[key] = val
                            #
                            else: # It's probably a static value to pass.
                                try: self.body[vName].__dict__[key] = vInstr[key]
                                except: print( 'Letter-Monster growls: "Macro Execute - Cannot change attributes for `%s` layer! Canceling."' % vName ) ; return
                            #
                        # Loop for every key.
                    #
                #
                else: print( 'Letter-Monster growls: "Macro Execute - `%s` is not an instruction! Canceling."' % vInstr['f'] ) ; return
Ejemplo n.º 43
0
 def process_request(self, request):
     import psyco
     psyco.profile()
     return None
Ejemplo n.º 44
0
#!/galaxy/home/mgehrin/hiclib/bin/python

"""
Read a MAF and print counts and frequencies of all n-mers
(words composed on n consecutive alignment columns)

TODO: reconcile this and maf_mapping_word_frequency.py

usage: %prog n < maf_file
"""

from __future__ import division

import psyco; psyco.profile()

from bx.cookbook import doc_optparse
import string
import sys

from align import maf


def __main__():

    motif_len = int( sys.argv[1] )

    big_map = {}
    total = 0
    
    maf_reader = maf.Reader( sys.stdin )
Ejemplo n.º 45
0
def main():
    """Main thread"""

    try:
        opts, args = getopt.getopt(sys.argv[1:], "vdc:p:D:P:m:N:", [
            "verbose", "debug", "config=", "play=", "diff=", "part=", "mode=",
            "nbrplayers="
        ])
    except getopt.GetoptError:
        print usage
        sys.exit(1)

    playing = None
    configFile = None
    debug = False
    difficulty = 0
    part = 0
    mode = 0
    nbrplayers = 1
    for opt, arg in opts:
        if opt in ["--verbose", "-v"]:
            Log.quiet = False
        if opt in ["--debug", "-d"]:
            debug = True
        if opt in ["--config", "-c"]:
            configFile = arg
        if opt in ["--play", "-p"]:
            playing = arg
        if opt in ["--diff", "-D"]:
            difficulty = arg
        if opt in ["--part", "-P"]:
            part = arg
        #evilynux - Multiplayer and mode selection support
        if opt in ["--mode", "-m"]:
            mode = int(arg)
        if opt in ["--nbrplayers", "-N"]:
            nbrplayers = int(arg)

    while True:
        if configFile != None:
            if configFile.lower() == "reset":
                fileName = os.path.join(Resource.getWritableResourcePath(),
                                        Version.appName() + ".ini")
                os.remove(fileName)
                config = Config.load(Version.appName() + ".ini",
                                     setAsDefault=True)
            else:
                config = Config.load(configFile, setAsDefault=True)
        else:
            config = Config.load(Version.appName() + ".ini", setAsDefault=True)
        engine = GameEngine(config)
        engine.cmdPlay = 0

        if playing != None:
            Config.set("game", "selected_library", "songs")
            Config.set("game", "selected_song", playing)
            engine.cmdPlay = 1
            engine.cmdDiff = int(difficulty)
            engine.cmdPart = int(part)
            #evilynux - Multiplayer and mode selection support
            Config.set("game", "players", nbrplayers)
            Config.set("player0", "mode_1p", mode)
            Config.set("player1", "mode_2p", mode)

        if debug == True:
            engine.setDebugModeEnabled(not engine.isDebugModeEnabled())
            engine.debugLayer.debugOut(engine)
            engine.quit()
            break

        encoding = Config.get("game", "encoding")
        if encoding != None:
            reload(sys)
            sys.setdefaultencoding(encoding)
        engine.setStartupLayer(MainMenu(engine))

        try:
            import psyco
            psyco.profile()
        except:
            Log.warn("Unable to enable psyco.")

        try:
            while engine.run():
                pass
        except KeyboardInterrupt:
            pass
        if engine.restartRequested:
            Log.notice("Restarting.")
            engine.audio.close()
            try:
                # Determine whether were running from an exe or not
                if hasattr(sys, "frozen"):
                    if os.name == "nt":
                        os.execl("FretsOnFire.exe", "FretsOnFire.exe",
                                 *sys.argv[1:])
                    elif sys.frozen == "macosx_app":
                        import string
                        import subprocess
                        appname = string.join(
                            string.split(sys.executable, '/')[:-1], '/')
                        appname = appname + "/Frets on Fire"
                        subprocess.Popen( ` appname `, shell=True)
                    else:
                        os.execl("./FretsOnFire", "./FretsOnFire",
                                 *sys.argv[1:])
                else:
                    if os.name == "nt":
                        bin = "c:/python24/python"
                    else:
                        bin = "/usr/bin/python2.4"
                    os.execl(bin, bin, "FretsOnFire.py", *sys.argv[1:])
            except:
                Log.warn("Restart failed.")
                raise
            break
        else:
            break
    engine.quit()
Ejemplo n.º 46
0
 def start_loop(self,
                companyName=None,
                companyCapital=None,
                loadPreviousGame=None):
     """
     companyName          string of a company that will play as current player. If none, the game will run in simulation mode
     companyCapital       int with the starting capital of the newly started company.
     loadPreviousGame    filename of a save game that can be loaded
     """
     #initilizing screen stuff
     window_size = global_variables.window_size
     pygame.init()
     if global_variables.fullscreen:
         window = pygame.display.set_mode(window_size, FULLSCREEN)
     else:
         window = pygame.display.set_mode(window_size)
     icon = pygame.image.load(os.path.join("images", "window_icon.png"))
     pygame.display.set_icon(icon)
     pygame.mouse.set_cursor(*pygame.cursors.arrow)
     #initializing the world - depends on if a previous game should be loaded
     if loadPreviousGame is not None:
         sol = solarsystem.solarsystem(global_variables.start_date,
                                       de_novo_initialization=False)
         sol.load_solar_system(loadPreviousGame)
     else:
         sol = solarsystem.solarsystem(global_variables.start_date,
                                       de_novo_initialization=True)
     #initialize current player company
     if companyName is not None:
         if sol.current_player is not None:
             raise Exception(
                 "The loaded solar system already had a current player")
         automation_dict = {
             "Demand bidding (initiate buying bids)": False,
             "Supply bidding (initiate selling bids)": False,
             "Asset market (buy bases and firms)": False,
             "Commodities market (start commodity producing firms)": False,
             "Tech market (buy and sell technology)": False,
             "Transport market (start up merchant firms)": False,
             "Evaluate firms (close problematic firms)": False,
             "Start research firms": False,
             "Pick research (pick research automatically)": False,
             "Expand area of operation (search for new home cities)": False
         }
         if companyName in sol.companies.keys():
             sol.current_player = sol.companies[companyName]
             sol.current_player.automation_dict = automation_dict
             sol.current_player.automation_dict[
                 "Demand bidding (initiate buying bids)"] = True
             sol.current_player.automation_dict[
                 "Supply bidding (initiate selling bids)"] = True
             sol.current_player.capital = companyCapital
         else:
             model_companyName = random.choice(sol.companies.keys())
             model_company = sol.companies[model_companyName]
             new_company = company.company(sol,
                                           model_company.company_database,
                                           deviation=5,
                                           companyName=companyName,
                                           capital=companyCapital)
             sol.companies[companyName] = new_company
             new_company.automation_dict = automation_dict
             sol.current_player = new_company
     #loading planets that are often used:
     print "loading earth"
     sol.planets["earth"].pickle_all_projections()
     print "finished loading"
     #divide the surface in action and non-action
     action_rect = pygame.Rect(0, 0, global_variables.window_size[0] - 150,
                               global_variables.window_size[1] - 100)
     right_side_rect = pygame.Rect(global_variables.window_size[0] - 150, 0,
                                   150, global_variables.window_size[1])
     message_rect = pygame.Rect(10, global_variables.window_size[1] - 100,
                                global_variables.window_size[0] - 170, 100)
     action_surface = window.subsurface(action_rect)
     right_side_surface = window.subsurface(right_side_rect)
     message_surface = window.subsurface(message_rect)
     #switch to determine planetary mode or solarsystem mode from beginning
     mode_before_change = sol.display_mode
     if sol.display_mode == "solar_system":
         surface = sol.draw_solar_system(
             zoom_level=sol.solar_system_zoom,
             date_variable=sol.current_date,
             center_object=sol.current_planet.planet_name)
     if sol.display_mode == "planetary":
         sol.current_planet = sol.planets["earth"]
         surface = sol.current_planet.draw_entire_planet(
             sol.current_planet.eastern_inclination,
             sol.current_planet.northern_inclination,
             sol.current_planet.projection_scaling)
     action_surface.blit(surface, (0, 0))
     pygame.display.flip()
     #Initialising the GUI
     gui_instance = gui.gui(right_side_surface, message_surface,
                            action_surface, sol)
     #getting psyco if available
     try:
         import psyco
         psyco.log()
         psyco.profile()
     except ImportError:
         pass
     i = 0
     sol.launchThread()
     while True:
         #            print "Game running another gui cycle"
         events = pygame.event.get()
         for event in events:
             if event.type == QUIT:
                 sys.exit(0)
             if event.type == 5:  #mouse down event
                 gui_instance.receive_click(event)
                 pygame.display.flip()
             if event.type == 2:  #key down event
                 if "text_receiver" in dir(gui_instance.active_window):
                     if gui_instance.active_window.text_receiver is not None:
                         gui_instance.active_window.text_receiver.receive_text(
                             event)
                         break
                 if event.key == 280:  #pgup
                     gui_instance.zoom_in(event)
                 if event.key == 281:  #pgdown
                     gui_instance.zoom_out(event)
                 if event.key == 276:  #left
                     gui_instance.go_left(event)
                 if event.key == 275:  #right
                     gui_instance.go_right(event)
                 if event.key == 273:  #up
                     gui_instance.go_up(event)
                 if event.key == 274:  #down
                     gui_instance.go_down(event)
                 pygame.display.flip()
         i = 0
         gui_instance.create_infobox()
         gui_instance.all_windows["Messages"].create()
         #in solar system the display needs updating all the time. However we need to protect whatever active window is shown:
         if sol.display_mode == "solar_system":
             surface = sol.draw_solar_system(
                 zoom_level=sol.solar_system_zoom,
                 date_variable=sol.current_date,
                 center_object=sol.current_planet.planet_name)
             if gui_instance.active_window is not None:
                 left_rect = pygame.Rect(0, 0,
                                         gui_instance.active_window.rect[0],
                                         global_variables.window_size[1])
                 right_rect = pygame.Rect(
                     gui_instance.active_window.rect[0] +
                     gui_instance.active_window.rect[2], 0,
                     global_variables.window_size[0] -
                     gui_instance.active_window.rect[0] -
                     gui_instance.active_window.rect[2],
                     global_variables.window_size[1])
                 top_rect = pygame.Rect(0, 0,
                                        global_variables.window_size[0],
                                        gui_instance.active_window.rect[1])
                 bottom_rect = pygame.Rect(
                     0, gui_instance.active_window.rect[1] +
                     gui_instance.active_window.rect[3],
                     global_variables.window_size[0],
                     global_variables.window_size[1] -
                     gui_instance.active_window.rect[3] - top_rect[3])
                 for rect in [left_rect, right_rect, top_rect, bottom_rect]:
                     action_surface.set_clip(rect)
                     action_surface.blit(surface, (0, 0))
                 action_surface.set_clip(None)
             else:
                 action_surface.blit(surface, (0, 0))
         pygame.display.flip()
Ejemplo n.º 47
0
    def start_loop(self,
                   companyName=None,
                   companyCapital=None,
                   loadPreviousGame=None):
        """
        companyName          string of a company that will play as current player. If none, 
        the game will run in simulation mode
                             
        companyCapital       int with the starting capital of the newly started company.

        loadPreviousGame    filename of a save game that can be loaded
        """
        #initilizing screen stuff
        window_size = global_variables.window_size
        pygame.init()
        if global_variables.fullscreen:
            window = pygame.display.set_mode(window_size, FULLSCREEN)
        else:
            window = pygame.display.set_mode(window_size)
        icon = pygame.image.load(os.path.join("images", "window_icon.png"))
        pygame.display.set_icon(icon)
        pygame.mouse.set_cursor(*pygame.cursors.arrow)
        #initializing the world - depends on if a previous game should be loaded
        if loadPreviousGame is not None:
            self.setSol(
                solarsystem.solarsystem(global_variables.start_date,
                                        de_novo_initialization=False))
            self.sol().load_solar_system(loadPreviousGame)
        else:
            self.setSol(
                solarsystem.solarsystem(global_variables.start_date,
                                        de_novo_initialization=True))
        #initialize current player company
        if companyName is not None:
            if self.sol().current_player is not None:
                raise Exception(
                    "The loaded solar system already had a current player")
            automation_dict = {
                "Demand bidding (initiate buying bids)": False,
                "Supply bidding (initiate selling bids)": False,
                "Asset market (buy bases and firms)": False,
                "Commodities market (start commodity producing firms)": False,
                "Tech market (buy and sell technology)": False,
                "Transport market (start up merchant firms)": False,
                "Evaluate firms (close problematic firms)": False,
                "Start research firms": False,
                "Pick research (pick research automatically)": False,
                "Expand area of operation (search for new home cities)": False
            }
            if companyName in self.sol().companies.keys():
                self.sol().current_player = self.sol().companies[companyName]
                self.sol().current_player.automation_dict = automation_dict
                self.sol().current_player.automation_dict[
                    "Demand bidding (initiate buying bids)"] = True
                self.sol().current_player.automation_dict[
                    "Supply bidding (initiate selling bids)"] = True
                self.sol().current_player.capital = companyCapital
            else:
                model_companyName = random.choice(self.sol().companies.keys())
                model_company = self.sol().companies[model_companyName]
                new_company = company.company(self.sol(),
                                              model_company.company_database,
                                              deviation=5,
                                              companyName=companyName,
                                              capital=companyCapital)
                self.sol().companies[companyName] = new_company
                new_company.automation_dict = automation_dict
                self.sol().current_player = new_company
        #loading planets that are often used:
        print "loading earth"
        self.sol().planets["earth"].pickle_all_projections()
        print "finished loading"
        #divide the surface in action and non-action
        action_rect = pygame.Rect(0, 0, global_variables.window_size[0] - 150,
                                  global_variables.window_size[1] - 100)
        right_side_rect = pygame.Rect(global_variables.window_size[0] - 150, 0,
                                      150, global_variables.window_size[1])
        message_rect = pygame.Rect(10, global_variables.window_size[1] - 100,
                                   global_variables.window_size[0] - 170, 100)
        action_surface = window.subsurface(action_rect)
        right_side_surface = window.subsurface(right_side_rect)
        message_surface = window.subsurface(message_rect)
        #switch to determine planetary mode or solarsystem mode from beginning
        mode_before_change = self.sol().display_mode
        if self.sol().display_mode == "solar_system":
            surface = self.sol().draw_solar_system(
                zoom_level=self.sol().solar_system_zoom,
                date_variable=self.sol().current_date,
                center_object=self.sol().current_planet.planet_name)
        if self.sol().display_mode == "planetary":
            self.sol().current_planet = self.sol().planets["earth"]
            surface = self.sol().current_planet.draw_entire_planet(
                self.sol().current_planet.eastern_inclination,
                self.sol().current_planet.northern_inclination,
                self.sol().current_planet.projection_scaling)
        action_surface.blit(surface, (0, 0))
        pygame.display.flip()
        #Initialising the GUI
        self.setGui(
            gui.gui(right_side_surface, message_surface, action_surface,
                    self.sol()))
        #getting psyco if available
        try:
            import psyco
            psyco.log()
            psyco.profile()
        except ImportError:
            pass
        i = 0
        self.sol().launchThread()
        self.eventLoop()
Ejemplo n.º 48
0
def main():
    pygame.display.init()
    tl = TopLevel()
    try:
	import psyco
	psyco.profile()
Ejemplo n.º 49
0
## {{{ http://code.activestate.com/recipes/498257/ (r1)
from string import digits
from random import randrange, randint
try:
    import psyco
    psyco.full(memory=100)
    psyco.profile(0.05, memory=100)
    psyco.profile(0.2)
except:
    pass
operators = "+-*/"

genes = {
    0: '0',
    1: '1',
    2: '2',
    3: '3',
    4: '4',
    5: '5',
    6: '6',
    7: '7',
    8: '8',
    9: '9',
    10: '+',
    11: '-',
    12: '*',
    13: '/'
}

traits = {}
for key, value in enumerate(genes):
def main():
    # Disabling garbage collection saves about 1 second out of 16 on a Linux
    # z620 workstation. Since this is a short-lived process it's not a problem to
    # leak a few cyclyc references in order to spare the CPU cycles for
    # scanning the heap.
    gc.disable()

    args = sys.argv[1:]

    use_analyzer = len(args) and args[0] == '--analyzer'
    if use_analyzer:
        args.pop(0)
        os.environ['GYP_GENERATORS'] = 'analyzer'
        args.append('-Gconfig_path=' + args.pop(0))
        args.append('-Ganalyzer_output_path=' + args.pop(0))

    if int(os.environ.get('GYP_CHROMIUM_NO_ACTION', 0)):
        print 'Skipping gyp_chromium due to GYP_CHROMIUM_NO_ACTION env var.'
        sys.exit(0)

    # Use the Psyco JIT if available.
    if psyco:
        psyco.profile()
        print "Enabled Psyco JIT."

    # Fall back on hermetic python if we happen to get run under cygwin.
    # TODO(bradnelson): take this out once this issue is fixed:
    #    http://code.google.com/p/gyp/issues/detail?id=177
    if sys.platform == 'cygwin':
        import find_depot_tools
        depot_tools_path = find_depot_tools.add_depot_tools_to_path()
        python_dir = sorted(
            glob.glob(os.path.join(depot_tools_path, 'python2*_bin')))[-1]
        env = os.environ.copy()
        env['PATH'] = python_dir + os.pathsep + env.get('PATH', '')
        cmd = [os.path.join(python_dir, 'python.exe')] + sys.argv
        sys.exit(subprocess.call(cmd, env=env))

    # This could give false positives since it doesn't actually do real option
    # parsing.  Oh well.
    gyp_file_specified = any(arg.endswith('.gyp') for arg in args)

    gyp_environment.SetEnvironment()

    # If we didn't get a file, check an env var, and then fall back to
    # assuming 'all.gyp' from the same directory as the script.
    if not gyp_file_specified:
        gyp_file = os.environ.get('CHROMIUM_GYP_FILE')
        if gyp_file:
            # Note that CHROMIUM_GYP_FILE values can't have backslashes as
            # path separators even on Windows due to the use of shlex.split().
            args.extend(shlex.split(gyp_file))
        else:
            args.append(os.path.join(script_dir, 'all.gyp'))

    supplemental_includes = GetSupplementalFiles()
    gyp_vars_dict = GetGypVars(supplemental_includes)
    # There shouldn't be a circular dependency relationship between .gyp files,
    # but in Chromium's .gyp files, on non-Mac platforms, circular relationships
    # currently exist.  The check for circular dependencies is currently
    # bypassed on other platforms, but is left enabled on iOS, where a violation
    # of the rule causes Xcode to misbehave badly.
    # TODO(mark): Find and kill remaining circular dependencies, and remove this
    # option.  http://crbug.com/35878.
    # TODO(tc): Fix circular dependencies in ChromiumOS then add linux2 to the
    # list.
    if gyp_vars_dict.get('OS') != 'ios':
        args.append('--no-circular-check')

    # libtool on Mac warns about duplicate basenames in static libraries, so
    # they're disallowed in general by gyp. We are lax on this point, so disable
    # this check other than on Mac. GN does not use static libraries as heavily,
    # so over time this restriction will mostly go away anyway, even on Mac.
    # https://code.google.com/p/gyp/issues/detail?id=384
    if sys.platform != 'darwin':
        args.append('--no-duplicate-basename-check')

    # We explicitly don't support the make gyp generator (crbug.com/348686). Be
    # nice and fail here, rather than choking in gyp.
    if re.search(r'(^|,|\s)make($|,|\s)', os.environ.get('GYP_GENERATORS',
                                                         '')):
        print 'Error: make gyp generator not supported (check GYP_GENERATORS).'
        sys.exit(1)

    # We explicitly don't support the native msvs gyp generator. Be nice and
    # fail here, rather than generating broken projects.
    if re.search(r'(^|,|\s)msvs($|,|\s)', os.environ.get('GYP_GENERATORS',
                                                         '')):
        print 'Error: msvs gyp generator not supported (check GYP_GENERATORS).'
        print 'Did you mean to use the `msvs-ninja` generator?'
        sys.exit(1)

    # If CHROMIUM_GYP_SYNTAX_CHECK is set to 1, it will invoke gyp with --check
    # to enfore syntax checking.
    syntax_check = os.environ.get('CHROMIUM_GYP_SYNTAX_CHECK')
    if syntax_check and int(syntax_check):
        args.append('--check')

    # TODO(dmikurube): Remove these checks and messages after a while.
    if ('linux_use_tcmalloc' in gyp_vars_dict
            or 'android_use_tcmalloc' in gyp_vars_dict):
        print '*****************************************************************'
        print '"linux_use_tcmalloc" and "android_use_tcmalloc" are deprecated!'
        print '-----------------------------------------------------------------'
        print 'You specify "linux_use_tcmalloc" or "android_use_tcmalloc" in'
        print 'your GYP_DEFINES. Please switch them into "use_allocator" now.'
        print 'See http://crbug.com/345554 for the details.'
        print '*****************************************************************'

    # Automatically turn on crosscompile support for platforms that need it.
    # (The Chrome OS build sets CC_host / CC_target which implicitly enables
    # this mode.)
    if all(('ninja' in os.environ.get('GYP_GENERATORS',
                                      ''), gyp_vars_dict.get('OS')
            in ['android', 'ios'], 'GYP_CROSSCOMPILE' not in os.environ)):
        os.environ['GYP_CROSSCOMPILE'] = '1'
    if gyp_vars_dict.get('OS') == 'android':
        args.append('--check')

    args.extend([
        '-I' + i for i in additional_include_files(supplemental_includes, args)
    ])

    args.extend(['-D', 'gyp_output_dir=' + GetOutputDirectory()])

    if not use_analyzer:
        print 'Updating projects from gyp files...'
        sys.stdout.flush()

    # Off we go...
    gyp_rc = gyp.main(args)

    if not use_analyzer:
        vs2013_runtime_dll_dirs = vs_toolchain.SetEnvironmentAndGetRuntimeDllDirs(
        )
        if vs2013_runtime_dll_dirs:
            x64_runtime, x86_runtime = vs2013_runtime_dll_dirs
            vs_toolchain.CopyVsRuntimeDlls(
                os.path.join(chrome_src, GetOutputDirectory()),
                (x86_runtime, x64_runtime))

    sys.exit(gyp_rc)
Ejemplo n.º 51
0
def startup_script(main_globals):
    """
    This is the main startup script for NE1.
    It is intended to be run only once, and only by the code in main.py.
    When this function returns, the caller is intended to immediately exit
    normally.
       Parameter main_globals should be the value of globals() in __main__,
    which is needed in case .atom-debug-rc is executed, since it must be
    executed in that global namespace.
    """

    # Note: importing all of NE1's functionality can take a long time.
    # To the extent possible, we want that time to be spent after
    # something is visible to the user, but (mostly) before the main
    # window is shown to the user (since showing the main window implies
    # that NE1 is almost ready to go). So we display a splashscreen
    # before doing most imports and initializations, then set up most
    # of our data structures and UI commands (thus importing the code
    # needed to implement them), and then show the main window.
    # (Some experimental commands are initialized after that, so that
    # errors that occur then can't prevent the main window from becoming
    # visible.)

    # TODO: turn the sections of code below into named functions or methods,
    # and perhaps split before_most_imports and before_creating_app into
    # more named functions or methods. The biggest split should be between
    # functions that need to be careful to do very few or no imports,
    # and functions that are free to do any imports.

    # Windows machines spawn and remove the shell, so no info is normally
    # captured.  This is a first attempt to try to capture some of the console
    # prints that would normally be lost.  The default for this code is that
    # it's turned off, and should remain that way until it's improved.
    if NE1_Build_Constants.NE1_CONSOLE_REDIRECT and os.name == "nt":
        capture_console = False
        capture_file = ""
        # if it's not reporting as python is the executable
        if not sys.executable.upper().endswith("PYTHON.EXE") and \
           not sys.executable.upper().endswith("PYTHON"):
            try:
                capture_file = u"".join((sys.executable[:-4], "_console.log"))
                sys.stdout = open(capture_file, 'w')
                capture_console = True  # already trapped, don't try more.
            except:
                pass
        if not capture_console:
            # Haven't captured the console log yet.  Find the default user
            # path and try to capture there this happens if we can't write to
            # the normal log location, or if python.exe is the executable.
            tmpFilePath = os.path.normpath(os.path.expanduser("~/Nanorex/"))
            if not os.path.exists(tmpFilePath):  #If it doesn't exist
                try:
                    os.mkdir(tmpFilePath)  #Try making one
                    capture_console = True
                except:
                    pass
                    # we tried, but there's no easy way to capture the console
            if capture_console or os.path.isdir(tmpFilePath):
                try:  # We made the directory or it already existed, try
                    # creating the log file.
                    capture_file = os.path.normpath(u"".join((tmpFilePath, \
                                             "/NE1_console.log")))
                    sys.stdout = open(capture_file, 'w')
                    capture_console = True
                except:
                    print >> sys.__stderr__, \
                          "Failed to create any console log file."
                    capture_console = False
        if capture_console:
            # Next two lines are specifically printed to the original console
            print >> sys.__stdout__, "The console has been redirected into:"
            print >> sys.__stdout__, capture_file.encode("utf_8")
            print
            print "starting NanoEngineer-1 in [%s]," % os.getcwd(
            ), time.asctime()
            print "using Python: " + sys.version
            try:
                print "on path: " + sys.executable
            except:
                pass

    # print the version information including official release candidate if it
    # is not 0 (false)
    if NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE:
        print "Version: NanoEngineer-1 v%s_RC%s" % \
              (NE1_Build_Constants.NE1_RELEASE_VERSION, \
               NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE)
    else:
        print "Version: NanoEngineer-1 v%s" % \
              NE1_Build_Constants.NE1_RELEASE_VERSION

    # "Do things that should be done before most imports occur."

    startup_before_most_imports.before_most_imports(main_globals)

    from PyQt4.Qt import QApplication, QSplashScreen

    # "Do things that should be done before creating the application object."

    startup_before_most_imports.before_creating_app()
    ### TODO: this imports undo, env, debug, and it got moved earlier
    # in the startup process at some point. Those imports are probably not
    # too likely to pull in a lot of others, but if possible we should put up
    # the splash screen before doing most of them. Sometime try to figure out
    # how to do that. The point of this function is mostly to wrap every signal->slot
    # connection -- maybe it's sufficient to do that before creating the main
    # window rather than before creating the app? [bruce 071008 comment]

    # do some imports used for putting up splashscreen

    # (this must be done before any code that loads images from cad/src/ui)
    import utilities.icon_utilities as icon_utilities
    icon_utilities.initialize_icon_utilities()

    # Create the application object (an instance of QApplication).
    QApplication.setColorSpec(QApplication.CustomColor)
    #russ 080505: Make it global so it can be run under debugging below.
    global app
    app = QApplication(sys.argv)

    # Put up the splashscreen (if its image file can be found in cad/images).
    #
    # Note for developers:
    # If you don't want the splashscreen, just rename the splash image file.

    splash_pixmap = icon_utilities.imagename_to_pixmap("images/splash.png")
    # splash_pixmap will be null if the image file was not found
    if not splash_pixmap.isNull():
        splash = QSplashScreen(splash_pixmap)  # create the splashscreen
        splash.show()
        MINIMUM_SPLASH_TIME = 3.0
        # I intend to add a user pref for MINIMUM_SPLASH_TIME for A7. mark 060131.
        splash_start = time.time()
    else:
        print "note: splash.png was not found"

    # connect the lastWindowClosed signal

    from PyQt4.Qt import SIGNAL
    app.connect(app, SIGNAL("lastWindowClosed ()"), app.quit)

    # NOTE: At this point, it is ok to do arbitrary imports as needed,
    # except of experimental code.

    # import MWsemantics.

    # An old comment (I don't know if it's still true -- bruce 071008):
    # this might have side effects other than defining things.

    from ne1_ui.MWsemantics import MWsemantics

    # initialize modules and data structures

    from ne1_startup import startup_misc
    # do this here, not earlier, so it's free to do whatever toplevel imports it wants
    # [bruce 071008 change]

    startup_misc.call_module_init_functions()

    startup_misc.register_MMP_RecordParsers()
    # do this before reading any mmp files

    # create the single main window object

    foo = MWsemantics(
    )  # This does a lot of initialization (in MainWindow.__init__)

    import __main__
    __main__.foo = foo
    # developers often access the main window object using __main__.foo when debugging,
    # so this is explicitly supported

    # initialize CoNTubGenerator
    # TODO: move this into one of the other initialization functions
    #Disabling the following code that initializes the ConTub plugin
    #(in UI it is called Heterojunction.) The Heterojunction generator or
    #ConTubGenerator was never ported to Qt4 platform. The plugin generator
    #needs a code cleanup  -- ninad 2007-11-16
    ##import CoNTubGenerator
    ##CoNTubGenerator.initialize()

    # for developers: run a hook function that .atom-debug-rc might have defined
    # in this module's global namespace, for doing things *before* showing the
    # main window.

    try:
        # do this, if user asked us to by defining it in .atom-debug-rc
        func = atom_debug_pre_main_show
    except NameError:
        pass
    else:
        func()

    # Do other things that should be done just before showing the main window

    startup_misc.pre_main_show(
        foo)  # this sets foo's geometry, among other things

    foo._init_after_geometry_is_set()

    if not splash_pixmap.isNull():
        # If the MINIMUM_SPLASH_TIME duration has not expired, sleep for a moment.
        while time.time() - splash_start < MINIMUM_SPLASH_TIME:
            time.sleep(0.1)
        splash.finish(foo)  # Take away the splashscreen

    # show the main window

    foo.show()

    # for developers: run a hook function that .atom-debug-rc might have defined
    # in this module's global namespace, for doing things *after* showing the
    # main window.

    try:
        # do this, if user asked us to by defining it in .atom-debug-rc
        func = atom_debug_post_main_show
    except NameError:
        pass
    else:
        func()

    # do other things after showing the main window
    startup_misc.post_main_show(foo)

    # start psyco runtime optimizer (EXPERIMENTAL) --
    # for doc see http://psyco.sourceforge.net/
    #
    # Example: it speeds up code like this by 17 times:
    # (in my test, Intel Mac OS 10.4, Python 2.4.4)
    #   x = 17
    #   for i in range(10**7):
    #       x += i % 3 - 1
    #
    #  [bruce 080524]
    from utilities.debug_prefs import debug_pref, Choice_boolean_False
    if debug_pref("Use psyco runtime optimizer (next session)?",
                  Choice_boolean_False,
                  prefs_key=True):
        # Import Psyco if available
        try:
            import psyco
            ## psyco.full() -- insert dna takes a lot of time, then segfaults
            # after printing "inside this what's this";
            # plan: be more conservative about what it should optimize...
            # preferably bind specific functions using psyco.bind().
            # For now, just tell it to only optimize the most important ones.
            psyco.log()  # manual says: log file name looks like xxx.log-psyco
            # by default, where xxx is the name of the script you ran
            # (when I ran "python main.py" in cad/src, it wrote to main.log-psyco there)
            # (maybe we can pass our own pathname as an argument?)
            ## psyco.profile(0.2) # use profiling, optimize funcs that use
            # more than 20% of the time (not sure what that means exactly)
            # (seems safe, but from log file, i guess it doesn't do much)
            psyco.profile(0.05)  # "aggressive"
            print "using psyco"
            pass
        except ImportError:
            print "not using psyco"
            pass
        pass

    # Decide whether to do profiling, and if so, with which
    # profiling command and into what file. Set local variables
    # to record the decision, which are used later when running
    # the Qt event loop.

    # If the user's .atom-debug-rc specifies PROFILE_WITH_HOTSHOT = True,
    # use hotshot, otherwise fall back to vanilla Python profiler.
    # (Note: to work, it probably has to import this module
    #  and set this variable in this module's namespace.)
    try:
        PROFILE_WITH_HOTSHOT
    except NameError:
        PROFILE_WITH_HOTSHOT = False

    try:
        # user can set atom_debug_profile_filename to a filename in .atom-debug-rc,
        # to enable profiling into that file. For example:
        # % cd
        # % cat > .atom-debug-rc
        # atom_debug_profile_filename = '/tmp/profile-output'
        # ^D
        # ... then run NE1, and quit it
        # ... then in a python shell:
        # import pstats
        # p = pstats.Stats('<filename>')
        # p.strip_dirs().sort_stats('time').print_stats(100) # order by internal time (top 100 functions)
        # p.strip_dirs().sort_stats('cumulative').print_stats(100) # order by cumulative time
        atom_debug_profile_filename = main_globals.get(
            'atom_debug_profile_filename')
        if atom_debug_profile_filename:
            print("\nUser's .atom-debug-rc requests profiling into file %r" %
                  (atom_debug_profile_filename, ))
            if not type(atom_debug_profile_filename) in [
                    type("x"), type(u"x")
            ]:
                print "error: atom_debug_profile_filename must be a string"
                assert 0  # caught and ignored, turns off profiling
            if PROFILE_WITH_HOTSHOT:
                try:
                    import hotshot
                except:
                    print "error during 'import hotshot'"
                    raise  # caught and ignored, turns off profiling
            else:
                try:
                    import cProfile as py_Profile
                except ImportError:
                    print "Unable to import cProfile. Using profile module instead."
                    py_Profile = None
                if py_Profile is None:
                    try:
                        import profile as py_Profile
                    except:
                        print "error during 'import profile'"
                        raise  # caught and ignored, turns off profiling
    except:
        print "exception setting up profiling (hopefully reported above); running without profiling"
        atom_debug_profile_filename = None

    # Create a fake "current exception", to help with debugging
    # (in case it's shown inappropriately in a later traceback).
    # One time this is seen is if a developer inserts a call to print_compact_traceback
    # when no exception is being handled (instead of the intended print_compact_stack).
    try:
        assert 0, "if you see this exception in a traceback, it is from the" \
            " startup script called by main.py, not the code that printed the traceback"
    except:
        pass

    # Handle a mmp file passed to it via the command line.  The mmp file
    # must be the first argument (after the program name) found on the
    # command line.  All other arguments are currently ignored and only
    # one mmp file can be loaded from the command line.
    # old revision with --initial-file is at: svn rev 12759
    # Derrick 20080520
    if ((len(sys.argv) >= 2) and sys.argv[1].endswith(".mmp")):
        foo.fileOpen(sys.argv[1])

    # Do other post-startup, pre-event-loop, non-profiled things, if any
    # (such as run optional startup commands for debugging).
    startup_misc.just_before_event_loop()

    if os.environ.has_key('WINGDB_ACTIVE'):
        # Hack to burn some Python bytecode periodically so Wing's
        # debugger can remain responsive while free-running
        # [from http://wingware.com/doc/howtos/pyqt; added by bruce 081227]
        # Addendum [bruce 090107]: this timer doesn't noticeably slow down NE1,
        # but with or without it, NE1 is about 4x slower in Wing than running
        # alone, at least when running test_selection_redraw.py.
        print "running under Wing IDE debugger; setting up timer"
        from PyQt4 import QtCore
        timer = QtCore.QTimer()

        def donothing(*args):
            x = 0
            for i in range(0, 100):
                x += i

        timer.connect(timer, QtCore.SIGNAL("timeout()"), donothing)
        timer.start(200)

    # Finally, run the main Qt event loop --
    # perhaps with profiling, depending on local variables set above.
    # This does not normally return until the user asks NE1 to exit.

    # Note that there are three copies of the statement which runs that loop,
    # two inside string literals, all of which presumably should be the same.

    if atom_debug_profile_filename:
        if PROFILE_WITH_HOTSHOT:
            profile = hotshot.Profile(atom_debug_profile_filename)
            profile.run('app.exec_()')
        else:
            py_Profile.run(
                'from ne1_startup.main_startup import app; app.exec_()',
                atom_debug_profile_filename)
        print("\nProfile data was presumably saved into %r" %
              (atom_debug_profile_filename, ))
    else:
        # if you change this code, also change both string literals just above
        app.exec_()

    # Now return to the caller in order to do a normal immediate exit of NE1.

    return  # from startup_script
Ejemplo n.º 52
0
def main():
    playing = None
    configFile = None
    fullscreen = None
    resolution = None
    theme = None
    debug = False
    difficulty = None
    part = None
    mode = 0
    nbrplayers = 1
    for opt, arg in opts:
        if opt in ["--verbose", "-v"]:
            Log.quiet = False
        if opt in ["--config", "-c"]:
            configFile = arg
        if opt in ["--fullscreen", "-f"]:
            fullscreen = arg
        if opt in ["--resolution", "-r"]:
            resolution = arg
        if opt in ["--theme", "-t"]:
            theme = arg
        if opt in ["--song", "-s"]:
            playing = arg
        if opt in ["--part", "-p"]:
            part = arg
        if opt in ["--diff", "-d", "-l"]:
            difficulty = arg
        #evilynux - Multiplayer and mode selection support
        if opt in ["--mode", "-m"]:
            mode = int(arg)
        if opt in ["--nbrplayers", "-n"]:
            nbrplayers = int(arg)

    # Load the configuration file.
    if configFile is not None:
        if configFile.lower() == "reset":
            fileName = os.path.join(Resource.getWritableResourcePath(),
                                    Version.PROGRAM_UNIXSTYLE_NAME + ".ini")
            os.remove(fileName)
            config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini",
                                 setAsDefault=True)
        else:
            config = Config.load(configFile, setAsDefault=True)
    else:
        config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini",
                             setAsDefault=True)

    #Lysdestic - Allow support for manipulating fullscreen via CLI
    if fullscreen is not None:
        Config.set("video", "fullscreen", fullscreen)

    #Lysdestic - Change resolution from CLI
    if resolution is not None:
        Config.set("video", "resolution", resolution)

    #Lysdestic - Alter theme from CLI
    if theme is not None:
        Config.set("coffee", "themename", theme)

    engine = GameEngine(config)
    engine.cmdPlay = 0

    # Check for a valid invocation of one-shot mode.
    if playing is not None:
        Log.debug('Validating song directory for one-shot mode.')
        library = Config.get("game", "base_library")
        basefolder = os.path.join(Version.dataPath(), library, "songs",
                                  playing)
        if not (os.path.exists(os.path.join(basefolder, "song.ini")) and
                (os.path.exists(os.path.join(basefolder, "notes.mid"))
                 or os.path.exists(
                     os.path.join(basefolder, "notes-unedited.mid"))) and
                (os.path.exists(os.path.join(basefolder, "song.ogg"))
                 or os.path.exists(os.path.join(basefolder, "guitar.ogg")))):
            Log.warn(
                "Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode."
                % playing)
            engine.startupMessages.append(
                _("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode."
                  ) % playing)
            playing = None

    # Set up one-shot mode if the invocation is valid for it.
    if playing is not None:
        Log.debug('Entering one-shot mode.')
        Config.set("game", "selected_library", "songs")
        Config.set("game", "selected_song", playing)
        engine.cmdPlay = 1
        if difficulty is not None:
            engine.cmdDiff = int(difficulty)
        if part is not None:
            engine.cmdPart = int(part)
        #evilynux - Multiplayer and mode selection support
        Config.set("game", "players", nbrplayers)
        if nbrplayers == 1:
            Config.set("game", "game_mode", mode)
        else:
            Config.set("game", "game_mode", 0)
            Config.set("game", "multiplayer_mode", mode)

    encoding = Config.get("game", "encoding")
    if encoding is not None:
        #stump: XXX: Everything I have seen indicates that this is a
        # horrible, horrible hack.  Is there another way?  Do we even need this?
        reload(sys)
        sys.setdefaultencoding(encoding)

    # Play the intro video if it is present, we have the capability, and
    # we are not in one-shot mode.
    videoLayer = False
    if videoAvailable and not engine.cmdPlay:
        # TODO: Parameters to add to theme.ini:
        #  - intro_video_file
        #  - intro_video_start_time
        #  - intro_video_end_time
        themename = Config.get("coffee", "themename")
        vidSource = os.path.join(Version.dataPath(), 'themes', themename, \
                                 'menu', 'intro.avi')
        if os.path.isfile(vidSource):
            winWidth, winHeight = engine.view.geometry[2:4]
            songVideoStartTime = 0
            songVideoEndTime = None
            vidPlayer = VideoPlayer(-1,
                                    vidSource, (winWidth, winHeight),
                                    startTime=songVideoStartTime,
                                    endTime=songVideoEndTime)
            if vidPlayer.validFile:
                engine.view.pushLayer(vidPlayer)
                videoLayer = True
                try:
                    engine.ticksAtStart = pygame.time.get_ticks()
                    while not vidPlayer.finished:
                        engine.run()
                    engine.view.popLayer(vidPlayer)
                    engine.view.pushLayer(MainMenu(engine))
                except KeyboardInterrupt:
                    engine.view.popLayer(vidPlayer)
                    engine.view.pushLayer(MainMenu(engine))
    if not videoLayer:
        engine.setStartupLayer(MainMenu(engine))

    #stump: make psyco optional
    if Config.get("performance", "use_psyco"):
        try:
            import psyco
            psyco.profile()
        except:
            Log.error("Unable to enable psyco as requested: ")

    # Run the main game loop.
    try:
        engine.ticksAtStart = pygame.time.get_ticks()
        while engine.run():
            pass
    except KeyboardInterrupt:
        Log.notice("Left mainloop due to KeyboardInterrupt.")
        # don't reraise

    # Restart the program if the engine is asking that we do so.
    if engine.restartRequested:
        Log.notice("Restarting.")
        engine.audio.close()
        try:
            # Extra arguments to insert between the executable we call and our
            # command line arguments.
            args = []
            # Figure out what executable to call.
            if hasattr(sys, "frozen"):
                if os.name == "nt":
                    # When py2exe'd, sys.executable is the name of the EXE.
                    exe = os.path.abspath(
                        unicode(sys.executable, sys.getfilesystemencoding()))
                elif sys.frozen == "macosx_app":
                    # When py2app'd, sys.executable is a Python interpreter copied
                    # into the same dir where we live.
                    exe = os.path.join(
                        os.path.dirname(sys.executable),
                        'FoFiX')  # FIXME: don't hard-code "FoFiX" here
                else:
                    raise RuntimeError, "Don't know how to restart when sys.frozen is %s" % repr(
                        sys.frozen)
            else:
                # When running from source, sys.executable is the Python interpreter
                # being used to run the program.
                exe = sys.executable
                # Pass the optimization level on iif python version >= 2.6.0 as
                # sys.flags has been introduced in 2.6.0.
                if sys.version_info[:3] >= (2, 6,
                                            0) and sys.flags.optimize > 0:
                    args.append('-%s' % ('O' * sys.flags.optimize))
                args.append(__file__)
            os.execv(exe, [sys.executable] + args + sys.argv[1:])
        except:
            Log.error("Restart failed: ")
            raise

    # evilynux - MainMenu class already calls this - useless?
    engine.quit()
Ejemplo n.º 53
0
                      help='number of test sentences')
    parser.add_option('-r', '--num-train-sents', metavar='NUM_TRAIN',
                      dest='num_train_sents', type=int, 
                      help='number of training sentences')
    parser.add_option('-p', '--psyco', action='store_true',
                      default=False, dest='psyco',
                      help='use Psyco JIT, if available')
    parser.add_option('-v', '--verbose', action='store_true',
                      default=False, dest='verbose',
                      help='verbose')
    (options, args) = parser.parse_args()

    if options.psyco:
        try:
            import psyco
            psyco.profile()
        except:
            pass

    if options.train_tagger:
        treebank_train = load_treebank('0[2-9]|1[0-9]|2[01]')
        treebank_train_sequence = treebank_train.tagged_sents()
        treebank_test = load_treebank('24')
        treebank_test_sequence = treebank_test.tagged_sents()
        treebank_estimator = LidstoneProbDistFactory
        model = train_model(HiddenMarkovModelTagger, 
                            treebank_train_sequence, 
                            treebank_test_sequence,
                            options.model_file, 
                            options.num_train_sents, 
                            options.num_test_sents,
Ejemplo n.º 54
0
def main():
    """Main thread"""

    try:
        opts, args = getopt.getopt(sys.argv[1:], "vdc:f:r:t:s:l:p:m:n:", [
            "verbose", "debug", "config=", "fullscreen=", "resolution=",
            "theme=", "song=", "diff=", "part=", "mode=", "nbrplayers="
        ])
    except getopt.GetoptError:
        print usage
        sys.exit(1)

    playing = None
    configFile = None
    fullscreen = None
    resolution = None
    theme = None
    debug = False
    difficulty = None
    part = None
    mode = 0
    nbrplayers = 1
    for opt, arg in opts:
        if opt in ["--verbose", "-v"]:
            Log.quiet = False
        if opt in ["--debug", "-d"]:
            debug = True
        if opt in ["--config", "-c"]:
            configFile = arg
        if opt in ["--fullscreen", "-f"]:
            fullscreen = arg
        if opt in ["--resolution", "-r"]:
            resolution = arg
        if opt in ["--theme", "-t"]:
            theme = arg
        if opt in ["--song", "-s"]:
            playing = arg
        if opt in ["--diff", "-l"]:
            difficulty = arg
        if opt in ["--part", "-p"]:
            part = arg
        #evilynux - Multiplayer and mode selection support
        if opt in ["--mode", "-m"]:
            mode = int(arg)
        if opt in ["--nbrplayers", "-n"]:
            nbrplayers = int(arg)

    while 1:
        if configFile != None:
            if configFile.lower() == "reset":
                fileName = os.path.join(Resource.getWritableResourcePath(),
                                        Version.appName() + ".ini")
                os.remove(fileName)
                config = Config.load(Version.appName() + ".ini",
                                     setAsDefault=True)
            else:
                config = Config.load(configFile, setAsDefault=True)
        else:
            config = Config.load(Version.appName() + ".ini", setAsDefault=True)

        #Lysdestic - Allow support for manipulating fullscreen via CLI
        if fullscreen != None:
            Config.set("video", "fullscreen", fullscreen)

        #Lysdestic - Change resolution from CLI
        if resolution != None:
            Config.set("video", "resolution", resolution)

        #Lysdestic - Alter theme from CLI
        if theme != None:
            Config.set("coffee", "themename", theme)

        if playing != None:
            library = Config.get("game", "base_library")
            basefolder = os.path.join(Version.dataPath(), library, "songs",
                                      playing)
            if not (os.path.exists(os.path.join(basefolder, "song.ini")) and
                    (os.path.exists(os.path.join(basefolder, "notes.mid"))
                     or os.path.exists(
                         os.path.join(basefolder, "notes-unedited.mid"))) and
                    (os.path.exists(os.path.join(basefolder, "song.ogg")) or
                     os.path.exists(os.path.join(basefolder, "guitar.ogg")))):
                Log.warn(
                    "Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode."
                    % playing)
                playing = None

        engine = GameEngine(config)
        engine.cmdPlay = 0

        if playing != None:
            Config.set("game", "selected_library", "songs")
            Config.set("game", "selected_song", playing)
            engine.cmdPlay = 1
            if difficulty is not None:
                engine.cmdDiff = int(difficulty)
            if part is not None:
                engine.cmdPart = int(part)
            #evilynux - Multiplayer and mode selection support
            Config.set("game", "players", nbrplayers)
            if nbrplayers == 1:
                Config.set("game", "game_mode", mode)
            else:
                Config.set("game", "game_mode", 0)
                Config.set("game", "multiplayer_mode", mode)

        if debug == True:
            engine.setDebugModeEnabled(not engine.isDebugModeEnabled())
            engine.debugLayer.debugOut(engine)
            engine.quit()
            break

        encoding = Config.get("game", "encoding")
        if encoding != None:
            reload(sys)
            sys.setdefaultencoding(encoding)
        engine.setStartupLayer(MainMenu(engine))

        #stump: make psyco optional
        if Config.get("performance", "use_psyco"):
            try:
                import psyco
                psyco.profile()
            except:
                Log.warn("Unable to enable psyco.")

        try:
            engine.ticksAtStart = pygame.time.get_ticks()
            while engine.run():
                pass
        except KeyboardInterrupt:
            pass
        if engine.restartRequested:
            Log.notice("Restarting.")
            engine.audio.close()
            try:
                # Determine whether were running from an exe or not
                if hasattr(sys, "frozen"):
                    if os.name == "nt":
                        os.execl("FoFiX.exe", "FoFiX.exe", *sys.argv[1:])
                    elif sys.frozen == "macosx_app":
                        import string
                        import subprocess
                        appname = string.join(
                            string.split(sys.executable, '/')[:-1], '/')
                        appname = appname + "/FoFiX"
                        subprocess.Popen( ` appname `, shell=True)
                    else:
                        os.execl("./FoFiX", "./FoFiX", *sys.argv[1:])
                else:
                    # stump: sys.executable points to the active python interpreter
                    os.execl(sys.executable, sys.executable, "FoFiX.py",
                             *sys.argv[1:])
            except:
                Log.warn("Restart failed.")
                raise
            break
        else:
            break
    # evilynux - MainMenu class already calls this - useless?
    engine.quit()
Ejemplo n.º 55
0
try:
    import psyco
    psyco.profile()
except:
    pass

import random, math, time
from pyalleg import *
from vector import Vec2d


def lim(a, v, b):
    if v < a: return a
    if v > b: return b
    return v


class Ball:
    def __init__(self):
        self.d = Vec2d()
        self.p = Vec2d(random.randint(20, 500), random.randint(20, 460))
        self.hit = 0
        self.mass = random.randint(4, 18)
        self.hue = random.randint(0, 360)

        r, g, b = hsvRgb(self.hue, 0.7, 0.5)
        self.color = Color(r, g, b)

    def draw(self, bmp, ac=0):
        solidMode()
        bmp.fillCircle(self.p.x, self.p.y, 10, self.color)
Ejemplo n.º 56
0
def open_file(filename):
    try:
        import psyco
        psyco.profile()
    except ImportError:
        print "Psyco not available to PyPRP..."
    start = time.clock()
    log = ptLog(sys.stdout, filename + ".log", "w")
    std = sys.stdout
    sys.stdout = log
    print("Exporting %s ..." % filename)
    args = __script__['arg']
    print("Args are %s " % args)
    ext = ".raw"
    w = args.split("_")
    print w
    ext = "." + w[1]
    basepath = dirname(filename)
    if filename.find(ext, -4) == -1:
        raise RuntimeError, "ERROR: Unsuported file %s, expecting an %s file" % (
            filename, ext)
    #check if final
    final = 0
    try:
        if w[2] == "final":
            final = 1
    except IndexError:
        pass
    if final:
        prp_Config.texture_compression = 1
        prp_Config.vertex_compression = 0
    else:
        prp_Config.texture_compression = 0
        prp_Config.vertex_compression = 0
    if w[1] == "age":
        agename = basename(filename[:-4])
        if w[0] == "e":
            selection = 0
            merge = 0
            pass
        elif w[0] == "et":
            selection = 0
            merge = 0
            prp_Config.export_textures_to_page_prp = 1
            pass
        elif w[0] == "es":
            selection = 1
            merge = 0
            pass
        elif w[0] == "em":
            selection = 0
            merge = 1
            pass
        elif w[0] == "esm":
            selection = 1
            merge = 1
            pass
        else:
            raise RuntimeError, "Unimplemented option %s" % (args)
        export_age(agename, basepath, selection, merge)
    elif w[1] == "prp":
        pagea = basename(filename[:-4])
        page = pagea.split("_")
        agename = page[0]
        pagename = pagea[len(page[0]) + 1 + len(page[1]) + 1:]
        if w[0] == "e":
            selection = 0
            merge = 0
            pass
        elif w[0] == "et":
            selection = 0
            merge = 0
            prp_Config.export_textures_to_page_prp = 1
            pass
        elif w[0] == "es":
            selection = 1
            merge = 0
            pass
        elif w[0] == "em":
            selection = 0
            merge = 1
            pass
        elif w[0] == "esm":
            selection = 1
            merge = 1
            pass
        else:
            raise RuntimeError, "Unimplemented option %s" % (args)
        export_age(agename, basepath, selection, merge, pagename)
    else:
        raise RuntimeError, "Unimplemented option %s" % (args)
    stop = time.clock()
    print("done in %.2f seconds" % (stop - start))
    sys.stdout = std
    log.close()