a convenience method for both adding a swagger.json route,
    as well as adding a page showing the html documentation
978483
def add_swagger(app, json_route, html_route):
    
    app.router.add_route('GET', json_route, create_swagger_json_handler(app))
    add_swagger_api_route(app, html_route, json_route)
472036
function renderPage(uri, req, res, hrStart) {
  const locals = res.locals,
    extension = getExtension(req),
    renderer = findRenderer(extension);

  // Add request route params, request query params
  // and the request extension to the locals object
  locals.params = req.params;
  locals.query = req.query;
  locals.extension = extension;

  // look up page alias' component instance
  return getDBObject(uri)
    .then(formDataFromLayout(locals, uri))
    .then(data => {
      logTime(hrStart, uri);
      return data;
    })
    .then(({ data, options }) => renderer.render(data, options, res))
    .catch(responses.handleError(res));
}
1149864
def add_route(self, template, controller, **kwargs):
        
        if isinstance(controller, basestring):
            controller = pymagic.import_name(controller)

        self.routes.append((self.parse_route(template), controller, kwargs))

        return self
1001847
function(){
    var authsModel;
    this.showMessage('Finished Loading Resource Information. Rendering Swagger UI...');
    this.mainView = new SwaggerUi.Views.MainView({
      model: this.api,
      el: $('#' + this.dom_id),
      swaggerOptions: this.options,
      router: this
    }).render();
    if (!_.isEmpty(this.api.securityDefinitions)){
      authsModel = _.map(this.api.securityDefinitions, function (auth, name) {
        var result = {};
        result[name] = auth;
        return result;
      });
      this.authView = new SwaggerUi.Views.AuthButtonView({
        data: SwaggerUi.utils.parseSecurityDefinitions(authsModel),
        router: this
      });
      $('#auth_container').append(this.authView.render().el);
    }
    this.showMessage();
    switch (this.options.docExpansion) {
      case 'full':
        this.expandAll(); break;
      case 'list':
        this.listAll(); break;
      default:
        break;
    }
    this.renderGFM();

    if (this.options.onComplete){
      this.options.onComplete(this.api, this);
    }

    setTimeout(Docs.shebang.bind(this), 100);
  }
1232625
def build_swagger_12_resource_listing(resource_listing):
    
    def view_for_resource_listing(request):
        # Thanks to the magic of closures, this means we gracefully return JSON
        # without file IO at request time.
        return resource_listing

    return PyramidEndpoint(
        path='',
        route_name='pyramid_swagger.swagger12.api_docs',
        view=view_for_resource_listing,
        renderer='json')
405650
def register_views(self, app):
        

        # Wrap the views in an arbitrary number of decorators.
        def wrap_view(view):
            if self.decorators:
                for decorator in self.decorators:
                    view = decorator(view)
            return view

        if self.config.get('swagger_ui', True):
            uiversion = self.config.get('uiversion', 3)
            blueprint = Blueprint(
                self.config.get('endpoint', 'flasgger'),
                __name__,
                url_prefix=self.config.get('url_prefix', None),
                subdomain=self.config.get('subdomain', None),
                template_folder=self.config.get(
                    'template_folder', 'ui{0}/templates'.format(uiversion)
                ),
                static_folder=self.config.get(
                    'static_folder', 'ui{0}/static'.format(uiversion)
                ),
                static_url_path=self.config.get('static_url_path', None)
            )

            blueprint.add_url_rule(
                self.config.get('specs_route', '/apidocs/'),
                'apidocs',
                view_func=wrap_view(APIDocsView().as_view(
                    'apidocs',
                    view_args=dict(config=self.config)
                ))
            )

            # backwards compatibility with old url style
            blueprint.add_url_rule(
                '/apidocs/index.html',
                view_func=lambda: redirect(url_for('flasgger.apidocs'))
            )
        else:
            blueprint = Blueprint(
                self.config.get('endpoint', 'flasgger'),
                __name__
            )

        for spec in self.config['specs']:
            self.endpoints.append(spec['endpoint'])
            blueprint.add_url_rule(
                spec['route'],
                spec['endpoint'],
                view_func=wrap_view(APISpecsView.as_view(
                    spec['endpoint'],
                    loader=partial(
                        self.get_apispecs, endpoint=spec['endpoint'])
                ))
            )

        app.register_blueprint(blueprint)
455481
def import_documentations
      require SwaggerDocsGenerator.file_base
      SwaggerDocsGenerator.file_docs.each { |rb| require rb }
    end
1186592
function () {

				this.router = this.getRouter();
				this.router.getRoute("entity").attachPatternMatched(this.onRouteMatched, this);

				this._oObjectPage = this.byId("ObjectPageLayout");

				this.getView().setModel(new JSONModel());
			}
1285678
def generate_swagger_html(swagger_static_root, swagger_json_url):
    
    tmpl = _get_template("swagger.html")
    return tmpl.render(
        swagger_root=swagger_static_root, swagger_json_url=swagger_json_url
    )
29942
function urlToRoutesFilePath (state, endpoint) {
  const [, scope] = endpoint.documentationUrl.match(/\/v3\/([^/#]+)((\/[^/#]+)*)/)
  return joinPath(
    __dirname,
    '..',
    'routes',
    state.folderName,
    kebabCase(scope),
    `${endpoint.idName}.json`
  )
}
26988
def show
      if params[:page_name] == "website"
        return render json: Website.unique_instance.as_json_for_page
      end

      page = Pwb::Page.find_by_slug(params[:page_name])
      if page
        render json: page.as_json_for_admin
      else
        render json: {}
      end
    end
546776
private ApiDoc getApiDoc(Class<?> controller, MethodDisplay displayMethodAs) {
		log.debug("Getting JSONDoc for class: " + controller.getName());
		ApiDoc apiDoc = initApiDoc(controller);

		apiDoc.setSupportedversions(JSONDocApiVersionDocBuilder.build(controller));
		apiDoc.setAuth(JSONDocApiAuthDocBuilder.getApiAuthDocForController(controller));
		apiDoc.setMethods(getApiMethodDocs(controller, displayMethodAs));
		
		if(controller.isAnnotationPresent(Api.class)) {
			apiDoc = mergeApiDoc(controller, apiDoc);
		}
		
		return apiDoc;
	}
256413
protected void registerOperation(Swagger swagger, Route route, ControllerHandler handler) {

        Class<? extends Controller> controller = handler.getControllerClass();
        Method method = handler.getControllerMethod();

        List<String> accepts = ControllerUtil.cleanupFuzzyContentTypes(handler.getDeclaredConsumes());
        List<String> produces = handler.getDeclaredProduces();

        Operation operation = new Operation();
        if (method.isAnnotationPresent(ApiSummary.class)) {
            ApiSummary apiSummary = method.getAnnotation(ApiSummary.class);
            String summary = translate(apiSummary.key(), apiSummary.value());
            if (Strings.isNullOrEmpty(summary)) {
                operation.setSummary(Util.toString(method));
            } else {
                operation.setSummary(summary);
            }
        } else if (Strings.isNullOrEmpty(route.getName())) {
            operation.setSummary(Util.toString(method));
        } else {
            operation.setSummary(route.getName());
        }

        if (operation.getSummary().length() > 120) {
            log.warn("'{}' api summary exceeds 120 characters", Util.toString(method));
        }

        StringBuilder sb = new StringBuilder();
        String notes = getNotes(method);
        if (!Strings.isNullOrEmpty(notes)) {
            sb.append(notes);
        }

        operation.setOperationId(Util.toString(method));
        operation.setConsumes(accepts.isEmpty() ? produces : accepts);
        operation.setProduces(produces);
        operation.setDeprecated(method.isAnnotationPresent(Deprecated.class)
                || controller.isAnnotationPresent(Deprecated.class));

        registerResponses(swagger, operation, method);
        registerSecurity(swagger, operation, method);

        Tag tag = getControllerTag(controller);
        if (tag == null) {
            operation.addTag(controller.getSimpleName());
        } else {
            swagger.addTag(tag);
            operation.addTag(tag.getName());
        }

        // identify and extract suffixes to automatically document those
        String operationPath = StringUtils.removeStart(registerParameters(swagger, operation, route, method), swagger.getBasePath());
        operationPath = stripContentTypeSuffixPattern(operationPath);

        Matcher suffixesMatcher = PATTERN_FOR_CONTENT_TYPE_SUFFIX.matcher(route.getUriPattern());
        boolean suffixRequired = false;
        List<String> suffixes = new ArrayList<>();
        while (suffixesMatcher.find()) {
            String suffixExpression = suffixesMatcher.group(1);
            suffixRequired = suffixExpression.charAt(suffixExpression.length() - 1) != '?';
            Matcher suffixMatcher = PATTERN_FOR_SUFFIX_EXTRACTION.matcher(suffixExpression);
            while (suffixMatcher.find()) {
                String suffix = suffixMatcher.group(1);
                suffixes.add(suffix);
            }
        }
        if (!suffixes.isEmpty()) {
            sb.append("\n\n");
            sb.append("#### ");
            String header = "Content-Type Suffixes";
            if (messages != null) {
                header = messages.getWithDefault("swagger.contentTypeSuffixHeader", header, "");
            }
            sb.append(header);
            sb.append("\n\n");
            if (suffixRequired) {
                String message = "A Content-Type suffix is **required**.";
                if (messages != null) {
                    message = messages.getWithDefault("swagger.contentTypeSuffixRequired", message, "");
                }
                sb.append(message);
            } else {
                String message = "A Content-Type suffix is *optional*.";
                if (messages != null) {
                    message = messages.getWithDefault("swagger.contentTypeSuffixOptional", message, "");
                }
                sb.append(message);
            }

            sb.append("\n\n");
            sb.append("| Content-Type | URI     |\n");
            sb.append("|--------------|---------|\n");
            if (!suffixRequired) {
                sb.append("| ").append(produces.size() > 1 ? "**negotiated**" : produces.get(0)).append(" ");
                sb.append("| ").append(operationPath).append(" ");
                sb.append("|\n");
            }
            for (String suffix : suffixes) {
                String contentType = engines == null ? "???" : engines.getContentTypeEngine(suffix).getContentType();
                sb.append("| ").append(contentType).append(" ");
                sb.append("| ").append(operationPath).append('.').append(suffix).append(" ");
                sb.append("|\n");
            }
            sb.append('\n');
        }

        if (sb.length() > 0) {
            operation.setDescription(sb.toString());
        }

        if (swagger.getPath(operationPath) == null) {
            swagger.path(operationPath, new Path());
        }

        Path path = swagger.getPath(operationPath);
        path.set(route.getRequestMethod().toLowerCase(), operation);
        log.debug("Add {} {} => {}",
                route.getRequestMethod(), operationPath, Util.toString(method));
    }
1280614
def add_page_if_missing(request):
    

    try:
        page = Page.objects.for_request(request, best_match=True)
        return {
            'leonardo_page': page,
            # DEPRECATED
            'feincms_page': page,
        }
    except Page.DoesNotExist:
        return {}
852254
def create_swagger_json_handler(app, **kwargs):
    

    spec = getattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
    _add_blueprint_specs(app, spec)
    spec_dict = spec.swagger_definition(**kwargs)
    encoded_spec = json.dumps(spec_dict).encode("UTF-8")

    def swagger():
        return Response(
            encoded_spec,
            # we allow CORS, so this can be requested at swagger.io
            headers={
                "Access-Control-Allow-Origin": "*"
            },
            content_type="application/json",
        )

    return swagger
785751
function createDocs() {
  if(!this.config.path.docs) return;
  try {
    var hasDocFolder = fs.existsSync(Component.appPath(this.config.path.docs)),
      hasTemplate = fs.existsSync(Component.appPath(this.config.docs.template));
    if(!hasDocFolder || !hasTemplate) throw new Error("No docs");
  } catch(e) {
    // No documentation support.
    return;
  }
  var docTwig = fs.readFileSync(Component.appPath(this.config.docs.template), { encoding: 'utf8' }).toString();
  var html = viewEngine.render(docTwig, {
    locals: {
      routes: this.routes
    }
  });
  try {
    fs.writeFileSync(Component.appPath(this.config.path.docs, 'doc.html'), html, { flag: 'w', encoding: 'utf8' });
    log.trace('CruxServer: Documented %s routes in ' + this.config.path.docs, routeCount);
  } catch(e) {}
}
909843
def add_bookmark(request):
    
    if request.method == "POST":
        form = BookmarkForm(user=request.user, data=request.POST)
        if form.is_valid():
            bookmark = form.save()
            if not request.is_ajax():
                messages.success(request, 'Bookmark added')
                if request.POST.get('next'):
                    return HttpResponseRedirect(request.POST.get('next'))
                return HttpResponse('Added')
            return render_to_response(
                'admin_tools/menu/remove_bookmark_form.html',
                {'bookmark': bookmark, 'url': bookmark.url}
            )
    else:
        form = BookmarkForm(user=request.user)
    return render_to_response(
        'admin_tools/menu/form.html',
        {'form': form, 'title': 'Add Bookmark'}
    )