Playback data from an episode.

    Args:
        ep_dir: The path to the directory containing data for an episode.
177113
def playback_trajectory(env, ep_dir):
    

    # first reload the model from the xml
    xml_path = os.path.join(ep_dir, "model.xml")
    with open(xml_path, "r") as f:
        env.reset_from_xml_string(f.read())

    state_paths = os.path.join(ep_dir, "state_*.npz")

    # read states back, load them one by one, and render
    t = 0
    for state_file in sorted(glob(state_paths)):
        print(state_file)
        dic = np.load(state_file)
        states = dic["states"]
        for state in states:
            env.sim.set_state_from_flattened(state)
            env.sim.forward()
            env.render()
            t += 1
            if t % 100 == 0:
                print(t)
1082705
def set_watched(db, aid, ep_type, number):
    """"""
    db.cursor().execute(
        """UPDATE episode SET user_watched=:watched
        WHERE aid=:aid AND type=:type AND number=:number""",
        {
            'aid': aid,
            'type': ep_type,
            'number': number,
            'watched': 1,
        })
267354
def download_series_gui(frame, urls, directory, min_file_size, max_file_size, no_redirects):
	

	# create directory to save files
	if not os.path.exists(directory):
		os.makedirs(directory)
	app = progress_class(frame, urls, directory, min_file_size, max_file_size, no_redirects)
171441
def cd(self, dir_p):
        
        if not isinstance(dir_p, basestring):
            raise TypeError("dir_p can only be an instance of type basestring")
        progress = self._call("cd",
                     in_p=[dir_p])
        progress = IProgress(progress)
        return progress
887983
private static Episode parseEpisode(Element eEpisode, String season) {
        Episode episode = new Episode();
        EpisodeNumber en = new EpisodeNumber();

        en.setSeason(season);
        en.setEpisode(DOMHelper.getValueFromElement(eEpisode, "seasonnum"));
        en.setAbsolute(DOMHelper.getValueFromElement(eEpisode, "epnum"));
        episode.setEpisodeNumber(en);

        episode.setProductionId(DOMHelper.getValueFromElement(eEpisode, "prodnum"));
        episode.setAirDate(DOMHelper.getValueFromElement(eEpisode, AIRDATE));
        episode.setLink(DOMHelper.getValueFromElement(eEpisode, "link"));
        episode.setTitle(DOMHelper.getValueFromElement(eEpisode, TITLE));
        episode.setSummary(DOMHelper.getValueFromElement(eEpisode, SUMMARY));
        episode.setRating(DOMHelper.getValueFromElement(eEpisode, "rating"));
        episode.setScreenCap(DOMHelper.getValueFromElement(eEpisode, "screencap"));

        return episode;
    }
29347
def directory(self, dir_key):
    ''''''
    dir_items = self.get(dir_key)
    if not isinstance(dir_items, list):
      self.put(dir_key, [])
352064
def train_episode(agent, envs, preprocessors, t_max, render):
    """"""
    num_envs = len(envs)

    # Buffers to hold trajectories, e.g. `env_xs[i]` will hold the observations
    # for environment `i`.
    env_xs, env_as = _2d_list(num_envs), _2d_list(num_envs)
    env_rs, env_vs = _2d_list(num_envs), _2d_list(num_envs)
    episode_rs = np.zeros(num_envs, dtype=np.float)

    for p in preprocessors:
        p.reset()

    observations = [p.preprocess(e.reset())
                    for p, e in zip(preprocessors, envs)]

    done = np.array([False for _ in range(num_envs)])
    all_done = False
    t = 1

    while not all_done:
        if render:
            envs[0].render()

        # NOTE(reed): Reshape to set the data shape.
        agent.model.reshape([('data', (num_envs, preprocessors[0].obs_size))])
        step_xs = np.vstack([o.ravel() for o in observations])

        # Get actions and values for all environments in a single forward pass.
        step_xs_nd = mx.nd.array(step_xs, ctx=agent.ctx)
        data_batch = mx.io.DataBatch(data=[step_xs_nd], label=None)
        agent.model.forward(data_batch, is_train=False)
        _, step_vs, _, step_ps = agent.model.get_outputs()

        step_ps = step_ps.asnumpy()
        step_vs = step_vs.asnumpy()
        step_as = agent.act(step_ps)

        # Step each environment whose episode has not completed.
        for i, env in enumerate(envs):
            if not done[i]:
                obs, r, done[i], _ = env.step(step_as[i])

                # Record the observation, action, value, and reward in the
                # buffers.
                env_xs[i].append(step_xs[i].ravel())
                env_as[i].append(step_as[i])
                env_vs[i].append(step_vs[i][0])
                env_rs[i].append(r)
                episode_rs[i] += r

                # Add 0 as the state value when done.
                if done[i]:
                    env_vs[i].append(0.0)
                else:
                    observations[i] = preprocessors[i].preprocess(obs)

        # Perform an update every `t_max` steps.
        if t == t_max:
            # If the episode has not finished, add current state's value. This
            # will be used to 'bootstrap' the final return (see Algorithm S3
            # in A3C paper).
            step_xs = np.vstack([o.ravel() for o in observations])
            step_xs_nd = mx.nd.array(step_xs, ctx=agent.ctx)
            data_batch = mx.io.DataBatch(data=[step_xs_nd], label=None)
            agent.model.forward(data_batch, is_train=False)
            _, extra_vs, _, _ = agent.model.get_outputs()
            extra_vs = extra_vs.asnumpy()
            for i in range(num_envs):
                if not done[i]:
                    env_vs[i].append(extra_vs[i][0])

            # Perform update and clear buffers.
            env_xs = np.vstack(list(chain.from_iterable(env_xs)))
            agent.train_step(env_xs, env_as, env_rs, env_vs)
            env_xs, env_as = _2d_list(num_envs), _2d_list(num_envs)
            env_rs, env_vs = _2d_list(num_envs), _2d_list(num_envs)
            t = 0

        all_done = np.all(done)
        t += 1

    return episode_rs
746611
def check_local() -> None:
    
    to_check = ['./replay', './replay/toDo', './replay/archive']

    for i in to_check:
        if not os.path.exists(i):
            os.makedirs(i)
632089
def check_directory(placeholders):
    
    feed = placeholders.feed
    args = feed.args
    placeholders.directory = "This very directory"  # wink, wink
    placeholders.fullpath = os.path.join(
        placeholders.directory, placeholders.filename)
    try:
        if args["downloaddirectory"]:
            ensure_dir(args["downloaddirectory"])
            placeholders.directory = args["downloaddirectory"]
    except KeyError:
        pass
    download_path = os.path.expanduser(
        feed.retrieve_config("Download Directory", "~/Podcasts"))
    subdirectory = feed.retrieve_config(
        "Create subdirectory", "no")
    if "no" in subdirectory:
        placeholders.directory = download_path
    elif "yes" in subdirectory:
        subdnametemplate = feed.retrieve_config(
            "subdirectory_name", "{podcasttitle}")
        subdname = substitute_placeholders(
            subdnametemplate, placeholders)
        placeholders.directory = os.path.join(download_path, subdname)
    ensure_dir(placeholders.directory)
    placeholders.fullpath = os.path.join(
        placeholders.directory, placeholders.filename)
    return placeholders
48746
def on_episode_begin(self, episode, logs):
        
        assert episode not in self.metrics
        assert episode not in self.starts
        self.metrics[episode] = []
        self.starts[episode] = timeit.default_timer()
829815
def podcast_episode(self, podcast_episode_id):
		

		response = self._call(
			mc_calls.PodcastFetchEpisode,
			podcast_episode_id
		)
		podcast_episode_info = [
			podcast_episode
			for podcast_episode in response.body
			if not podcast_episode['deleted']
		]

		return podcast_episode_info
1059131
def _update_trial_info(self, expr_dir):
        
        trial_id = expr_dir[-8:]

        meta_file = os.path.join(expr_dir, EXPR_META_FILE)
        meta = parse_json(meta_file)

        result_file = os.path.join(expr_dir, EXPR_RESULT_FILE)
        offset = self._result_offsets.get(trial_id, 0)
        results, new_offset = parse_multiple_json(result_file, offset)
        self._add_results(results, trial_id)
        self._result_offsets[trial_id] = new_offset

        if meta:
            TrialRecord.objects \
                .filter(trial_id=trial_id) \
                .update(trial_status=meta["status"],
                        end_time=timestamp2date(meta.get("end_time", None)))
        elif len(results) > 0:
            metrics = {
                "episode_reward": results[-1].get("episode_reward_mean", None),
                "accuracy": results[-1].get("mean_accuracy", None),
                "loss": results[-1].get("loss", None)
            }
            if results[-1].get("done"):
                TrialRecord.objects \
                    .filter(trial_id=trial_id) \
                    .update(trial_status="TERMINATED",
                            end_time=results[-1].get("date", None),
                            metrics=str(metrics))
            else:
                TrialRecord.objects \
                    .filter(trial_id=trial_id) \
                    .update(metrics=str(metrics))
115201
def _start_new_episode(self):
        

        # flush any data left over from the previous episode if any interactions have happened
        if self.has_interaction:
            self._flush()

        # timesteps in current episode
        self.t = 0
        self.has_interaction = False
345100
def add(self, filename):
        """"""
        basename = os.path.basename(filename)
        match = self.regexp.search(basename)
        if match:
            self.by_episode[int(match.group('ep'))].add(filename)
1372033
private function deliver( \ZipArchive &$epub, $src, $dir = ''){
		if( !$dir ){
			$dir = $src;
		}
		if( is_dir($src) ){
			$root = rtrim($src, DIRECTORY_SEPARATOR);
			foreach( scandir($src) as $file ){
				if( !preg_match('/^\./', $file) ){
					// Skip dot files
					$path = $root.DIRECTORY_SEPARATOR.$file;
					$this->deliver($epub, $path, $dir);
				}
			}
		}elseif( file_exists($src) ){
			$relative_path = ltrim(str_replace($dir, '', $src), DIRECTORY_SEPARATOR);
			$epub->addFile($src, $relative_path);
		}else{
			throw new CompileException(sprintf('Cannot copy file %s.', $src));
		}
	}
1062794
def callback_datadirs(attr, old, new):
    ''''''
    import os

    global data

    try:
        # Load data from new data directory
        path_dir = os.path.join(parent_input.value, new)
        data, params_tag, params_data = load_data(path_dir)

        # Make title with new data directory
        p.title.text = 'Calibrating {}'.format(params_tag['experiment'])

        # Update `source` data fields from dataframe
        dt_str = [dt.strftime(dt_fmt) for dt in data['datetimes']]
        source.data = dict(x      = list(data['acceleration_x']),
                           y      = list(data['acceleration_y']),
                           z      = list(data['acceleration_z']),
                           ind    = list(data.index),
                           dt     = list(data['datetimes']),
                           dt_str = dt_str)

        # Update values for control widgets
        param_checkbox.active = [0, 1, 2]
        param_select.options = params_data
        param_select.value = params_data[0]
        regions = ['lower', 'upper']
        region_select.options = regions
        region_select.value = regions[0]
        start_input.value = str(data.index[0])
        end_input.value = str(data.index[-1])
    except Exception as e:
        msg = '''
              Problem loading data directory `{}`.

              Please check that data exists in that directory.

              Details:
              {}
              '''.format(new, e)
        output_window.text = output_template.format(msg)


    return None
708619
def get_episode_types(db) -> Iterator[EpisodeType]:
    """"""
    cur = db.cursor()
    cur.execute('SELECT id, name, prefix FROM episode_type')
    for type_id, name, prefix in cur:
        yield EpisodeType(type_id, name, prefix)