save feature index
967608
private void saveFeatureIndexes(FeatureIndex[] index, String outputDir) throws IOException
	{
		logger.info("");

		// save the indexes
		for (int i=0;i<index.length;i++)
		{
			logger.debug("dic" + i + " size " + index[i].size());

			File tmp = new File(outputDir + "dic" + i);
			//File tmp = File.createTempFile("dic" + i, null);
			//tmp.deleteOnExit();

			BufferedWriter bwd = new BufferedWriter(new FileWriter(tmp));
			index[i].write(bwd);
			bwd.close();

			// add the dictionary to the model
			//model.add(tmp, "dic" + i);
		} // end for
	}
1369620
public void saveToFilename(String file) {
    try {
      File tgtFile = new File(file);
      BufferedWriter out = new BufferedWriter(new FileWriter(tgtFile));
      // output index first, blank delimiter, outline feature index, then weights
      labelIndex.saveToWriter(out);
      featureIndex.saveToWriter(out);
      int numLabels = labelIndex.size();
      int numFeatures = featureIndex.size();
      for (int featIndex=0; featIndex<numFeatures; featIndex++) {
        for (int labelIndex=0;labelIndex<numLabels;labelIndex++) {
          out.write(String.valueOf(featIndex));
          out.write(TEXT_SERIALIZATION_DELIMITER);
          out.write(String.valueOf(labelIndex));
          out.write(TEXT_SERIALIZATION_DELIMITER);
          out.write(String.valueOf(weight(featIndex, labelIndex)));
          out.write("\n");
        }
      }

      // write out thresholds: first item after blank is the number of thresholds, after is the threshold array values.
      out.write("\n");
      out.write(String.valueOf(thresholds.length));
      out.write("\n");
      for (double val : thresholds) {
        out.write(String.valueOf(val));
        out.write("\n");
      }
      out.close();
    } catch (Exception e) {
      System.err.println("Error attempting to save classifier to file="+file);
      e.printStackTrace();
    }
  }
1298677
private FeatureIndex[] createFeatureIndex(int subspaceCount) // throws
                                                                 // Exception
    {
        logger.info("");

        FeatureIndex[] index = new FeatureIndex[subspaceCount];
        for (int i = 0; i < subspaceCount; i++)
            index[i] = new FeatureIndex(false, 1);

        return index;
    }
513242
def save_as outfile
      _t = "(all rows)"
      if @selected_indices.size > 0
        _t = "(selected rows)"
      end
      unless outfile
        outfile = get_string "Enter file name to save #{_t} as "
        return unless outfile
      end

      # if there is a selection, then write only selected rows
      l = nil
      if @selected_indices.size > 0
        l = []
        @list.each_with_index { |v,i| l << v if @selected_indices.include? i }
      else
        l = @list
      end

      File.open(outfile, 'w') {|f|
        l.each {|r|
          line = r.join "\t"
          f.puts line
        }
      }
    end
165393
def reindex_model_on_save(sender, document, **kwargs):
    ''''''
    if current_app.config.get('AUTO_INDEX'):
        reindex.delay(document)
258409
function saveIndexInfo() {

    // reset the cache
    var tmpCache = cache.idxInfo;
    cache.idxInfo = {};

    var promises = [];

    // add promise for each things being saved/updated
    _.each(tmpCache, function (idxInfo, key) {
        var where = { str: key };
        var select = '_id count';

        var promise = IdxInfoModel.findOne(where, select).exec()
            .then(function (savedItem) {
                if (savedItem) {
                    return IdxInfoModel.findOneAndUpdate(where, { $inc: { count: idxInfo.count }});
                }
                else {
                    var model = new IdxInfoModel(idxInfo);
                    var deferred = Q.defer();
                    model.save(function (modelErr) {
                        modelErr ? deferred.reject(modelErr) : deferred.resolve(model.toObject());
                    });
                    return deferred.promise;
                }
            });

        promises.push(promise);
    });

    return Q.all(promises);
}
1115301
def dump_index(args, idx):
    """"""

    import csv
    import sys

    from metatab import MetatabDoc

    doc = MetatabDoc()

    pack_section = doc.new_section('Packages', ['Identifier', 'Name', 'Nvname', 'Version', 'Format'])

    r = doc['Root']
    r.new_term('Root.Title', 'Package Index')

    for p in idx.list():

        pack_section.new_term('Package',
                   p['url'],
                   identifier=p['ident'],
                   name=p['name'],
                   nvname=p['nvname'],
                   version=p['version'],
                   format=p['format'])

    doc.write_csv(args.dump)
690743
def indexXY(self, index):
        
        rect = self.visualRect(index)
        return rect.x(), rect.y()
1156172
def write_index(fn, index):
    
    with open(fn, "wb") as o_file:
        o_file.write(_CHECK_STRING)
        o_file.write(zlib.compress(bytes(
            index.to_csv(None, index=False, encoding="utf-8"),
            encoding="utf-8",
        )))
451473
def save_indexed_audio(self, indexed_audio_file_abs_path):
        
        with open(indexed_audio_file_abs_path, "wb") as f:
            pickle.dump(self.get_timestamps(), f, pickle.HIGHEST_PROTOCOL)
105877
def _save_until_eos(ids, skip=False):
  """"""
  ids = ids.flatten()
  if skip:
    return ids
  try:
    index = list(ids).index(text_encoder.EOS_ID)
    return ids[0:index]
  except ValueError:
    # No EOS_ID: return the array as-is.
    return ids
268459
def feature_subset(self, indices):
        
        if isinstance(indices, np.ndarray):
            indices = indices.tolist()
        if not isinstance(indices, list):
            raise ValueError('Can only index with lists')
        return [self.features_[i] for i in indices]
1350307
def _index_file(self):
        
        with self.filename.open() as fd:
            data = fd.read()

        ident = "Contour in frame"
        self._data = data.split(ident)[1:]
        self._initialized = True
245638
def _feature_file(self, parallel = None, index = None):
    """"""
    if index is None:
      index = 0 if parallel is None or "SGE_TASK_ID" not in os.environ else int(os.environ["SGE_TASK_ID"])
    return os.path.join(self.feature_directory, "Features_%02d.hdf5" % index)
427501
def save_dictionary(data, filename):
    """"""
    filename = osp.abspath(filename)
    old_cwd = getcwd()
    os.chdir(osp.dirname(filename))
    error_message = None
    skipped_keys = []
    data_copy = {}

    try:
        # Copy dictionary before modifying it to fix #6689
        for obj_name, obj_value in data.items():
            # Skip modules, since they can't be pickled, users virtually never
            # would want them to be and so they don't show up in the skip list.
            # Skip callables, since they are only pickled by reference and thus
            # must already be present in the user's environment anyway.
            if not (callable(obj_value) or isinstance(obj_value,
                                                      types.ModuleType)):
                # If an object cannot be deepcopied, then it cannot be pickled.
                # Ergo, we skip it and list it later.
                try:
                    data_copy[obj_name] = copy.deepcopy(obj_value)
                except Exception:
                    skipped_keys.append(obj_name)
        data = data_copy
        if not data:
            raise RuntimeError('No supported objects to save')

        saved_arrays = {}
        if load_array is not None:
            # Saving numpy arrays with np.save
            arr_fname = osp.splitext(filename)[0]
            for name in list(data.keys()):
                try:
                    if isinstance(data[name],
                                  np.ndarray) and data[name].size > 0:
                        # Save arrays at data root
                        fname = __save_array(data[name], arr_fname,
                                             len(saved_arrays))
                        saved_arrays[(name, None)] = osp.basename(fname)
                        data.pop(name)
                    elif isinstance(data[name], (list, dict)):
                        # Save arrays nested in lists or dictionaries
                        if isinstance(data[name], list):
                            iterator = enumerate(data[name])
                        else:
                            iterator = iter(list(data[name].items()))
                        to_remove = []
                        for index, value in iterator:
                            if isinstance(value,
                                          np.ndarray) and value.size > 0:
                                fname = __save_array(value, arr_fname,
                                                     len(saved_arrays))
                                saved_arrays[(name, index)] = (
                                    osp.basename(fname))
                                to_remove.append(index)
                        for index in sorted(to_remove, reverse=True):
                            data[name].pop(index)
                except (RuntimeError, pickle.PicklingError, TypeError,
                        AttributeError, IndexError):
                    # If an array can't be saved with numpy for some reason,
                    # leave the object intact and try to save it normally.
                    pass
            if saved_arrays:
                data['__saved_arrays__'] = saved_arrays

        pickle_filename = osp.splitext(filename)[0] + '.pickle'
        # Attempt to pickle everything.
        # If pickling fails, iterate through to eliminate problem objs & retry.
        with open(pickle_filename, 'w+b') as fdesc:
            try:
                pickle.dump(data, fdesc, protocol=2)
            except (pickle.PicklingError, AttributeError, TypeError,
                    ImportError, IndexError, RuntimeError):
                data_filtered = {}
                for obj_name, obj_value in data.items():
                    try:
                        pickle.dumps(obj_value, protocol=2)
                    except Exception:
                        skipped_keys.append(obj_name)
                    else:
                        data_filtered[obj_name] = obj_value
                if not data_filtered:
                    raise RuntimeError('No supported objects to save')
                pickle.dump(data_filtered, fdesc, protocol=2)

        # Use PAX (POSIX.1-2001) format instead of default GNU.
        # This improves interoperability and UTF-8/long variable name support.
        with tarfile.open(filename, "w", format=tarfile.PAX_FORMAT) as tar:
            for fname in ([pickle_filename]
                          + [fn for fn in list(saved_arrays.values())]):
                tar.add(osp.basename(fname))
                os.remove(fname)
    except (RuntimeError, pickle.PicklingError, TypeError) as error:
        error_message = to_text_string(error)
    else:
        if skipped_keys:
            skipped_keys.sort()
            error_message = ('Some objects could not be saved: '
                             + ', '.join(skipped_keys))
    finally:
        os.chdir(old_cwd)
    return error_message
775988
def dump_index(self, obj):
        """"""
        if isinstance(obj, PIDNodeOrdered) and self._is_child(obj):
            return obj.index(self.context['pid'])
        else:
            return None
1296758
def __wrap_index(self):
        """"""
        if self.current_index < 0:
            self.current_index = len(self.gui_buttons) - 1
        elif self.current_index >= len(self.gui_buttons):
            self.current_index = 0