Generate Remote API from a list of controllers
357693
public function generateRemotingApi() {
        $list = array();
        foreach($this->remotingBundles as $bundle) {
            $bundleRef = new \ReflectionClass($bundle);
            $controllerDir = new Finder();
            $controllerDir->files()->in(dirname($bundleRef->getFileName()).'/Controller/')->name('/.*Controller\.php$/');
            foreach($controllerDir as $controllerFile) {
                $controller = $bundleRef->getNamespaceName() . "\\Controller\\" . substr($controllerFile->getFilename(), 0, -4);
                $controllerRef = new \ReflectionClass($controller);
                foreach ($controllerRef->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
                    /** @var $methodDirectAnnotation Direct */
                    $methodDirectAnnotation = $this->annoReader->getMethodAnnotation($method, 'Tpg\ExtjsBundle\Annotation\Direct');
                    if ($methodDirectAnnotation !== null) {
                        $nameSpace = str_replace("\\", ".", $bundleRef->getNamespaceName());
                        $className = str_replace("Controller", "", $controllerRef->getShortName());
                        $methodName = str_replace("Action", "", $method->getName());
                        $list[$nameSpace][$className][] = array(
                            'name'=>$methodName,
                            'len' => count($method->getParameters())
                        );
                    }
                }
            }
        }
        return $list;
    }
54701
function generateResourceListing(options) {
  var controllers = options.controllers;
  var opts = options.options || {};

  var listing = {
    openapi: '3.0.0',
    info: buildInfo(opts),
    servers: opts.servers || buildDefaultServers(),
    tags: buildTags(opts, controllers),
    paths: buildPaths(opts, controllers),
    components: buildComponents(opts, controllers)
  };

  mergeIn(listing.paths, opts.paths);

  if (opts.security) {
    listing.security = opts.security;
  }
  if (opts.externalDocs) {
    listing.externalDocs = opts.externalDocs;
  }

  return listing;
}
555320
function DumpInternals() {
    for (let ck in exports.globalKCState.controllers) {
        console.log("============================================");
        console.log(`Controller on path ${exports.globalKCState.controllers[ck].path} built from Class ${exports.globalKCState.controllers[ck].ctr.name}`);
        console.log("With Methods:");
        for (let mk in exports.globalKCState.controllers[ck].methods) {
            let m = exports.globalKCState.controllers[ck].methods[mk];
            console.log(`== ${mk} ==`);
            console.log(m);
            console.log("");
        }
    }
}
169175
def _handle_list(reclist):
    
    ret = []
    for item in reclist:
        recs = _handle_resource_setting(item)
        ret += [resource for resource in recs if resource.access_controller]
    return ret
683426
function() {
      // Used for de-duping
      var paths = {};

      // Each controller has a `routes` object
      // Connect all routes defined in controllers
      _.forEach(router.controllers, function(controller) {
        _.forEach(controller.routes, function(route, method) {
          _.forEach(route, function(routeOptions, path) {
            // If path/method has already been defined, skip
            if (paths[path] === method) {
              debug.warn('Skipping duplicate route: [%s] %s', method, path);
              return;
            }

            // If no route action is defined, skip
            if (!routeOptions.action) {
              debug.warn('No action defined for route: [%s] %s', method, path);
              return;
            }

            // Setup controller scoped middleware
            // These apply to all routes in the controller
            var pre = _.invokeMap(controller.pre, 'bind', controller) || [];
            var before = _.invokeMap(controller.before, 'bind', controller) || [];
            var after = _.invokeMap(controller.after, 'bind', controller) || [];

            // Setup route scoped middleware
            // These apply only to this route
            var middleware = routeOptions.middleware || [];

            // Build the route handler (callback)
            var handler = router._buildHandler(controller, routeOptions);

            // Connect the route
            router[method](path, pre, middleware, before, handler, after);

            // Add route to set of connected routes
            router.routes.push({
              url: router.url,
              method: method,
              path: path
            });

            // Use for de-duping
            paths[path] = method;
          });
        });
      });

      // Debug logging
      _.forEach(router.routes, function(route) {
        debug.info('Route [%s] %s', route.method, route.url + route.path);
      });
    }
502542
def determine_hooks(self, controller=None):
        '''
        
        '''

        controller_hooks = []
        if controller:
            controller_hooks = _cfg(controller).get('hooks', [])
            if controller_hooks:
                return list(
                    sorted(
                        chain(controller_hooks, self.hooks),
                        key=operator.attrgetter('priority')
                    )
                )
        return self.hooks
947158
def generate(self, api):
        """"""
        # Create a file for each namespace.
        for namespace in api.namespaces.values():
            with self.output_to_relative_path('%s.stone' % namespace.name):
                # Output a namespace header.
                self.emit('namespace %s' % namespace.name)
                # Output all data type (struct and union) definitions.
                for data_type in namespace.linearize_data_types():
                    self.generate_data_type(data_type)
                # Output all route definitions.
                for route in namespace.routes:
                    self.generate_route(route)
1234947
def _instantiate_remote_sources(self, kwargs):
    """"""
    kwargs['dest'] = _DestWrapper((self._target_types[kwargs['dest']],))
    return RemoteSources(build_graph=self, **kwargs)
335172
def execute(self, requests, resp_generator, *args, **kwargs):
        '''
            
        '''
        return [resp_generator(request) for request in requests]
627993
def controllers(self):
        
        controllers = []
        try:
            while True:
                controller = self.lib.tdController()
                del controller["name"]
                del controller["available"]
                controllers.append(Controller(lib=self.lib, **controller))
        except TelldusError as e:
            if e.error != const.TELLSTICK_ERROR_NOT_FOUND:
                raise
        return controllers
612727
def auto_discover():
    
    urls = [
        url(r'^admin/', admin.site.urls),
    ]

    # TODO: we can create python package to have a lot of controllers
    # in separate files
    def get_controllers(module_name):
        """Return list of controllers in a module."""
        module = import_module('app.controllers.{}'.format(module_name))
        controllers = []
        for obj_name in dir(module):
            # we ignore import of Controller and hidden names
            if obj_name.startswith('_') or obj_name == 'Controller':
                continue
            obj = getattr(module, obj_name)
            # include only controllers
            if issubclass(obj, Controller):
                controllers.append(obj)
        return controllers

    def controller_to_path(controller):
        """
        Convert controller's name to a valid path.

        Make url in lower case by replace capital letters to small
        and adding underscore between words.
        """
        words = re.findall('[A-Z][a-z]*', controller.__name__)
        if words[-1] == 'Controller':
            del words[-1]
        # transform words to a url address
        url_path = '_'.join(words).lower()
        # main controller is a root handler
        # TODO: root address inside the file should always come last
        if url_path == 'main':
            url_path = ''
        return url_path

    # load all controllers (excluding main controllers)
    for file_name in listdir('controllers', get_files=True, hide_ignored=True):
        # remove .py extension from file name
        app_name = file_name.split('.', 1)[0]
        # we will include main controller at the end
        if app_name == 'main':
            continue
        # add url for each controller
        for controller in get_controllers(app_name):
            url_path = controller_to_path(controller)
            urls.append(url(
                r'^{}/{}$'.format(app_name, url_path),
                controller.as_view()
            ))

    # add urls for main controllers
    for controller in get_controllers('main'):
        url_path = controller_to_path(controller)
        # map urls to a root path
        urls.append(url(
            r'^{}$'.format(url_path),
            controller.as_view()
        ))

    return urls
230334
def _get_results_from_api(identifiers, endpoints, api_key, api_secret):
    """"""

    if api_key is not None and api_secret is not None:
        client = housecanary.ApiClient(api_key, api_secret)
    else:
        client = housecanary.ApiClient()

    wrapper = getattr(client, endpoints[0].split('/')[0])

    if len(endpoints) > 1:
        # use component_mget to request multiple endpoints in one call
        return wrapper.component_mget(identifiers, endpoints)
    else:
        return wrapper.fetch_identifier_component(endpoints[0], identifiers)
1209679
function loadControllers() {
  
  // Note: runs on app context
  
  // Get controllers/
  var cpath = this.mvcpath + 'controllers/',
      files = protos.util.getFiles(cpath);

  // Create controllers and attach to app
  var controllerCtor = protos.lib.controller;
  for (var controller, key, file, instance, className, Ctor, i=0; i < files.length; i++) {
    file = files[i];
    key = file.replace(this.regex.jsFile, '');
    className = file.replace(this.regex.jsFile, '');
    Ctor = protos.require(cpath + className, true); // Don't use module cache (allow reloading)
    Ctor = createControllerFunction.call(this, Ctor);
    instance = new Ctor(this);
    instance.className = instance.constructor.name;
    this.controllers[key.replace(/_controller$/, '')] = instance;
  }

  this.controller = this.controllers.main;
  
  this.emit('controllers_loaded', this.controllers);

}
748984
private function pushControllersInDefinition($alias_namespace, $controllers_directory, &$default_definitions)
    {
        $controller_files = get_files($controllers_directory);
        if (!empty($controller_files))
        {
            $controllers = array_map(function($controller) use($controllers_directory) {
                $new_controller = str_replace("{$controllers_directory}/", "", $controller);
                return basename(str_replace("/", "\\", $new_controller), ".php");
            }, $controller_files);

            $errors = [];

            foreach ($controllers as $controller) {
                if ($alias_namespace === "\\")
                {
                    $controller_definition = $controller;
                    $controller_definition_value = get_app_namespace() . "Controllers\\{$controller}";
                }
                else
                {
                    $module_name = str_replace("App\\", "", $alias_namespace);

                    $controller_sub_namespace = str_replace(app_path() . "/{$module_name}/Controllers", "", $controllers_directory);
                    $controller_sub_namespace = str_replace("/", "\\", $controller_sub_namespace);

                    $controller_definition = "{$alias_namespace}{$controller}";
                    $controller_definition_value = "{$alias_namespace}Controllers\\{$controller}";
                }

                if (!array_key_exists("{$controller_definition}", $default_definitions))
                {
                    $default_definitions["{$controller_definition}"] = function(ContainerInterface $c) use ($controller_definition_value)
                    {
                        return new $controller_definition_value($c);
                    };
                }
                else
                {
                    $errors[] = "{$controller} is already exist inside of definitions.";
                }
            }

            if (!empty($errors))
            {
                exit("Error: Please fix the ff. before run the application: <li>" . implode("</li><li>", $errors));
            }
        }
        else
        {
            exit("Error: No controller found in {$controllers_directory} path.");
        }
    }
861184
def merge_controller(content, namespaces, index, values = {})

      if (index == (namespaces.length - 1))
        content[namespaces[index]] = {} unless content.has_key?(namespaces[index])
        content[namespaces[index]].merge!(values)
      else
        content[namespaces[index]] = {} unless content.has_key?(namespaces[index])
        content[namespaces[index]] = merge_controller(content[namespaces[index]], namespaces, index + 1, values)
      end
      return content
    end
1290102
def make_remote_view(data, settings, more_excluded_names=None):
    
    data = get_remote_data(data, settings, mode='editable',
                           more_excluded_names=more_excluded_names)
    remote = {}
    for key, value in list(data.items()):
        view = value_to_display(value, minmax=settings['minmax'])
        remote[key] = {'type':  get_human_readable_type(value),
                       'size':  get_size(value),
                       'color': get_color_name(value),
                       'view':  view}
    return remote
845520
def get(self, url, controller):
        

        self.request_type = 'GET'
        controller_class, controller_method = self.__return_controller__(controller)

        self.controller = controller_class
        self.method = controller_method
        self.url_ = url

        self.url.append((url, controller_class, dict(method=controller_method, request_type=self.request_type, middleware=None)))
        return self