Copy generated and validated openapi specs to reana-commons module.
773098
def copy_openapi_specs(output_path, component):
    """"""
    if component == 'reana-server':
        file = 'reana_server.json'
    elif component == 'reana-workflow-controller':
        file = 'reana_workflow_controller.json'
    elif component == 'reana-job-controller':
        file = 'reana_job_controller.json'
    if os.environ.get('REANA_SRCDIR'):
        reana_srcdir = os.environ.get('REANA_SRCDIR')
    else:
        reana_srcdir = os.path.join('..')
    try:
        reana_commons_specs_path = os.path.join(
            reana_srcdir,
            'reana-commons',
            'reana_commons',
            'openapi_specifications')
        if os.path.exists(reana_commons_specs_path):
            if os.path.isfile(output_path):
                shutil.copy(output_path,
                            os.path.join(reana_commons_specs_path,
                                         file))
                # copy openapi specs file as well to docs
                shutil.copy(output_path,
                            os.path.join('docs', 'openapi.json'))
    except Exception as e:
        click.echo('Something went wrong, could not copy openapi '
                   'specifications to reana-commons \n{0}'.format(e))
1242524
def build_request_to_validator_map(schema, resolver):
    
    schema_models = schema.get('models', {})
    return dict(
        (
            RequestMatcher(api['path'], operation['method']),
            ValidatorMap.from_operation(operation, schema_models, resolver)
        )
        for api in schema['apis']
        for operation in api['operations']
    )
1132223
def template(client, src, dest, paths, opt):
    """"""
    key_map = cli_hash(opt.key_map)
    obj = {}
    for path in paths:
        response = client.read(path)
        if not response:
            raise aomi.exceptions.VaultData("Unable to retrieve %s" % path)
        if is_aws(response['data']) and 'sts' not in path:
            renew_secret(client, response, opt)

        for s_k, s_v in response['data'].items():
            o_key = s_k
            if s_k in key_map:
                o_key = key_map[s_k]

            k_name = secret_key_name(path, o_key, opt) \
                .lower() \
                .replace('-', '_')
            obj[k_name] = s_v

    template_obj = blend_vars(obj, opt)
    output = render(grok_template_file(src),
                    template_obj)
    write_raw_file(output, abspath(dest))
95309
def from_json(cls, name, spec):
        
        if "run" not in spec:
            raise TuneError("No trainable specified!")

        # Special case the `env` param for RLlib by automatically
        # moving it into the `config` section.
        if "env" in spec:
            spec["config"] = spec.get("config", {})
            spec["config"]["env"] = spec["env"]
            del spec["env"]

        spec = copy.deepcopy(spec)

        run_value = spec.pop("run")
        try:
            exp = cls(name, run_value, **spec)
        except TypeError:
            raise TuneError("Improper argument from JSON: {}.".format(spec))
        return exp
1351912
def _dump_spec(spec):
    
    with open("spec.yaml", "w") as f:
        yaml.dump(spec, f, Dumper=MyDumper, default_flow_style=False)
199963
def generate_base(model, model_dict, config, manifest, source_config,
                  provider, adapter=None):
    """"""
    if provider is None:
        raise dbt.exceptions.InternalException(
            "Invalid provider given to context: {}".format(provider))

    target_name = config.target_name
    target = config.to_profile_info()
    del target['credentials']
    target.update(config.credentials.serialize(with_aliases=True))
    target['type'] = config.credentials.type
    target.pop('pass', None)
    target['name'] = target_name

    adapter = get_adapter(config)

    context = {'env': target}

    pre_hooks = None
    post_hooks = None

    db_wrapper = DatabaseWrapper(adapter)

    context = dbt.utils.merge(context, {
        "adapter": db_wrapper,
        "api": {
            "Relation": db_wrapper.Relation,
            "Column": adapter.Column,
        },
        "column": adapter.Column,
        "config": provider.Config(model_dict, source_config),
        "database": config.credentials.database,
        "env_var": env_var,
        "exceptions": dbt.exceptions.wrapped_exports(model),
        "execute": provider.execute,
        "flags": dbt.flags,
        # TODO: Do we have to leave this in?
        "graph": manifest.to_flat_graph(),
        "log": log,
        "model": model_dict,
        "modules": {
            "pytz": get_pytz_module_context(),
            "datetime": get_datetime_module_context(),
        },
        "post_hooks": post_hooks,
        "pre_hooks": pre_hooks,
        "ref": provider.ref(db_wrapper, model, config, manifest),
        "return": _return,
        "schema": config.credentials.schema,
        "sql": None,
        "sql_now": adapter.date_function(),
        "source": provider.source(db_wrapper, model, config, manifest),
        "fromjson": fromjson,
        "tojson": tojson,
        "target": target,
        "try_or_compiler_error": try_or_compiler_error(model)
    })

    return context
511123
def generate(self, api):
        
        rsrc_folder = os.path.join(os.path.dirname(__file__), 'obj_c_rsrc')
        rsrc_output_folder = os.path.join(self.target_folder_path, 'Resources')

        if not os.path.exists(rsrc_output_folder):
            os.makedirs(rsrc_output_folder)

        self.logger.info('Copying DBStoneValidators.{h,m} to output folder')
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneValidators.h'),
            rsrc_output_folder)
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneValidators.m'),
            rsrc_output_folder)
        self.logger.info('Copying DBStoneSerializers.{h,m} to output folder')
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneSerializers.h'),
            rsrc_output_folder)
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneSerializers.m'),
            rsrc_output_folder)
        self.logger.info('Copying DBStoneBase.{h,m} to output folder')
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneBase.h'), rsrc_output_folder)
        shutil.copy(
            os.path.join(rsrc_folder, 'DBStoneBase.m'), rsrc_output_folder)
        self.logger.info('Copying DBSerializableProtocol.h to output folder')
        shutil.copy(
            os.path.join(rsrc_folder, 'DBSerializableProtocol.h'),
            rsrc_output_folder)

        jazzy_cfg = None

        if self.args.documentation:
            jazzy_cfg_path = os.path.join('../Format', 'jazzy.json')
            with open(jazzy_cfg_path) as jazzy_file:
                jazzy_cfg = json.load(jazzy_file)

            for idx, namespace in enumerate(api.namespaces.values()):
                ns_name = fmt_public_name(namespace.name)
                ns_dict = {"name": ns_name, "children": [], }
                jazzy_cfg['custom_categories'].insert(idx, ns_dict)

        for namespace in api.namespaces.values():
            self.namespace_to_has_route_auth_list[namespace] = set()
            if namespace.routes:
                for route in namespace.routes:
                    if route.attrs.get('auth') != 'noauth':
                        self.namespace_to_has_route_auth_list[namespace].add(
                            route.attrs.get('auth'))
                    else:
                        self.namespace_to_has_route_auth_list[namespace].add(
                            'user')

        with self.output_to_relative_path('DBSDKImportsGenerated.h'):
            self._generate_all_imports(api)

        for namespace in api.namespaces.values():
            for data_type in namespace.linearize_data_types():
                self.obj_name_to_namespace[data_type.name] = fmt_class_prefix(
                    data_type)

        for namespace in api.namespaces.values():
            ns_name = fmt_public_name(namespace.name)
            self._generate_namespace_types(namespace, jazzy_cfg)

            if namespace.routes:
                if self.args.documentation:
                    for auth_type in self.namespace_to_has_route_auth_list[
                            namespace]:
                        append_to_jazzy_category_dict(
                            jazzy_cfg, 'Routes', fmt_routes_class(ns_name, auth_type))
                    append_to_jazzy_category_dict(
                        jazzy_cfg, 'RouteObjects', fmt_route_obj_class(ns_name))
                self._generate_route_objects_m(api.route_schema, namespace)
                self._generate_route_objects_h(api.route_schema, namespace)

        if self.args.documentation:
            with self.output_to_relative_path('../../../../.jazzy.json'):
                self.emit_raw(json.dumps(jazzy_cfg, indent=2) + '\n')
341395
def build_metadata_class(specfile):
    """"""
    with open(specfile) as f:
        spec = json.load(f)
        name = os.path.basename(specfile).split('.')[0]
        spec['name'] = name

        env = get_jinja_env()

        metadata_template = env.get_template('metadata.py.jinja2')
        with open('pycanvas/meta/{}.py'.format(name), 'w') as t:
            t.write(metadata_template.render(spec=spec))
502429
def build_clonespec(config_spec, object_ref, reloc_spec, template):
    '''
    
    '''
    if reloc_spec.diskMoveType == QUICK_LINKED_CLONE:
        return vim.vm.CloneSpec(
            template=template,
            location=reloc_spec,
            config=config_spec,
            snapshot=object_ref.snapshot.currentSnapshot
        )

    return vim.vm.CloneSpec(
        template=template,
        location=reloc_spec,
        config=config_spec
    )
845572
function addRaw() {
	openapi.tags = openapi.tags.concat(raw.tags);
	for (var p in raw.paths) {
		openapi.paths[p] = raw.paths[p];
		openapi.paths[p].get.responses['200'].description = 'Nitro response';
		openapi.paths[p].get.responses['200'].content = {};
		openapi.paths[p].get.responses['200'].content['application/json'] = {};
		openapi.paths[p].get.responses['200'].content['application/json'].schema = {};
		openapi.paths[p].get.responses['200'].content['application/json'].schema.$ref = '#/components/schemas/nitro';
		openapi.paths[p].get.responses['200'].content['application/xml'] = clone(openapi.paths[p].get.responses['200'].content['application/json']);
	}
}
392023
def _to_swagger(base=None, description=None, resource=None, options=None):
    # type: (Dict[str, str], str, Resource, Dict[str, str]) -> Dict[str, str]
    
    definition = dict_filter(base or {}, options or {})

    if description:
        definition['description'] = description.format(
            name=getmeta(resource).name if resource else "UNKNOWN"
        )

    if resource:
        definition['schema'] = {
            '$ref': '#/definitions/{}'.format(getmeta(resource).resource_name)
        }

    return definition
986278
def fromapi(_class, apiresponse):
        """"""
        for resp in apiresponse['sb']:
            # Extract details from dict
            _id = "n/a" or resp.get("nm")
            subject = resp.get("sbj")
            text = resp.get('dtl') + "\n" + resp.get('brf')
            priority = "n/a" or resp.get('prty')
            for_stops, for_routes = [], []
            svc = resp.get('srvc')
        
            # Create list of affected routes/stops, if there are any
            if svc:
                has_stop = 'stpid' in svc or 'stpnm' in svc
                has_rt = 'rt' in svc or 'rtdir' in svc
            
                if has_stop: 
                    aff = _class.affected_service('stop', svc.get('stpid'), svc.get('stpnm'))
                    for_stops.append(aff)
                if has_rt:
                    aff = _class.affected_service('route', svc.get('rt'), svc.get('rtdir'))
                    for_routes.append(aff)

            yield _class(_id, subject, text, priority, for_stops, for_routes)
1125875
def _ask_openapi():
        """"""
        if Path('openapi.yml').exists():
            question = 'Override local openapi.yml with a new skeleton? (y/N) '
            default = False
        else:
            question = 'Do you have REST endpoints and wish to create an API' \
                ' skeleton in openapi.yml? (Y/n) '
            default = True

        while True:
            answer = input(question)
            if answer == '':
                return default
            if answer.lower() in ['y', 'yes']:
                return True
            if answer.lower() in ['n', 'no']:
                return False
382731
def export_module_spec(spec, path, checkpoint_path, name_transform_fn):
  """"""
  with tf.Graph().as_default():
    m = Module(spec)
    assign_map = {
        name_transform_fn(name): value for name, value in m.variable_map.items()
    }
    tf_v1.train.init_from_checkpoint(checkpoint_path, assign_map)
    init_op = tf_v1.initializers.global_variables()
    with tf_v1.Session() as session:
      session.run(init_op)
      m.export(path, session)
522999
function createApi(projectInfo, awsDetails, callback) {
    return appsyncCreate.run(projectInfo, awsDetails).then(()=>{
        if(callback){
            callback()
        }
    })
}
680497
def reqresp_middleware(api=None):
    """"""
    def decorator(middleware_generator):
        apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_generator)

        class MiddlewareRouter(object):
            __slots__ = ('gen', )

            def process_request(self, request, response):
                self.gen = middleware_generator(request)
                return self.gen.__next__()

            def process_response(self, request, response, resource, req_succeeded):
                return self.gen.send((response, resource))

        apply_to_api.http.add_middleware(MiddlewareRouter())
        return middleware_generator
    return decorator
594584
def _reprJSON(self):
        
        return {'__Ci__': (self.id, self.specfile, self.dataProcessingRef,
                           self.precursor, self.product, self.params,
                           self.attrib, self.arrayInfo
                           )
                }