Create injection function and source for a file, category, declaration and result handler
177268
function createInjection(fileId, categoryPrefix, declaration, idx, declarationResultHandler) {
  const fnName = `${FN_PREFIX}_${fileId}_${categoryPrefix}_${declaration.declarationClean}_${idx}`;

  const injectedFunction = function(sassValue) {
    const value = createStructuredValue(sassValue);
    declarationResultHandler(declaration, value, sassValue);
    return sassValue;
  };

  let injectedCode = `@if global_variable_exists('${declaration.declarationClean}') { 
    $${fnName}: ${fnName}(${declaration.declaration}); 
  }\n`

  return { fnName, injectedFunction, injectedCode };
}
880794
function createInternalInjector(cache, factory) {

    function getService(serviceName, caller) {
      if (cache.hasOwnProperty(serviceName)) {
        if (cache[serviceName] === INSTANTIATING) {
          throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
                    serviceName + ' <- ' + path.join(' <- '));
        }
        return cache[serviceName];
      } else {
        try {
          path.unshift(serviceName);
          cache[serviceName] = INSTANTIATING;
          return cache[serviceName] = factory(serviceName, caller);
        } catch (err) {
          if (cache[serviceName] === INSTANTIATING) {
            delete cache[serviceName];
          }
          throw err;
        } finally {
          path.shift();
        }
      }
    }

    function invoke(fn, self, locals, serviceName) {
      if (typeof locals === 'string') {
        serviceName = locals;
        locals = null;
      }

      var args = [],
          $inject = createInjector.$$annotate(fn, strictDi, serviceName),
          length, i,
          key;

      for (i = 0, length = $inject.length; i < length; i++) {
        key = $inject[i];
        if (typeof key !== 'string') {
          throw $injectorMinErr('itkn',
                  'Incorrect injection token! Expected service name as string, got {0}', key);
        }
        args.push(
          locals && locals.hasOwnProperty(key)
          ? locals[key]
          : getService(key, serviceName)
        );
      }
      if (isArray(fn)) {
        fn = fn[length];
      }

      // http://jsperf.com/angularjs-invoke-apply-vs-switch
      // #5388
      return fn.apply(self, args);
    }

    function instantiate(Type, locals, serviceName) {
      // Check if Type is annotated and use just the given function at n-1 as parameter
      // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
      // Object creation: http://jsperf.com/create-constructor/2
      var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
      var returnedValue = invoke(Type, instance, locals, serviceName);

      return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
    }

    return {
      invoke: invoke,
      instantiate: instantiate,
      get: getService,
      annotate: createInjector.$$annotate,
      has: function(name) {
        return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
      }
    };
  }
179209
function inject(config) {
    const context = global;
    // setup variables
    // safeAdd( context, 'steps', {} )
    safeAddAll(context, [Functions]);
    context.Workflo = {
        Object: {},
        Array: {},
        String: {},
        Class: {},
        Util: {},
    };
    safeAddAll(context.Workflo.Object, [objectFunctions]);
    safeAddAll(context.Workflo.Array, [arrayFunctions]);
    safeAddAll(context.Workflo.Class, [classFunctions]);
    safeAddAll(context.Workflo.Util, [utilFunctions]);
    context.expectElement = matchers_1.expectElement;
    context.expectList = matchers_1.expectList;
    context.expectMap = matchers_1.expectMap;
    context.expectGroup = matchers_1.expectGroup;
    context.expectPage = matchers_1.expectPage;
    // add enum definitions
    context.Workflo.WaitType = enums_1.WaitType;
    context.Workflo.Comparator = enums_1.Comparator;
}
586840
def _generate_handler_wrapper(api_name, api_spec, endpoint, handler_func, error_callback, global_decorator):
    """"""

    # Decorate the handler function, if Swagger spec tells us to
    if endpoint.decorate_server:
        endpoint_decorator = get_function(endpoint.decorate_server)
        handler_func = endpoint_decorator(handler_func)

    @wraps(handler_func)
    def handler_wrapper(**path_params):
        log.info(" ")
        log.info(" ")
        log.info("=> INCOMING REQUEST %s %s -> %s" %
                 (endpoint.method, endpoint.path, handler_func.__name__))
        log.info(" ")
        log.info(" ")

        # Get caller's pym-call-id or generate one
        call_id = request.headers.get('PymCallID', None)
        if not call_id:
            call_id = str(uuid.uuid4())
        stack.top.call_id = call_id

        # Append current server to call path, or start one
        call_path = request.headers.get('PymCallPath', None)
        if call_path:
            call_path = "%s.%s" % (call_path, api_name)
        else:
            call_path = api_name
        stack.top.call_path = call_path

        if endpoint.param_in_body or endpoint.param_in_query:
            # Turn the flask request into something bravado-core can process...
            try:
                req = FlaskRequestProxy(request, endpoint.param_in_body)
            except BadRequest:
                ee = error_callback(ValidationError("Cannot parse json data: have you set 'Content-Type' to 'application/json'?"))
                return _responsify(api_spec, ee, 400)

            try:
                # Note: unmarshall validates parameters but does not fail
                # if extra unknown parameters are submitted
                parameters = unmarshal_request(req, endpoint.operation)
                # Example of parameters: {'body': RegisterCredentials()}
            except jsonschema.exceptions.ValidationError as e:
                ee = error_callback(ValidationError(str(e)))
                return _responsify(api_spec, ee, 400)

        # Call the endpoint, with proper parameters depending on whether
        # parameters are in body, query or url
        args = []
        kwargs = {}

        if endpoint.param_in_path:
            kwargs = path_params

        if endpoint.param_in_body:
            # Remove the parameters already defined in path_params
            for k in list(path_params.keys()):
                del parameters[k]
            lst = list(parameters.values())
            assert len(lst) == 1
            args.append(lst[0])

        if endpoint.param_in_query:
            kwargs.update(parameters)

        result = handler_func(*args, **kwargs)

        if not result:
            e = error_callback(PyMacaronCoreException("Have nothing to send in response"))
            return _responsify(api_spec, e, 500)

        # Did we get the expected response?
        if endpoint.produces_html:
            if type(result) is not tuple:
                e = error_callback(PyMacaronCoreException("Method %s should return %s but returned %s" %
                                                          (endpoint.handler_server, endpoint.produces, type(result))))
                return _responsify(api_spec, e, 500)

            # Return an html page
            return result

        elif endpoint.produces_json:
            if not hasattr(result, '__module__') or not hasattr(result, '__class__'):
                e = error_callback(PyMacaronCoreException("Method %s did not return a class instance but a %s" %
                                                          (endpoint.handler_server, type(result))))
                return _responsify(api_spec, e, 500)

            # If it's already a flask Response, just pass it through.
            # Errors in particular may be either passed back as flask Responses, or
            # raised as exceptions to be caught and formatted by the error_callback
            result_type = result.__module__ + "." + result.__class__.__name__
            if result_type == 'flask.wrappers.Response':
                return result

            # We may have got a pymacaron Error instance, in which case
            # it has a http_reply() method...
            if hasattr(result, 'http_reply'):
                # Let's transform this Error into a flask Response
                log.info("Looks like a pymacaron error instance - calling .http_reply()")
                return result.http_reply()

            # Otherwise, assume no error occured and make a flask Response out of
            # the result.

            # TODO: check that result is an instance of a model expected as response from this endpoint
            result_json = api_spec.model_to_json(result)

            # Send a Flask Response with code 200 and result_json
            r = jsonify(result_json)
            r.status_code = 200
            return r

    handler_wrapper = cross_origin(headers=['Content-Type', 'Authorization'])(handler_wrapper)

    # And encapsulate all in a global decorator, if given one
    if global_decorator:
        handler_wrapper = global_decorator(handler_wrapper)

    return handler_wrapper
866999
function injectReporter() {
  page.evaluate(function (script) {
    function print(msg) {
      console.log(msg);
    }

    function onComplete(passed) {
      window.callPhantom(passed);
    }

    eval(script);

    var reporter = new ConsoleReporter();
    reporter.setOptions({
      print: print,
      printDeprecation: print,
      showColors: true,
      onComplete: onComplete
    });

    jasmine.getEnv().addReporter(reporter);
  }, reporterScript);
}
1181878
function injectDependencies(globalConfig) {
  config = globalConfig;
  var stream = config.get('stream');

  globalDependenciesSorted = config.get('global-dependencies-sorted');
  ignorePath = config.get('ignore-path');
  fileTypes = config.get('file-types');

  if (stream.src) {
    config.set('stream', {
      src: injectScriptsStream(stream.path, stream.src, stream.fileType),
      fileType: stream.fileType
    });
  } else {
    config.get('src').forEach(injectScripts);
  }

  return config;
}
699573
function injectRegistry(entry) {
  const extraFiles = [registryFile, actBuildInfoFile, actMetaData];
  // build also the registry
  if (typeof entry === 'string') {
    return extraFiles.concat(entry);
  }
  const transformed = {};
  Object.keys(entry).forEach((eentry) => {
    transformed[eentry] = extraFiles.concat(entry[eentry]);
  });
  return transformed;
}
972241
function injectScripts(filePath) {
  var contents = String($.fs.readFileSync(filePath));
  var fileExt = $.path.extname(filePath).substr(1);
  var fileType = fileTypes[fileExt] || fileTypes['default'];
  var returnType = /\r\n/.test(contents) ? '\r\n' : '\n';

  var newContents = contents.replace(
    fileType.block,
    replaceIncludes(filePath, fileType, returnType)
  );

  if (contents !== newContents) {
    $.fs.writeFileSync(filePath, newContents);

    config.get('on-file-updated')(filePath);
  }
}
1126340
function processFile(argv, inputPath, opt_outputPath) {
  // Setup output path.
  var outputPath = opt_outputPath;
  if (!opt_outputPath) {
    var ext = path.extname(inputPath);
    if (ext.length) {
      outputPath = inputPath.substr(0, inputPath.length - ext.length) +
          '.instrumented' + ext;
    } else {
      outputPath = inputPath + '.instrumented.js';
    }
  }

  var sourceCode = fs.readFileSync(inputPath).toString();

  // TODO(benvanik): support setting the module ID?
  var targetCode = transformCode(0, inputPath, sourceCode, argv);

  console.log('Writing ' + outputPath + '...');
  fs.writeFileSync(outputPath, targetCode);
  fs.chmodSync(outputPath, fs.statSync(inputPath).mode);
}
311308
def _generate_lambda_handler(config, output='.slam/handler.py'):
    """"""
    # Determine what the start up code is. The default is to just run the
    # function, but it can be overriden by a plugin such as wsgi for a more
    # elaborated way to run the function.
    run_function = _run_lambda_function
    for name, plugin in plugins.items():
        if name in config and hasattr(plugin, 'run_lambda_function'):
            run_function = plugin.run_lambda_function
    run_code = ''.join(inspect.getsourcelines(run_function)[0][1:])

    # generate handler.py
    with open(os.path.join(os.path.dirname(__file__),
                           'templates/handler.py.template')) as f:
        template = f.read()
    template = render_template(template, module=config['function']['module'],
                               app=config['function']['app'],
                               run_lambda_function=run_code,
                               config_json=json.dumps(config,
                                                      separators=(',', ':')))
    with open(output, 'wt') as f:
        f.write(template + '\n')
152493
function injectEnvs(node) {
    switch (node.type) {
        case 'Program':
            node.$env = new Map;
            node.$depth = 0;
            break;
        case 'FunctionExpression':
            node.$env = new Map;
            node.$depth = 1 + getEnclosingScope(node.$parent).$depth;
            if (node.id) {
                node.$env.put(node.id.name, node.id)
            }
            for (var i=0; i<node.params.length; i++) {
                node.$env.put(node.params[i].name, node.params[i])
            }
            node.$env.put('arguments', node)
            break;
        case 'FunctionDeclaration':
            var parent = getEnclosingFunction(node.$parent); // note: use getEnclosingFunction, because fun decls are lifted outside catch clauses
            node.$env = new Map;
            node.$depth = 1 + parent.$depth;
            parent.$env.put(node.id.name, node.id)
            for (var i=0; i<node.params.length; i++) {
                node.$env.put(node.params[i].name, node.params[i])
            }
            node.$env.put('arguments', node)
            break;
        case 'CatchClause':
            node.$env = new Map;
            node.$env.put(node.param.name, node.param)
            node.$depth = 1 + getEnclosingScope(node.$parent).$depth;
            break;
        case 'VariableDeclarator':
            var parent = getEnclosingFunction(node) // note: use getEnclosingFunction, because vars ignore catch clauses
            parent.$env.put(node.id.name, node.id)
            break;
    }
    children(node).forEach(injectEnvs)
}
816219
def execute_from_file(self, url, file_var):
        '''
        

        '''
        if isinstance(file_var, file):
            f = file_var
        elif isinstance(file_var, str):
            try:
                f = open(file_var)
            except IOError, e:
                raise e
        else:
            raise TypeError("This function only accepts a 'file' type  or file path")

        inputs = json.loads(f.read())
        resp = self.execute(url, inputs)
        return resp
1066429
def _inject_func(func, conn):
    
    name = func.__name__
    if not name in conn.namespace:
        if isbuiltin(func):
            inject_code = '%s = %s' % (name, name)
        elif isfunction(func):
            inject_code = getsource(func)
        conn.execute(inject_code)
    return conn.namespace[name]
1361750
def process_ioc(args):
    """"""
    client = IndicatorClient.from_config()
    client.set_debug(True)

    if args.get:
        response = client.get_indicators()
    elif args.single:
        response = client.add_indicators(indicators=[args.single],
                                         private=args.private, tags=args.tags)
    else:
        if not os.path.isfile(args.file):
            raise Exception("File path isn't valid!")

        indicators = list()
        with open(args.file, 'r') as handle:
            for line in handle:
                line = line.strip()
                if line == '':
                    continue
                indicators.append(line)

        response = client.add_indicators(indicators=indicators,
                                         private=args.private, tags=args.tags)

    return response
648364
def create_push_handlers():
    """"""
    # pylint: disable=fixme
    # HACK: hacky territory - Dynamically generate a handler for each of the
    # package formats, until we have slightly more clever 'guess type'
    # handling. :-)
    handlers = create_push_handlers.handlers = {}
    context = create_push_handlers.context = get_package_formats()

    for key, parameters in six.iteritems(context):
        kwargs = parameters.copy()

        # Remove standard arguments
        kwargs.pop("package_file")
        if "distribution" in parameters:
            has_distribution_param = True
            kwargs.pop("distribution")
        else:
            has_distribution_param = False

        has_additional_params = len(kwargs) > 0

        help_text = """
            Push/upload a new %(type)s package upstream.
            """ % {
            "type": key.capitalize()
        }

        if has_additional_params:
            help_text += """

            PACKAGE_FILE: The main file to create the package from.
            """
        else:
            help_text += """

            PACKAGE_FILE: Any number of files to create packages from. Each
            file will result in a separate package.
            """

        if has_distribution_param:
            target_metavar = "OWNER/REPO/DISTRO/RELEASE"
            target_callback = validators.validate_owner_repo_distro
            help_text += """

            OWNER/REPO/DISTRO/RELEASE: Specify the OWNER namespace (i.e.
            user or org), the REPO name where the package file will be uploaded
            to, and the DISTRO and RELEASE the package is for. All separated by
            a slash.

            Example: 'your-org/awesome-repo/ubuntu/xenial'.
            """
        else:
            target_metavar = "OWNER/REPO"
            target_callback = validators.validate_owner_repo
            help_text += """

            OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the
            REPO name where the package file will be uploaded to. All separated
            by a slash.

            Example: 'your-org/awesome-repo'.
            """

        @push.command(name=key, help=help_text)
        @decorators.common_api_auth_options
        @decorators.common_cli_config_options
        @decorators.common_cli_output_options
        @decorators.common_package_action_options
        @decorators.initialise_api
        @click.argument("owner_repo", metavar=target_metavar, callback=target_callback)
        @click.argument(
            "package_file",
            nargs=1 if has_additional_params else -1,
            type=ExpandPath(
                dir_okay=False, exists=True, writable=False, resolve_path=True
            ),
        )
        @click.option(
            "-n",
            "--dry-run",
            default=False,
            is_flag=True,
            help="Execute in dry run mode (don't upload anything.)",
        )
        @click.option(
            "-n",
            "--dry-run",
            default=False,
            is_flag=True,
            help="Execute in dry run mode (don't upload anything.)",
        )
        @click.pass_context
        def push_handler(ctx, *args, **kwargs):
            """Handle upload for a specific package format."""
            parameters = context.get(ctx.info_name)
            kwargs["package_type"] = ctx.info_name

            owner_repo = kwargs.pop("owner_repo")
            if "distribution" in parameters:
                kwargs["distribution"] = "/".join(owner_repo[2:])
                owner_repo = owner_repo[0:2]
            kwargs["owner_repo"] = owner_repo

            package_files = kwargs.pop("package_file")
            if not isinstance(package_files, tuple):
                package_files = (package_files,)

            for package_file in package_files:
                kwargs["package_file"] = package_file

                try:
                    click.echo()
                    upload_files_and_create_package(ctx, *args, **kwargs)
                except ApiException:
                    click.secho("Skipping error and moving on.", fg="yellow")

                click.echo()

        # Add any additional arguments
        for k, info in six.iteritems(kwargs):
            option_kwargs = {}
            option_name_fmt = "--%(key)s"

            if k.endswith("_file"):
                # Treat parameters that end with _file as uploadable filepaths.
                option_kwargs["type"] = ExpandPath(
                    dir_okay=False, exists=True, writable=False, resolve_path=True
                )
            elif info["type"] == "bool":
                option_name_fmt = "--%(key)s/--no-%(key)s"
                option_kwargs["is_flag"] = True
            else:
                option_kwargs["type"] = str

            option_name = option_name_fmt % {"key": k.replace("_", "-")}
            decorator = click.option(
                option_name,
                required=info["required"],
                help=info["help"],
                **option_kwargs
            )
            push_handler = decorator(push_handler)

        handlers[key] = push_handler
581823
def inject_mode(arg_namespace):
    """"""

    try:
        injector.inject_into_files(arg_namespace.scheme, arg_namespace.file)
    except (IndexError, FileNotFoundError,
            PermissionError, IsADirectoryError) as exception:
        if isinstance(exception, IndexError):
            print('"{}" has no valid injection marker lines.'.format(
                exception.args[0]))
        if isinstance(exception, FileNotFoundError):
            print('Lacking resource "{}" to complete operation.'.format(
                exception.filename))
        if isinstance(exception, PermissionError):
            print('No write permission for current working directory.')
        if isinstance(exception, IsADirectoryError):
            print('"{}" is a directory. Provide a *.yaml scheme file instead.'
                  .format(exception.filename))
979488
def insert(self, filename):
        
        errors = []
        if os.path.isfile(filename):
            log.info('loading IOC from: {}'.format(filename))
            try:
                self.parse(ioc_api.IOC(filename))
            except ioc_api.IOCParseError:
                log.exception('Parse Error')
                errors.append(filename)
        elif os.path.isdir(filename):
            log.info('loading IOCs from: {}'.format(filename))
            for fn in glob.glob(filename + os.path.sep + '*.ioc'):
                if not os.path.isfile(fn):
                    continue
                else:
                    try:
                        self.parse(ioc_api.IOC(fn))
                    except ioc_api.IOCParseError:
                        log.exception('Parse Error')
                        errors.append(fn)
        else:
            pass
        log.info('Parsed [{}] IOCs'.format(len(self)))
        return errors