Imports model defined in specified file
434445
def dynare_import(filename,full_output=False, debug=False):
    ''''''
    import os
    basename = os.path.basename(filename)
    fname = re.compile('(.*)\.(.*)').match(basename).group(1)
    f = open(filename)
    txt = f.read()
    model = parse_dynare_text(txt,full_output=full_output, debug=debug)
    model.name = fname
    return model
773761
def import_file(self, ):
        
        tfi = self.get_taskfileinfo_selection()
        if tfi:
            self.reftrack.import_file(tfi)
203705
def import_file(self, file_obj, folder):
        
        created = False
        for cls in MEDIA_MODELS:
            if cls.matches_file_type(file_obj.name):

                obj, created = cls.objects.get_or_create(
                    original_filename=file_obj.name,
                    file=file_obj,
                    folder=folder,
                    is_public=FILER_IS_PUBLIC_DEFAULT)
                if created:
                    self.image_created += 1
        if not created:
            obj, created = File.objects.get_or_create(
                original_filename=file_obj.name,
                file=file_obj,
                folder=folder,
                is_public=FILER_IS_PUBLIC_DEFAULT)
            if created:
                self.file_created += 1
        if self.verbosity >= 2:
            print("file_created #%s / image_created #%s -- file : %s -- created : %s" % (self.file_created,
                                                                                         self.image_created,
                                                                                         obj, created))
        return obj
461701
def model_export_to_file(f, model=None, repo=None):
    
    if not model and not repo:
        raise Exception("specity either a model or a repo")
    if model and repo:
        raise Exception("specity either a model or a repo")

    processed_set = set()
    f.write(HEADER)

    def _export(obj):

        if obj is None or obj in processed_set or type(obj) \
                in PRIMITIVE_PYTHON_TYPES:
            return

        processed_set.add(obj)

        attrs = ""
        obj_cls = obj.__class__
        name = ""
        for attr_name, attr in obj_cls._tx_attrs.items():

            attr_value = getattr(obj, attr_name)

            endmark = 'arrowtail=diamond dir=both' if attr.cont else ""
            required = "+" if attr.mult in \
                [MULT_ONE, MULT_ONEORMORE] else ""

            if attr.mult in [MULT_ONEORMORE, MULT_ZEROORMORE]:
                if all([type(x) in PRIMITIVE_PYTHON_TYPES
                        for x in attr_value]):
                    attrs += "{}{}:list=[".format(required, attr_name)
                    attrs += ",".join([dot_repr(x) for x in attr_value])
                    attrs += "]\\l"
                else:
                    for idx, list_obj in enumerate(attr_value):
                        if list_obj is not None:
                            if type(list_obj) in PRIMITIVE_PYTHON_TYPES:
                                f.write(
                                    '{} -> "{}:{}" [label="{}:{}" {}]\n'
                                    .format(id(obj), list_obj,
                                            type(list_obj).__name__,
                                            attr_name, idx, endmark))
                            else:
                                f.write('{} -> {} [label="{}:{}" {}]\n'
                                        .format(id(obj), id(list_obj),
                                                attr_name, idx, endmark))
                                _export(list_obj)
            else:

                # Plain attributes
                if type(attr_value) is text and attr_name != 'name':
                    attr_value = dot_repr(attr_value)

                if type(attr_value) in PRIMITIVE_PYTHON_TYPES:
                    if attr_name == 'name':
                        name = attr_value
                    else:
                        attrs += "{}{}:{}={}\\l".format(
                            required, attr_name, type(attr_value)
                            .__name__, attr_value)
                else:
                    # Object references
                    if attr_value is not None:
                        f.write('{} -> {} [label="{}" {}]\n'.format(
                            id(obj), id(attr_value),
                            attr_name, endmark))
                        _export(attr_value)

        name = "{}:{}".format(name, obj_cls.__name__)

        f.write('{}[label="{{{}|{}}}"]\n'.format(id(obj), name, attrs))

    def _export_subgraph(m):
        from textx import get_children
        f.write('subgraph "cluster_{}" {{\n'.format(m._tx_filename))
        f.write('''
        penwidth=2.0
        color=darkorange4;
        label = "{}";
                    '''.format(m._tx_filename))
        for obj in get_children(lambda _: True, m):
            f.write('{};\n'.format(id(obj)))
        f.write('\n}\n')

    if repo or hasattr(model, "_tx_model_repository"):
        if not repo:
            repo = model._tx_model_repository.all_models
        for m in repo.filename_to_model.values():
            _export_subgraph(m)
            _export(m)
    else:
        _export(model)

    f.write('\n}\n')
970016
function initModels(seqObj, modelFiles, models, tablePrefix) {
    modelFiles.forEach((item) => {
      var modelFn;
      try {
        modelFn = require(item.fullPath);
      } catch (e) {
        console.error('Thorin.sql: could not require model: ' + item.fullPath + '\n', e.stack);
        return;
      }
      if (modelFn == null) return;  // we skip it
      if (typeof modelFn !== 'function') {
        console.error(thorin.error('SQL.INVALID_MODEL', 'SQL Model: ' + item.fullPath + ' must export a function(modelObj){}'));
        return;
      }
      if (modelFn.name === 'extend') {
        if (typeof extendModels[item.code] === 'undefined') extendModels[item.code] = [];
        extendModels[item.code].push(modelFn);
        return;
      }
      let modelObj = loader.buildModel(seqObj, modelFn, item, tablePrefix);
      if (modelObj) {
        if (typeof models[modelObj.code] !== 'undefined') {
          console.error(thorin.error('SQL.ADD_MODEL', 'SQL Store: model ' + modelObj.code + ' was already declared.'));
          return;
        }
        models[modelObj.code] = modelObj;
      }
    });
  }
638856
def load(self, filename, fv_extern=None):
        
        self.modelparams["mdl_stored_file"] = filename
        if fv_extern is not None:
            self.modelparams["fv_extern"] = fv_extern

        # segparams['modelparams'] = {
        #     'mdl_stored_file': mdl_stored_file,
        #     # 'fv_extern': fv_function
        # }
        self.mdl = Model(modelparams=self.modelparams)
905995
def load_model(model_file):
    
    # Extract tar
    with tarfile.open(model_file) as tar:
        tarfolder = tempfile.mkdtemp()
        tar.extractall(path=tarfolder)

    from . import features
    from . import preprocessing

    # Get the preprocessing
    with open(os.path.join(tarfolder, "preprocessing.yml"), 'r') as ymlfile:
        preprocessing_description = yaml.load(ymlfile)
    preprocessing_queue = preprocessing.get_preprocessing_queue(
        preprocessing_description['queue'])

    # Get the features
    with open(os.path.join(tarfolder, "features.yml"), 'r') as ymlfile:
        feature_description = yaml.load(ymlfile)
    feature_str_list = feature_description['features']
    feature_list = features.get_features(feature_str_list)

    # Get the model
    import nntoolkit.utils
    model = nntoolkit.utils.get_model(model_file)

    output_semantics_file = os.path.join(tarfolder, 'output_semantics.csv')
    output_semantics = nntoolkit.utils.get_outputs(output_semantics_file)

    # Cleanup
    shutil.rmtree(tarfolder)

    return (preprocessing_queue, feature_list, model, output_semantics)
1005353
def load_model_class(model_path):
    
    dot = model_path.rindex('.')
    module_name = model_path[:dot]
    class_name = model_path[dot + 1:]
    try:
        _class = getattr(import_module(module_name), class_name)
        return _class
    except (ImportError, AttributeError):
        raise ImproperlyConfigured('%s cannot be imported' % model_path)
199853
def open_imports(self, imported_definitions):
        """"""
        for imp in self.imports:
            imp.load(self, imported_definitions)
313476
def load_model_from_path(model_path, meta=False, **overrides):
    """"""
    from .tokenizer_loader import TokenizerLoader

    if not meta:
        meta = get_model_meta(model_path)
    tokenizer_loader = TokenizerLoader(meta=meta, **overrides)
    tokenizers = meta.get('tokenizers', [])
    disable = overrides.get('disable', [])
    if tokenizers is True:
        tokenizers = TokenizerLoader.Defaults.tokenizers
    elif tokenizers in (False, None):
        tokenizers = []
    for tokenizer_name in tokenizers:
        if tokenizer_name not in disable:
            config = meta.get('tokenizer_args', {}).get(tokenizer_name, {})
            component = tokenizer_loader.create_tokenizer(tokenizer_name, config=config)
            tokenizer_loader.add_tokenizer(component, name=tokenizer_name)
    return tokenizer_loader.from_disk(model_path)
774769
function modelExport(m) {
  const result = _.mapValues(m.classes, _.head)
  result[m.__name] = m
  return result
}
1315316
def ingest_to_model(file, model, engine=None):
    
    if engine is None:
        engine = db.engine
    reader = csv.reader(file)
    columns = tuple('"{}"'.format(n) for n in next(reader))
    postgres_copy.copy_from(
        file, model, engine, columns=columns, format="csv", HEADER=False
    )
    fix_autoincrement(model.__table__.name)
1085911
def _bundle_models(custom_models):
    
    exports = []
    modules = []

    def read_json(name):
        with io.open(join(bokehjs_dir, "js", name + ".json"), encoding="utf-8") as f:
            return json.loads(f.read())

    bundles = ["bokeh", "bokeh-api", "bokeh-widgets", "bokeh-tables", "bokeh-gl"]
    known_modules = set(sum([ read_json(name) for name in bundles ], []))
    custom_impls = _compile_models(custom_models)

    extra_modules = {}

    def resolve_modules(to_resolve, root):
        resolved = {}
        for module in to_resolve:
            if module.startswith(("./", "../")):
                def mkpath(module, ext=""):
                    return abspath(join(root, *module.split("/")) + ext)

                if module.endswith(exts):
                    path = mkpath(module)
                    if not exists(path):
                        raise RuntimeError("no such module: %s" % module)
                else:
                    for ext in exts:
                        path = mkpath(module, ext)
                        if exists(path):
                            break
                    else:
                        raise RuntimeError("no such module: %s" % module)

                impl = FromFile(path)
                compiled = nodejs_compile(impl.code, lang=impl.lang, file=impl.file)

                if "error" in compiled:
                    raise CompilationError(compiled.error)

                if impl.lang == "less":
                    code = _style_template % dict(css=json.dumps(compiled.code))
                    deps = []
                else:
                    code = compiled.code
                    deps = compiled.deps

                sig = hashlib.sha256(code.encode('utf-8')).hexdigest()
                resolved[module] = sig

                deps_map = resolve_deps(deps, dirname(path))

                if sig not in extra_modules:
                    extra_modules[sig] = True
                    modules.append((sig, code, deps_map))
            else:
                index = module + ("" if module.endswith("/") else "/") + "index"
                if index not in known_modules:
                    raise RuntimeError("no such module: %s" % module)

        return resolved

    def resolve_deps(deps, root):
        custom_modules = set(model.module for model in custom_models.values())
        missing = set(deps) - known_modules - custom_modules
        return resolve_modules(missing, root)

    for model in custom_models.values():
        compiled = custom_impls[model.full_name]
        deps_map = resolve_deps(compiled.deps, model.path)

        exports.append((model.name, model.module))
        modules.append((model.module, compiled.code, deps_map))

    # sort everything by module name
    exports = sorted(exports, key=lambda spec: spec[1])
    modules = sorted(modules, key=lambda spec: spec[0])

    for i, (module, code, deps) in enumerate(modules):
        for name, ref in deps.items():
            code = code.replace("""require("%s")""" % name, """require("%s")""" % ref)
            code = code.replace("""require('%s')""" % name, """require('%s')""" % ref)
        modules[i] = (module, code)

    sep = ",\n"

    exports = sep.join(_export_template % dict(name=name, module=module) for (name, module) in exports)
    modules = sep.join(_module_template % dict(module=module, source=code) for (module, code) in modules)

    content = _plugin_template % dict(prelude=_plugin_prelude, exports=exports, modules=modules)
    return _plugin_umd % dict(content=content)
459647
def do_imports(self):
        
        self.do_import('worker_class', Worker)
        self.do_import('queue_model', self.options.worker_class.queue_model)
        self.do_import('error_model', self.options.worker_class.error_model)
        self.do_import('callback', self.options.worker_class.callback)
1113464
def _import_model(models, crumbs):
    
    logger_jsons.info("enter import_model".format(crumbs))
    _models = OrderedDict()
    try:
        for _idx, model in enumerate(models):
            # Keep the original dictionary, but replace the three main entries below

            # Do a direct replacement of chronModelTable columns. No table name, no table work needed.
            if "summaryTable" in model:
                model["summaryTable"] = _idx_table_by_name(model["summaryTable"], "{}{}{}".format(crumbs, _idx, "summary"))
            # Do a direct replacement of ensembleTable columns. No table name, no table work needed.
            if "ensembleTable" in model:
                model["ensembleTable"] = _idx_table_by_name(model["ensembleTable"], "{}{}{}".format(crumbs, _idx, "ensemble"))
            if "distributionTable" in model:
                model["distributionTable"] = _idx_table_by_name(model["distributionTable"], "{}{}{}".format(crumbs, _idx, "distribution"))

            _table_name = "{}{}".format(crumbs, _idx)
            _models[_table_name] = model
    except Exception as e:
        logger_jsons.error("import_model: {}".format(e))
        print("Error: import_model: {}".format(e))
    logger_jsons.info("exit import_model: {}".format(crumbs))
    return _models
732311
def load_model(self, config):
        
        for package_name in getattr(config.app, 'modules', []):
            module = __import__(package_name, fromlist=['model'])
            if hasattr(module, 'model'):
                return module.model
        return None
114577
@Override
    public I importFrom(final File file) throws ArchiveImportException {
        return importFrom(file, Filters.includeAll());
    }