inject code into sitecustomize.py that will inject pout into the builtins
        so it will be available globally
480296
def inject(self):
        """"""
        if self.is_injected():
            return False

        with open(self, mode="a+") as fp:
            fp.seek(0)
            fp.write("\n".join([
                "",
                "try:",
                "    import pout",
                "except ImportError:",
                "    pass",
                "else:",
                "    pout.inject()",
                "",
            ]))

        return True
544807
function() {

    var hookPath = path.resolve(this.options.dest, this.hookName);

    var existingCode = this.getHookContent(hookPath);

    if (existingCode) {
      this.validateScriptLanguage(existingCode);
    }

    var hookContent;
    if(this.hasMarkers(existingCode)) {
      hookContent = this.insertBindingCode(existingCode);
    } else {
      hookContent = this.appendBindingCode(existingCode);
    }

    fs.writeFileSync(hookPath, hookContent);

    fs.chmodSync(hookPath, '755');
  }
1307935
def _inject_execstr(modname, import_tuples):
    
    if modname == 'utool':
        # Special case import of the util_inject module
        injecter = 'util_inject'
        injecter_import = ''
    else:
        # Normal case implicit import of util_inject
        injecter_import = 'import utool'
        injecter = 'utool'
    injectstr_fmt = textwrap.dedent(
        r'''
        # STARTBLOCK
        {injecter_import}
        print, rrr, profile = {injecter}.inject2(__name__, '[{modname}]')


        def reassign_submodule_attributes(verbose=1):
            """
            Updates attributes in the __init__ modules with updated attributes
            in the submodules.
            """
            import sys
            if verbose and '--quiet' not in sys.argv:
                print('dev reimport')
            # Self import
            import {modname}
            # Implicit reassignment.
            seen_ = set([])
            for tup in IMPORT_TUPLES:
                if len(tup) > 2 and tup[2]:
                    continue  # dont import package names
                submodname, fromimports = tup[0:2]
                submod = getattr({modname}, submodname)
                for attr in dir(submod):
                    if attr.startswith('_'):
                        continue
                    if attr in seen_:
                        # This just holds off bad behavior
                        # but it does mimic normal util_import behavior
                        # which is good
                        continue
                    seen_.add(attr)
                    setattr({modname}, attr, getattr(submod, attr))


        def reload_subs(verbose=1):
            """ Reloads {modname} and submodules """
            if verbose:
                print('Reloading {modname} submodules')
            rrr(verbose > 1)
            def wrap_fbrrr(mod):
                def fbrrr(*args, **kwargs):
                    """ fallback reload """
                    if verbose > 0:
                        print('Auto-reload (using rrr) not setup for mod=%r' % (mod,))
                return fbrrr
            def get_rrr(mod):
                if hasattr(mod, 'rrr'):
                    return mod.rrr
                else:
                    return wrap_fbrrr(mod)
            def get_reload_subs(mod):
                return getattr(mod, 'reload_subs', wrap_fbrrr(mod))
            {reload_body}
            rrr(verbose > 1)
            try:
                # hackish way of propogating up the new reloaded submodule attributes
                reassign_submodule_attributes(verbose=verbose)
            except Exception as ex:
                print(ex)
        rrrr = reload_subs
        # ENDBLOCK
        ''')
    injectstr_fmt = injectstr_fmt.replace('# STARTBLOCK', '')
    injectstr_fmt = injectstr_fmt.replace('# ENDBLOCK', '')
    rrrdir_fmt  = '    get_reload_subs({modname})(verbose=verbose)'
    rrrfile_fmt = '    get_rrr({modname})(verbose > 1)'

    def _reload_command(tup):
        if len(tup) > 2 and tup[2] is True:
            return rrrdir_fmt.format(modname=tup[0])
        else:
            return rrrfile_fmt.format(modname=tup[0])
    reload_body = '\n'.join(map(_reload_command, import_tuples)).strip()
    format_dict = {
        'modname': modname,
        'reload_body': reload_body,
        'injecter': injecter,
        'injecter_import': injecter_import,
    }
    inject_execstr = injectstr_fmt.format(**format_dict).strip()
    return inject_execstr
1075313
def do_modload(self, arg):
        
        filename = self.split_tokens(arg, 1, 1)[0]
        process  = self.get_process_from_prefix()
        try:
            process.inject_dll(filename, bWait=False)
        except RuntimeError:
            print("Can't inject module: %r" % filename)
638168
def RegisterBuiltin(cls, arg):
        '''
        '''
        if arg in cls.types_dict:
            raise RuntimeError, '%s already registered' %arg
        class _Wrapper(arg):
            'Wrapper for builtin %s\n%s' %(arg, cls.__doc__)
        _Wrapper.__name__ = '_%sWrapper' %arg.__name__
        cls.types_dict[arg] = _Wrapper
675202
function (pluginName, moduleName, write) {

			var module,
				content,
				cutPos,
				modPath,
				relCssPath;
			if (_genericCssToRootPath && _buildMap.hasOwnProperty(moduleName)) {

				module = _buildMap[moduleName];
				if (module.write) {

					// #1: fix urls in css
					// get folder path to the current module
					cutPos = moduleName.lastIndexOf("/");
					modPath = cutPos >= 0 ? moduleName.slice(0, cutPos + 1) : "";
					// form a new base path for substituting in css
					relCssPath = _genericCssToRootPath + modPath;

					// replace all links like 'url(folder/file.png)' in the module's content (css)
					// to make them relative to the generic.css location
					content = _replaceCssRelativeUrls(module.data, relCssPath);

					// #2: add module's css into common generic.css
					module.write(moduleName, module.path, content);
				}
			}
		}
158283
def _run_module_code(code, init_globals=None,
                    mod_name=None, mod_fname=None,
                    mod_loader=None, pkg_name=None):
    """"""
    with _ModifiedArgv0(mod_fname):
        with _TempModule(mod_name) as temp_module:
            mod_globals = temp_module.module.__dict__
            _run_code(code, mod_globals, init_globals,
                      mod_name, mod_fname, mod_loader, pkg_name)
    # Copy the globals of the temporary module, as they
    # may be cleared when the temporary module goes away
    return mod_globals.copy()
60503
def inject_python_code(fpath, patch_code, tag=None,
                       inject_location='after_imports'):
    
    import utool as ut
    assert tag is not None, 'TAG MUST BE SPECIFIED IN INJECTED CODETEXT'
    text = ut.read_from(fpath)
    comment_start_tag = '# <util_inject:%s>' % tag
    comment_end_tag  = '# </util_inject:%s>' % tag

    tagstart_txtpos = text.find(comment_start_tag)
    tagend_txtpos = text.find(comment_end_tag)

    text_lines = ut.split_python_text_into_lines(text)

    # split the file into two parts and inject code between them
    if tagstart_txtpos != -1 or tagend_txtpos != -1:
        assert tagstart_txtpos != -1, 'both tags must not be found'
        assert tagend_txtpos != -1, 'both tags must not be found'

        for pos, line in enumerate(text_lines):
            if line.startswith(comment_start_tag):
                tagstart_pos = pos
            if line.startswith(comment_end_tag):
                tagend_pos = pos
        part1 = text_lines[0:tagstart_pos]
        part2 = text_lines[tagend_pos + 1:]
    else:
        if inject_location == 'after_imports':
            first_nonimport_pos = 0
            for line in text_lines:
                list_ = ['import ', 'from ', '#', ' ']
                isvalid = (len(line) == 0 or
                           any(line.startswith(str_) for str_ in list_))
                if not isvalid:
                    break
                first_nonimport_pos += 1
            part1 = text_lines[0:first_nonimport_pos]
            part2 = text_lines[first_nonimport_pos:]
        else:
            raise AssertionError('Unknown inject location')

    newtext = (
        '\n'.join(part1 + [comment_start_tag]) +
        '\n' + patch_code + '\n' +
        '\n'.join( [comment_end_tag] + part2)
    )
    text_backup_fname = fpath + '.' + ut.get_timestamp() + '.bak'
    ut.write_to(text_backup_fname, text)
    ut.write_to(fpath, newtext)
759891
def make_site_obj(argdict):
    ''''''
    #d = '.'
    d = None
    if 'dirname' in argdict:
        d = argdict['dirname']
    try:
        s = s2site.Site(d)
    except Exception : # pragma: no cover
        print "Could not instantiate site object."
        sys.exit()
    return s
756944
def generate_code(meta, prefix=None, node=False, min=False):
    
    if isinstance(meta, dict):
        url_prefix, auth_header, resources = parse_meta(meta)
    else:
        url_prefix, auth_header, resources = meta
    if prefix is not None:
        url_prefix = prefix
    core = render_core(url_prefix, auth_header, resources)
    if min:
        filename = 'res.web.min.js'
    else:
        filename = 'res.web.js'
    if node:
        filename = 'res.node.js'
    base = read_file(filename)
    return base.replace('"#res.core.js#"', core)
835727
def _inject_function_into_js(context, name, func):
    
    context.export_function(name, func)
    context.evaljs(""";
        {name} = function() {{
            var args = Array.prototype.slice.call(arguments);
            args.unshift('{name}');
            return call_python.apply(null, args);
        }};
    """.format(name=name))
351150
function plugin(params) {
	logger = params.logger;
	params.dirname = params.dirname ? _.template(params.dirname)(params) : params.event.dir.resourcesPlatform;
	logger.trace("fixing underscore in directory: " + params.dirname);

	replace_content(path.join(params.dirname, "alloy.js"))
	replace_content(path.join(params.dirname, "alloy", "sync", "properties.js"))
	replace_content(path.join(params.dirname, "alloy", "sync", "sql.js"))
}
271289
function plugin(config) {

    checkProperty(config, 'url');

    return function(files, metalsmith, done){
        // initialize the API
        Prismic.Api(config['url'], retrieveContent, config['accessToken']);

        function retrieveContent(err, api) {
            if (err) {
                console.error("Could not initialize API: " + err);
            }
            else {

                // obtain the reference
                var release = config['release'];
                var ref;
                var ctx = {};
                for (var currentRef in api.data.refs) {
                    if ((!release || release.toLowerCase() == "master") && (api.data.refs[currentRef].isMaster)) {
                        ref = api.data.refs[currentRef].ref;
                    }
                    else if (release == api.data.refs[currentRef].label) {
                        ref = api.data.refs[currentRef].ref;
                    }
                }

                // user release as reference if no reference found
                if (!ref) {
                  ref = release || 'master';
                }

                // setup the context object
                ctx.api = api;
                ctx.linkResolver = getLinkResolver(ctx);
                ctx.htmlSerializer = config['htmlSerializer'] || function() {};
                ctx.ref = ref;
                ctx.OAuth = config['accessToken'];

                each(Object.keys(files), function (fileName, callback) {
                    retrieveContentForFile(fileName, callback, ctx)
                }, function(err) {debug("metalsmith-prismic done!"); done(err)})
            }
        }

        function getLinkResolver(ctx) {
            return function(doc, isBroken) {
                if (config['linkResolver'] != undefined) {
                    return config['linkResolver'](ctx, doc);
                } else {
                    if (isBroken) return false;
                    return '/' + doc.type + '/' + doc.id + '/' + doc.slug + (ctx.maybeRef ? '?ref=' + ctx.maybeRef : '');
                }
            }
        }

        // retrieves and processes the content for the given filename
        function retrieveContentForFile(fileName, callback, ctx) {
            var file = files[fileName];
            if (file.prismic) {
                debug("Pulling in content for file: %s", fileName);
                var queryKeys = {};
                var collectionQuery;

                // create associative array of query keys and their query & formName
                for (var queryKey in file.prismic) {
                    debug("processing %s", queryKey);
                    file.prismic[queryKey].results = [];
                    var queryString = file.prismic[queryKey].query;
                    var bookmark = file.prismic[queryKey].bookmark;
                    var orderings = file.prismic[queryKey].orderings;
                    var fetchLinks = file.prismic[queryKey].fetchLinks;
                    var pageSize = file.prismic[queryKey].pageSize;
                    var allPages = file.prismic[queryKey].allPages;
                    var formName = file.prismic[queryKey].formName;
                    if (formName == null) {
                        formName = "everything"
                    }
                    var collectionMetaData = file.prismic[queryKey].collection;
                    if (collectionMetaData != null) {
                        if (collectionQuery != null) {
                            throw new TypeError('Only one query can be designated the collection query. Please update the configuration settings appropriately.');
                        } else if (typeof collectionMetaData != "boolean" && file.prismic[queryKey].collection.fileExtension == null) {
                            throw new TypeError('The file extension to use when generating the files for the collection must be specified.');
                        } else if (collectionMetaData === true || typeof collectionMetaData != "boolean") {
                            collectionQuery = queryKey;
                        }
                    }
                    queryKeys[queryKey] = {"queryString": queryString,
                                           "bookmark": bookmark,
                                           "pageSize": pageSize,
                                           "allPages": allPages,
                                           "orderings": orderings,
                                           "fetchLinks": fetchLinks,
                                           "formName": formName};
                }

                // asynchronously retrieve and process each query
                each(Object.keys(queryKeys), function (currentQueryKey, queriedAndProcessedCallback) {
                    debug("%s: api.form(\"%s\").query('%s').ref(ctx.ref).submit()", queryKey, formName, queryString);
                    var totalPages;
                    var page = 1;

                    if (queryKeys[currentQueryKey].queryString) {
                        // fetch by query
                        queryNextPage();
                    } else if (queryKeys[currentQueryKey].bookmark) {
                        // fetch by bookmark
                        var bookmarkID = ctx.api.bookmarks[queryKeys[currentQueryKey].bookmark];
                        if (bookmarkID) {
                            ctx.api.getByID(bookmarkID, {}, prismicBookmarkCallback);
                        } else {
                            // Missing bookmark, leave data empty
                            queriedAndProcessedCallback();
                        }
                    } else {
                        throw new TypeError('Must specify either query or bookmark');
                    }

                    function queryNextPage() {
                        ctx.api.form(queryKeys[currentQueryKey].formName)
                            .query(queryKeys[currentQueryKey].queryString)
                            .pageSize(queryKeys[currentQueryKey].pageSize)
                            .page(page)
                            .orderings(queryKeys[currentQueryKey].orderings)
                            .fetchLinks(queryKeys[currentQueryKey].fetchLinks)
                            .ref(ctx.ref).submit(prismicQueryCallback);
                    }

                    function prismicQueryCallback(err, d) {
                        if (err) {
                            queriedAndProcessedCallback(err);
                        }
                        else {
                            processRetrievedContent(d, file.prismic, currentQueryKey, ctx);
                            totalPages = d.total_pages;
                            if (queryKeys[currentQueryKey].allPages &&
                                page < totalPages) {
                                page++;
                                queryNextPage();
                            } else {
                                queriedAndProcessedCallback();
                            }
                        }
                    }

                    function prismicBookmarkCallback(err, d) {
                        if (err) {
                            queriedAndProcessedCallback(err);
                        } else {
                            file.prismic[currentQueryKey] = processRetrievedDocument(d, file.prismic, currentQueryKey, ctx);
                            queriedAndProcessedCallback();
                        }
                    }

                }, function(err){
                    if(err != null) {
                        console.log(err);
                        callback(err);
                        return;
                    }
                    generateCollectionFiles(fileName, collectionQuery, callback, ctx);
                });
            } else {
                callback();
            }
        }

        // processes the retrieved content and adds it to the metadata
        function processRetrievedContent(content, filePrismicMetadata, queryKey, ctx) {
            if (content.results != null && content.results.length > 0) {
                var queryMetadata = filePrismicMetadata[queryKey];
                for (var i = 0; i < content.results.length; i++) {
                    var result = processRetrievedDocument(content.results[i], filePrismicMetadata, queryKey, ctx);
                    filePrismicMetadata[queryKey].results.push(result);
                }
            }
        }

        // processes and return single retrieved document
        function processRetrievedDocument(document, filePrismicMetadata, queryKey, ctx) {
            // add the complete result except for the data fragments
            var result = _.omit(document, 'fragments');
            result.data = {};

            // process the data fragments, invoking helpers to make the data more usable
            if (document.fragments != null && Object.keys(document.fragments).length  > 0) {
                for (var fragmentFullName in document.fragments) {

                    // strip the document type from the fragment name
                    var fragmentName = fragmentFullName.substr(fragmentFullName.lastIndexOf('.') + 1);

                    var fragment = document.fragments[fragmentFullName];
                    result.data[fragmentName] = processSingleFragment(fragment, ctx, filePrismicMetadata[queryKey]);
                }
            }

            return result;
        }

        // process a single fragment, and return the fragment object with json and html data
        function processSingleFragment(fragment, ctx, queryMetadata) {
          // return array fragments (link[0], link[1], ... named fragments) as arrays if arrayFragments are enabled
          if (Array.isArray(fragment)) {
            if (queryMetadata.arrayFragments) {
              return fragment.map(function(subFragment) {
                return processSingleFragment(subFragment, ctx, queryMetadata);
              });
            } else {
              // only return first element of array
              if (fragment.length) {
                return processSingleFragment(fragment[0], ctx, queryMetadata);
              } else {
                // only return one element of empty array, lets say that is null
                return null;
              }
            }
          }

          // initialize Prismic fragment javascript wrapper, unless already initialized
          if (!fragment.asHtml) {
            fragment = Prismic.Fragments.initField(fragment);
          }
          var fragmentObject = {
            json: fragment
          };

          if (!queryMetadata.output || queryMetadata.output.indexOf('html') > -1) {
            fragmentObject.html = fragment.asHtml(ctx.linkResolver, ctx.htmlSerializer);
          }

          if (queryMetadata.output && queryMetadata.output.indexOf('text') > -1) {
            //  https://github.com/prismicio/javascript-kit/issues/104
            if (!(fragment instanceof Prismic.Fragments.SliceZone) && !(fragment instanceof Prismic.Fragments.SliceZone)) {
              fragmentObject.text = fragment.asText(ctx.linkResolver);
            }
          }

          // Add child fragments
          if (fragment instanceof Prismic.Fragments.DocumentLink && fragment.document.data) {
            // from document links
            fragmentObject.children = _.mapObject(fragment.document.data[fragment.type], function(subFragment) {
              if (subFragment.type) {
                return processSingleFragment(subFragment, ctx, queryMetadata);
              } else {
                // some document link subfragments aren't proper fragments
                // for example StructuredText isn't supported
                // we can't really do anything else than return the raw data
                return {
                  json: subFragment
                };
              }
            });
          } else if (fragment instanceof Prismic.Fragments.Group) {
            // from groups
            fragmentObject.children = _.map(fragment.toArray(), function(group) {
              return _.mapObject(group.fragments, function(subFragment) {
                return processSingleFragment(subFragment, ctx, queryMetadata);
              });
            });
          } else if (fragment instanceof Prismic.Fragments.SliceZone) {
            // TODO
            fragmentObject.children = _.map(fragment.value, function(sliceFragment) {
              var subFragmentObject = processSingleFragment(sliceFragment.value, ctx, queryMetadata);
              subFragmentObject.sliceType = sliceFragment.sliceType;
              subFragmentObject.sliceLabel = sliceFragment.label;
              return subFragmentObject;
            });
          }

          // Add fragment url
          if (fragment instanceof Prismic.Fragments.DocumentLink) {
            fragmentObject.url = fragment.url(ctx.linkResolver);
          } else if (fragment instanceof Prismic.Fragments.WebLink) {
            fragmentObject.url = fragment.url();
          } else if (fragment instanceof Prismic.Fragments.FileLink) {
            fragmentObject.url = fragment.url();
          } else if (fragment instanceof Prismic.Fragments.ImageLink) {
            fragmentObject.url = fragment.url();
          } else if (fragment instanceof Prismic.Fragments.Image) {
            fragmentObject.url = fragment.url;
          }

          return fragmentObject;
        }

        // if any of the queries are designated the collection query, then generate a file for each of the results
        function generateCollectionFiles(fileName, collectionQuery, callback, ctx) {
            if (collectionQuery != null) {
                var file = files[fileName];
                var newFiles = {};
                var fileExtension = file.prismic[collectionQuery].collection.fileExtension;
                var fileSuffix = (fileExtension != undefined && fileExtension !== "")? "." + fileExtension:"";
                // for every result in the collection query
                for (var i = 0; i < file.prismic[collectionQuery].results.length; i++) {

                    // clone the file and replace the original collectionQuery results with the current result
                    var newFile = clone(file);
                    newFile.prismic[collectionQuery].results = [file.prismic[collectionQuery].results[i]];

                    // add the filename to the ctx object to make it available for use in the linkResolver function
                    ctx.path = fileName;

                    // use the linkResolver to generate the filename removing the leading slash if present
                    newFiles[(ctx.linkResolver(file.prismic[collectionQuery].results[i]) + fileSuffix).replace(/^\//g, '')] = newFile;
                }

                delete files[fileName];
                _.extend(files, newFiles);
            }

            callback();
        }

    }


    function checkProperty(object, property) {
        if ((object[property]) == null) {
            throw new TypeError('Missing property \'' + property + '\'. Please update the configuration settings appropriately.');
        }
    }
}
1368322
def inject(self, func, **kwargs):
        
        args, varargs, keywords, defaults = self._get_argspec(func)
        if defaults:
            required_args = args[:-len(defaults)]
            optional_args = args[len(required_args):]
        else:
            required_args = args
            optional_args = []
        values = [
            kwargs[arg] if arg in kwargs else self[arg]
            for arg in required_args
        ]
        if defaults:
            values.extend(
                kwargs[arg] if arg in kwargs else self.get(arg, default)
                for arg, default in zip(optional_args, defaults)
            )
        return func(*values)
1136483
function injectTemplate(template) {
  let js = [
    '',
    'var __vue__options__ = (module.exports.__esModule) ?',
    'module.exports.default : module.exports;',
    '__vue__options__.template = ' + JSON.stringify(template) + ';',
    '',
  ];

  return js.join(os.EOL);
}
13543
def import_spydercustomize():
    """"""
    here = osp.dirname(__file__)
    parent = osp.dirname(here)
    customize_dir = osp.join(parent, 'customize')

    # Remove current directory from sys.path to prevent kernel
    # crashes when people name Python files or modules with
    # the same name as standard library modules.
    # See spyder-ide/spyder#8007
    while '' in sys.path:
        sys.path.remove('')

    # Import our customizations
    site.addsitedir(customize_dir)
    import spydercustomize

    # Remove our customize path from sys.path
    try:
        sys.path.remove(customize_dir)
    except ValueError:
        pass
1086731
def _patch_awx_callback():
    
    # AWX uses sitecustomize.py to force-load this package. If it exists, we're
    # running under AWX.
    try:
        from awx_display_callback.events import EventContext
        from awx_display_callback.events import event_context
    except ImportError:
        return

    if hasattr(EventContext(), '_local'):
        # Patched version.
        return

    def patch_add_local(self, **kwargs):
        tls = vars(self._local)
        ctx = tls.setdefault('_ctx', {})
        ctx.update(kwargs)

    EventContext._local = threading.local()
    EventContext.add_local = patch_add_local