Construct EstimatorSpec for EVAL mode.
978880
def estimator_spec_eval(
      self, features, logits, labels, loss, restore_hook, use_tpu):
    """"""
    hparams = self.hparams
    problem = hparams.problem
    if logits.get_shape().ndims == 3:
      logits = tf.expand_dims(tf.expand_dims(logits, 2), 3)

    # Support for multiproblem
    task_list = [problem]
    if hasattr(problem, "task_list"):
      task_list = problem.task_list

    eval_metrics_fns = metrics.create_evaluation_metrics(task_list, hparams)

    if use_tpu:
      def metric_fn(tf_logits, labels):
        with tf.device("cpu:0"), mtf.utils.outside_all_rewrites():
          eval_metrics = {}
          for metric_name, metric_fn in six.iteritems(eval_metrics_fns):
            if metric_name.split("/")[-1] not in t2t_model.TPU_METRIC_BLACKLIST:
              eval_metrics[metric_name] = metric_fn(
                  tf_logits, None, tf.identity(labels))
          return eval_metrics
      return tpu_estimator.TPUEstimatorSpec(
          tf.estimator.ModeKeys.EVAL,
          evaluation_hooks=[restore_hook],
          loss=loss,
          eval_metrics=(metric_fn, [logits, labels]))
    else:
      eval_metrics = {}
      predictions = {"predictions": logits}
      for metric_name, metric_fn in six.iteritems(eval_metrics_fns):
        eval_metrics[metric_name] = metric_fn(logits, features,
                                              features["targets"])

      return tf.estimator.EstimatorSpec(
          tf.estimator.ModeKeys.EVAL,
          predictions=predictions,
          eval_metric_ops=eval_metrics,
          evaluation_hooks=[restore_hook],
          loss=loss)
639318
def _make_eval_func(self, tensors, session, feed_dict, fetches,
                      callback=None):
    """"""
    if not isinstance(tensors, list):
      tensors = [tensors]
    num_tensors = len(tensors)

    def eval_func(x):
      """Function to evaluate a `Tensor`."""
      shapes = dict(zip(self._vars, self._var_shapes))
      augmented_feed_dict = {
          var: x[packing_slice].reshape(shapes[var])
          for var, packing_slice in zip(self._vars, self._packing_slices)
      }
      augmented_feed_dict.update(feed_dict)
      augmented_fetches = tensors + fetches

      augmented_fetch_vals = session.run(
          augmented_fetches, feed_dict=augmented_feed_dict)

      if callable(callback):
        callback(*augmented_fetch_vals[num_tensors:])

      return augmented_fetch_vals[:num_tensors]

    return eval_func
524077
def exec_then_eval(code, namespace=None):
    """"""
    # TODO: make this less brittle.
    namespace = namespace or {}

    block = ast.parse(code, mode='exec')
    last = ast.Expression(block.body.pop().value)

    exec(compile(block, '<string>', mode='exec'), namespace)
    return eval(compile(last, '<string>', mode='eval'), namespace)
750354
function evalConfig(configStr) {
    var configArr = configStr,
        config = {};

    configStr = configStr.replace(/\{/, '');
    configArr = configStr.split(',');

    configArr.forEach(function (item) {
        var index, key, value;

        index = item.indexOf(':');
        key = item.slice(0, index).replace(/['"]/g, '');
        value = item.slice(index + 1);

        key = key.trim();
        value = value.trim();

        try {
            value = eval('(function(){return ' + value + '})()');
            config[key] = value;
        } catch (_) {}
    });

    return config;
}
711473
def create_estimator(model_name,
                     hparams,
                     run_config,
                     schedule="train_and_evaluate",
                     decode_hparams=None,
                     use_tpu=False,
                     use_tpu_estimator=False,
                     use_xla=False):
  """"""
  model_fn = t2t_model.T2TModel.make_estimator_model_fn(
      model_name, hparams, decode_hparams=decode_hparams, use_tpu=use_tpu)


  del use_xla
  if use_tpu or use_tpu_estimator:
    problem = hparams.problem
    batch_size = (
        problem.tpu_batch_size_per_shard(hparams) *
        run_config.tpu_config.num_shards)
    mlperf_log.transformer_print(
        key=mlperf_log.INPUT_BATCH_SIZE, value=batch_size)
    if getattr(hparams, "mtf_mode", False):
      batch_size = problem.tpu_batch_size_per_shard(hparams)
    predict_batch_size = batch_size
    if decode_hparams and decode_hparams.batch_size:
      predict_batch_size = decode_hparams.batch_size
    if decode_hparams and run_config.tpu_config:
      decode_hparams.add_hparam("iterations_per_loop",
                                run_config.tpu_config.iterations_per_loop)
    estimator = tf.contrib.tpu.TPUEstimator(
        model_fn=model_fn,
        model_dir=run_config.model_dir,
        config=run_config,
        use_tpu=use_tpu,
        train_batch_size=batch_size,
        eval_batch_size=batch_size if "eval" in schedule else None,
        predict_batch_size=predict_batch_size,
        experimental_export_device_assignment=True)
  else:
    estimator = tf.estimator.Estimator(
        model_fn=model_fn,
        model_dir=run_config.model_dir,
        config=run_config,
    )
  return estimator
770526
def _exec_eval(data, expr):
  
  ns = {}
  exec(data, ns)
  return eval(expr, ns)
419038
def eval(self, iteration, feval):
        """""""
        return self.bst.eval_set(self.watchlist, iteration, feval)
1146930
def predict(self, testing_features):
        """"""
        # print("best_inds:",self._best_inds)
        # print("best estimator size:",self._best_estimator.coef_.shape)
        if self.clean:
            testing_features = self.impute_data(testing_features)

        if self._best_inds:
            X_transform = self.transform(testing_features)
            try:
                return self._best_estimator.predict(self.transform(testing_features))
            except ValueError as detail:
                # pdb.set_trace()
                print('shape of X:',testing_features.shape)
                print('shape of X_transform:',X_transform.transpose().shape)
                print('best inds:',self.stacks_2_eqns(self._best_inds))
                print('valid locs:',self.valid_loc(self._best_inds))
                raise ValueError(detail)
        else:
            return self._best_estimator.predict(testing_features)
110557
private static String do_eval(Context cx, StackFrame frame, String expr) {
        String resultString;
        Debugger saved_debugger = cx.getDebugger();
        Object saved_data = cx.getDebuggerContextData();
        int saved_level = cx.getOptimizationLevel();

        cx.setDebugger(null, null);
        cx.setOptimizationLevel(-1);
        cx.setGeneratingDebug(false);
        try {
            Callable script = (Callable)cx.compileString(expr, "", 0, null);
            Object result = script.call(cx, frame.scope, frame.thisObj,
                                        ScriptRuntime.emptyArgs);
            if (result == Undefined.instance) {
                resultString = "";
            } else {
                resultString = ScriptRuntime.toString(result);
            }
        } catch (Exception exc) {
            resultString = exc.getMessage();
        } finally {
            cx.setGeneratingDebug(true);
            cx.setOptimizationLevel(saved_level);
            cx.setDebugger(saved_debugger, saved_data);
        }
        if (resultString == null) {
            resultString = "null";
        }
        return resultString;
    }
627569
def _eval_wrapper(self, fit_key, q, chiA, chiB, **kwargs):
        
        chiA = np.array(chiA)
        chiB = np.array(chiB)

        # Warn/Exit if extrapolating
        allow_extrap = kwargs.pop('allow_extrap', False)
        self._check_param_limits(q, chiA, chiB, allow_extrap)

        self._check_unused_kwargs(kwargs)

        x = [q, chiA[2], chiB[2]]
        if fit_key == 'mf' or fit_key == 'all':
            mf, mf_err = self._evaluate_fits(x, 'mf')
            if fit_key == 'mf':
                return mf, mf_err
        if fit_key == 'chif' or fit_key == 'all':
            chifz, chifz_err = self._evaluate_fits(x, 'chifz')
            chif = np.array([0,0,chifz])
            chif_err = np.array([0,0,chifz_err])
            if fit_key == 'chif':
                return chif, chif_err
        if fit_key == 'vf' or fit_key == 'all':
            vfx, vfx_err = self._evaluate_fits(x, 'vfx')
            vfy, vfy_err = self._evaluate_fits(x, 'vfy')
            vf = np.array([vfx, vfy, 0])
            vf_err = np.array([vfx_err, vfy_err, 0])
            if fit_key == 'vf':
                return vf, vf_err
        if fit_key == 'all':
            return mf, chif, vf, mf_err, chif_err, vf_err
985764
def _eval_args(args):
    """"""
    res = []
    for arg in args:
        if not isinstance(arg, tuple):
            res.append(arg)
        elif is_callable_type(arg[0]):
            callable_args = _eval_args(arg[1:])
            if len(arg) == 2:
                res.append(Callable[[], callable_args[0]])
            elif arg[1] is Ellipsis:
                res.append(Callable[..., callable_args[1]])
            else:
                res.append(Callable[list(callable_args[:-1]), callable_args[-1]])
        else:
            res.append(type(arg[0]).__getitem__(arg[0], _eval_args(arg[1:])))
    return tuple(res)
973252
function evalModule( source, context ) {

    const argumentKeys = Object.keys( context );
    const argumentValues = argumentKeys.map( argument => context[ argument ] );

    const sandbox = { exports: {} };
    argumentKeys.push( "module", "exports", source );
    argumentValues.push( sandbox, sandbox.exports );

    Function( ...argumentKeys )( ...argumentValues );

    return sandbox.exports;

}
711896
public Object eval( CallStack callstack, Interpreter interpreter )
        throws EvalError
    {
        if ( paramTypes != null )
            return paramTypes;

        insureParsed();
        Class [] paramTypes = new Class[numArgs];

        for(int i=0; i<numArgs; i++)
        {
            BSHFormalParameter param = (BSHFormalParameter)jjtGetChild(i);
            paramTypes[i] = (Class)param.eval( callstack, interpreter );
        }

        this.paramTypes = paramTypes;

        return paramTypes;
    }
66026
def eval(cls, exp, files=None):
        
        return cls.show(cls.get(exp, files=files))
1302033
def make_eval_fn_with_agent(
    agent_type, eval_mode, planner_hparams, model_dir, log_every_steps=None,
    video_writers=(), random_starts_step_limit=None
):
  """"""
  def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp):
    """Eval function."""
    base_env = env
    env = rl_utils.BatchStackWrapper(env, loop_hparams.frame_stack_size)
    agent = make_agent_from_hparams(
        agent_type, base_env, env, loop_hparams, policy_hparams,
        planner_hparams, model_dir, policy_dir, sampling_temp, video_writers
    )

    if eval_mode == "agent_simulated":
      real_env = base_env.new_like(batch_size=1)
      stacked_env = rl_utils.BatchStackWrapper(
          real_env, loop_hparams.frame_stack_size
      )
      collect_frames_for_random_starts(
          real_env, stacked_env, agent, loop_hparams.frame_stack_size,
          random_starts_step_limit, log_every_steps
      )
      initial_frame_chooser = rl_utils.make_initial_frame_chooser(
          real_env, loop_hparams.frame_stack_size,
          simulation_random_starts=True,
          simulation_flip_first_random_for_beginning=False,
          split=None,
      )
      env_fn = rl.make_simulated_env_fn_from_hparams(
          real_env, loop_hparams, batch_size=loop_hparams.eval_batch_size,
          initial_frame_chooser=initial_frame_chooser, model_dir=model_dir
      )
      sim_env = env_fn(in_graph=False)
      env = rl_utils.BatchStackWrapper(sim_env, loop_hparams.frame_stack_size)

    kwargs = {}
    if not agent.records_own_videos:
      kwargs["video_writers"] = video_writers
    step_limit = base_env.rl_env_max_episode_steps
    if step_limit == -1:
      step_limit = None
    rl_utils.run_rollouts(
        env, agent, env.reset(), log_every_steps=log_every_steps,
        step_limit=step_limit, **kwargs
    )
    if eval_mode == "agent_real":
      assert len(base_env.current_epoch_rollouts()) == env.batch_size
  return eval_fn
268240
def do_eval(self, inputs, ctx):
        """"""
        return cwltool.expression.do_eval(
            self.expr, inputs, self.req, None, None, {}, context=ctx)
739239
private void buildPluralMethod(
      TypeSpec.Builder type, String pluralType, Map<String, PluralData> pluralMap, Map<String, FieldSpec> fieldMap) {

    MethodSpec.Builder method = MethodSpec.methodBuilder("eval" + pluralType)
        .addModifiers(PUBLIC)
        .addParameter(String.class, "language")
        .addParameter(NUMBER_OPERANDS, "o")
        .returns(PLURAL_CATEGORY);

    method.beginControlFlow("switch (language)");

    List<MethodSpec> ruleMethods = new ArrayList<>();
    for (Map.Entry<String, PluralData> entry : pluralMap.entrySet()) {
      String language = entry.getKey();
      String methodName = String.format("eval%s%s", pluralType, language.toUpperCase());
      method.addStatement("case $S:\n  return $L(o)", language, methodName);

      MethodSpec ruleMethod = buildRuleMethod(methodName, entry.getValue(), fieldMap);
      ruleMethods.add(ruleMethod);
    }

    method.addStatement("default:\n  return null");

    method.endControlFlow();
    type.addMethod(method.build());

    for (MethodSpec ruleMethod : ruleMethods) {
      type.addMethod(ruleMethod);
    }
  }