Redirect pylivetrader.api.* operations to the algorithm
    in the local context.
16851
def api_method(f):
    '''
    
    '''

    @wraps(f)
    def wrapped(*args, **kwargs):
        # Get the instance and call the method
        algorithm = get_context()
        if algorithm is None:
            raise RuntimeError(
                '{} method must be called during live trading'.format(
                    f.__name__))
        return getattr(algorithm, f.__name__)(*args, **kwargs)

    # register api redirection
    setattr(pylivetrader.api, f.__name__, wrapped)
    pylivetrader.api.__all__.append(f.__name__)
    f.is_api_method = True

    return f
309033
def urlopen(self, method, url, redirect=True, **kw):
        ""
        u = parse_url(url)

        if u.scheme == "http":
            # For proxied HTTPS requests, httplib sets the necessary headers
            # on the CONNECT to the proxy. For HTTP, we'll definitely
            # need to set 'Host' at the very least.
            headers = kw.get('headers', self.headers)
            kw['headers'] = self._set_proxy_headers(url, headers)

        return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
1295676
def lazy_raise_or_redirect():
    '''
    
    '''
    if not request.view_args:
        return
    for name, value in request.view_args.items():
        if isinstance(value, NotFound):
            request.routing_exception = value
            break
        elif isinstance(value, LazyRedirect):
            new_args = request.view_args
            new_args[name] = value.arg
            new_url = url_for(request.endpoint, **new_args)
            return redirect(new_url)
124857
def hijack_local_run(context)
      (class << context; self; end).class_eval do
        alias_method :transactionless_local_run, :local_run
        def local_run(*args)
          ::ActiveRecord::Base.transaction do
            transactionless_local_run(*args)
            raise ::ActiveRecord::Rollback
          end
        end # local_run
      end # metaclass
    end
756536
def get_redirect_url(self, **kwargs):
        ""
        name = kwargs.get('provider', '')
        try:
            provider = Provider.objects.get(name=name)
        except Provider.DoesNotExist:
            raise Http404('Unknown OAuth provider.')
        else:
            if not provider.enabled():
                raise Http404('Provider %s is not enabled.' % name)
            client = self.get_client(provider)
            callback = self.get_callback_url(provider)
            params = self.get_additional_parameters(provider)
            return client.get_redirect_url(self.request, callback=callback, parameters=params)
6590
def get_safe_redirect_target(arg='next'):
    """"""
    for target in request.args.get(arg), request.referrer:
        if not target:
            continue
        if is_local_url(target):
            return target
    return None
42457
def AuthenticatedOrRedirect(invocation):
    
    class AuthenticatedOrRedirect(GiottoInputMiddleware):
        def http(self, request):
            if request.user:
                return request
            return Redirection(invocation)

        def cmd(self, request):
            if request.user:
                return request
            return Redirection(invocation)

    return AuthenticatedOrRedirect
309594
def run_local(client):
  """"""
  webbrowser.open(client.get_auth_uri())
  code = wait_for_redirect()
  return client.get_token(code)
1125841
def redirect(url, code=303):
    
    scriptname = request.environ.get('SCRIPT_NAME', '').rstrip('/') + '/'
    location = urljoin(request.url, urljoin(scriptname, url))
    raise HTTPResponse("", status=code, header=dict(Location=location))
292251
def getalgo(self, operation, name):
        ''''''
        if operation not in self._algorithms:
            raise NotAvailable('{0} not registered.'.format(operation))
        oper = self._algorithms[operation]
        try:
            return oper[name]
        except KeyError:
            raise NotAvailable('{0} algorithm {1} not registered.'
                               .format(operation, name))
1349993
def api_call(self, method, **params):
        
        coro = self._api_call(method, **params)
        # Explicitly ensure that API call is executed
        return asyncio.ensure_future(coro)
728648
def success_redirect(self, msg='', log=''):
        '''
        
        '''
        from django.shortcuts import redirect
        self.lti_msg = msg
        self.lti_log = log
        return redirect(self.build_return_url())
328342
def get_redirect_target():
    """"""
    for target in request.values.get('next'), request.referrer:
        if target and is_local_url(target):
            return target
574359
def redirect(location, code=302, **kw):
    """"""
    if not 300 <= code < 400:
        raise ValueError("Not a 3xx status code: '%s'" % code)
    return response(code=code, location=location, **kw)
622000
def redirectSTDOUTtoDebugFile():
    """"""
    import sys
    kwargs = {}
    if sys.version_info >= (3,):
        kwargs["encoding"] = "utf8"
    sys.stdout = open(
        os.path.join(
            getDebugDirectory(),
            "{0}.stdout".format(getDebugIdentifier()),
        ),
        "w",
        1, # Buffering by line
        **kwargs
    )
    sys.stderr = open(
        os.path.join(
            getDebugDirectory(),
            "{0}.stderr".format(getDebugIdentifier()),
        ),
        "w",
        1, # Buffering by line
        **kwargs
    )
653010
def _openapi_redoc(self):
        
        return render_template('openapi/redoc.html',
                               title=self.app.config.API_TITLE or self.app.name,
                               redoc_url=self.app.config.API_REDOC_SOURCE_URL)
1008890
def get_redirect_target(self, resp):
        """"""
        # Due to the nature of how requests processes redirects this method will
        # be called at least once upon the original response and at least twice
        # on each subsequent redirect response (if any).
        # If a custom mixin is used to handle this logic, it may be advantageous
        # to cache the redirect location onto the response object as a private
        # attribute.
        if resp.is_redirect:
            location = resp.headers['location']
            # Currently the underlying http module on py3 decode headers
            # in latin1, but empirical evidence suggests that latin1 is very
            # rarely used with non-ASCII characters in HTTP headers.
            # It is more likely to get UTF8 header rather than latin1.
            # This causes incorrect handling of UTF8 encoded location headers.
            # To solve this, we re-encode the location in latin1.
            if is_py3:
                location = location.encode('latin1')
            return to_native_string(location, 'utf8')
        return None