Configure :class:`mitogen.master.ModuleResponder` to only permit
        certain packages, and to generate custom responses for certain modules.
431480
def _setup_responder(self, responder):
        
        responder.whitelist_prefix('ansible')
        responder.whitelist_prefix('ansible_mitogen')
        self._setup_simplejson(responder)

        # Ansible 2.3 is compatible with Python 2.4 targets, however
        # ansible/__init__.py is not. Instead, executor/module_common.py writes
        # out a 2.4-compatible namespace package for unknown reasons. So we
        # copy it here.
        responder.add_source_override(
            fullname='ansible',
            path=ansible.__file__,
            source=(ANSIBLE_PKG_OVERRIDE % (
                ansible.__version__,
                ansible.__author__,
            )).encode(),
            is_pkg=True,
        )
466319
function makeRespondMiddleware(opts) {
  opts = Object.assign({}, opts)

  // Make the respond function.
  const respond = makeRespond(opts)

  /**
   * Installs the functions in the context.
   *
   * @param  {KoaContext} ctx
   */
  function patch(ctx) {
    const statusMethods = Object.assign({}, opts.statusMethods, statusCodeMap)
    ctx.send = respond.bind(ctx, ctx)

    // Bind status methods.
    for (const method in statusMethods) {
      const code = statusMethods[method]
      ctx[method] = respond.bind(ctx, ctx, code)
    }

    // Bind other methods
    const methods = Object.assign({}, opts.methods)
    for (const method in methods) {
      const fn = methods[method]
      ctx[method] = fn.bind(ctx, ctx)
    }

    return ctx
  }

  /**
   * The respond middleware adds the methods to the context.
   *
   * @param  {KoaContext} ctx
   */
  function respondMiddleware(ctx, next) {
    patch(ctx)
    return next()
  }

  // Tack on the patch method to allow Koa 1 users
  // to install it, too.
  respondMiddleware.patch = patch
  return respondMiddleware
}
929974
private function proceedResponsePackage() {
		if($this->isActiveClient()) {
			$response = new Response();
			$response->isSslOnlyMode = $this->isSslOnlyMode;

			if(isset($_POST[self::POST_VAR_NAME]['getBackData'])) {
				$response->getBackData = $_POST[self::POST_VAR_NAME]['getBackData'];
			}

			if(!$this->isSslOnlyMode || $this->isSsl()) {
				if($this->auth) {
					$response->auth = $this->auth->getServerAuthStatus($this->client->auth);
				}
				if(!$this->auth || $this->isAuthorized()) {
					$response->isLocal = isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] == '127.0.0.1';
					$response->docRoot = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : null;
					$response->sourcesBasePath = $this->sourcesBasePath;
					$response->isEvalEnabled = $this->isEvalListenerStarted;
					$response->messages = $this->messages;
				}
			}

			$responseData = $this->serializeResponse($response);

			if(strlen($responseData) > $this->headersLimit || !$this->setHeaderData($responseData, self::HEADER_NAME, false)) {
				$this->getPostponeStorage()->push($this->postponeResponseId, $responseData);
			}
		}
	}
433209
def utils(opts, whitelist=None, context=None, proxy=proxy):
    '''
    
    '''
    return LazyLoader(
        _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'),
        opts,
        tag='utils',
        whitelist=whitelist,
        pack={'__context__': context, '__proxy__': proxy or {}},
    )
869128
def create_module(project, name, sourcefolder=None):
    """"""
    if sourcefolder is None:
        sourcefolder = project.root
    packages = name.split('.')
    parent = sourcefolder
    for package in packages[:-1]:
        parent = parent.get_child(package)
    return parent.create_file(packages[-1] + '.py')
1320594
def make_app(include_packages: Sequence[str] = ()) -> Flask:
    
    # Load modules
    for package_name in include_packages:
        import_submodules(package_name)

    app = Flask(__name__)  # pylint: disable=invalid-name

    @app.errorhandler(ServerError)
    def handle_invalid_usage(error: ServerError) -> Response:  # pylint: disable=unused-variable
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response

    @app.route('/')
    def index() -> Response:  # pylint: disable=unused-variable
        return send_file('config_explorer.html')

    @app.route('/api/config/')
    def api_config() -> Response:  # pylint: disable=unused-variable
        """
        There are basically two things that can happen here.
        If this method is called with a ``Registrable`` class (e.g. ``Model``),
        it should return the list of possible ``Model`` subclasses.
        If it is called with an instantiable subclass (e.g. ``CrfTagger``),
        is should return the config for that subclass.

        This is complicated by the fact that some Registrable base classes
        (e.g. Vocabulary, Trainer) are _themselves_ instantiable.

        We handle this in two ways: first, we insist that the first case
        include an extra ``get_choices`` parameter. That is, if you call
        this method for ``Trainer`` with get_choices=true, you get the list
        of Trainer subclasses. If you call it without that extra flag, you
        get the config for the class itself.

        There are basically two UX situations in which this API is called.
        The first is when you have a dropdown list of choices (e.g. Model types)
        and you select one. Such an API request is made *without* the get_choices flag,
        which means that the config is returned *even if the class in question
        is a Registrable class that has subclass choices*.

        The second is when you click a "Configure" button, which configures
        a class that may (e.g. ``Model``) or may not (e.g. ``FeedForward``)
        have registrable subclasses. In this case the API request is made
        with the "get_choices" flag, but will return the corresponding config
        object if no choices are available (e.g. in the ``FeedForward``) case.

        This is not elegant, but it works.
        """
        class_name = request.args.get('class', '')
        get_choices = request.args.get('get_choices', None)

        # Get the configuration for this class name
        config = configure(class_name)
        try:
            # May not have choices
            choice5 = choices(class_name)
        except ValueError:
            choice5 = []

        if get_choices and choice5:
            return jsonify({
                    "className": class_name,
                    "choices": choice5
            })
        else:
            return jsonify({
                    "className": class_name,
                    "config": config.to_json()
            })

    return app
1302261
def decorate(self, app):
		
		from functools import wraps

		@wraps(app)
		def decorated(environ, start_response):
			# capture any start_response from the app
			app_response = {}
			app_response['status'] = "200 OK"
			app_response['headers'] = []
			app_response['written'] = BytesIO()
			def custom_start_response(status, headers, *args, **kwargs):
				app_response['status'] = status
				app_response['headers'] = headers
				app_response['args'] = args
				app_response['kwargs'] = kwargs
				return app_response['written'].write
			returned = app(environ, custom_start_response)

			# callbacks from the serialization
			def set_http_code(status):
				app_response['status'] = str(status)
			def set_header(header, value):
				app_response['headers'] = [(h,v) for (h,v) in app_response['headers'] if h.lower() != header.lower()]
				app_response['headers'].append((header, value))
			def set_content_type(content_type):
				set_header('Content-Type', content_type)

			# do the serialization
			accept = environ.get('HTTP_ACCEPT', '')
			new_return = self.output(returned, accept, set_http_code, set_content_type)

			# set the Vary header
			vary_headers = (v for (h,v) in app_response['headers'] if h.lower() == 'vary')
			vary_elements = list(itertools.chain(*[v.split(',') for v in vary_headers]))
			vary_elements = list(set([v.strip() for v in vary_elements]))
			if '*' not in vary_elements and 'accept' not in (v.lower() for v in vary_elements):
				vary_elements.append('Accept')
				set_header('Vary', ', '.join(vary_elements))

			# pass on the result to the parent WSGI server
			parent_writer = start_response(app_response['status'],
			                               app_response['headers'],
			                               *app_response.get('args', []),
			                               **app_response.get('kwargs', {}))
			written = app_response['written'].getvalue()
			if len(written) > 0:
				parent_writer(written)
			return new_return
		return decorated
318169
def getAvailableClassesInPackage(package):
    
    l = list(x[1] for x in inspect.getmembers(package, inspect.isclass))

    modules = list(x[1] for x in inspect.getmembers(package, inspect.ismodule))
    for m in modules:
        l.extend(list(x[1] for x in inspect.getmembers(m, inspect.isclass)))
    l = [x for x in l if x.__name__[0] != "_"]
    n = 0
    while n < len(l):
        cls = l[n]
        if not cls.__module__.startswith(package.__name__):
            l.pop(n)
            n -= 1
        n += 1
    return l
794407
def prepare_mainsubstituter():
    """"""
    substituter = Substituter()
    for module in (builtins, numpy, datetime, unittest, doctest, inspect, io,
                   os, sys, time, collections, itertools, subprocess, scipy,
                   typing):
        substituter.add_module(module)
    for subpackage in (auxs, core, cythons, exe):
        for dummy, name, dummy in pkgutil.walk_packages(subpackage.__path__):
            full_name = subpackage.__name__ + '.' + name
            substituter.add_module(importlib.import_module(full_name))
    substituter.add_modules(models)
    for cymodule in (annutils, smoothutils, pointerutils):
        substituter.add_module(cymodule, cython=True)
    substituter._short2long['|pub|'] = ':mod:`~hydpy.pub`'
    substituter._short2long['|config|'] = ':mod:`~hydpy.config`'
    return substituter
57207
def handle_addSubmodule(repo, **kwargs):
    """"""
    log.info('addSubmodule: %s %s' %(repo, kwargs))
    try:
        proxy = repo.addSubmodule(**kwargs)
        return [serialize(proxy, type='submodule', url=proxy.url)]
    except RepoError, e:
        raise
787703
function(moduleRegex) {
        var self = this;

        moduleRegex = moduleRegex || /^(.+)\.js$/;

        return function(req, res, next) {
            var match = req.url.match(moduleRegex);
            if(!match) return next();

            var module= match[1];

            self.bundle(module, function(err, src) {
                res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
                res.setHeader('Cache-Control', 'no-cache');

                // expose event to allow for custom headers
                self.emit('pre-response', err, res, module, src);

                res.send(src);
            });
        };
    }
862584
def requested_packages(self, include_implicit=False):
        
        if include_implicit:
            return self._package_requests + self.implicit_packages
        else:
            return self._package_requests
980876
def make_response(status, headers, payload, environ):
    
    headers_dict = {}
    content_type = None
    for h in headers:
        if h[0].lower() == 'content-type':
            content_type = h[1]
        else:
            headers_dict[h[0]] = h[1]
    return HTTPResponse(body_bytes=payload, content_type=content_type,
                        status=int(status.split()[0]), headers=headers_dict)
658658
def configure_importer
      # The default package conforms to the JRuby convention for mapping a package name
      # to a module name.
      @packages ||= [name.split('::').map { |n| n.downcase }.join('.')]
      @packages.each do |pkg|
        begin
          eval "java_package Java::#{pkg}"
        rescue Exception => e
          raise ArgumentError.new("#{self} Java package #{pkg} not found - #{$!}")
        end
      end
      # The introspected classes.
      @introspected = Set.new
      # The name => file hash for file definitions that are not in the packages.
      @unresolved_defs = {}
    end
1255261
def _handle_response(response, **kwargs) -> XMLResponse:
        
        if not response.encoding:
            response.encoding = DEFAULT_ENCODING

        return response
908102
def AsHandler(request=None, modules=None, **kw):
    ''''''
    ps = ParsedSoap(request)
    kw['request'] = request
    _Dispatch(ps, modules, _ModPythonSendXML, _ModPythonSendFault, **kw)
698506
def generate_module_content(self, module):
        
        if isinstance(module, Module):
            return module.render()
        else:  # pragma: no cover
            raise Exception("%r is not a Module object" % module)