save a data file such that all processes know the game that is running
185406
def save(self, filename=None, debug=False):
        """"""
        if not filename: filename = self.name
        with open(filename, "w") as f: # save config data file
            f.write(self.toJson(self.attrs))
        if self.debug or debug:
            print("saved configuration %s"%(self.name))
            for k,v in sorted(iteritems(self.attrs)):
                print("%15s : %s"%(k,v))
726960
def save(self):
        """"""
        files = [f.depotFile for f in self._files]
        cmd = ['reopen', '-c', 'default']
        self._connection.run(cmd + files)
        self._dirty = False
158821
def _save_cache_to_file(self):
        '''
        
        '''
        if self._cache_dir is None:
            raise DataSourceWithFileCacheError(
                'Use this class with "with statement" if you don\'t specify cache dir.')
        cache_data = OrderedDict()

        def get_data(args):
            pos = args[0]
            q = args[1]
            retry = 1
            while True:
                if retry > 10:
                    logger.log(
                        99, '_get_current_data() retry count over give up.')
                    raise
                d = self._data_source._get_data(pos)
                if d is not None:
                    break
                logger.log(99, '_get_data() fails. retrying count {}/10.'.format(
                           retry))
                retry += 1

            q.put((pos, d))

        q = Queue()
        with closing(ThreadPool(processes=self._num_of_threads)) as pool:
            pool.map(get_data, [(pos, q) for pos in self._cache_positions])

        while len(cache_data) < len(self._cache_positions):
            index, data = q.get()
            cache_data[index] = data
        start_position = self.position - len(cache_data) + 1
        end_position = self.position
        cache_filename = os.path.join(
            self._cache_dir, '{}_{:08d}_{:08d}{}'.format(self._cache_file_name_prefix,
                                                         start_position,
                                                         end_position,
                                                         self._cache_file_format))

        data = OrderedDict([(n, []) for n in self._data_source.variables])
        for pos in sorted(cache_data):
            cd = cache_data[pos]
            for i, n in enumerate(self._data_source.variables):
                if isinstance(cd[i], numpy.ndarray):
                    d = cd[i]
                else:
                    d = numpy.array(cd[i]).astype(numpy.float32)
                data[n].append(d)

        logger.info('Creating cache file {}'.format(cache_filename))
        try:
            if self._cache_file_format == ".h5":
                h5 = h5py.File(cache_filename, 'w')
                for k, v in data.items():
                    h5.create_dataset(k, data=v)
                h5.close()
            else:
                retry_count = 1
                is_create_cache_imcomplete = True
                while is_create_cache_imcomplete:
                    try:
                        with open(cache_filename, 'wb') as f:
                            for v in data.values():
                                numpy.save(f, v)
                        is_create_cache_imcomplete = False
                    except OSError:
                        retry_count += 1
                        if retry_count > 10:
                            raise
                        logger.info(
                            'Creating cache retry {}/10'.format(retry_count))
        except:
            logger.critical(
                'An error occurred while creating cache file from dataset.')
            for k, v in data.items():
                size = v[0].shape
                for d in v:
                    if size != d.shape:
                        logger.critical('The sizes of data "{}" are not the same. ({} != {})'.format(
                            k, size, d.shape))
            raise

        self._cache_file_names.append(cache_filename)
        self._cache_file_order.append(len(self._cache_file_order))
        self._cache_file_data_orders.append(list(range(len(cache_data))))
        self._cache_positions = []
843309
def main(unused_argv):
  """"""
  run_config = run_configs.get()

  if not gfile.Exists(FLAGS.replays):
    sys.exit("{} doesn't exist.".format(FLAGS.replays))

  stats_queue = multiprocessing.Queue()
  stats_thread = threading.Thread(target=stats_printer, args=(stats_queue,))
  stats_thread.start()
  try:
    # For some reason buffering everything into a JoinableQueue makes the
    # program not exit, so save it into a list then slowly fill it into the
    # queue in a separate thread. Grab the list synchronously so we know there
    # is work in the queue before the SC2 processes actually run, otherwise
    # The replay_queue.join below succeeds without doing any work, and exits.
    print("Getting replay list:", FLAGS.replays)
    replay_list = sorted(run_config.replay_paths(FLAGS.replays))
    print(len(replay_list), "replays found.\n")
    replay_queue = multiprocessing.JoinableQueue(FLAGS.parallel * 10)
    replay_queue_thread = threading.Thread(target=replay_queue_filler,
                                           args=(replay_queue, replay_list))
    replay_queue_thread.daemon = True
    replay_queue_thread.start()

    for i in range(FLAGS.parallel):
      p = ReplayProcessor(i, run_config, replay_queue, stats_queue)
      p.daemon = True
      p.start()
      time.sleep(1)  # Stagger startups, otherwise they seem to conflict somehow

    replay_queue.join()  # Wait for the queue to empty.
  except KeyboardInterrupt:
    print("Caught KeyboardInterrupt, exiting.")
  finally:
    stats_queue.put(None)  # Tell the stats_thread to print and exit.
    stats_thread.join()
1331098
def filter_by_program(self, prg, opFile):
        
        log_1 = open(self.process_file, 'r')
        log_2 = open(self.command_file, 'r')
        log_3 = open(self.result_file, 'r')
        log_4 = open(self.source_file, 'r')
        
        with open(opFile, 'a') as f:
            for line in log_1:
                if prg in line:
                    f.write('PROCESS, ' + line)
            for line in log_2:
                if prg in line:
                    f.write('COMMAND, ' + line)
            for line in log_3:
                if prg in line:
                    f.write('RESULT, ' + line)
            for line in log_4:
                if prg in line:
                    f.write('SOURCE, ' + line)
                    
        log_1.close()
        log_2.close()
        log_3.close()
        log_4.close()
1044127
def save(self, *args):
        
        with open(self.file_root + '.pkl', "wb") as f:
            pickle.dump(args, f, protocol=pickle.HIGHEST_PROTOCOL)
1288964
def _read_execute_info(path, parents):
  """"""
  path = os.path.join(path, "StarCraft II/ExecuteInfo.txt")
  if os.path.exists(path):
    with open(path, "rb") as f:  # Binary because the game appends a '\0' :(.
      for line in f:
        parts = [p.strip() for p in line.decode("utf-8").split("=")]
        if len(parts) == 2 and parts[0] == "executable":
          exec_path = parts[1].replace("\\", "/")  # For windows compatibility.
          for _ in range(parents):
            exec_path = os.path.dirname(exec_path)
          return exec_path
859892
def _save(self, url, path, data):
        """"""
        worker = self._workers[url]
        path = self._paths[url]

        if len(data):
            try:
                with open(path, 'wb') as f:
                    f.write(data)
            except Exception:
                logger.error((url, path))

        # Clean up
        worker.finished = True
        worker.sig_download_finished.emit(url, path)
        worker.sig_finished.emit(worker, path, None)
        self._get_requests.pop(url)
        self._workers.pop(url)
        self._paths.pop(url)
397496
function save_allstate() {
    var res = {};

    if (gli_rootwin)
        res.rootwin = gli_rootwin.disprock;

    if (gli_currentstr)
        res.currentstr = gli_currentstr.disprock;

    if (gli_timer_interval)
        res.timer_interval = gli_timer_interval;

    res.windows = [];
    for (var win = gli_windowlist; win; win = win.next) {
        var obj = {
            type: win.type, rock: win.rock, disprock: win.disprock,
            style: win.style, hyperlink: win.hyperlink
        };
        if (win.parent)
            obj.parent = win.parent.disprock;
        obj.str = win.str.disprock;
        if (win.echostr)
            obj.echostr = win.echostr.disprock;

        obj.bbox = { 
            left: win.bbox.left, right: win.bbox.right,
            top: win.bbox.top, bottom: win.bbox.bottom 
        };

        if (win.linebuf !== null) {
            var info = GiDispa.get_retained_array(win.linebuf);
            obj.linebuf = {
                addr: info.addr,
                len: info.len,
                arr: info.arr.slice(0),
                arg: info.arg.serialize()
            };
        }
        obj.char_request = win.char_request;
        obj.line_request = win.line_request;
        obj.char_request_uni = win.char_request_uni;
        obj.line_request_uni = win.line_request_uni;
        obj.hyperlink_request = win.hyperlink_request;
        obj.mouse_request = win.mouse_request;
        obj.echo_line_input = win.echo_line_input;
        obj.request_echo_line_input = win.request_echo_line_input;
        obj.line_input_terminators = win.line_input_terminators.slice(0);
        //### should have a request_line_input_terminators as well

        switch (win.type) {
        case Const.wintype_TextBuffer:
            obj.reserve = win.reserve.slice(0);
            break;
        case Const.wintype_TextGrid:
            obj.gridwidth = win.gridwidth;
            obj.gridheight = win.gridheight;
            obj.lines = [];
            for (var ix=0; ix<win.lines.length; ix++) {
                var ln = win.lines[ix];
                obj.lines.push({
                        chars: ln.chars.slice(0),
                        styles: ln.styles.slice(0),
                        hyperlinks: ln.hyperlinks.slice(0)
                    });
            }
            obj.cursorx = win.cursorx;
            obj.cursory = win.cursory;
            break;
        case Const.wintype_Graphics:
            obj.graphwidth = win.graphwidth;
            obj.graphheight = win.graphheight;
            obj.reserve = win.reserve.slice(0);
            break;
        case Const.wintype_Pair:
            obj.pair_dir = win.pair_dir;
            obj.pair_division = win.pair_division;
            obj.pair_key = win.pair_key.disprock;
            obj.pair_keydamage = false;
            obj.pair_size = win.pair_size;
            obj.pair_hasborder = win.pair_hasborder;
            obj.pair_vertical = win.pair_vertical;
            obj.pair_backward = win.pair_backward;
            obj.child1 = win.child1.disprock;
            obj.child2 = win.child2.disprock;
            break;
        }

        res.windows.push(obj);
    }

    res.streams = [];
    for (var str = gli_streamlist; str; str = str.next) {
        var obj = {
            type: str.type, rock: str.rock, disprock: str.disprock,
            unicode: str.unicode, isbinary: str.isbinary,
            readcount: str.readcount, writecount: str.writecount,
            readable: str.readable, writable: str.writable,
            streaming: str.streaming
        };

        switch (str.type) {

        case strtype_Window:
            if (str.win)
                obj.win = str.win.disprock;
            break;

        case strtype_Memory:
            if (str.buf !== null) {
                var info = GiDispa.get_retained_array(str.buf);
                obj.buf = {
                    addr: info.addr,
                    len: info.len,
                    arr: info.arr.slice(0),
                    arg: info.arg.serialize()
                };
            }
            obj.buflen = str.buflen;
            obj.bufpos = str.bufpos;
            obj.bufeof = str.bufeof;
            break;

        case strtype_Resource:
            obj.resfilenum = str.resfilenum;
            // Don't need str.buf
            obj.buflen = str.buflen;
            obj.bufpos = str.bufpos;
            obj.bufeof = str.bufeof;
            break;

        case strtype_File:
            obj.origfmode = str.origfmode;
            if (!Dialog.streaming) {
                obj.ref = str.ref;
                gli_stream_flush_file(str);
                // Don't need str.buf
                obj.buflen = str.buflen;
                obj.bufpos = str.bufpos;
                obj.bufeof = str.bufeof;
            }
            else {
                str.fstream.fflush();
                obj.ref = str.ref;
                obj.filepos = str.fstream.ftell();
            }
            break;

        }

        res.streams.push(obj);
    }

    res.filerefs = [];
    for (var fref = gli_filereflist; fref; fref = fref.next) {
        var obj = {
            type: fref.type, rock: fref.rock, disprock: fref.disprock,
            filename: fref.filename, textmode: fref.textmode,
            filetype: fref.filetype, filetypename: fref.filetypename
        };

        obj.ref = fref.ref;

        res.filerefs.push(obj);
    }

    // Ignore gli_schannellist, as it's currently always empty.

    /* Save GlkOte-level information. This includes the overall metrics. */
    res.glkote = GlkOte.save_allstate();

    return res;
}
846711
def play(quiet, session_file, shell, speed, prompt, commentecho):
    """"""
    run(
        session_file.readlines(),
        shell=shell,
        speed=speed,
        quiet=quiet,
        test_mode=TESTING,
        prompt_template=prompt,
        commentecho=commentecho,
    )
713581
def save_state(state, output_dir, keep=False):
  """"""
  params_file = os.path.join(output_dir, "model.pkl")
  with gfile.GFile(params_file, "wb") as f:
    pickle.dump((state.params, state.step, state.history), f)
  if keep:
    params_file = os.path.join(output_dir, "model_{}.pkl".format(state.step))
    with gfile.GFile(params_file, "wb") as f:
      pickle.dump((state.params, state.step, state.history), f)
  log("Model saved to %s" % params_file, stdout=False)
1209237
def save_process():
    ''''''
    from MAVProxy.modules.lib import wx_processguard
    from MAVProxy.modules.lib.wx_loader import wx
    from MAVProxy.modules.lib.wxgrapheditor import GraphDialog
    app = wx.App(False)
    frame = GraphDialog('Graph Editor',
                        mestate.last_graph,
                        save_callback)
    frame.ShowModal()
    frame.Destroy()
678853
def save(self, incoming_stream, size_limit=None, size=None,
             chunk_size=None, progress_callback=None):
        """"""
        fp = self.open(mode='wb')
        try:
            bytes_written, checksum = self._write_stream(
                incoming_stream, fp, chunk_size=chunk_size,
                progress_callback=progress_callback,
                size_limit=size_limit, size=size)
        except Exception:
            fp.close()
            self.delete()
            raise
        finally:
            fp.close()

        self._size = bytes_written

        return self.fileurl, bytes_written, checksum
949514
private void save() {
		int resp = saveChooser.showSaveDialog(this);
		if (resp == JFileChooser.APPROVE_OPTION) {
			File out = saveChooser.getSelectedFile();
			
			ArrayList list = new ArrayList();
			for (int i=0;i<sprites.size();i++) {
				list.add(sprites.elementAt(i));
			}
			
			try {
				int b = ((Integer) border.getValue()).intValue();
				pack.packImages(list, twidth, theight, b, out);
			} catch (IOException e) {
				// shouldn't happen 
				e.printStackTrace();
				JOptionPane.showMessageDialog(this, "Failed to write output");
			}
		}
	}
594150
def saveShp(self, target):
        """"""
        if not hasattr(target, "write"):
            target = os.path.splitext(target)[0] + '.shp'
        if not self.shapeType:
            self.shapeType = self._shapes[0].shapeType
        self.shp = self.__getFileObj(target)
        self.__shapefileHeader(self.shp, headerType='shp')
        self.__shpRecords()
712683
def _save_files(self, data, dtype_out_time):
        """"""
        path = self.path_out[dtype_out_time]
        if not os.path.isdir(self.dir_out):
            os.makedirs(self.dir_out)
        if 'reg' in dtype_out_time:
            try:
                reg_data = xr.open_dataset(path)
            except (EOFError, RuntimeError, IOError):
                reg_data = xr.Dataset()
            reg_data.update(data)
            data_out = reg_data
        else:
            data_out = data
        if isinstance(data_out, xr.DataArray):
            data_out = xr.Dataset({self.name: data_out})
        data_out.to_netcdf(path, engine='netcdf4', format='NETCDF3_64BIT')
696389
def _distribute_save_datasets(self, scenes_iter, client, batch_size=1, **kwargs):
        """"""
        def load_data(q):
            idx = 0
            while True:
                future_list = q.get()
                if future_list is None:
                    break

                # save_datasets shouldn't be returning anything
                for future in future_list:
                    future.result()
                    log.info("Finished saving %d scenes", idx)
                    idx += 1
                q.task_done()

        input_q = Queue(batch_size if batch_size is not None else 1)
        load_thread = Thread(target=load_data, args=(input_q,))
        load_thread.start()

        for scene in scenes_iter:
            delayed = scene.save_datasets(compute=False, **kwargs)
            if isinstance(delayed, (list, tuple)) and len(delayed) == 2:
                # TODO Make this work for (source, target) datasets
                # given a target, source combination
                raise NotImplementedError("Distributed save_datasets does not support writers "
                                          "that return (source, target) combinations at this time. Use "
                                          "the non-distributed save_datasets instead.")
            future = client.compute(delayed)
            input_q.put(future)
        input_q.put(None)

        log.debug("Waiting for child thread to get saved results...")
        load_thread.join()
        log.debug("Child thread died successfully")