Import minimum needs from an existing json file.

        The minimum needs are loaded from a file into the table. This state
        is only saved if the form is accepted.
771062
def import_profile(self):
        
        # noinspection PyCallByClass,PyTypeChecker
        file_name_dialog = QFileDialog(self)
        file_name_dialog.setAcceptMode(QFileDialog.AcceptOpen)
        file_name_dialog.setNameFilter(self.tr('JSON files (*.json *.JSON)'))
        file_name_dialog.setDefaultSuffix('json')
        path_name = resources_path('minimum_needs')
        file_name_dialog.setDirectory(path_name)
        if file_name_dialog.exec_():
            file_name = file_name_dialog.selectedFiles()[0]
        else:
            return -1

        if self.minimum_needs.read_from_file(file_name) == -1:
            return -1

        self.clear_resource_list()
        self.populate_resource_list()
        self.switch_context(self.profile_edit_page)
380063
def load(self, schemafile=None):
        """"""
        if schemafile is not None:
            self._schemafile = schemafile

        try:
            self.data = json.load(open(self._schemafile))
        except (IOError, ValueError), e:
            msg = "Could not load schema file '" + self._schemafile + "': '" + str(e) + "'"
            raise jsonschema.SchemaError(msg)

        self.loaded = True
117883
def requires(self, require=None):
		

		# If require is None, this is a getter
		if require is None:
			return self._requires

		# If it's not a valid dict
		if not isinstance(require, dict):
			raise ValueError('__require__')

		# Go through each key and make sure it goes with a field
		for k,v in iteritems(require):

			# If the field doesn't exist
			if k not in self._nodes:
				raise ValueError('__require__[%s]' % str(k))

			# If the value is a string
			if isinstance(v, basestring):
				v = [v]

			# Else if it's not a list type
			elif not isinstance(v, (tuple,list)):
				raise ValueError('__require__[%s]' % str(k))

			# Make sure each required field also exists
			for s in v:
				if s not in self._nodes:
					raise ValueError('__require__[%s]: %s' % (str(k), str(v)))

			# If it's all good
			self._requires[k] = v
846872
def load_existing_json():
        
        dir = logger.get_logger_dir()
        fname = os.path.join(dir, JSONWriter.FILENAME)
        if tf.gfile.Exists(fname):
            with open(fname) as f:
                stats = json.load(f)
                assert isinstance(stats, list), type(stats)
                return stats
        return None
851274
def requirements(self, requires):
        '''
        
        '''
        if requires:
            if isinstance(requires, basestring) and \
               os.path.isfile(os.path.abspath(requires)):
                self._requirements_file = os.path.abspath(requires)
            else:
                if isinstance(self._requirements, basestring):
                    requires = requires.split()
                self._requirements_file = None
                self._requirements = requires
        else:
            # If the default requirements file is found use that
            if os.path.isfile(self._requirements_file):
                return
            self._requirements, self._requirements_file = None, None
476818
def afw_json_importer(input_file: str) -> dict:
    
    file = open(input_file)
    json_file = json.load(file)

    transitions = {}  # key [state in states, action in alphabet]
    #  value [string representing boolean expression]
    for p in json_file['transitions']:
        transitions[p[0], p[1]] = p[2]

    # return map
    afw = {
        'alphabet': set(json_file['alphabet']),
        'states': set(json_file['states']),
        'initial_state': json_file['initial_state'],
        'accepting_states': set(json_file['accepting_states']),
        'transitions': transitions
    }
    return afw
628432
def requires_application_json(f):
    """"""

    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        from flask import request
        if request.get_json(silent=True) is None:
            er = ErrorResponse(description='Improper Content-Type header. Expecting "application/json"')
            return to_json_response(er), HTTPStatus.BAD_REQUEST
        else:
            return f(*args, **kwargs)

    return wrapped
1222627
def requirements_from_file(filename):
    """"""
    return [line.strip() for line in open(filename, 'r')
            if line.strip() and not line.strip().startswith('--')]
776545
def dfa_json_importer(input_file: str) -> dict:
    
    file = open(input_file)
    json_file = json.load(file)

    transitions = {}  # key [state ∈ states, action ∈ alphabet]
    #                   value [arriving state ∈ states]
    for (origin, action, destination) in json_file['transitions']:
        transitions[origin, action] = destination

    dfa = {
        'alphabet': set(json_file['alphabet']),
        'states': set(json_file['states']),
        'initial_state': json_file['initial_state'],
        'accepting_states': set(json_file['accepting_states']),
        'transitions': transitions
    }
    return dfa
1303412
def load(cls, file):
        
        d = json.load(file)
        return cls.create(d)
326843
function load(file) {
    if (path.extname(file) === ".yaml" || path.extname(file) === ".yml") {
      return yaml.safeLoad(fs.readFileSync(file));

    } else if (path.extname(file) === ".json") {
      var r = JSON.parse(fs.readFileSync(file));
      return r;

    } else if (path.extname(file) === ".js") {
      var obj = require(file);
      
      if (typeof(obj) !== "object") {
        throw {error: "needs to export object, not "+typeof(obj), file: file};

      } else {
        return clone(obj);
      }
    } else {
      throw {error: path+" has invalid extension: "+path.extname(file)};
    }
  }
368577
def _load(self):
        
        if self.dbfile is not None:
            with open(self.dbfile, 'r') as f:
                self._db = json.loads(f.read())
        else:
            self._db = {}
258276
public function import()
    {
        if (!empty($this->request->data['json'])) {
            $this->loadModel('User.Acos');
            $json = $this->request->data['json'];
            $dst = TMP . $json['name'];
            if (file_exists($dst)) {
                $file = new File($dst);
                $file->delete();
            }

            if (!move_uploaded_file($json['tmp_name'], $dst)) {
                $this->Flash->danger(__d('user', 'File could not be uploaded, please check write permissions on /tmp directory.'));
            } else {
                $file = new File($dst);
                $info = json_decode($file->read(), true);
                $added = [];
                $error = false;

                if (is_array($info) && !empty($info)) {
                    foreach ($info as $role => $paths) {
                        if (!is_string($role)) {
                            $error = true;
                            $this->Flash->danger(__d('user', 'Given file seems to be corrupt.'));
                            break;
                        }
                        $role = $this->Acos->Roles
                            ->find()
                            ->where(['slug' => $role])
                            ->limit(1)
                            ->first();

                        if (!$role) {
                            continue;
                        }

                        if (is_array($paths)) {
                            foreach ($paths as $path) {
                                $nodes = $this->Acos->node($path);

                                if ($nodes) {
                                    $leaf = $nodes->first();
                                    $exists = $this->Acos->Permissions
                                        ->exists([
                                            'aco_id' => $leaf->id,
                                            'role_id' => $role->id
                                        ]);
                                    if (!$exists) {
                                        $newPermission = $this->Acos->Permissions->newEntity([
                                            'aco_id' => $leaf->id,
                                            'role_id' => $role->id
                                        ]);
                                        if ($this->Acos->Permissions->save($newPermission)) {
                                            $added[] = "<strong>{$role->name}</strong>: {$path}";
                                        }
                                    }
                                }
                            }
                        } else {
                            $error = true;
                            $this->Flash->danger(__d('user', 'Given file seems to be corrupt.'));
                            break;
                        }
                    }
                } else {
                    $error = true;
                    $this->Flash->danger(__d('user', 'Invalid file given.'));
                }

                if (!$error) {
                    if (!empty($added)) {
                        $imported = '<br />' . implode('<br />', $added);
                        $this->Flash->success(__d('user', 'The following entries were imported: {0}', $imported));
                    } else {
                        $this->Flash->success(__d('user', 'Success, but nothing was imported'));
                    }
                }
            }
        }

        $this->title(__d('user', 'Import Permissions'));
        $this->redirect($this->referer());
    }
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
1055982
def _load_json(self):
        
        if os.path.isfile(self.expectations_json):
            self.log.info("Loading expectation config from file {file}".format(file=self.expectations_json))
            return json.load(open(self.expectations_json))
        else:
            self.log.info("Loading expectation config from string")
            return json.loads(self.expectations_json)
223447
def import_from_json(filename_or_fobj, encoding="utf-8", *args, **kwargs):
    

    source = Source.from_file(filename_or_fobj, mode="rb", plugin_name="json", encoding=encoding)

    json_obj = json.load(source.fobj, encoding=source.encoding)
    field_names = list(json_obj[0].keys())
    table_rows = [[item[key] for key in field_names] for item in json_obj]

    meta = {"imported_from": "json", "source": source}
    return create_table([field_names] + table_rows, meta=meta, *args, **kwargs)
77421
def new_profile(self):
        
        # noinspection PyCallByClass,PyTypeChecker
        dir = os.path.join(QgsApplication.qgisSettingsDirPath(),
                           'inasafe', 'minimum_needs')
        file_name, __ = QFileDialog.getSaveFileName(
            self,
            self.tr('Create a minimum needs profile'),
            expanduser(dir),
            self.tr('JSON files (*.json *.JSON)'),
            options=QFileDialog.DontUseNativeDialog)
        if not file_name:
            return
        file_name = basename(file_name)
        if self.profile_combo.findText(file_name) == -1:
            minimum_needs = {
                'resources': [], 'provenance': '', 'profile': file_name}
            self.minimum_needs.update_minimum_needs(minimum_needs)
            self.minimum_needs.save_profile(file_name)
            self.profile_combo.addItem(file_name)
            self.clear_resource_list()
            self.profile_combo.setCurrentIndex(
                self.profile_combo.findText(file_name))
        else:
            self.profile_combo.setCurrentIndex(
                self.profile_combo.findText(file_name))
            self.select_profile_by_name(file_name)