Launch Spotify application.

        Will raise a LaunchError exception if there is no response from the
        Spotify app within timeout seconds.
346383
def launch_app(self, timeout=10):
        

        def callback():
            """Callback function"""
            self.send_message({"type": TYPE_STATUS,
                               "credentials": self.access_token,
                               "expiresIn": self.expires})

        self.launch(callback_function=callback)

        # Need to wait for Spotify to be launched on Chromecast completely
        while not self.is_launched and timeout:
            time.sleep(1)
            timeout -= 1

        if not self.is_launched:
            raise LaunchError(
                "Timeout when waiting for status response from Spotify app")
775678
def launch():
    """"""
    try:
        exp = Experiment(db.init_db(drop_all=False))
    except Exception as ex:
        return error_response(
            error_text="Failed to load experiment in /launch: {}".format(str(ex)),
            status=500,
            simple=True,
        )
    try:
        exp.log("Launching experiment...", "-----")
    except IOError as ex:
        return error_response(
            error_text="IOError writing to experiment log: {}".format(str(ex)),
            status=500,
            simple=True,
        )

    try:
        recruitment_details = exp.recruiter.open_recruitment(
            n=exp.initial_recruitment_size
        )
        session.commit()
    except Exception as e:
        return error_response(
            error_text="Failed to open recruitment, check experiment server log "
            "for details: {}".format(str(e)),
            status=500,
            simple=True,
        )

    for task in exp.background_tasks:
        try:
            gevent.spawn(task)
        except Exception:
            return error_response(
                error_text="Failed to spawn task on launch: {}, ".format(task)
                + "check experiment server log for details",
                status=500,
                simple=True,
            )

    if _config().get("replay", False):
        try:
            task = ReplayBackend(exp)
            gevent.spawn(task)
        except Exception:
            return error_response(
                error_text="Failed to launch replay task for experiment."
                "check experiment server log for details",
                status=500,
                simple=True,
            )

    # If the experiment defines a channel, subscribe the experiment to the
    # redis communication channel:
    if exp.channel is not None:
        try:
            from dallinger.experiment_server.sockets import chat_backend

            chat_backend.subscribe(exp, exp.channel)
        except Exception:
            return error_response(
                error_text="Failed to subscribe to chat for channel on launch "
                + "{}".format(exp.channel)
                + ", check experiment server log for details",
                status=500,
                simple=True,
            )

    message = "\n".join(
        (
            "Initial recruitment list:\n{}".format(
                "\n".join(recruitment_details["items"])
            ),
            "Additional details:\n{}".format(recruitment_details["message"]),
        )
    )

    return success_response(recruitment_msg=message)
1315299
private static synchronized void startup() {
		try {
			CONFIG = ApiConfigurations.fromProperties();
			
			String clientName = ApiClients.getApiClient(LogManager.class, "/stackify-api-common.properties", "stackify-api-common");

			LOG_APPENDER = new LogAppender<LogEvent>(clientName, new LogEventAdapter(CONFIG.getEnvDetail()), MaskerConfiguration.fromProperties(), CONFIG.getSkipJson());
			LOG_APPENDER.activate(CONFIG);
		} catch (Throwable t) {
			LOGGER.error("Exception starting Stackify Log API service", t);
		}
	}
536862
def handle(self, **options):
        """"""
        template = os.path.dirname(os.path.abspath(__file__)) + "/app_template"
        name = options.pop("name")
        call_command("startapp", name, template=template, **options)
872683
def launch_browser(self, profile, timeout=30):
        
        self.profile = profile

        self._start_from_profile_path(self.profile.path)
        self._wait_until_connectable(timeout=timeout)
163089
def _wait_for_request(self, uuid, connection_adapter=None):
        
        start_time = time.time()
        while not self._response[uuid]:
            connection_adapter.check_for_errors()
            if time.time() - start_time > self._timeout:
                self._raise_rpc_timeout_error(uuid)
            time.sleep(IDLE_WAIT)
182198
def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
    
    lua_script = create_lua_script(plugins)
    lua = urllib.parse.quote_plus(lua_script)
    page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}'

    try:
        with docker_container():
            logger.debug('[+] Sending request to Splash instance')
            res = requests.get(page_url)
    except requests.exceptions.ConnectionError:
        raise SplashError("Could not connect to Splash server {}".format(SPLASH_URL))

    logger.debug('[+] Response received')

    json_data = res.json()

    if res.status_code in ERROR_STATUS_CODES:
        raise SplashError(get_splash_error(json_data))

    softwares = json_data['softwares']
    scripts = json_data['scripts'].values()
    har = get_valid_har(json_data['har'])

    js_error = get_evaljs_error(json_data)
    if js_error:
        logger.debug('[+] WARNING: failed to eval JS matchers: %(n)s', {'n': js_error})
    else:
        logger.debug('[+] Detected %(n)d softwares from the DOM', {'n': len(softwares)})
    logger.debug('[+] Detected %(n)d scripts from the DOM', {'n': len(scripts)})
    logger.debug('[+] Final HAR has %(n)d valid entries', {'n': len(har)})

    return {'har': har, 'scripts': scripts, 'softwares': softwares}
918673
def _send_and_wait(self, **kwargs):
        
        frame_id = self.next_frame_id
        kwargs.update(dict(frame_id=frame_id))
        self._send(**kwargs)
        timeout = datetime.now() + const.RX_TIMEOUT
        while datetime.now() < timeout:
            try:
                frame = self._rx_frames.pop(frame_id)
                raise_if_error(frame)
                return frame
            except KeyError:
                sleep(0.1)
                continue
        _LOGGER.exception(
            "Did not receive response within configured timeout period.")
        raise exceptions.ZigBeeResponseTimeout()
357427
def call(self, request=None, *args, **kwargs):
        
        if request is not None:
            self.request = request

        retry = self.request.configuration.retry
        if not isinstance(retry, SimpleRetry):
            raise Error('Currently only the fast retry strategy is supported')

        last_exception = None
        for i in range(0, retry.max_retry):
            try:
                if i > 0:
                    retry.sleep_jitter()

                self.call_once()
                return self.response

            except Exception as ex:
                last_exception = RequestFailed(message='Request failed', cause=ex)
                logger.debug("Request %d failed, exception: %s" % (i, ex))

                # Last exception - throw it here to have a stack
                if i+1 == retry.max_retry:
                    raise last_exception

        raise last_exception
1368618
def _parse_launch_error(data):
        
        return LaunchFailure(
            data.get(ERROR_REASON, None),
            data.get(APP_ID),
            data.get(REQUEST_ID),
        )
1086518
def wait(self, timeout=None):
        

        if timeout is not None:
            if not self._thread:
                self._thread = threading.Thread(target=self._wait4process)
                self._thread.daemon = 1
                self._thread.start()

        if self._thread:
            self._thread.join(timeout=timeout)
            self.timeout_happened = self.timeout_happened or self._thread.isAlive()
        else:
            # no timeout and no existing thread
            self._wait4process()

        return self
782006
def _on_timeout(self, info: str = None) -> None:
        
        self._timeout = None
        error_message = "Timeout {0}".format(info) if info else "Timeout"
        if self.final_callback is not None:
            self._handle_exception(
                HTTPTimeoutError, HTTPTimeoutError(error_message), None
            )
516290
def wait_init(self):
        
        init_done = self.init_done.wait(timeout=self.init_wait_timeout)
        if not init_done:
            if hasattr(self, "peek"):
                app = self.config.get("application")
                if app:
                    bef_init_cmds = app.get("cli_ready_trigger")
                    if bef_init_cmds in self.peek():  # pylint: disable=no-member
                        init_done = True
        return init_done
565798
def send(self):
        """"""
        success = False
        if self.method is None:
            raise ParamsError()
        try:
            if self.method == 'SEARCH':
                req = self._get_requests()
                _url = self.__NETEAST_HOST + self._METHODS[self.method]
                resp = req.post(_url, data=self.data)
                self._build_response(resp)
                self.response.ok = True
            else:
                if isinstance(self.data, dict):
                    data = encrypted_request(self.data)

                req = self._get_webapi_requests()
                _url = self.__NETEAST_HOST + self._METHODS[self.method]

                if self.method in ('USER_DJ', 'USER_FOLLOWS', 'USER_EVENT'):
                    _url = _url % self.params['uid']

                if self.method in ('LYRIC', 'MUSIC_COMMENT'):
                    _url = _url % self.params['id']
                # GET
                if self.method in ('LYRIC'):
                    resp = req.get(_url)
                else:
                    resp = req.post(_url, data=data)
                self._build_response(resp)
                self.response.ok = True
        except Exception as why:
            traceback.print_exc()
            print 'Requests Exception', why
            # self._build_response(why)
            self.response.error = why
887820
def launch(self, timeout=2):
        
        self.start_time = time.time()
        self.end_time = time.time()
        instance = self.app.launch(environment=self.env)
        time.sleep(2) # Instance need time to appear in ui

        assert instance.running(timeout=timeout), "Monitor didn't get Active state"
        launched = instance.status == 'Active'
        instance.reschedule_workflow(workflow_name='destroy', timestamp=self.destroy_interval)
        assert instance.destroyed(timeout=timeout), "Monitor didn't get Destroyed after short time"
        stopped = instance.status == 'Destroyed'
        instance.force_remove()
        self.end_time = time.time()
        self.status = launched and stopped
228875
public void start() throws AppiumServerHasNotBeenStartedLocallyException {
        lock.lock();
        try {
            if (isRunning()) {
                return;
            }

            try {
                process = new CommandLine(this.nodeJSExec.getCanonicalPath(),
                    nodeJSArgs.toArray(new String[] {}));
                process.setEnvironmentVariables(nodeJSEnvironment);
                process.copyOutputTo(stream);
                process.executeAsync();
                ping(startupTimeout, timeUnit);
            } catch (Throwable e) {
                destroyProcess();
                String msgTxt = "The local appium server has not been started. "
                    + "The given Node.js executable: " + this.nodeJSExec.getAbsolutePath()
                    + " Arguments: " + nodeJSArgs.toString() + " " + "\n";
                if (process != null) {
                    String processStream = process.getStdOut();
                    if (!StringUtils.isBlank(processStream)) {
                        msgTxt = msgTxt + "Process output: " + processStream + "\n";
                    }
                }

                throw new AppiumServerHasNotBeenStartedLocallyException(msgTxt, e);
            }
        } finally {
            lock.unlock();
        }
    }
393594
def _timeout(self, timeout, handler, *args, **kw):
        
        t = spawn_thread(target=handler, args=args, kw=kw)
        t.daemon = True
        t.start()
        t.join(timeout)

        if not t.is_alive():
            if t.exc_info:
                return t.exc_info
            return t.result
        else:
            try:
                msg = '[%s] Execution was forcefully terminated'
                raise RuntimeError(msg % t.name)
            except:
                return sys.exc_info()