Wrap Elsevier methods which directly use the API keys.

    Ensure that the keys are retrieved from the environment or config file when
    first called, and store global scope. Subsequently use globally stashed
    results and check for required ids.
337629
def _ensure_api_keys(task_desc, failure_ret=None):
    
    def check_func_wrapper(func):
        @wraps(func)
        def check_api_keys(*args, **kwargs):
            global ELSEVIER_KEYS
            if ELSEVIER_KEYS is None:
                ELSEVIER_KEYS = {}
                # Try to read in Elsevier API keys. For each key, first check
                # the environment variables, then check the INDRA config file.
                if not has_config(INST_KEY_ENV_NAME):
                    logger.warning('Institution API key %s not found in config '
                                   'file or environment variable: this will '
                                   'limit access for %s'
                                   % (INST_KEY_ENV_NAME, task_desc))
                ELSEVIER_KEYS['X-ELS-Insttoken'] = get_config(INST_KEY_ENV_NAME)

                if not has_config(API_KEY_ENV_NAME):
                    logger.error('API key %s not found in configuration file '
                                 'or environment variable: cannot %s'
                                 % (API_KEY_ENV_NAME, task_desc))
                    return failure_ret
                ELSEVIER_KEYS['X-ELS-APIKey'] = get_config(API_KEY_ENV_NAME)
            elif 'X-ELS-APIKey' not in ELSEVIER_KEYS.keys():
                logger.error('No Elsevier API key %s found: cannot %s'
                             % (API_KEY_ENV_NAME, task_desc))
                return failure_ret
            return func(*args, **kwargs)
        return check_api_keys
    return check_func_wrapper
1222903
def cached(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        global cache
        key = json.dumps((func, args, kwargs), sort_keys=True, default=str)
        try:
            return cache[key]
        except KeyError:
            pass  # Drop out of the exception handler scope.
        res = func(*args, **kwargs)
        cache[key] = res
        return res
    wrapper._wrapped = func
    return wrapper
674919
function wrapQueryMethod(method) {
  Druid.prototype[method] = function(query, callback) {
    if (!this.ready) {
      var self = this
        , onready
        , onerror

      onready = function() {
        self.removeListener('error', onerror)
        self[method](query, callback)
      }

      onerror = function(err) {
        self.removeListener('ready', onready)
        callback(err)
      }

      this.once('ready', onready)
      this.once('error', onerror)

      return
    }

    var ds = query.dataSource()

    if (!this.dataSources.hasOwnProperty(ds)) {
      callback(new DruidError('No node serves data source: ' + ds))
    }
    else {
      var node = getLessLoaded(this, ds)

      node[method](query, callback)
    }
  }
}
657334
def set_api_key_from_file(path, set_global=True):
    """"""
    with open(path, 'r+b') as f:
        global api_key
        api_key = f.read().strip()
    return api_key
1202906
def global_add(self, key: str, value: Any) -> None:
        
        self.global_context[key] = value
51937
def inject_request_ids_into_environment(func):
    """"""

    @wraps(func)
    def wrapper(event, context):
        # This might not always be an API Gateway event, so only log the
        # request ID, if it looks like to be coming from there.
        if 'requestContext' in event:
            os.environ[ENV_APIG_REQUEST_ID] = event['requestContext'].get(
                'requestId', 'N/A')
        os.environ[ENV_LAMBDA_REQUEST_ID] = context.aws_request_id
        return func(event, context)

    return wrapper
351182
function wrapmethods(sess) {
  var _save = sess.save;

  function save() {
    debug('saving %s', this.id);
    savedHash = hash(this);
    _save.apply(this, arguments);
  }

  Object.defineProperty(sess, 'save', {
    configurable: true,
    enumerable: false,
    value: save,
    writable: true
  });
}
866122
def requires_public_key(func):
    

    def func_wrapper(self, *args, **kwargs):
        if hasattr(self, "public_key"):
            func(self, *args, **kwargs)
        else:
            self.generate_public_key()
            func(self, *args, **kwargs)

    return func_wrapper
118410
def save
            unless [ :handle, :new, :modify, :save ].all?{|method| api_methods[method] }
                raise "Not all necessary api methods are defined to process this action!"            
            end
            entry = self.class.find_one(name)
            self.class.in_transaction(true) do |token|
                if entry
                    entryid = self.class.make_call(api_methods[:handle],name,token) 
                else
                    entryid = self.class.make_call(api_methods[:new],token)
                    self.class.make_call(api_methods[:modify],entryid,'name', name, token)
                end
                
                cobbler_record_fields.each do |field|
                    field_s = field.to_s
                    if !locked_fields.include?(field) && user_definitions.has_key?(field_s)
                        self.class.make_call(api_methods[:modify],entryid,field_s, user_definitions[field_s], token)
                    end
                end
                
                cobbler_collections_store_callbacks.each do |callback|
                    send(callback,entryid,token)
                end
                
                self.class.make_call(api_methods[:save],entryid,token)
            end
        end
560620
def collect_plugins_in(provides_map, collected)
      provides_map.each_key do |plugin|
        if plugin.eql?("_plugins")
          collected.concat(provides_map[plugin])
        else
          collect_plugins_in(provides_map[plugin], collected)
        end
      end
      collected
    end
483767
def inject_global(node: Node, global_key: str, inject_key: Any):
    """"""
    value = get_current_scope().container.get(inject_key)
    set_global(node, global_key, value)
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
150895
def hide(*keys):
    
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            g.hide_request_fields = keys
            g.hide_response_fields = keys
            return func(*args, **kwargs)
        return wrapper
    return decorator
1360220
private void storeMethod(Method method, Map<Key, Array> methodsMap) {
	Key methodName = KeyImpl.init(method.getName());

	Array methodArgs;
	synchronized (methodsMap) {
	    methodArgs = methodsMap.get(methodName);
	    if (methodArgs == null) {
		methodArgs = new ArrayImpl();
		methodsMap.put(methodName, methodArgs);
	    }
	}

	storeArgs(method, methodArgs);
	// Modifier.isStatic(method.getModifiers());
    }
433218
def _apply_args_to_func(global_args, func):
    
    global_args = vars(global_args)
    local_args = dict()
    for argument in inspect.getargspec(func).args:
        local_args[argument] = global_args[argument]
    return func(**local_args)
372921
def prepare_env(app, env, docname):
    
    if not hasattr(env, 'needs_all_needs'):
        # Used to store all needed information about all needs in document
        env.needs_all_needs = {}

    if not hasattr(env, 'needs_functions'):
        # Used to store all registered functions for supporting dynamic need values.
        env.needs_functions = {}

        # needs_functions = getattr(app.config, 'needs_functions', [])
        needs_functions = app.needs_functions
        if needs_functions is None:
            needs_functions = []
        if not isinstance(needs_functions, list):
            raise SphinxError('Config parameter needs_functions must be a list!')

        # Register built-in functions
        for need_common_func in needs_common_functions:
            register_func(env, need_common_func)

        # Register functions configured by user
        for needs_func in needs_functions:
            register_func(env, needs_func)

    app.config.needs_hide_options += ['hidden']
    app.config.needs_extra_options['hidden'] = directives.unchanged

    if not hasattr(env, 'needs_workflow'):
        # Used to store workflow status information for already executed tasks.
        # Some tasks like backlink_creation need be be performed only once.
        # But most sphinx-events get called several times (for each single document file), which would also
        # execute our code several times...
        env.needs_workflow = {
            'backlink_creation': False,
            'dynamic_values_resolved': False
        }
706749
def mdel(keys)
      validate_key_array(keys)

      encapsulate_error do
        GitHub::SQL.run(<<-SQL, :keys => keys, :connection => connection)
          DELETE FROM key_values WHERE `key` IN :keys
        SQL
      end

      nil
    end