Exemple #1
0
def main(url, log):
    log1 = log
    while True:
        if not os.path.exists(log1):
            os.makedirs(log1)
            break
        else : log1 = log1+'_'
    content = content_extractor.get_content(url)

    logFile = open(log1+'/metadata',"a")
    logFile.write("URL : "+url+"\n\n")
    logFile.write("Title : "+content['title']+"\n\n")
    logFile.write("Meta Desc. : "+content['meta']+"\n\n")
    logFile.write("Content : "+content['content'].encode("utf8")+"\n\n")
    logFile.close()

    d = TextRank.text_rank(content['content'])
    sortd = sorted(d.iteritems(), key = operator.itemgetter(1), reverse=True)

    logtext = open(log1+'/textrank_result',"a")
    logtext.write(str(sortd))
    logtext.close()

    final=[]
    for i in sortd:
        for j in range(len(source_probs)):
            final.append((i[0], j, i[1]*source_probs[j]))

    fsort = sorted(final, key = operator.itemgetter(2), reverse=True)
    logres = open(log1+'/result',"a")
    logres.write(str(fsort))
    logres.close()
    server.run_server(fsort[:10])
Exemple #2
0
def main():
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s - %(levelname)s - %(message)s')
    try:
        run_server()
    except KeyboardInterrupt:
        pass
Exemple #3
0
def main(num, song, bearer, folder, serve, port):
    """Console script for playlistfromsong."""
    if folder is None:
        folder = getcwd()
    if serve:
        run_server(folder, port)
    elif song != None:
        while True:
            song = getTopFromLastFM(song)
            if (version_info > (3, 0)):
                getinput = input
            else:
                getinput = raw_input
            c = getinput('Did you mean "' + song + '"? (y/n) ')
            if c is "y":
                click.echo(
                    "Generating playlist for %d songs from '%s' \n(for generating more songs, use -n NUMBER)"
                    % (num, song))
                run(song.replace(" - ", " "),
                    num,
                    bearer=bearer,
                    folder=folder)
                break
            song = getinput(
                "Please enter the artist and song (e.g. The Beatles Let It Be): "
            )
    else:
        click.echo("Specify a song with --song 'The Beatles Let It Be'")
Exemple #4
0
def main(args):
    def load_yaml(file):
        with open(file, 'r', encoding="utf-8") as stream:
            # some versions of yaml we need Fullloader
            data = yaml.load(stream, Loader=yaml.FullLoader)

        return data

    args = parse_args(args)
    mode = args.command
    RELATIVE_YAML_FILENAME = args.conf_file
    conf_file = load_yaml(RELATIVE_YAML_FILENAME)


    if mode == TRAIN:
        epochs = args.epochs
        batch_size = args.batch
        log_dir = conf_file['log_dir']
        output_dir = conf_file['output_dir']
        pic_dir = conf_file['pics_dir']
        models_dir = conf_file['models_dir']
        # size of the latent space
        latent_dim = conf_file['latent_dim']

        time1 = datetime.datetime.now()
        timestampStr = time1.strftime("%H_%M_%S_%f_%b_%d_%Y")
        file_name = log_dir + '/dcgan_' + str(timestampStr)
        log_obj = Logger(file_name)
        log_obj.warning("Start process {} ".format(time1))
        log_obj.warning("Create DCGAN object: ")

        dcgan= dcgan_class(log_obj, output_dir, pic_dir, models_dir, latent_dim)
        # create the discriminator
        d_model = dcgan.define_discriminator(in_shape=(32, 32, 3))
        # create the generator
        g_model = dcgan.define_generator(dcgan.latent_dim)
        # create the gan
        gan_model = dcgan.define_gan(g_model, d_model)
        # load image data
        dataset = dcgan.load_real_samples()
        #print(dataset.shape)
        log_obj.warning(f"Train DCGAN model number epochs{epochs}: ")
        dcgan.train(g_model, d_model, gan_model, dataset,  dcgan.latent_dim, epochs, batch_size)
        #embed()
        return

    elif mode == SERVER:
        # create log object
        model_file = args.model_file
        log_dir = conf_file['log_dir']
        time1 = datetime.datetime.now()
        timestampStr = time1.strftime("%H_%M_%S_%f_%b_%d_%Y")
        file_name = log_dir + '/nlp_'+str(timestampStr)
        log_obj = Logger(file_name)
        app = create_app(conf_file, log_obj, model_file)
        run_server(app)
        return
    return
Exemple #5
0
def game_init():
    # Generate keys
    signature_verify = sign.Sign()

    uid = str(uuid.uuid4())  # generate a unique ID to identify ourselves

    # Start a local server for receiving messages from other players
    if len(sys.argv) > 1 and type(sys.argv[1]) == str:
        server_at = sys.argv[1]
    else:
        server_at = raw_input("Starting local server...hostname:port? ")
    hostname, port = server_at.split(':')
    port = int(port)
    if port < 1000 or port > 65535:
        print "Port must be 1000-65535"
        return
    gp = gameplay.Gameplay(uid)
    server.run_server(hostname, port, gp)

    # And connect to other players' servers to send messages.  This two-way
    # network structure should simplify trying to figure out who we're already
    # connected to, etc.  Each player should just make a connection to each other,
    # so in the end there should be 2*N connections.
    print "Welcome to crypto-settlers!  To begin, enter [ip:port] of each user who will be playing the game."
    player_ips = []
    player_clients = []
    while True:
        ip = raw_input("Player ip:port [or enter to finish]: ")
        if ip == "": break
        player_ips.append(ip)
    print "Connecting..."
    for addr in player_ips:
        ip, port = addr.split(':')
        port = int(port)
        new_client = client.SettlersNetworkClient(ip, port, signature_verify,
                                                  uid)
        success = new_client.connect()
        # Loop around and try to connect until all players are online
        while not success:
            print "Couldn't connect to ", addr, ", trying again in 2s..."
            time.sleep(2)
            success = new_client.connect()
        # Send public key
        new_client.send_key()
        # Add connection to a list
        player_clients.append(new_client)
    print "All connected!"

    gp.setup_client_connections(player_clients)
    gp.run()

    print "Game is finished! Disconnecting clients..."
    for c in player_clients:
        c.disconnect()

    print "Shutting down local server..."
    server.shutdown_server()
    sys.exit(0)
def _run_server(pipe):
    pipe.send('read')
    class StandardOutput:
        def write(self, data):
            if not data.strip():
                return
            pipe.send(data)
    sys.stdout = StandardOutput()
    server.run_server(_SERVER_ADDRESS)
Exemple #7
0
def run():
    '''
    ()-->None
    allow using python connect to CMD and run the sh script to open the django
    server
    '''
    config = server.configuration()['server']
    server.run_server(config['ip_address'], config['port'])
    showinfo("Notice", "Server on!")
def main(address=None, port=5000, cors=None):
    from server import run_server
    from db import InMemoryDb

    _initialize_logging()

    db = InMemoryDb(MAX_AGE)

    run_server(port, db, address=address, cors=cors)
Exemple #9
0
def game_init():
    # Generate keys
    signature_verify = sign.Sign()
    
    uid = str(uuid.uuid4()) # generate a unique ID to identify ourselves

    # Start a local server for receiving messages from other players
    if len(sys.argv) > 1 and type(sys.argv[1]) == str:
        server_at = sys.argv[1]
    else:
        server_at = raw_input("Starting local server...hostname:port? ")
    hostname, port = server_at.split(':')
    port = int(port)
    if port < 1000 or port > 65535:
        print "Port must be 1000-65535"
        return
    gp = gameplay.Gameplay(uid)
    server.run_server(hostname, port, gp)
    
    # And connect to other players' servers to send messages.  This two-way
    # network structure should simplify trying to figure out who we're already
    # connected to, etc.  Each player should just make a connection to each other,
    # so in the end there should be 2*N connections.
    print "Welcome to crypto-settlers!  To begin, enter [ip:port] of each user who will be playing the game."
    player_ips = []
    player_clients = []
    while True:
        ip = raw_input("Player ip:port [or enter to finish]: ")
        if ip == "": break
        player_ips.append(ip)
    print "Connecting..."
    for addr in player_ips:
        ip, port = addr.split(':')
        port = int(port)
        new_client = client.SettlersNetworkClient(ip, port, signature_verify, uid)
        success = new_client.connect()
        # Loop around and try to connect until all players are online
        while not success:
            print "Couldn't connect to ", addr, ", trying again in 2s..."
            time.sleep(2)
            success = new_client.connect()
        # Send public key 
        new_client.send_key()
        # Add connection to a list
        player_clients.append(new_client)
    print "All connected!"
    
    gp.setup_client_connections(player_clients)
    gp.run()

    print "Game is finished! Disconnecting clients..."
    for c in player_clients:
        c.disconnect()

    print "Shutting down local server..."
    server.shutdown_server()
    sys.exit(0)
Exemple #10
0
 def start(self):
     cm = self.cm
     #if cm.phone_from == 'console':
     #    # from console
     #    qr = pyzcqq.QQReg(random=int(cm.random), phone='console')
     #    qr.do_reg()
     #elif cm.phone_from == 'remote':
         # from remote, will start http server
     server.run_server(cm.server_host, int(cm.server_port), self.dbman)
def run(serve_the_things=False,
        scrape_the_things=True,
        count=None):

    if serve_the_things:
        server.run_server(db)
        return

    if scrape_the_things:
        scrape_plugins(count)
Exemple #12
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--fakedev', action='store_true')
    parser.add_argument('--date')
    args = parser.parse_args()
    tt_time_shift = _prepare_time_shift(args.date)

    state = State(tt_time_shift=tt_time_shift)
    device_thread = DeviceThread(state, fake=args.fakedev)
    device_thread.start()
    run_server(state)
Exemple #13
0
    def __init__(self):
        self.rfid_read_queue = Queue()
        self.rfid_command_queue = Queue()
        print("initializing database")
        self.dbm = dbm()
        self.rfid = RFID_util(self.rfid_read_queue, self.rfid_command_queue)
        self.apsrv = app_serv(self.rfid_read_queue)

        print("starting services...")
        #threading.Thread(target = server.run_server, args = (self.rfid_command_queue)).start()
        threading.Thread(target=self.rfid.read_while).start()
        threading.Thread(target=self.apsrv.check_for_pet).start()
        server.run_server(self.rfid_command_queue)
Exemple #14
0
def run():
    from mudsling.options import get_options

    # We are not interested in the script name part of the argv list.
    options = get_options()
    options['gamedir'] = init_game_dir(options['gamedir'])

    # Simple means we want to keep everything in a single process.
    if options['simple']:
        from server import run_server
        os.chdir(options['gamedir'])
        run_server(options)
    else:
        # Imports shouldn't resolve to this file since we added src to the
        # front of the search path above.
        from mudsling.config import config
        from mudsling.logs import open_log
        from mudsling.pid import check_pid

        argv = sys.argv[1:]

        open_log(stdout=True, level=logging.DEBUG)
        pidfile = os.path.join(options['gamedir'], 'mudsling.pid')
        check_pid(pidfile)
        config.read(options.config_paths())

        processes['server'] = MUDSlingProcess('server', argv,
                                              options['gamedir'])
        if config.getboolean('Proxy', 'enabled'):
            processes['proxy'] = MUDSlingProcess('proxy', argv,
                                                 options['gamedir'])

        for process in processes.itervalues():
            process.spawn()

        reactor.addSystemEventTrigger('before', 'shutdown', kill_all_processes)

        import signal

        def handle_sighup(signal, frame):
            processes['server'].signal('HUP')

        try:
            signal.signal(signal.SIGHUP, handle_sighup)
        except ValueError as e:
            logging.warning('No SIGHUP handler: %s', e.message)

        reactor.run()
        os.remove(pidfile)
Exemple #15
0
def main():
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s - %(name)-12s - %(levelname)-5s - %(message)s',
        datefmt='%y-%m-%d %H:%M:%S'
    )

    parser = argparse.ArgumentParser()
    commandline.standard_argparse_options(parser, default_config='config/config.yaml')

    options, unknown = parser.parse_known_args()
    config = commandline.config_from_options(options, TRAFARET)

    server.on_startup.append(on_startup)
    server.on_shutdown.append(on_shutdown)
    server.run_server(config)
Exemple #16
0
def main():
    FILE_DIR = os.path.dirname(
        os.path.abspath(inspect.getfile(inspect.currentframe())))
    parser = argparse.ArgumentParser(description="")
    parser.add_argument(
        "settings_yaml",
        nargs="?",
        help="Path to a yaml file with settings",
        default="{}/default.yaml".format(FILE_DIR),
    )
    args = parser.parse_args()

    logging.root.setLevel(logging.DEBUG)
    event_logging.setLevel(logging.DEBUG)

    event_logging_queue = Queue()  # no limit on size
    event_logging_handler = logging.handlers.QueueHandler(event_logging_queue)
    event_logging.addHandler(event_logging_handler)

    events = []

    app = server.run_server(event_logging_queue, events)

    application = QApplication(sys.argv)
    application.setOverrideCursor(Qt.BlankCursor)

    load_events(args.settings_yaml, events)

    timer = QTimer()
    timer.timeout.connect(lambda: tick(events))
    timer.start(1000)

    sys.exit(application.exec_())
Exemple #17
0
    def __init__(self, handle):

        if not hasattr(self, 'confvars'):
            self.confvars = read_conf_from_info(get_bundle_path())

        logging.error("Starting server database: %s port: %s" %
                      (self.confvars['path'], self.confvars['port']))

        os.chdir(os.environ['SUGAR_BUNDLE_PATH'])

        self.confvars['ip'] = '0.0.0.0'

        server.run_server(self.confvars)

        handle.uri = 'http://%s:%s%s' % (
            self.confvars['ip'], self.confvars['port'],
            self.confvars['home_page'])

        webactivity.WebActivity.__init__(self, handle)

        if USE_GTK2:
            # Use xpcom to set a RAM cache limit.  (Trac #7081.)
            from xpcom import components
            from xpcom.components import interfaces
            cls = components.classes['@mozilla.org/preferences-service;1']
            pref_service = cls.getService(interfaces.nsIPrefService)
            branch = pref_service.getBranch("browser.cache.memory.")
            branch.setIntPref("capacity", "5000")

            # Use xpcom to turn off "offline mode" detection, which disables
            # access to localhost for no good reason.  (Trac #6250.)
            ios_class = components.classes["@mozilla.org/network/io-service;1"]
            io_service = ios_class.getService(interfaces.nsIIOService2)
            io_service.manageOfflineStatus = False

        self.searchtoolbar = SearchToolbar(self)
        search_toolbar_button = ToolbarButton()
        search_toolbar_button.set_page(self.searchtoolbar)
        search_toolbar_button.props.icon_name = 'search-wiki'
        search_toolbar_button.props.label = _('Search')
        self.get_toolbar_box().toolbar.insert(search_toolbar_button, 1)
        search_toolbar_button.show()
        # Hide add-tabs button
        if hasattr(self._primary_toolbar, '_add_tab'):
            self._primary_toolbar._add_tab.hide()

        self.searchtoolbar.show()
Exemple #18
0
def main():
    parser = argparse.ArgumentParser(
        description='A dynamic documentation server')
    parser.add_argument('--config-file', default=None)
    # TODO: other arguments
    args = parser.parse_args()

    app = run_server(config_file=args.config_file)
Exemple #19
0
    def do_httpfs(self,arg):
        arguments = arg.split(' ')
        is_v = False
        port = 9988
        dir_path = '../ass3'

        if '-v' in arguments:
            is_v = True

        if '-p' in arguments:
            p_index = arguments.index('-p')
            port = int(arguments[p_index + 1])

        if '-d' in arguments:
            d_index = arguments.index('-d')
            dir_path = arguments[d_index + 1]

        server.run_server(is_v, port, dir_path)
Exemple #20
0
def main():
    if len(sys.argv) < 2:
        print 'enter arg form console/server/client'
        return
    if sys.argv[1] == 'client':
        host, port = None, None
        if len(sys.argv) >= 4:
            host, port = sys.argv[2], sys.argv[3]
        client.run_client(host, port)
    elif sys.argv[1] == 'server':
        host, port = None, None
        if len(sys.argv) >= 4:
            host, port = sys.argv[2], sys.argv[3]
        server.run_server(host, port)
    elif sys.argv[1] == 'console':

        console.console_mode()
    else:
        print 'enter arg form console/server/client'
    return
Exemple #21
0
def main():
    lock = threading.Lock()

    site_name = sys.argv[1]
    target_site = importlib.import_module(site_name)

    swf_path, swf_url = get_swf(target_site)
    patch_swf(target_site, swf_path)
    SeleniumRunner(lock, target_site.PAGE_URL).start()
    collected_data = run_server(swf_path, swf_url, lock, target_site)
    enc_key = os.path.commonprefix(collected_data)
    print('enc_key = %s' % enc_key)
Exemple #22
0
def main():
    if args.makemigrations:
        # Create migrations file
        alembic_agent = AlembicAgent.setup(manage_file_path)
        alembic_agent.make_migrations(args.message)

    if args.upgrade:
        # upgrade to latest revision
        alembic_agent = AlembicAgent.setup(manage_file_path)
        alembic_agent.upgrade()

    if args.downgrade:
        # upgrade to latest revision
        alembic_agent = AlembicAgent.setup(manage_file_path)
        alembic_agent.downgrade()

    elif args.run:
        # run server
        host = args.host or config['server']['host']
        port = args.port or config['server']['port']
        run_server(host=host, port=port)
Exemple #23
0
async def main():
    game_state = GameState()

    await asyncio.gather(
        run_server(
            host='0.0.0.0',
            port=31455,
            game_state=game_state,
        ),
        game_state.update_clients_loop(),
        game_state.backup_loop(),
    )
Exemple #24
0
def main():
    lock = threading.Lock()

    site_name = sys.argv[1]
    target_site = importlib.import_module(site_name)

    swf_path, swf_url = get_swf(target_site)
    patch_swf(target_site, swf_path)
    SeleniumRunner(lock, target_site.PAGE_URL).start()
    collected_data = run_server(swf_path, swf_url, lock, target_site)
    enc_key = os.path.commonprefix(collected_data)
    print('enc_key = %s' % enc_key)
Exemple #25
0
    def server_handle(self):
        btnthread = ButtonThread(self.button)

        if self.button.text() == 'Start':
            try:
                pathlist = []
                scalerlist = []
                modelnamelist = []

                if self.le1.text() == '' or self.sle1.text() == '':
                    raise ModelNumberError()

                pathlist.append(self.le1.text())
                scalerlist.append(self.sle1.text())
                modelnamelist.append(ModelNames(self.cb1.currentIndex()))

                if int(self.cb.currentText()) >= 2:
                    if self.le2.text() == '' or self.sle2.text() == '':
                        raise ModelNumberError()
                    pathlist.append(self.le2.text())
                    scalerlist.append(self.sle2.text())
                    modelnamelist.append(ModelNames(self.cb2.currentIndex()))

                if int(self.cb.currentText()) >= 3:
                    if self.le3.text() == '' or self.sle3.text() == '':
                        raise ModelNumberError()
                    pathlist.append(self.le3.text())
                    scalerlist.append(self.sle3.text())
                    modelnamelist.append(ModelNames(self.cb3.currentIndex()))

                score = self.getThresholdScore()
                self.button.setText('Stop')

                self.logtext.clear()
                self._stdout.start()

                btnthread.start()
                self.serverthread = server.run_server(
                    (HOST, PORT), pathlist, scalerlist, modelnamelist, score)

            except ModelNumberError:
                msgbox = QMessageBox()
                msgbox.setText('Please select models correctly')
                msgbox.exec()

        elif self.button.text() == 'Stop':

            # 서버 중지작업
            btnthread.start()
            self.serverthread.stop()
            self._stdout.stop()
            self.button.setText('Start')
def serve(args):
    if not args.gh_url or not args.jira_url:
        fail('Both GitHub and JIRA URL have to be specified!')

    if not args.gh_token:
        fail('No GitHub token specified!')

    if not args.jira_user or not args.jira_token:
        fail('No JIRA credentials specified!')

    if not args.jira_project:
        fail('No JIRA project specified!')

    if not args.secret:
        fail('No Webhook secret specified!')

    github = ghlib.GitHub(args.gh_url, args.gh_token)
    jira = jiralib.Jira(args.jira_url, args.jira_user, args.jira_token)
    sync = util.Sync(github,
                     jira.getProject(args.jira_project),
                     direction=direction_str_to_num(args.direction))
    server.run_server(sync, args.secret, port=args.port)
Exemple #27
0
 def test_run_server(self):
     self.assertIsInstance(run_server(), socket.socket)
Exemple #28
0
def run_server(args):
    import server
    server.run_server(args)
Exemple #29
0
def runserver():
    server.run_server()
Exemple #30
0
#!/usr/bin/env python3
from utils import logger
from server import run_server

if __name__ == "__main__":
    run_server(port=80)
Exemple #31
0
    'documentación libre de GNU</a>. <br/> Wikipedia es una marca ' + \
    'registrada de la organización sin ánimo de lucro Wikimedia ' + \
    'Foundation, Inc.<br/><a href="/static/about_pt.html">Acerca de ' + \
    'Wikipedia</a>'
    confvars['resultstitle'] = "Resultados de la búsqueda sobre '%s'."
    return confvars


if __name__ == '__main__':
    import server
    import sys
    conf = configure()
    conf['path'] = sys.argv[1]
    conf['port'] = int(sys.argv[2])
    conf['comandline'] = True

    if len(sys.argv) > 3:
        conf['editdir'] = sys.argv[3]
    if len(sys.argv) > 4:
        conf['giturl'] = sys.argv[4]

    server.run_server(conf)

else:
    import activity

    class WikipediaActivityPT(activity.WikipediaActivity):
        def __init__(self, handle):
            self.confvars = configure()
            activity.WikipediaActivity.__init__(self, handle)
Exemple #32
0
def run_guess_server(port):
    """run guessing game server on the port"""
    server.run_server(port, Server)
Exemple #33
0
    ' <br/> Wikipedia is a registered trademark of the non-profit ' + \
    'Wikimedia Foundation, Inc.<br/><a href="/static/about_en.html">' + \
    'About Wikipedia</a>'
    confvars['resultstitle'] = "Search results for '%s'."
    return confvars


if __name__ == '__main__':
    import server
    import sys
    conf = configure()
    conf['path'] = sys.argv[1]
    conf['port'] = int(sys.argv[2])
    conf['comandline'] = True

    if len(sys.argv) > 3:
        conf['editdir'] = sys.argv[3]
    if len(sys.argv) > 4:
        conf['giturl'] = sys.argv[4]

    server.run_server(conf)

else:
    import activity

    class WikipediaActivityHI(activity.WikipediaActivity):

        def __init__(self, handle):
            self.confvars = configure()
            activity.WikipediaActivity.__init__(self, handle)
Exemple #34
0
	def run(self):
		run_server(self.port)
Exemple #35
0
def serve(folder):
    run_server(os.path.join(folder, 'content'), os.path.join(folder, 'templates'), os.path.join(
        folder, 'media'))
Exemple #36
0
import connection
import directory
import server

conn = connection.Connection('141.76.82.170', 12345)

server.run_server(conn)
Exemple #37
0
 def run(self):
     """
     HTTPD
     """
     server.run_server(SERVER_ADDR, SERVER_PORT, LISTEN_CLIENTS_NUMB,
                       MAX_SERVER_BUFFER_SIZE)
Exemple #38
0
# Launches the server as a deamon

import deamon

from server import run_server
with deamon.DeamonContext():
    run_server()
    
Exemple #39
0
        print >> sys.stderr, '[ERROR] Incorrect settings file: %s' % opts.settings
        sys.exit(1)
    except env_config.UndefinedSettingsFile:
        print >> sys.stderr, '[ERROR] Settings file is empty: %s' % opts.settings
        sys.exit(1)
    except env_config.EmptyPlatformName:
        print >> sys.stderr, '[ERROR] Platform name is empty in the settings file: %s' % opts.settings
        sys.exit(1)
    except env_config.MissingMandatoryParameter, err:
        print >> sys.stderr, '[ERROR] Missing mandatory parameter in the settings file: %s' % err
        sys.exit(1)

    # Mapping file error handling

    except env_config.IncorrectMappingFile:
        print >> sys.stderr, '[ERROR] Incorrect mapping file: %s' % opts.mapping
        sys.exit(1)
    except env_config.IncorrectMappingFile:
        print >> sys.stderr, '[ERROR] mMpping file is empty: %s' % opts.mapping
        sys.exit(1)

    # Hadoop web server

    if hadoop_env_config.settings.get('server', None):

        from server import run_server

        address, port = hadoop_env_config.settings.get('server',
                                                       None).split(':')
        run_server(address, port, hadoop_env_config)
def _run_server(pipe, data_dir):
    pipe.send('read')
    server.run_server(_SERVER_ADDRESS, data_dir)
Exemple #41
0
 def run_server(data, root):
     utils.set_server_root(root)
     server.init_server(data)
     server.run_server()
Exemple #42
0
def main(args):
  opts = parse_args(args)
  server.run_server(opts.port)
Exemple #43
0
	def run(self):
		server.run_server(host='0.0.0.0', port=8080)
Exemple #44
0
__author__ = 'mandriy'
# -*- coding: utf-8 -*-

import os
import utils
import server

if os.getenv('LAB2_TASKS'):
    server.init_server(utils.get_files(os.getenv('LAB2_TASKS')))
    server.run_server(host='0.0.0.0')

Exemple #45
0
 def run(self):
     server.run_server(host='0.0.0.0', port=8080)
Exemple #46
0
#!/usr/bin/env python3

from konf import Konf
k = Konf('config.yaml')

from dota2info import Dota2info
address = k('address', str)
info_source = Dota2info(address)

from server import run_server
serving_port = k('serving_port', int, 80)

run_server(info_source, serving_port)
Exemple #47
0
from server import run_server

run_server()
Exemple #48
0
parser_add_page.set_defaults(func=lambda args: add_page(args.page))

# create the parser for the "list" command
parser_list_page = subparsers.add_parser('list', help="list pages (for each page: name, fan count, ID)")
parser_list_page.set_defaults(func=lambda args: print_page_list())

# create the parser for the "update" command
parser_update = subparsers.add_parser('update', help="update posts from facebook/twitter")
parser_update.add_argument('--posts', type=int, default=100, help="posts limits")
parser_update.set_defaults(func=lambda args: update_posts_per_page(args.posts))

# create the parser for the "serve" command
parser_serve = subparsers.add_parser('serve', help="start a web server to access collected data")
parser_serve.add_argument('--port', type=int, default=8000, help="server port")
parser_serve.add_argument('--interface', default='127.0.0.1', help="server ip")
parser_serve.add_argument('--debug', default=False, help="enable debugger")
parser_serve.add_argument('--reloader', default=False, help="enable auto reload")
parser_serve.set_defaults(func=lambda args: run_server(args.interface, args.port, args.debug, args.reloader))

# create the parser for the "remove" command
parser_remove_page = subparsers.add_parser('remove', help="remove posts from facebook/twitter")
parser_remove_page.add_argument('page_id', help="page id")
parser_remove_page.set_defaults(func=lambda args: remove_page(args.page_id))


# # parse the args and call whatever function was selected
args = parser.parse_args()
if not any(vars(args).values()):
    sys.exit('Please supply a command to call\nUse -h for help')
args.func(args)
Exemple #49
0
        self.image = Gtk.Image()
        self.image.set_name('qr')
        self.add(self.image)
        pixbuf = pixbuf_from_pil(get_qr_code(ip=get_interfaces()[0][1]))
        self.image.set_from_pixbuf(pixbuf)

    def run(self):
        css_provider = Gtk.CssProvider()
        css_provider.load_from_data(CSS_DATA)
        context = Gtk.StyleContext()
        screen = Gdk.Screen.get_default()
        context.add_provider_for_screen(
            screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
        self.connect("destroy", Gtk.main_quit)
        self.show_all()
        Gtk.main()


if __name__ == "__main__":
    if os.getenv('DEV') == 'true':
        run_server(debug=True)
    else:
        t = threading.Thread(target=run_server, daemon=True)
        t.start()
        print("running...")
        dropapp = DropAppGtk3()
        dropapp.run()

    print("exiting...")
import server

server.run_server()
Exemple #51
0
    app = Redirector(app, '/', '/flex/DecodingGenerator.swf')
    app = CrossdomainMiddleware(app)
    app = DecodingGeneratorGateway(app)
    app = ServeStatic(app, 'flex', '/flex/')

    return app


def run_server(options):
    from wsgiref import simple_server

    httpd = simple_server.WSGIServer(
        (options.iface, options.port),
        simple_server.WSGIRequestHandler,
    )

    httpd.set_app(get_app(options))

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass


if __name__ == '__main__':
    import server

    options, args = parse_options()

    server.run_server(options)
Exemple #52
0
 def start_server():
     server.run_server(self)
Exemple #53
0
def patch_swf(swf_path):
    swf_name = os.path.splitext(os.path.basename(swf_path))[0]
    abc_index = 0
    abc_id = '%s-%d' % (swf_name, abc_index)

    try:
        os.remove(full_path('%s.abc' % abc_id))
        shutil.rmtree(full_path(abc_id))
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise

    run(['abcexport', full_path('%s.swf' % swf_name)])
    run(['rabcdasm', full_path('%s.abc' % abc_id)])
    subprocess.Popen([
        'patch', '-p0', '-i', '../asasm.patch'], cwd=full_path(abc_id)).wait()
    run(['rabcasm', full_path('%s/%s.main.asasm' % (abc_id, abc_id))])
    run([
        'abcreplace', full_path('%s.swf' % swf_name), str(abc_index),
        full_path('%s/%s.main.abc' % (abc_id, abc_id))])

if __name__ == '__main__':
    lock = threading.Lock()
    swf_path, swf_url = get_swf()
    patch_swf(swf_path)
    SeleniumRunner(lock).start()
    collected_data = run_server(swf_url, lock)
    enc_key = os.path.commonprefix(collected_data)
    print('enc_key = %s' % enc_key)
Exemple #54
0
            self.startTimer()

dog = BotWatchDog()
dog.startTimer()

print """Running BotWatchDog: 
    WATCH_DOG_APP_NAME = %s
    WATCH_DOG_SCRENSHOTS_DIR = %s
    WATCH_DOG_LOG_FILE = %s
    WATCH_DOG_MAX_SCREENSHOTS = %d
    WATCH_DOG_SCREENSHOTS_TIMEOUT = %d
    WATCH_DOG_SLEEP_AFTER = %d

""" %(BotWatchDog.APP_NAME, 
    BotWatchDog.SCRENSHOTS_DIR, 
    BotWatchDog.LOG_FILE, 
    BotWatchDog.MAX_SCREENSHOTS,
    BotWatchDog.SCREENSHOTS_TIMEOUT,
    BotWatchDog.SLEEP_AFTER
    )
dog.wake()



from server import run_server


run_server(dog)