Start an interactive `MockupDB`.

    Use like ``python -m mockupdb``.
962657
def main():
    
    from optparse import OptionParser
    parser = OptionParser('Start mock MongoDB server')
    parser.add_option('-p', '--port', dest='port', default=27017,
                      help='port on which mock mongod listens')
    parser.add_option('-q', '--quiet',
                      action='store_false', dest='verbose', default=True,
                      help="don't print messages to stdout")

    options, cmdline_args = parser.parse_args()
    if cmdline_args:
        parser.error('Unrecognized argument(s): %s' % ' '.join(cmdline_args))

    server = interactive_server(port=options.port, verbose=options.verbose)
    try:
        server.run()
        print('Listening on port %d' % server.port)
        time.sleep(1e6)
    except KeyboardInterrupt:
        server.stop()
566798
def init_db(drop_all=False):
    """"""
    if drop_all:
        Base.metadata.drop_all(bind=engine)
    Base.metadata.create_all(bind=engine)

    return session
146711
def init(**kwargs):
    

    # TODO: Iterate through all engines in name set.
    database = kwargs.pop('database', False)
    if database and not database_exists(engine['default'].url):
        create_database(engine['default'].url, encoding='utf8')
        clear_cache()

    expression = lambda target, table: table.create(target)
    test = lambda target, table: table.exists(target)
    op(expression, test=test, primary='init', secondary='create', **kwargs)
1188508
def main(argv=None):
    """"""
    global Verbose, Mock
    if argv is None:
        argv = sys.argv

    if len(argv) < 5: die('Bad args')
    try:
        opts, argv = getopt.getopt(argv[1:], 'hs:p:mv',
          ['help', 'server=', 'port=', 'mock', 'verbose'])
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err) # will print something like "option -a not recognized"
        die()

    serverEndpoint = DefaultServerEndpoint
    # TODO: Fix this
    for opt, val in opts:
        if opt   in ('-h', '--help'):    echo2(USAGE); sys.exit()
        elif opt in ('-s', '--server'):  serverEndpoint = val
        elif opt in ('-p', '--port'):    serverEndpoint = 'http://localhost:%s' % val
        elif opt in ('-m', '--mock'):    Mock = 1
        elif opt in ('-v', '--verbose'): Verbose = 1
        else: die(USAGE)

    cmd = argv[0]
    crawlId = argv[1]
    confId = argv[2]
    urlDir = argv[3]
    args = {}
    if len(argv) > 4: args = eval(argv[4])

    nt = Nutch(crawlId, confId, serverEndpoint, urlDir)
    nt.Jobs().create(cmd, **args)
189666
def start_ipython_player(commands, speed=1):
    """"""
    PlayerTerminalIPythonApp.commands = commands
    PlayerTerminalIPythonApp.speed = speed
    PlayerTerminalIPythonApp.launch_instance()
4727
def in_interactive_session():
    
    from pandas import get_option

    def check_main():
        try:
            import __main__ as main
        except ModuleNotFoundError:
            return get_option('mode.sim_interactive')
        return (not hasattr(main, '__file__') or
                get_option('mode.sim_interactive'))

    try:
        return __IPYTHON__ or check_main()  # noqa
    except NameError:
        return check_main()
510403
def init_db(sqlalchemy_url):
    
    engine = create_engine(sqlalchemy_url)
    start = time.time()
    metadata.create_all(engine)
    return time.time() - start
231457
def _init_db(self):
        """"""
        with self._get_db() as db:
            with open(self.schemapath) as f:
                db.cursor().executescript(f.read())
            db.commit()
439638
function setupDb( app ) {
  app.setupDb = setupMongoose(
    {
      connection: {
        debug: config.debug,
        uri: {
          database: config.database,
          password: config.password,
          username: config.username
        }
      },
      schemas: [
        {
          'User': User
        }
      ]
    }
  )

  app.setupDb()
    .then(
      function ( db ) {
        app.db = db
      }
    )
    .catch(
      function ( err ) {
        app.db = {
          error: err
        }
      }
    )
}
2373
def cli(ctx, **kwargs):
    
    if kwargs['add_sys_path']:
        sys.path.append(os.getcwd())

    logging.config.fileConfig(kwargs['logging_config'])

    # get db from env
    for db in ('taskdb', 'projectdb', 'resultdb'):
        if kwargs[db] is not None:
            continue
        if os.environ.get('MYSQL_NAME'):
            kwargs[db] = utils.Get(lambda db=db: connect_database(
                'sqlalchemy+mysql+%s://%s:%s/%s' % (
                    db, os.environ['MYSQL_PORT_3306_TCP_ADDR'],
                    os.environ['MYSQL_PORT_3306_TCP_PORT'], db)))
        elif os.environ.get('MONGODB_NAME'):
            kwargs[db] = utils.Get(lambda db=db: connect_database(
                'mongodb+%s://%s:%s/%s' % (
                    db, os.environ['MONGODB_PORT_27017_TCP_ADDR'],
                    os.environ['MONGODB_PORT_27017_TCP_PORT'], db)))
        elif ctx.invoked_subcommand == 'bench':
            if kwargs['data_path'] == './data':
                kwargs['data_path'] += '/bench'
                shutil.rmtree(kwargs['data_path'], ignore_errors=True)
                os.mkdir(kwargs['data_path'])
            if db in ('taskdb', 'resultdb'):
                kwargs[db] = utils.Get(lambda db=db: connect_database('sqlite+%s://' % (db)))
            elif db in ('projectdb', ):
                kwargs[db] = utils.Get(lambda db=db: connect_database('local+%s://%s' % (
                    db, os.path.join(os.path.dirname(__file__), 'libs/bench.py'))))
        else:
            if not os.path.exists(kwargs['data_path']):
                os.mkdir(kwargs['data_path'])
            kwargs[db] = utils.Get(lambda db=db: connect_database('sqlite+%s:///%s/%s.db' % (
                db, kwargs['data_path'], db[:-2])))
            kwargs['is_%s_default' % db] = True

    # create folder for counter.dump
    if not os.path.exists(kwargs['data_path']):
        os.mkdir(kwargs['data_path'])

    # message queue, compatible with old version
    if kwargs.get('message_queue'):
        pass
    elif kwargs.get('amqp_url'):
        kwargs['message_queue'] = kwargs['amqp_url']
    elif os.environ.get('RABBITMQ_NAME'):
        kwargs['message_queue'] = ("amqp://guest:guest@%(RABBITMQ_PORT_5672_TCP_ADDR)s"
                                   ":%(RABBITMQ_PORT_5672_TCP_PORT)s/%%2F" % os.environ)
    elif kwargs.get('beanstalk'):
        kwargs['message_queue'] = "beanstalk://%s/" % kwargs['beanstalk']

    for name in ('newtask_queue', 'status_queue', 'scheduler2fetcher',
                 'fetcher2processor', 'processor2result'):
        if kwargs.get('message_queue'):
            kwargs[name] = utils.Get(lambda name=name: connect_message_queue(
                name, kwargs.get('message_queue'), kwargs['queue_maxsize']))
        else:
            kwargs[name] = connect_message_queue(name, kwargs.get('message_queue'),
                                                 kwargs['queue_maxsize'])

    # phantomjs-proxy
    if kwargs.get('phantomjs_proxy'):
        pass
    elif os.environ.get('PHANTOMJS_NAME'):
        kwargs['phantomjs_proxy'] = os.environ['PHANTOMJS_PORT_25555_TCP'][len('tcp://'):]

    # puppeteer-proxy
    if kwargs.get('puppeteer_proxy'):
        pass
    elif os.environ.get('PUPPETEER_NAME'):
        kwargs['puppeteer_proxy'] = os.environ['PUPPETEER_PORT_22222_TCP'][len('tcp://'):]

    ctx.obj = utils.ObjectDict(ctx.obj or {})
    ctx.obj['instances'] = []
    ctx.obj.update(kwargs)

    if ctx.invoked_subcommand is None and not ctx.obj.get('testing_mode'):
        ctx.invoke(all)
    return ctx
1244452
def init_app(self, app, **kwargs):
        """"""
        self.init_db(app, **kwargs)

        app.config.setdefault('ALEMBIC', {
            'script_location': pkg_resources.resource_filename(
                'invenio_db', 'alembic'
            ),
            'version_locations': [
                (base_entry.name, pkg_resources.resource_filename(
                    base_entry.module_name, os.path.join(*base_entry.attrs)
                )) for base_entry in pkg_resources.iter_entry_points(
                    'invenio_db.alembic'
                )
            ],
        })

        self.alembic.init_app(app)
        app.extensions['invenio-db'] = self
        app.cli.add_command(db_cmd)
726361
def initiate(self, database=None, journaler=None, *backends):
        '''
        
        '''
        return self._initiate(database=database, journaler=journaler,
                              backends=backends)
1263409
def demo(quiet, shell, speed, prompt, commentecho):
    """"""
    run(
        DEMO,
        shell=shell,
        speed=speed,
        test_mode=TESTING,
        prompt_template=prompt,
        quiet=quiet,
        commentecho=commentecho,
    )
1080669
def StartGdb(self):
    
    if self.attached:
      raise GdbProcessError('Gdb is already running.')
    self._gdb = GdbProxy(arch=self.arch)
    self._gdb.Attach(self.position)

    if self.auto_symfile_loading:
      try:
        self.LoadSymbolFile()
      except (ProxyError, TimeoutError) as err:
        self._gdb = GdbProxy(arch=self.arch)
        self._gdb.Attach(self.position)
        if not self.gdb.IsSymbolFileSane(self.position):
          logging.warning('Failed to automatically load a sane symbol file, '
                          'most functionality will be unavailable until symbol'
                          'file is provided.')
          logging.debug(err.message)
761671
def run(self):
        
        self.print_message("\nBeginning database replacement process.\n")

        if self.args.source_settings:
            settings = self.parse_db_settings(self.args.source_settings)
            self.initialize_db_args(settings, 'source')

        if self.args.settings:
            settings = self.parse_db_settings(self.args.settings)
            self.initialize_db_args(settings, 'destination')

        if self.args.capture:
            self.capture_heroku_database()

        file_url = self.args.url
        if self.args.source_app:
            self.print_message("Sourcing data from backup for Heroku app '%s'"
                               % self.args.source_app)
            file_url = self.get_file_url_for_heroku_app(self.args.source_app)

        if self.args.destination_app:
            self.replace_heroku_db(file_url)
        elif self.databases['destination']['name']:
            self.replace_postgres_db(file_url)

        self.print_message("\nDone.\n\nDon't forget to update the Django Site entry if necessary!")
197674
def initdb(self):
        """"""
        if hasattr(self, 'alchemist'):
            self.alchemist.meta.create_all(self.engine)
            if 'branch' not in self.globl:
                self.globl['branch'] = 'trunk'
            if 'rev' not in self.globl:
                self.globl['rev'] = 0
            return
        from sqlite3 import OperationalError
        cursor = self.connection.cursor()
        try:
            cursor.execute('SELECT * FROM global;')
        except OperationalError:
            cursor.execute(self.strings['create_global'])
        if 'branch' not in self.globl:
            self.globl['branch'] = 'trunk'
        if 'turn' not in self.globl:
            self.globl['turn'] = 0
        if 'tick' not in self.globl:
            self.globl['tick'] = 0
        for table in (
            'branches',
            'turns',
            'graphs',
            'graph_val',
            'nodes',
            'node_val',
            'edges',
            'edge_val',
            'plans',
            'plan_ticks'
        ):
            try:
                cursor.execute('SELECT * FROM ' + table + ';')
            except OperationalError:
                cursor.execute(self.strings['create_' + table])
184509
def main(demo=False, aschild=False, targets=[]):
    

    if aschild:
        print("Starting pyblish-qml")
        compat.main()
        app = Application(APP_PATH, targets)
        app.listen()

        print("Done, don't forget to call `show()`")
        return app.exec_()

    else:
        print("Starting pyblish-qml server..")
        service = ipc.service.MockService() if demo else ipc.service.Service()
        server = ipc.server.Server(service, targets=targets)

        proxy = ipc.server.Proxy(server)
        proxy.show(settings.to_dict())

        server.listen()
        server.wait()