Save a complete particle system XML description
488819
public void saveSystem() {
		int resp = chooser.showSaveDialog(this);
		if (resp == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			if (!file.getName().endsWith(".xml")) {
				file = new File(file.getAbsolutePath()+".xml");
			}
			
			try {
				ParticleIO.saveConfiguredSystem(file, game.getSystem());
			} catch (IOException e) {
				Log.error(e);
				JOptionPane.showMessageDialog(this, e.getMessage());
			}
		}
	}
555439
def save(self):
        """"""
        spike_clusters = self.clustering.spike_clusters
        groups = {c: self.cluster_meta.get('group', c) or 'unsorted'
                  for c in self.clustering.cluster_ids}
        # List of tuples (field_name, dictionary).
        labels = [(field, self.get_labels(field))
                  for field in self.cluster_meta.fields
                  if field not in ('next_cluster')]
        # TODO: add option in add_field to declare a field unsavable.
        self.emit('request_save', spike_clusters, groups, *labels)
        # Cache the spikes_per_cluster array.
        self._save_spikes_per_cluster()
353519
def save_as(self):
        """"""
        filename = splitext(
                self.parent.notes.annot.xml_file)[0] + '_data'
        filename, _ = QFileDialog.getSaveFileName(self, 'Export analysis data',
                                                  filename,
                                                  'CSV (*.csv)')
        if filename == '':
            return

        self.filename = filename
        short_filename = short_strings(basename(self.filename))
        self.idx_filename.setText(short_filename)
72442
def writeDataTable(self, file, type):
        
        agents = self.experiment.agents
        numAgents = len(self.experiment.agents)

        colWidth = 8
        idxColWidth = 3

        sep = ("=" * idxColWidth) + " " + \
            ("=" * colWidth + " ") * numAgents + "\n"

        file.write(sep)

        # Table column headers.
        file.write("..".rjust(idxColWidth) + " ")
        for agent in agents:
            # The end of the name is typically the unique part.
            file.write(agent.name[-colWidth:].center(colWidth) + " ")
        file.write("\n")

        file.write(sep)

        # Table values.
        if agents:
            rows, _ = agents[0].history.getField( type ).shape
        else:
            rows, _ = (0, 0)

        for sequence in range( min(rows, 999) ):
            file.write( str(sequence + 1).rjust(idxColWidth) + " " )

            for agent in agents:
                field = agent.history.getField( type )
                # FIXME: Handle multiple state values.
                file.write("%8.3f " % field[sequence, 0])

            file.write("\n")

        file.write(sep)
1242831
private void writeModelDetails() throws IOException {
    ModelSchemaV3 modelSchema = (ModelSchemaV3) SchemaServer.schema(3, model).fillFromImpl(model);
    startWritingTextFile("experimental/modelDetails.json");
    writeln(modelSchema.toJsonString());
    finishWritingTextFile();
  }
1058216
def save():
    '''
    '''
    if request.method == 'POST':
        exp_id = session.get('exp_id')
        app.logger.debug('Saving data for %s' %exp_id)

        fields = get_post_fields(request)
        result_file = app.save_data(session=session, content=fields, exp_id=exp_id)

        experiments = app.finish_experiment(session, exp_id)
        app.logger.info('Finished %s, %s remaining.' % (exp_id, len(experiments)))

        # Note, this doesn't seem to be enough to trigger ajax success
        return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 
    return json.dumps({'success':False}), 403, {'ContentType':'application/json'}
99822
def save(self, data, xparent=None):
        
        if xparent is not None:
            elem = ElementTree.SubElement(xparent, 'dict')
        else:
            elem = ElementTree.Element('dict')

        for key, value in sorted(data.items()):
            xitem = ElementTree.SubElement(elem, 'item')
            xitem.set('key', nstr(key))
            XmlDataIO.toXml(value, xitem)

        return elem
807080
def save_xml(self, doc, element):
        ''''''
        element.setAttributeNS(XSI_NS, XSI_NS_S + 'type', 'rtsExt:execution_context_ext')
        element.setAttributeNS(RTS_NS, RTS_NS_S + 'id', self.id)
        element.setAttributeNS(RTS_NS, RTS_NS_S + 'kind', self.kind)
        element.setAttributeNS(RTS_NS, RTS_NS_S + 'rate', str(self.rate))
        for p in self.participants:
            new_element = doc.createElementNS(RTS_NS,
                                              RTS_NS_S + 'Participants')
            p.save_xml(doc, new_element)
            element.appendChild(new_element)
        for p in self.properties:
            new_prop_element = doc.createElementNS(RTS_EXT_NS,
                                                   RTS_EXT_NS_S + 'Properties')
            properties_to_xml(new_prop_element, p, self.properties[p])
            element.appendChild(new_prop_element)
654879
def save_xml(self, doc, element):
        ''''''
        element.setAttributeNS(RTS_NS, RTS_NS_S + 'id', self.id)
        for c in self._config_data:
            new_element = doc.createElementNS(RTS_NS,
                                              RTS_NS_S + 'ConfigurationData')
            c.save_xml(doc, new_element)
            element.appendChild(new_element)
941253
def export(cls, folder, particles, datetimes):
        
        if not os.path.exists(folder):
            os.makedirs(folder)

        particle_path = os.path.join(folder, 'particles.pickle')
        f = open(particle_path, "wb")
        pickle.dump(particles, f)
        f.close()

        datetimes_path = os.path.join(folder, 'datetimes.pickle')
        f = open(datetimes_path, "wb")
        pickle.dump(datetimes, f)
        f.close()
1350850
def save_graph(graphdef):
    ''''''
    if graphdef.filename is None:
        if 'HOME' in os.environ:
            dname = os.path.join(os.environ['HOME'], '.mavproxy')
            if os.path.exists(dname):
                mp_util.mkdir_p(dname)
                graphdef.filename = os.path.join(dname, 'mavgraphs.xml')
        elif 'LOCALAPPDATA' in os.environ:
            dname = os.path.join(os.environ['LOCALAPPDATA'], 'MAVProxy')
            if os.path.exists(dname):
                mp_util.mkdir_p(dname)
                graphdef.filename = os.path.join(dname, 'mavgraphs.xml')
        else:
            graphdef.filename = 'mavgraphs.xml'
    if graphdef.filename is None:
        print("No file to save graph to")
        return
    try:
        graphs = load_graph_xml(open(graphdef.filename).read(), graphdef.filename, load_all=True)
    except Exception:
        graphs = []
    found_name = False
    for i in range(len(graphs)):
        if graphs[i].name == graphdef.name:
            graphs[i] = graphdef
            found_name = True
            break
    if not found_name:
        graphs.append(graphdef)
    pipe_console_input.send("Saving %u graphs to %s" % (len(graphs), graphdef.filename))
    f = open(graphdef.filename, "w")
    f.write("<graphs>\n\n")
    for g in graphs:
        f.write(" <graph name='%s'>\n" % g.name.strip())
        if g.description is None:
            g.description = ''
        f.write("  <description>%s</description>\n" % g.description.strip())
        for e in g.expressions:
            f.write("  <expression>%s</expression>\n" % e.strip())
        f.write(" </graph>\n\n")
    f.write("</graphs>\n")
    f.close()
826725
def pybel_to_json(molecule, name=None):
    
    # Save atom element type and 3D location.
    atoms = [{'element': table.GetSymbol(atom.atomicnum),
              'location': list(atom.coords)}
             for atom in molecule.atoms]
    # Recover auxiliary data, if exists
    for json_atom, pybel_atom in zip(atoms, molecule.atoms):
        if pybel_atom.partialcharge != 0:
            json_atom['charge'] = pybel_atom.partialcharge
        if pybel_atom.OBAtom.HasData('_atom_site_label'):
            obatom = pybel_atom.OBAtom
            json_atom['label'] = obatom.GetData('_atom_site_label').GetValue()
        if pybel_atom.OBAtom.HasData('color'):
            obatom = pybel_atom.OBAtom
            json_atom['color'] = obatom.GetData('color').GetValue()

    # Save number of bonds and indices of endpoint atoms
    bonds = [{'atoms': [b.GetBeginAtom().GetIndex(),
                        b.GetEndAtom().GetIndex()],
              'order': b.GetBondOrder()}
             for b in ob.OBMolBondIter(molecule.OBMol)]
    output = {'atoms': atoms, 'bonds': bonds, 'units': {}}

    # If there's unit cell data, save it to the json output
    if hasattr(molecule, 'unitcell'):
        uc = molecule.unitcell
        output['unitcell'] = [[v.GetX(), v.GetY(), v.GetZ()]
                              for v in uc.GetCellVectors()]
        density = (sum(atom.atomicmass for atom in molecule.atoms) /
                   (uc.GetCellVolume() * 0.6022))
        output['density'] = density
        output['units']['density'] = 'kg / L'

    # Save the formula to json. Use Hill notation, just to have a standard.
    element_count = Counter(table.GetSymbol(a.atomicnum) for a in molecule)
    hill_count = []
    for element in ['C', 'H']:
        if element in element_count:
            hill_count += [(element, element_count[element])]
            del element_count[element]
    hill_count += sorted(element_count.items())

    # If it's a crystal, then reduce the Hill formula
    div = (reduce(gcd, (c[1] for c in hill_count))
           if hasattr(molecule, 'unitcell') else 1)

    output['formula'] = ''.join(n if c / div == 1 else '%s%d' % (n, c / div)
                                for n, c in hill_count)
    output['molecular_weight'] = molecule.molwt / div
    output['units']['molecular_weight'] = 'g / mol'

    # If the input has been given a name, add that
    if name:
        output['name'] = name

    return output
1311035
def save_template
      path = "/tmp/ufo/#{@stack_name}/stack.yml"
      FileUtils.mkdir_p(File.dirname(path))
      IO.write(path, template_body)
      puts "Generated template saved at: #{path}"

      path = "/tmp/ufo/#{@stack_name}/parameters.yml"
      IO.write(path, JSON.pretty_generate(parameters))
      puts "Generated parameters saved at: #{path}"
    end
226275
def getMissionXML(summary):
    ''' '''
    spawn_end_tag = ' type="mob_spawner" variant="' + MOB_TYPE + '"/>'
    return '''<?xml version="1.0" encoding="UTF-8" ?>
    <Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <About>
            <Summary>''' + summary + '''</Summary>
        </About>

        <ModSettings>
            <MsPerTick>20</MsPerTick>
        </ModSettings>
        <ServerSection>
            <ServerInitialConditions>
                <Time>
                    <StartTime>13000</StartTime>
                    <AllowPassageOfTime>false</AllowPassageOfTime>
                </Time>
                <AllowSpawning>true</AllowSpawning>
                <AllowedMobs>''' + MOB_TYPE + '''</AllowedMobs>
            </ServerInitialConditions>
            <ServerHandlers>
                <FlatWorldGenerator generatorString="3;7,220*1,5*3,2;3;,biome_1" />
                <DrawingDecorator>
                    <DrawCuboid ''' + getCorner("1",True,True,expand=1) + " " + getCorner("2",False,False,y=226,expand=1) + ''' type="stone"/>
                    <DrawCuboid ''' + getCorner("1",True,True,y=207) + " " + getCorner("2",False,False,y=226) + ''' type="air"/>

                    <DrawLine ''' + getCorner("1",True,True) + " " + getCorner("2",True,False) + spawn_end_tag + '''
                    <DrawLine ''' + getCorner("1",True,True) + " " + getCorner("2",False,True) + spawn_end_tag + '''
                    <DrawLine ''' + getCorner("1",False,False) + " " + getCorner("2",True,False) + spawn_end_tag + '''
                    <DrawLine ''' + getCorner("1",False,False) + " " + getCorner("2",False,True) + spawn_end_tag + '''
                    <DrawCuboid x1="-1" y1="206" z1="-1" x2="1" y2="206" z2="1" ''' + spawn_end_tag + '''
                    ''' + getItemXML() + '''
                </DrawingDecorator>
                <ServerQuitWhenAnyAgentFinishes />
            </ServerHandlers>
        </ServerSection>

        <AgentSection mode="Survival">
            <Name>The Hunted</Name>
            <AgentStart>
                <Placement x="0.5" y="207.0" z="0.5"/>
                <Inventory>
                </Inventory>
            </AgentStart>
            <AgentHandlers>
                <ChatCommands/>
                <ContinuousMovementCommands turnSpeedDegs="360"/>
                <AbsoluteMovementCommands/>
                <ObservationFromNearbyEntities>
                    <Range name="entities" xrange="'''+str(ARENA_WIDTH)+'''" yrange="2" zrange="'''+str(ARENA_BREADTH)+'''" />
                </ObservationFromNearbyEntities>
                <ObservationFromFullStats/>
                <RewardForCollectingItem>
                    <Item type="'''+GOAL_TYPE+'''" reward="'''+str(GOAL_REWARD)+'''"/>
                </RewardForCollectingItem>''' + malmoutils.get_video_xml(agent_host) + '''
            </AgentHandlers>
        </AgentSection>

    </Mission>'''
746407
def save_controls(self, parameterstep: 'timetools.PeriodConstrArg' = None,
                      simulationstep: 'timetools.PeriodConstrArg' = None,
                      auxfiler: 'Optional[auxfiletools.Auxfiler]' = None):
        """"""
        if auxfiler:
            auxfiler.save(parameterstep, simulationstep)
        for element in printtools.progressbar(self):
            element.model.parameters.save_controls(
                parameterstep=parameterstep,
                simulationstep=simulationstep,
                auxfiler=auxfiler)
433151
private void saveMatrix() {

		for (String chainId : currentChainIDs) {
			BiologicalAssemblyTransformation transformation = new BiologicalAssemblyTransformation();
			transformation.setRotationMatrix(currentMatrix.getArray());
			transformation.setTranslation(shift);
			transformation.setId(String.valueOf(modelNumber));
			transformation.setChainId(chainId);
			transformations.add(transformation);
		}

		if (!transformationMap.containsKey(currentBioMolecule)) {
			BioAssemblyInfo bioAssembly = new BioAssemblyInfo();
			bioAssembly.setId(currentBioMolecule);
			bioAssembly.setTransforms(transformations);
			transformationMap.put(currentBioMolecule,bioAssembly);
		}
	}
904452
def save_to_object(self):
        

        tmpdir = tempfile.mkdtemp("save_to_object", dir=self.logdir)
        checkpoint_prefix = self.save(tmpdir)

        data = {}
        base_dir = os.path.dirname(checkpoint_prefix)
        for path in os.listdir(base_dir):
            path = os.path.join(base_dir, path)
            if path.startswith(checkpoint_prefix):
                with open(path, "rb") as f:
                    data[os.path.basename(path)] = f.read()

        out = io.BytesIO()
        data_dict = pickle.dumps({
            "checkpoint_name": os.path.basename(checkpoint_prefix),
            "data": data,
        })
        if len(data_dict) > 10e6:  # getting pretty large
            logger.info("Checkpoint size is {} bytes".format(len(data_dict)))
        out.write(data_dict)

        shutil.rmtree(tmpdir)
        return out.getvalue()