text:
<?php

namespace Oro\Component\Action\Tests\Unit\Action;

use Oro\Component\Action\Action\TreeExecutor;

class TreeExecutorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var TreeExecutor
     */
    protected $listAction;

    /**
     * @var \PHPUnit_Framework_MockObject_MockBuilder
     */
    protected $actionBuilder;

    protected function setUp()
    {
        $this->listAction = new TreeExecutor();
    }

    protected function tearDown()
    {
        unset($this->listAction);
    }

    public function testAddAction()
    {
        $expectedActions = array();
        for ($i = 0; $i < 3; $i++) {
            $action = $this->getActionMock();
            $breakOnFailure = (bool)$i % 2;
            $this->listAction->addAction($action, $breakOnFailure);
            $expectedActions[] = array(
                'instance' => $action,
                'breakOnFailure' => $breakOnFailure
            );
        }

        $this->assertAttributeEquals($expectedActions, 'actions', $this->listAction);
    }

    public function testExecute()
    {
        $context = array(1, 2, 3);

        for ($i = 0; $i < 3; $i++) {
            $action = $this->getActionMock();
            $action->expects($this->once())
                ->method('execute')
                ->with($context);
            $this->listAction->addAction($action);
        }

        $dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcher')
            ->disableOriginalConstructor()
            ->getMock();
        $this->listAction->setDispatcher($dispatcher);

        $this->listAction->execute($context);
    }

    /**
     * @expectedException \Exception
     * @expectedExceptionMessage TEST
     */
    public function testBreakOnFailureEnabledException()
    {
        $actionError = $this->getExceptionAction();
        $action = $this->getMockBuilder('Oro\Component\Action\Action\ActionInterface')
            ->getMockForAbstractClass();
        $action->expects($this->never())
            ->method('execute');

        $dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcher')
            ->disableOriginalConstructor()
            ->getMock();
        $this->listAction->setDispatcher($dispatcher);
        $this->listAction->addAction($actionError, true);
        $this->listAction->addAction($action);
        $this->listAction->execute(array());
    }

    public function testBreakOnFailureDisabledException()
    {
        $actionError = $this->getExceptionAction();
        $action = $this->getMockBuilder('Oro\Component\Action\Action\ActionInterface')
            ->getMockForAbstractClass();
        $action->expects($this->once())
            ->method('execute');

        $dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcher')
            ->disableOriginalConstructor()
            ->getMock();
        $this->listAction->setDispatcher($dispatcher);
        $this->listAction->addAction($actionError, false);
        $this->listAction->addAction($action);
        $this->listAction->execute(array());
    }

    public function testBreakOnFailureDisabledLogException()
    {
        $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')
            ->getMockForAbstractClass();
        $logger->expects($this->once())
            ->method('log')
            ->with('ALERT', 'TEST');
        $listAction = new TreeExecutor($logger);
        $dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcher')
            ->disableOriginalConstructor()
            ->getMock();
        $listAction->setDispatcher($dispatcher);
        $actionError = $this->getExceptionAction();
        $listAction->addAction($actionError, false);
        $listAction->execute(array());
    }

    protected function getExceptionAction()
    {
        $action = $this->getMockBuilder('Oro\Component\Action\Action\ActionInterface')
            ->setMethods(array('execute'))
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();
        $action->expects($this->once())
            ->method('execute')
            ->will(
                $this->returnCallback(
                    function () {
                        throw new \Exception('TEST');
                    }
                )
            );
        return $action;
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function getActionMock()
    {
        if (!$this->actionBuilder) {
            $this->actionBuilder =
                $this->getMockBuilder('Oro\Component\Action\Action\ActionInterface')
                    ->setMethods(array('execute'))
                    ->disableOriginalConstructor();
        }

        return $this->actionBuilder->getMockForAbstractClass();
    }

    public function testInitialize()
    {
        $this->assertEquals($this->listAction, $this->listAction->initialize(array()));
    }
}


text:
pub mod functions;
pub mod globals;
mod ops;
mod string_table;

use std::{
    cell::RefCell,
    convert::TryInto,
    error::Error,
    fmt,
    io::{Read, Seek, SeekFrom},
    rc::Rc,
};

use crate::server::world::{EntityError, EntityTypeDef};

use byteorder::{LittleEndian, ReadBytesExt};
use num::FromPrimitive;

use self::{
    functions::{BuiltinFunctionId, FunctionDef, FunctionKind, Statement, MAX_ARGS},
    globals::{GLOBAL_ADDR_ARG_0, GLOBAL_STATIC_COUNT},
};
pub use self::{
    functions::{FunctionId, Functions},
    globals::{
        GlobalAddrEntity, GlobalAddrFloat, GlobalAddrFunction, GlobalAddrVector, Globals,
        GlobalsError,
    },
    ops::Opcode,
    string_table::StringTable,
};

const VERSION: i32 = 6;
const CRC: i32 = 5927;
const MAX_CALL_STACK_DEPTH: usize = 32;
const MAX_LOCAL_STACK_DEPTH: usize = 2048;
const LUMP_COUNT: usize = 6;
const SAVE_GLOBAL: u16 = 1 << 15;

// the on-disk size of a bytecode statement
const STATEMENT_SIZE: usize = 8;

// the on-disk size of a function declaration
const FUNCTION_SIZE: usize = 36;

// the on-disk size of a global or field definition
const DEF_SIZE: usize = 8;

#[derive(Debug)]
pub enum ProgsError {
    Io(::std::io::Error),
    Globals(GlobalsError),
    Entity(EntityError),
    CallStackOverflow,
    LocalStackOverflow,
    Other(String),
}

impl ProgsError {
    pub fn with_msg<S>(msg: S) -> Self
    where
        S: AsRef<str>,
    {
        ProgsError::Other(msg.as_ref().to_owned())
    }
}

impl fmt::Display for ProgsError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::ProgsError::*;
        match *self {
            Io(ref err) => {
                write!(f, "I/O error: ")?;
                err.fmt(f)
            }
            Globals(ref err) => {
                write!(f, "Globals error: ")?;
                err.fmt(f)
            }
            Entity(ref err) => {
                write!(f, "Entity error: ")?;
                err.fmt(f)
            }
            CallStackOverflow => write!(f, "Call stack overflow"),
            LocalStackOverflow => write!(f, "Local stack overflow"),
            Other(ref msg) => write!(f, "{}", msg),
        }
    }
}

impl Error for ProgsError {}

impl From<::std::io::Error> for ProgsError {
    fn from(error: ::std::io::Error) -> Self {
        ProgsError::Io(error)
    }
}

impl From<GlobalsError> for ProgsError {
    fn from(error: GlobalsError) -> Self {
        ProgsError::Globals(error)
    }
}

impl From<EntityError> for ProgsError {
    fn from(error: EntityError) -> Self {
        ProgsError::Entity(error)
    }
}

#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq)]
#[repr(C)]
pub struct StringId(pub usize);

impl TryInto<i32> for StringId {
    type Error = ProgsError;

    fn try_into(self) -> Result<i32, Self::Error> {
        if self.0 > ::std::i32::MAX as usize {
            Err(ProgsError::with_msg("string id out of i32 range"))
        } else {
            Ok(self.0 as i32)
        }
    }
}

impl StringId {
    pub fn new() -> StringId {
        StringId(0)
    }
}

#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq)]
#[repr(C)]
pub struct EntityId(pub usize);

#[derive(Copy, Clone, Debug, Default, PartialEq)]
#[repr(C)]
pub struct FieldAddr(pub usize);

#[derive(Copy, Clone, Debug, Default, PartialEq)]
#[repr(C)]
pub struct EntityFieldAddr {
    pub entity_id: EntityId,
    pub field_addr: FieldAddr,
}

enum LumpId {
    Statements = 0,
    GlobalDefs = 1,
    Fielddefs = 2,
    Functions = 3,
    Strings = 4,
    Globals = 5,
}

#[derive(Copy, Clone, Debug, FromPrimitive, PartialEq)]
#[repr(u16)]
pub enum Type {
    QVoid = 0,
    QString = 1,
    QFloat = 2,
    QVector = 3,
    QEntity = 4,
    QField = 5,
    QFunction = 6,
    QPointer = 7,
}

#[derive(Copy, Clone, Debug)]
struct Lump {
    offset: usize,
    count: usize,
}

#[derive(Debug)]
pub struct GlobalDef {
    save: bool,
    type_: Type,
    offset: u16,
    name_id: StringId,
}

/// An entity field definition.
///
/// These definitions can be used to look up entity fields by name. This is
/// required for custom fields defined in QuakeC code; their offsets are not
/// known at compile time.
#[derive(Debug)]
pub struct FieldDef {
    pub type_: Type,
    pub offset: u16,
    pub name_id: StringId,
}

/// The values returned by loading a `progs.dat` file.
pub struct LoadProgs {
    pub cx: ExecutionContext,
    pub globals: Globals,
    pub entity_def: Rc<EntityTypeDef>,
    pub string_table: Rc<RefCell<StringTable>>,
}

/// Loads all data from a `progs.dat` file.
///
/// This returns objects representing the necessary context to execute QuakeC bytecode.
pub fn load<R>(mut src: R) -> Result<LoadProgs, ProgsError>
where
    R: Read + Seek,
{
    assert!(src.read_i32::<LittleEndian>()? == VERSION);
    assert!(src.read_i32::<LittleEndian>()? == CRC);

    let mut lumps = [Lump {
        offset: 0,
        count: 0,
    }; LUMP_COUNT];

    for l in 0..lumps.len() as usize {
        lumps[l] = Lump {
            offset: src.read_i32::<LittleEndian>()? as usize,
            count: src.read_i32::<LittleEndian>()? as usize,
        };

        debug!("{:?}: {:?}", l, lumps[l]);
    }

    let ent_addr_count = src.read_i32::<LittleEndian>()? as usize;
    debug!("Field count: {}", ent_addr_count);

    // Read string data and construct StringTable

    let string_lump = &lumps[LumpId::Strings as usize];
    src.seek(SeekFrom::Start(string_lump.offset as u64))?;
    let mut strings = Vec::new();
    (&mut src)
        .take(string_lump.count as u64)
        .read_to_end(&mut strings)?;
    let string_table = Rc::new(RefCell::new(StringTable::new(strings)));

    assert_eq!(
        src.seek(SeekFrom::Current(0))?,
        src.seek(SeekFrom::Start(
            (string_lump.offset + string_lump.count) as u64,
        ))?
    );

    // Read function definitions and statements and construct Functions

    let function_lump = &lumps[LumpId::Functions as usize];
    src.seek(SeekFrom::Start(function_lump.offset as u64))?;
    let mut function_defs = Vec::with_capacity(function_lump.count);
    for i in 0..function_lump.count {
        assert_eq!(
            src.seek(SeekFrom::Current(0))?,
            src.seek(SeekFrom::Start(
                (function_lump.offset + i * FUNCTION_SIZE) as u64,
            ))?
        );

        let kind = match src.read_i32::<LittleEndian>()? {
            x if x < 0 => match BuiltinFunctionId::from_i32(-x) {
                Some(f) => FunctionKind::BuiltIn(f),
                None => {
                    return Err(ProgsError::with_msg(format!(
                        "Invalid built-in function ID {}",
                        -x
                    )))
                }
            },
            x => FunctionKind::QuakeC(x as usize),
        };

        let arg_start = src.read_i32::<LittleEndian>()?;
        let locals = src.read_i32::<LittleEndian>()?;

        // throw away profile variable
        let _ = src.read_i32::<LittleEndian>()?;

        let name_id = string_table
            .borrow()
            .id_from_i32(src.read_i32::<LittleEndian>()?)?;
        let srcfile_id = string_table
            .borrow()
            .id_from_i32(src.read_i32::<LittleEndian>()?)?;

        let argc = src.read_i32::<LittleEndian>()?;
        let mut argsz = [0; MAX_ARGS];
        src.read(&mut argsz)?;

        function_defs.push(FunctionDef {
            kind,
            arg_start: arg_start as usize,
            locals: locals as usize,
            name_id,
            srcfile_id,
            argc: argc as usize,
            argsz,
        });
    }

    assert_eq!(
        src.seek(SeekFrom::Current(0))?,
        src.seek(SeekFrom::Start(
            (function_lump.offset + function_lump.count * FUNCTION_SIZE) as u64,
        ))?
    );

    let statement_lump = &lumps[LumpId::Statements as usize];
    src.seek(SeekFrom::Start(statement_lump.offset as u64))?;
    let mut statements = Vec::with_capacity(statement_lump.count);
    for _ in 0..statement_lump.count {
        statements.push(Statement::new(
            src.read_i16::<LittleEndian>()?,
            src.read_i16::<LittleEndian>()?,
            src.read_i16::<LittleEndian>()?,
            src.read_i16::<LittleEndian>()?,
        )?);
    }

    assert_eq!(
        src.seek(SeekFrom::Current(0))?,
        src.seek(SeekFrom::Start(
            (statement_lump.offset + statement_lump.count * STATEMENT_SIZE) as u64,
        ))?
    );

    let functions = Functions {
        string_table: string_table.clone(),
        defs: function_defs.into_boxed_slice(),
        statements: statements.into_boxed_slice(),
    };

    let globaldef_lump = &lumps[LumpId::GlobalDefs as usize];
    src.seek(SeekFrom::Start(globaldef_lump.offset as u64))?;
    let mut globaldefs = Vec::new();
    for _ in 0..globaldef_lump.count {
        let type_ = src.read_u16::<LittleEndian>()?;
        let offset = src.read_u16::<LittleEndian>()?;
        let name_id = string_table
            .borrow()
            .id_from_i32(src.read_i32::<LittleEndian>()?)?;
        globaldefs.push(GlobalDef {
            save: type_ & SAVE_GLOBAL != 0,
            type_: Type::from_u16(type_ & !SAVE_GLOBAL).unwrap(),
            offset,
            name_id,
        });
    }

    assert_eq!(
        src.seek(SeekFrom::Current(0))?,
        src.seek(SeekFrom::Start(
            (globaldef_lump.offset + globaldef_lump.count * DEF_SIZE) as u64,
        ))?
    );

    let fielddef_lump = &lumps[LumpId::Fielddefs as usize];
    src.seek(SeekFrom::Start(fielddef_lump.offset as u64))?;
    let mut field_defs = Vec::new();
    for _ in 0..fielddef_lump.count {
        let type_ = src.read_u16::<LittleEndian>()?;
        let offset = src.read_u16::<LittleEndian>()?;
        let name_id = string_table
            .borrow()
            .id_from_i32(src.read_i32::<LittleEndian>()?)?;

        if type_ & SAVE_GLOBAL != 0 {
            return Err(ProgsError::with_msg(
                "Save flag not allowed in field definitions",
            ));
        }
        field_defs.push(FieldDef {
            type_: Type::from_u16(type_).unwrap(),
            offset,
            name_id,
        });
    }

    assert_eq!(
        src.seek(SeekFrom::Current(0))?,
        src.seek(SeekFrom::Start(
            (fielddef_lump.offset + fielddef_lump.count * DEF_SIZE) as u64,
        ))?
    );

    let globals_lump = &lumps[LumpId::Globals as usize];
    src.seek(SeekFrom::Start(globals_lump.offset as u64))?;

    if globals_lump.count < GLOBAL_STATIC_COUNT {
        return Err(ProgsError::with_msg(
            "Global count lower than static global count",
        ));
    }

    let mut addrs = Vec::with_capacity(globals_lump.count);
    for _ in 0..globals_lump.count {
        let mut block = [0; 4];
        src.read(&mut block)?;

        // TODO: handle endian conversions (BigEndian systems should use BigEndian internally)
        addrs.push(block);
    }

    assert_eq!(
        src.seek(SeekFrom::Current(0))?,
        src.seek(SeekFrom::Start(
            (globals_lump.offset + globals_lump.count * 4) as u64,
        ))?
    );

    let functions_rc = Rc::new(functions);

    let cx = ExecutionContext::create(string_table.clone(), functions_rc.clone());

    let globals = Globals::new(
        string_table.clone(),
        globaldefs.into_boxed_slice(),
        addrs.into_boxed_slice(),
    );

    let entity_def = Rc::new(EntityTypeDef::new(
        string_table.clone(),
        ent_addr_count,
        field_defs.into_boxed_slice(),
    )?);

    Ok(LoadProgs {
        cx,
        globals,
        entity_def,
        string_table,
    })
}

#[derive(Debug)]
struct StackFrame {
    instr_id: usize,
    func_id: FunctionId,
}

/// A QuakeC VM context.
#[derive(Debug)]
pub struct ExecutionContext {
    string_table: Rc<RefCell<StringTable>>,
    functions: Rc<Functions>,
    pc: usize,
    current_function: FunctionId,
    call_stack: Vec<StackFrame>,
    local_stack: Vec<[u8; 4]>,
}

impl ExecutionContext {
    pub fn create(
        string_table: Rc<RefCell<StringTable>>,
        functions: Rc<Functions>,
    ) -> ExecutionContext {
        ExecutionContext {
            string_table,
            functions,
            pc: 0,
            current_function: FunctionId(0),
            call_stack: Vec::with_capacity(MAX_CALL_STACK_DEPTH),
            local_stack: Vec::with_capacity(MAX_LOCAL_STACK_DEPTH),
        }
    }

    pub fn call_stack_depth(&self) -> usize {
        self.call_stack.len()
    }

    pub fn find_function_by_name<S: AsRef<str>>(
        &mut self,
        name: S,
    ) -> Result<FunctionId, ProgsError> {
        self.functions.find_function_by_name(name)
    }

    pub fn function_def(&self, id: FunctionId) -> Result<&FunctionDef, ProgsError> {
        self.functions.get_def(id)
    }

    pub fn enter_function(
        &mut self,
        globals: &mut Globals,
        f: FunctionId,
    ) -> Result<(), ProgsError> {
        let def = self.functions.get_def(f)?;
        debug!(
            "Calling QuakeC function {}",
            self.string_table.borrow().get(def.name_id).unwrap()
        );

        // save stack frame
        self.call_stack.push(StackFrame {
            instr_id: self.pc,
            func_id: self.current_function,
        });

        // check call stack overflow
        if self.call_stack.len() >= MAX_CALL_STACK_DEPTH {
            return Err(ProgsError::CallStackOverflow);
        }

        // preemptively check local stack overflow
        if self.local_stack.len() + def.locals > MAX_LOCAL_STACK_DEPTH {
            return Err(ProgsError::LocalStackOverflow);
        }

        // save locals to stack
        for i in 0..def.locals {
            self.local_stack
                .push(globals.get_bytes((def.arg_start + i) as i16)?);
        }

        for arg in 0..def.argc {
            for component in 0..def.argsz[arg] as usize {
                let val = globals.get_bytes((GLOBAL_ADDR_ARG_0 + arg * 3 + component) as i16)?;
                globals.put_bytes(val, def.arg_start as i16)?;
            }
        }

        self.current_function = f;

        match def.kind {
            FunctionKind::BuiltIn(_) => {
                panic!("built-in functions should not be called with enter_function()")
            }
            FunctionKind::QuakeC(pc) => self.pc = pc,
        }

        Ok(())
    }

    pub fn leave_function(&mut self, globals: &mut Globals) -> Result<(), ProgsError> {
        let def = self.functions.get_def(self.current_function)?;
        debug!(
            "Returning from QuakeC function {}",
            self.string_table.borrow().get(def.name_id).unwrap()
        );

        for i in (0..def.locals).rev() {
            globals.put_bytes(self.local_stack.pop().unwrap(), (def.arg_start + i) as i16)?;
        }

        let frame = match self.call_stack.pop() {
            Some(f) => f,
            None => return Err(ProgsError::with_msg("call stack underflow")),
        };

        self.current_function = frame.func_id;
        self.pc = frame.instr_id;

        Ok(())
    }

    pub fn load_statement(&self) -> Statement {
        self.functions.statements[self.pc].clone()
    }

    /// Performs an unconditional relative jump.
    pub fn jump_relative(&mut self, rel: i16) {
        self.pc = (self.pc as isize + rel as isize) as usize;
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Auxiliary class and functions for eval jobs."""

import csv
import os
import time
from typing import Any, Dict, Iterable, Optional, TypeVar

from absl import logging
import flax
from flax.training import checkpoints as flax_checkpoints
import jax
import tensorflow as tf

T = TypeVar("T")

def restore_checkpoint(state, workdir):
  return flax_checkpoints.restore_checkpoint(workdir, state)

def save_checkpoint(state, workdir):
  if jax.process_index() == 0:
    # get train state from the first replica
    state = jax.device_get(jax.tree_map(lambda x: x[0], state))
    step = int(state.step)
    flax_checkpoints.save_checkpoint(workdir, state, step, keep=5,
                                     overwrite=True)

def restore_from_path(state, path):
  with tf.io.gfile.GFile(path, "rb") as f:
    state = flax.serialization.from_bytes(state, f.read())
  return state

def load_state_dict(path):
  with tf.io.gfile.GFile(path, "rb") as f:
    return flax.serialization.msgpack_restore(f.read())

class TaskManager:
  """Class for checking the model folder repeately for evaluation."""

  def __init__(self, model_dir):
    self._model_dir = model_dir

  @property
  def model_dir(self):
    return self._model_dir

  def mark_training_done(self):
    with tf.io.gfile.GFile(
        os.path.join(self.model_dir, "TRAIN_DONE"), "w") as f:
      f.write("")

  def is_training_done(self):
    return tf.io.gfile.exists(os.path.join(self.model_dir, "TRAIN_DONE"))

  def add_eval_result(
      self,
      checkpoint_path,
      result_dict,
      default_value = -1):
    pass

  def _get_checkpoints_with_results(self):
    return set()

  def unevaluated_checkpoints(self,
                              timeout = 3600 * 8,
                              num_batched_steps = 1,
                              eval_every_steps = None,
                              ):
    """Generator for checkpoints without evaluation results.

    Args:
      timeout: Optional timeout for waiting for new checkpoints. Set this to
        do continious evaluation.
      num_batched_steps: Steps that are batched into a single tf.function.
        Required for computing correct evaluation checkpoints.
      eval_every_steps: Only evaluate checkpoints from steps divisible by this
                         integer.

    Yields:
      Path to checkpoints that have not yet been evaluated.
    """
    logging.info("Looking for checkpoints in %s", self._model_dir)
    evaluated_checkpoints = self._get_checkpoints_with_results()
    last_eval = time.time()
    while True:
      # Check if directory exists. The train job may only create the directory
      # some time after the test job starts.
      if not tf.io.gfile.exists(self.model_dir):
        logging.info("Directory %s does not exist!", self.model_dir)
      else:
        logging.info("what is in %s:  are  %s", self.model_dir,
                     tf.io.gfile.listdir(self.model_dir))
        unevaluated_checkpoints = []
        checkpoints = tf.io.gfile.glob(
            os.path.join(self._model_dir, "checkpoint*"))
        checkpoints = set([x for x in checkpoints if "tmp" not in x])
        logging.info("checkpoints: %s", checkpoints)
        unevaluated_checkpoints = checkpoints - evaluated_checkpoints
        step_and_ckpt = sorted(
            (int(x.split("_")[-1]), x) for x in unevaluated_checkpoints)

        unevaluated_checkpoints = []
        for step, ckpt in step_and_ckpt:
          if eval_every_steps:
            if step > num_batched_steps and (
                step % eval_every_steps < num_batched_steps):
              unevaluated_checkpoints.append(ckpt)
          else:
            unevaluated_checkpoints.append(ckpt)

        logging.info(
            "Found checkpoints: %s\nEvaluated checkpoints: %s\n"
            "Unevaluated checkpoints: %s", checkpoints, evaluated_checkpoints,
            unevaluated_checkpoints)
        for checkpoint_path in unevaluated_checkpoints:
          yield checkpoint_path

        if unevaluated_checkpoints:
          evaluated_checkpoints |= set(unevaluated_checkpoints)
          last_eval = time.time()
          continue
      if time.time() - last_eval > timeout or self.is_training_done():
        break
      time.sleep(5)

class TaskManagerWithCsvResults(TaskManager):
  """Task Manager that writes results to a CSV file."""

  def __init__(self,
               model_dir,
               score_file = None):
    super().__init__(model_dir)
    if score_file is None:
      score_file = os.path.join(self._model_dir, "scores.csv")
    else:
      score_file = os.path.join(self._model_dir, score_file)
    self._score_file = score_file

  def _get_checkpoints_with_results(self):
    """Return the checkpoints as set."""
    if not tf.io.gfile.exists(self._score_file):
      return set()
    with tf.io.gfile.GFile(self._score_file) as f:
      reader = csv.DictReader(f)
      return {r["checkpoint_path"] for r in reader}
    return set()

  def add_eval_result(self,
                      checkpoint_path,
                      result_dict,
                      default_value):
    """Add eval result to the CSV file."""
    if jax.process_index() == 0:
      step = int(os.path.basename(checkpoint_path).split("_")[-1])
      csv_header = (
          ["checkpoint_path", "step"] + sorted(result_dict))
      write_header = not tf.io.gfile.exists(self._score_file)
      if write_header:
        with tf.io.gfile.GFile(self._score_file, "w") as f:
          writer = csv.DictWriter(
              f, fieldnames=csv_header, extrasaction="ignore")
          writer.writeheader()
      row = dict(checkpoint_path=checkpoint_path, step=str(step))
      for k, v in result_dict.items():
        if isinstance(v, float):
          v = "{:.3f}".format(v)
        row[k] = v
      with tf.io.gfile.GFile(self._score_file, "a") as f:
        writer = csv.DictWriter(f, fieldnames=csv_header, extrasaction="ignore")
        writer.writerow(row)


text:
/** @file AnalyticalContinuer.cpp
 *
 *  @author Kristofer Björnson
 */

#include "TBTK/Array.h"
#include "TBTK/PadeApproximator.h"
#include "TBTK/Solver/AnalyticalContinuer.h"
#include "TBTK/Streams.h"
#include "TBTK/TBTKMacros.h"

using namespace std;

namespace TBTK{
namespace Solver{

DynamicTypeInformation AnalyticalContinuer::dynamicTypeInformation(
	"Solver::AnalyticalContinuer",
	{&Solver::dynamicTypeInformation}
);

AnalyticalContinuer::AnalyticalContinuer() : Communicator(true){
	numeratorDegree = 0;
	denominatorDegree = 0;
	lowerBound = -1;
	upperBound = 1;
	resolution = 1000;
	energyInfinitesimal = ENERGY_INFINITESIMAL;
	energyShift = 0.;
	scaleFactor = 1.;
}

Property::GreensFunction AnalyticalContinuer::convert(
	const Property::GreensFunction &greensFunction,
	Property::GreensFunction::Type newType
) const{
	TBTKAssert(
		greensFunction.getType()
			== Property::GreensFunction::Type::Matsubara,
		"Solver::AnalyticalContinuer::convert()",
		"Ivalid Green's function type. This function is only"
		<< " applicable for Green's functions with type"
		<< " Property::GreensFunction::Type::Matsubara.",
		""
	);

	switch(greensFunction.getIndexDescriptor().getFormat()){
	case IndexDescriptor::Format::Custom:
	{
		const IndexTree &indexTree
			= greensFunction.getIndexDescriptor().getIndexTree();

		Property::GreensFunction newGreensFunction;
		switch(newType){
		case Property::GreensFunction::Type::Retarded:
		case Property::GreensFunction::Type::Advanced:
			newGreensFunction = Property::GreensFunction(
				indexTree,
				newType,
				Range(
					lowerBound,
					upperBound,
					resolution
				)
			);

			break;
		default:
			TBTKExit(
				"Solver::AnalyticalContinuer::convert()",
				"Invalid 'newType'. Only conversion to the"
				<< " retarded and advanced Green's function is"
				<< " supported yet.",
				""
			);
		}

		for(
			IndexTree::ConstIterator iterator = indexTree.cbegin();
			iterator != indexTree.cend();
			++iterator
		){
			vector<complex<double>> matsubaraValues;
			vector<complex<double>> matsubaraEnergies;
			for(
				unsigned int n = 0;
				n < greensFunction.getNumMatsubaraEnergies();
				n++
			){
				if(newType == Property::GreensFunction::Type::Retarded){
					if(imag(greensFunction.getMatsubaraEnergy(n)) < 0)
						continue;
				}
				else if(newType == Property::GreensFunction::Type::Advanced){
					if(imag(greensFunction.getMatsubaraEnergy(n)) > 0)
						continue;
				}
				else{
					TBTKExit(
						"Solver::AnalyticalContinuer::convert()",
						"Invalid 'newType'. Only"
						<< " conversion to the"
						<< " retarded and advanced"
						<< " Green's function is"
						<< " supported yet.",
						""
					);
				}

				matsubaraValues.push_back(
					greensFunction(*iterator, n)
				);
				matsubaraEnergies.push_back(
					(
						greensFunction.getMatsubaraEnergy(n)
						+ getModel().getChemicalPotential()
						- energyShift
					)/scaleFactor
				);
			}

			PadeApproximator padeApproximator;
			padeApproximator.setNumeratorDegree(numeratorDegree);
			padeApproximator.setDenominatorDegree(
				denominatorDegree
			);
			vector<Polynomial<>> padePolynomials
				= padeApproximator.approximate(
					matsubaraValues,
					matsubaraEnergies
				);

			for(
				unsigned int n = 0;
				n < newGreensFunction.getResolution();
				n++
			){
				double energy = newGreensFunction.getEnergy(n);
				complex<double> contourDeformation
					= getContourDeformation(
						energy,
						newType
					);

				newGreensFunction(*iterator, n)
					= padePolynomials[0](
						{
							(
								energy
								+ contourDeformation
								- energyShift
							)/scaleFactor
						}
					)/padePolynomials[1]({
						(
							energy
							+ contourDeformation
							- energyShift
						)/scaleFactor
					});
			}
		}

		return newGreensFunction;
	}
	default:
		TBTKExit(
			"Solver::AnalyticalContinuer::convert()",
			"Only Green's functions on the custom format are"
			<< " supported yet.",
			""
		);
	}
}

complex<double> AnalyticalContinuer::getContourDeformation(
	double energy,
	Property::GreensFunction::Type type
) const{
	switch(type){
	case Property::GreensFunction::Type::Retarded:
		return complex<double>(0, 1)*energyInfinitesimal;
	case Property::GreensFunction::Type::Advanced:
		return complex<double>(0, -1)*energyInfinitesimal;
	default:
		TBTKExit(
			"Solver::AnalyticalContinuer::convert()",
			"Invalid Green's function type. Only contours for the"
			<< " retarded, and advanced Green's functions are"
			<< " supported yet.",
			""
		);
	}
}

};	//End of namespace Solver
};	//End of namespace TBTK


text:
namespace IECoreSceneModule
{
void bindRenderable();
}

#endif // IECORESCENEMODULE_RENDERABLEBINDING_H


text:
'use strict';

/*!
 * import(s)
 */
var hogan = require('hogan.js');
var debug = require('debug')('component-render-hogan');
var path = require('path');
var fs = require('fs');

/*!
 * export(s)
 */
module.exports = function (template, program, fn) {
  debug('call hogan renderer:', template);

  var local = {};
  if (program.local) {
    var resolve_path = path.resolve(program.local);
    local = fs.existsSync(resolve_path) ? require(resolve_path) : require(resolve_path + '.json');
  }

  fs.readFile(template, { encoding: 'utf8' }, function (err, data) {
    if (err) { return fn(err); }
    var renderer = hogan.compile(data);
    var html = renderer.render(local);
    debug('html:', html);
    fn(null, html);
  });
};


text:
![Version: 0.1.6](https://img.shields.io/badge/Version-0.1.6-informational?style=flat-square) ![AppVersion: 957](https://img.shields.io/badge/AppVersion-957-informational?style=flat-square)

Deploys a k8s pod to collect data and generate reports based or resources usages, costs and other possibilities. Please check more about it on: https://www.cloudhealthtech.com/solutions/containers

Chart based on its official k8s resources: https://s3.amazonaws.com/cloudhealth-public/containers/kubernetes-collector-pod-template.yaml

A Cloudhealth account is required.

To install the chart a valid api token should be generated from adding a new cluster: https://apps.cloudhealthtech.com/containers_clusters

**Homepage:** <https://github.com/deliveryhero/helm-charts>

## How to install this chart

Add Delivery Hero public chart repo:

```console
helm repo add deliveryhero https://charts.deliveryhero.io/
```

A simple install with default values:

```console
helm install deliveryhero/cloudhealth-collector
```

To install the chart with the release name `my-release`:

```console
helm install my-release deliveryhero/cloudhealth-collector
```

To install with some set values:

```console
helm install my-release deliveryhero/cloudhealth-collector --set values_key1=value1 --set values_key2=value2
```

To install with custom values file:

```console
helm install my-release deliveryhero/cloudhealth-collector -f values.yaml
```

## Source Code

* <https://s3.amazonaws.com/cloudhealth-public/containers/kubernetes-collector-pod-template.yaml>

## Values

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| affinity | object | `{}` |  |
| api_token | string | `"<change-me>"` |  |
| cluster_name | string | `"your-cluster-name"` |  |
| deploymentAnnotations | object | `{}` |  |
| existingSecret.secretName | string | `""` |  |
| existingSecret.tokenKey | string | `""` |  |
| extraEnv | list | `[]` |  |
| extraLabels | object | `{}` |  |
| extraVolumeMounts | list | `[]` |  |
| extraVolumes | list | `[]` |  |
| fullnameOverride | string | `""` |  |
| image.pullPolicy | string | `"IfNotPresent"` |  |
| image.repository | string | `"cloudhealth/container-collector"` |  |
| image.tag | int | `957` |  |
| imagePullSecrets | list | `[]` |  |
| nameOverride | string | `""` |  |
| nodeSelector | object | `{}` |  |
| podAnnotations | object | `{}` |  |
| podSecurityContext | object | `{}` |  |
| replicaCount | int | `1` |  |
| resources.limits.cpu | string | `"1000m"` |  |
| resources.limits.memory | string | `"512Mi"` |  |
| resources.requests.cpu | string | `"500m"` |  |
| resources.requests.memory | string | `"512Mi"` |  |
| securityContext | object | `{}` |  |
| serviceAccount.annotations | object | `{}` |  |
| serviceAccount.create | bool | `true` |  |
| serviceAccount.name | string | `""` |  |
| tolerations | list | `[]` |  |

## Maintainers

| Name | Email | Url |
| ---- | ------ | --- |
| max-rocket-internet | <no-reply@deliveryhero.com> |  |


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface io.ebean.config.EncryptKey (ebean 11.35.3 API)</title>
<meta name="date" content="2019-03-05">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
io.ebean.config.EncryptKey

Packages that use EncryptKey

Package
Description

io.ebean.config

Configuration settings for EbeanServer construction

Uses of EncryptKey in io.ebean.config

Methods in io.ebean.config that return EncryptKey

Modifier and Type
Method and Description

EncryptKey
EncryptKeyManager.getEncryptKey(String tableName,
             String columnName)

Return the key used to encrypt and decrypt a property mapping to the given
table and column.

Methods in io.ebean.config with parameters of type EncryptKey

Modifier and Type
Method and Description

byte[]
Encryptor.decrypt(byte[] data,
       EncryptKey key)

Decrypt the data using the key.

String
Encryptor.decryptString(byte[] data,
             EncryptKey key)

Decrypt the data returning a formatted string value using a key.

byte[]
Encryptor.encrypt(byte[] data,
       EncryptKey key)

Encrypt the data using the key.

byte[]
Encryptor.encryptString(String formattedValue,
             EncryptKey key)

Encrypt the formatted string value using a key.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2019. All rights reserved.


text:
package org.openfact.models;

import io.github.carlosthe19916.webservices.providers.BillServiceModel;
import org.json.JSONObject;
import org.openfact.models.types.DestinyType;
import org.openfact.models.types.DocumentRequiredAction;
import org.openfact.provider.ProviderEvent;
import org.w3c.dom.Document;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

public interface DocumentModel {

    enum Status {
        ACEPTADO,
        RECHAZADO,
        BAJA,
        EXCEPCION,
        EN_PROCESO,

        // DEPRECATED
        VERIFICAR_TICKET;

        public static Status from(BillServiceModel.Status status) {
            return valueOf(status.toString());
        }
    }

    String DOCUMENT_TYPE = "documentType";
    String DOCUMENT_ID = "documentId";
    String DOCUMENT_CURRENCY_CODE = "documentCurrencyCode";
    String CUSTOMER_REGISTRATION_NAME = "customerRegistrationName";
    String CUSTOMER_ASSIGNED_ACCOUNT_ID = "customerAssignedAccountId";
    String CUSTOMER_ELECTRONIC_MAIL = "customerElectronicMail";

    String CREATED_TIMESTAMP = "createdTimestamp";
    String ISSUE_DATE="issueDate";

    String ENABLED = "enabled";

    String getId();

    String getDocumentId();

    String getDocumentType();

    Date getIssueDate();
    void setIssueDate(Date issueDate);

    Date getCreatedTimestamp();

    Status getStatus();
    void setStatus(Status status);
    Integer getStatusCode();
    void setStatusCode(int statusCode);
    String getStatusMessage();
    void setStatusMessage(String statusMessage);

    boolean isClosed();
    void close();

    boolean isBajaEnProceso();
    void setBajaEnProceso();

    boolean isSummaryVoided();
    void summaryVoided();

    String getObservacion();
    void setObservacion(String observacion);

    /**
     * Document Line
     */
    List<DocumentLineModel> getDocumentLines();

    DocumentLineModel addDocumentLine();

    boolean removeDocumentLine(DocumentLineModel documentLine);
    boolean removeAllDocumentLines();

    /**
     * Organization
     */
    OrganizationModel getOrganization();

    /**
     * Document information
     */
    String getDocumentCurrencyCode();

    void setDocumentCurrencyCode(String currencyCode);

    String getCustomerRegistrationName();

    void setCustomerRegistrationName(String customerRegistrationName);

    String getCustomerAssignedAccountId();

    void setCustomerAssignedAccountId(String customerAssignedAccountId);

    String getCustomerElectronicMail();

    void setCustomerElectronicMail(String customerElectronicMail);

    /**
     * Xml
     */
    FileModel getXmlAsFile();
    void attachXmlFile(FileModel file);

    Document getXmlAsDocument();
    JSONObject getXmlAsJSONObject();

    FileModel getCdrFile();
    void setCrdFile(FileModel cdrFile);

    String getXmlDigestValue();
    void setXmlDigestValue(String digestValue);

    /**
     * attributes
     */
    void setSingleAttribute(String name, String value);

    void setAttribute(String name, List<String> values);

    void removeAttribute(String name);

    String getFirstAttribute(String name);

    List<String> getAttribute(String name);

    Map<String, List<String>> getAttributes();

    /**
     * Required Actions
     */
    String REQUIRED_ACTIONS = "requiredActions";

    Set<String> getRequiredActions();

    void addRequiredAction(String action);

    void removeRequiredAction(String action);

    void addRequiredAction(DocumentRequiredAction action);

    void removeRequiredAction(DocumentRequiredAction action);

    /**
     * Send events
     */
    String SEND_EVENT_DESTINY = "destiny";
    String SEND_EVENT_STATUS = "status";

    int getCustomerSendEventFailures();

    void incrementCustomerSendEventFailures();

    int getThirdPartySendEventFailures();

    void incrementThirdPartySendEventFailures();

    SendEventModel addSendEvent(DestinyType destinyType);

    SendEventModel getSendEventById(String id);

    boolean removeSendEvent(SendEventModel sendEvent);

    List<SendEventModel> getSendEvents();

    List<SendEventModel> getSendEvents(Integer firstResult, Integer maxResults);

    List<SendEventModel> searchForSendEvent(Map<String, String> params);

    List<SendEventModel> searchForSendEvent(Map<String, String> params, int firstResult, int maxResults);

    /**
     * Attatched documents
     */
    List<DocumentModel> getAttachedDocumentsAsOrigin();

    List<DocumentModel> getAttachedDocumentsAsDestiny();

    void addAttachedDocument(DocumentModel document);

    boolean removeAttachedDocument(DocumentModel document);

    boolean removeAllAttachedDocuments();
    /**
     * Events interfaces
     */
    @FunctionalInterface
    interface DocumentCreationEvent extends ProviderEvent {
        DocumentModel getCreatedDocument();
    }

    @FunctionalInterface
    interface DocumentPostCreateEvent extends ProviderEvent {
        DocumentModel getCreatedDocument();
    }

    interface DocumentRemovedEvent extends ProviderEvent {
        OrganizationModel getOrganization();

        DocumentModel getDocument();
    }

}


text:
<?php

namespace Brickoo\Component\Common;

use ArrayIterator;
use Brickoo\Component\Common\Exception\InvalidIndexException;
use Brickoo\Component\Common\Assert;
use Countable;
use InvalidArgumentException;
use IteratorAggregate;

/**
 * ArrayList
 *
 * Implementation of an array based list.
 */
class ArrayList implements IteratorAggregate, Countable {

    /** @var array */
    private $items;

    /**
     * Class constructor.
     * @param array $items
     * @throws \InvalidArgumentException
     */
    public function __construct(array $items = []) {
        $this->items = $items;
    }

    /**
     * Return the list item by index.
     * @param integer $index
     * @throws \Brickoo\Component\Common\Exception\InvalidIndexException
     * @return string
     */
    public function get($index) {
        Assert::isInteger($index);
        if (!$this->has($index)) {
            throw new InvalidIndexException($index);
        }
        return $this->items[$index];
    }

    /**
     * Add an item to the list.
     * @param mixed $value
     * @return \Brickoo\Component\Common\ArrayList
     */
    public function add($value) {
        array_push($this->items, $value);
        return $this;
    }

    /**
     * @param integer $index
     * @return \Brickoo\Component\Common\ArrayList
     * @throws InvalidIndexException
     */
    public function remove($index) {
        if (!$this->has($index)) {
            throw new InvalidIndexException($index);
        }
        unset($this->items[$index]);
        $this->items = array_values($this->items);
        return $this;
    }

    /**
     * Reverse the items order.
     * @return \Brickoo\Component\Common\ArrayList
     */
    public function reverse() {
        if (!$this->isEmpty()) {
            $this->items = array_reverse($this->items, false);
        }
        return $this;
    }

    /**
     * Shuffle the items order.
     * @return \Brickoo\Component\Common\ArrayList
     */
    public function shuffle() {
        shuffle($this->items);
        return $this;
    }

    /**
     * Remove duplicate items from list.
     * @return \Brickoo\Component\Common\ArrayList
     */
    public function uniquify() {
        $this->items = array_unique($this->items, SORT_REGULAR);
        return $this;
    }

    /**
     * Check if an item with the index is available.
     * @param integer $index
     * @return boolean
     */
    public function has($index) {
        Assert::isInteger($index);
        return array_key_exists($index, $this->items);
    }

    /**
     * Return the index of the first occurrence of the value.
     * Return -1 if the value is not in list.
     * @param mixed $value
     * @return integer
     */
    public function indexOf($value) {
        $index = array_search($value, $this->items, true);
        return ($index === false) ? -1 : intval($index);
    }

    /**
     * Check if list contains a value.
     * @param mixed $value
     * @return boolean
     */
    public function contains($value) {
        return $this->indexOf($value) !== -1;
    }

    /**
     * Return the first item in list or null if empty list.
     * @throws \Brickoo\Component\Common\Exception\InvalidIndexException
     * @return mixed
     */
    public function first() {
        if ($this->isEmpty()) {
            return null;
        }

        reset($this->items);
        return current($this->items);
    }

    /**
     * Return the last item in list or null if empty list.
     * @throws \Brickoo\Component\Common\Exception\InvalidIndexException
     * @return mixed
     */
    public function last() {
        if ($this->isEmpty()) {
            return null;
        }

        $last = end($this->items);
        reset($this->items);
        return $last;
    }

    /**
     * Check if the list is empty.
     * @return boolean
     */
    public function isEmpty() {
        return empty($this->items);
    }

    /**
     * Return the list items as an array.
     * @return array
     */
    public function toArray() {
        return $this->items;
    }

    /**
     * Retrieve an external iterator containing all items.
     * @return \ArrayIterator
     */
    public function getIterator() {
        return new ArrayIterator($this->items);
    }

    /**
     * Count number of list items.
     * @return integer
     */
    public function count() {
        return count($this->items);
    }

    /**
     * Return a string representation of the list.
     * The values are linefeed separated.
     * @return string
     */
    public function toString() {
        return implode("\n", array_map(
            function($value) {
                if (!is_scalar($value)) {
                    return serialize($value);
                }
                return is_bool($value) ? ($value ? "true" : "false") : (string)$value;
            },
            $this->items
        ));
    }

}


text:
CC=g++
DEBUG=
CFLAGS=-c -Wall $(DEBUG)
LDFLAGS=-lncursesw $(DEBUG)
SOURCES=Bet.cpp Card.cpp ComputerPlayer.cpp Dealer.cpp Deck.cpp Game.cpp\
Gui.cpp Hand.cpp HumanPlayer.cpp MainDeck.cpp Player.cpp PlayerList.cpp\
PlayerNode.cpp SmallDeck.cpp Game_test.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=test

all: clean $(SOURCES) $(EXECUTABLE)

debug: clean
debug: DEBUG +=-g
debug: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
	$(CC) $(LDFLAGS) $(OBJECTS) -o $@
.cpp.o:
	$(CC) $(CFLAGS) $< -o $@

clean:
	rm -rf *.o $(EXECUTABLE)


text:
\section{Introduction}

This manual describes \textsf{libzerocoin}, an implementation of the cryptographic components of the Zerocoin protocol.


text:
package com.fedevela.dms.util;

/**
 * Created by fvelazquez on 9/04/14.
 */
import javax.accessibility.Accessible;
import javax.swing.JRadioButton;

public class JRadioButtonDms extends JRadioButton implements Accessible {

    private int idxButtonGroup = 0;
    private Short idDocumento = null;

    public JRadioButtonDms() {
        super();
    }

    public JRadioButtonDms(String text) {
        super(text);
    }

    /**
     * @return the idxButtonGroup
     */
    public int getIdxButtonGroup() {
        return idxButtonGroup;
    }

    /**
     * @param idxButtonGroup the idxButtonGroup to set
     */
    public void setIdxButtonGroup(int idxButtonGroup) {
        this.idxButtonGroup = idxButtonGroup;
    }

    /**
     * @return the idDocumento
     */
    public Short getIdDocumento() {
        return idDocumento;
    }

    /**
     * @param idDocumento the idDocumento to set
     */
    public void setIdDocumento(Short idDocumento) {
        this.idDocumento = idDocumento;
    }
}


text:
@interface EvstPrivacyTests : EvstKIFMockTestCase

@end


text:
package com.cloudera.science.ml.core.vectors;

import static org.junit.Assert.assertEquals;

import java.util.List;
import java.util.Random;

import org.junit.Test;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

public class WeightedTest {

  private final Random rand = new Random(1729L);

  private static class ThingFn<T> implements Function<Weighted<T>, T> {
    @Override
    public T apply(Weighted<T> arg0) {
      return arg0.thing();
    }
  }

  @Test
  public void testBasic() throws Exception {
    List<Weighted<Integer>> things = Lists.newArrayList();
    for (int i = 0; i < 50; i++) {
      things.add(new Weighted<Integer>(i, rand.nextDouble()));
    }
    List<Weighted<Integer>> s = Weighted.sample(things, 5, rand);
    assertEquals(ImmutableList.of(2, 29, 21, 0, 3), Lists.transform(s, new ThingFn<Integer>()));
  }

  @Test
  public void testEmpty() throws Exception {
    assertEquals(0, Weighted.sample(ImmutableList.<Weighted<Long>>of(), 10, rand).size());
  }

  @Test
  public void testSmallerCollectionThanSize() throws Exception {
    List<Weighted<Integer>> things = Lists.newArrayList();
    for (int i = 0; i < 5; i++) {
      things.add(new Weighted<Integer>(i, rand.nextDouble()));
    }
    List<Weighted<Integer>> s = Weighted.sample(things, 10, rand);
    assertEquals(ImmutableList.of(3, 0, 1, 2, 4), Lists.transform(s, new ThingFn<Integer>()));
  }
}


text:
package workers

import (
	"fmt"
	"log"

	"github.com/AsynkronIT/protoactor-go/actor"
	"github.com/ansrivas/fwatcher/messages"
)

// CoordinatorActor to supervise other actors
type CoordinatorActor struct {
	fileReader       *actor.PID
	BootStrapServers string
}

// Receive on a coordinator actor
func (parent *CoordinatorActor) Receive(context actor.Context) {
	switch msg := context.Message().(type) {
	case *actor.Started:
		fmt.Println("Parent actor started now ...")
		parent.fileReader = CreateFileReaderProps(context, parent.BootStrapServers)
	case *messages.FileModified:
		parent.fileReader.Tell(&messages.ReadFile{Filename: msg.Filepath})
		// context.Request(parent.fileReader, &messages.ReadFile{Filename: msg.Filepath})
	case *messages.PublishAck:
		log.Printf("File %v has been successfully published to kafka", msg.Filename)
	}
}


text:
/*
 * There are multiple ways to cache data in ASP.NET Core which are used in Orchard Core as well. For example the
 * content items are cached using the IMemoryCache service. In-memory caching holds the copy of data in local server's
 * memory which could be enough in most cases. Some features, however, require some extra functionality and more
 * complex ways of caching such as shapes. In Orchard Core there is a so-called Dynamic Cache which is built upon the
 * Distributed Cache. Distributed cache maintains cache in a centralized location which is accessible by servers in a
 * cluster. In Orchard Core this is also memory cache but opens up the possibility to use Redis for example. In this
 * tutorial we will see a couple of examples of caching a DateTime object and shape caching will also be demonstrated.
 */

using Lombiq.TrainingDemo.Services;
using Lombiq.TrainingDemo.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace Lombiq.TrainingDemo.Controllers;

public class CacheController : Controller
{
    // The actual caching is implemented in a service which we'll soon investigate.
    private readonly IDateTimeCachingService _dateTimeCachingService;

    public CacheController(IDateTimeCachingService dateTimeCachingService) => _dateTimeCachingService = dateTimeCachingService;

    // In this action we'll cache a DateTime three different ways. You can open it under
    // /Lombiq.TrainingDemo/Cache/Index
    public async Task<ActionResult> Index()
    {
        // This one will be cached using the built-in ASP.NET Core IMemoryCache.
        var memoryCachedDateTime = await _dateTimeCachingService.GetMemoryCachedDateTimeAsync();

        // This one will be using the DynamicCache provided by Orchard Core. It will have a 30 second expiration.
        var dynamicCachedDateTimeWith30SecondsExpiry =
            await _dateTimeCachingService.GetDynamicCachedDateTimeWith30SecondsExpiryAsync();

        // Finally this date will be cached only for this route.
        var dynamicCachedDateTimeVariedByRoutes =
            await _dateTimeCachingService.GetDynamicCachedDateTimeVariedByRoutesAsync();

        // NEXT STATION: Services/DateTimeCachingService.cs

        return View("Index", new CacheViewModel
        {
            MemoryCachedDateTime = memoryCachedDateTime,
            DynamicCachedDateTimeWith30SecondsExpiry = dynamicCachedDateTimeWith30SecondsExpiry,
            DynamicCachedDateTimeVariedByRoutes = dynamicCachedDateTimeVariedByRoutes,
        });
    }

    // This action will result in the same page as Index, however, the route will be different so the route-specific
    // cache can be tested. You can open it under /Lombiq.TrainingDemo/Cache/DifferentRoute
    public Task<ActionResult> DifferentRoute() =>
        Index();

    // This action will invalidate the memory cache and all the route-specific caches. Calling this action will redirect
    // back to the Index page and you will notice that the date value is updated. You can open it under
    // /Lombiq.TrainingDemo/Cache/InvalidateDateTimeCache
    public async Task<ActionResult> InvalidateDateTimeCache()
    {
        await _dateTimeCachingService.InvalidateCachedDateTimeAsync();

        return RedirectToAction("Index");
    }

    // Now let's see how Orchard Core utilizes the Dynamic Cache the most. In this action you will see how shapes are
    // cached. You can open it under /Lombiq.TrainingDemo/Cache/Shape
    public ActionResult Shape() =>
        View();

    // NEXT STATION: Views/Cache/Shape.cshtml
}


text:
package com.esri.gpt.control.webharvest.client.arcgis;

import com.esri.gpt.framework.http.CredentialProvider;
import com.esri.gpt.framework.robots.BotsMode;
import com.esri.gpt.framework.security.credentials.UsernamePasswordCredentials;
import com.esri.gpt.framework.util.Val;

/**
 * ArcGIS server info.
 */
public class ArcGISInfo {
/** REST url */
private final String restUrl;
/** SOAP url */
private final String soapUrl;
/** user name */
private final String userName;
/** password */
private final String password;
/** robots mode */
private final BotsMode robotsTxtMode;

/**
 * Creates instance of the service info.
 * @param restUrl REST URL
 * @param soapUrl SOAP URL
 * @param userName user name
 * @param password password
 */
public ArcGISInfo(String restUrl, String soapUrl, String userName, String password, BotsMode mode) {
  this.restUrl = Val.chkStr(restUrl);
  this.soapUrl = Val.chkStr(soapUrl);
  this.userName = Val.chkStr(userName);
  this.password = Val.chkStr(password);
  this.robotsTxtMode = mode!=null? mode: BotsMode.getDefault();
}

/**
 * Gets REST URL.
 * @return REST URL
 */
public String getRestUrl() {
  return restUrl;
}

/**
 * Gets SOAP URL.
 * @return SOAP URL
 */
public String getSoapUrl() {
  return soapUrl;
}

/**
 * Creates new credential provider.
 * @return credential provider
 */
public CredentialProvider newCredentialProvider() {
  if (userName.length() > 0 && password.length() > 0) {
    return new CredentialProvider(userName, password);
  } else {
    return null;
  }
}

/**
 * Creates new credentials.
 * @return credentials
 */
public UsernamePasswordCredentials newCredentials() {
  if (userName.length() > 0 && password.length() > 0) {
    return new UsernamePasswordCredentials(userName, password);
  } else {
    return null;
  }
}

/**
 * Gets robots.txt mode.
 * @return robots.txt mode
 */
public BotsMode getRobotsTxtMode() {
  return robotsTxtMode;
}

@Override
public String toString() {
  return "{type: arcgis, restUrl: \"" +getRestUrl()+ ", soapUrl: \"" +getSoapUrl()+ "\"\"}";
}

}


text:
namespace base {
class Time;
}  // namespace base

namespace fileapi {
class AsyncFileUtil;
class FileSystemContext;
class FileSystemURL;
class FileStreamWriter;
}  // namespace fileapi

namespace webkit_blob {
class FileStreamReader;
}  // namespace webkit_blob

namespace chromeos {

// This is delegate interface to inject the implementation of the some methods
// of FileSystemBackend. The main goal is to inject Drive File System.
class FileSystemBackendDelegate {
 public:
  virtual ~FileSystemBackendDelegate() {}

  // Called from FileSystemBackend::GetAsyncFileUtil().
  virtual fileapi::AsyncFileUtil* GetAsyncFileUtil(
      fileapi::FileSystemType type) = 0;

  // Called from FileSystemBackend::CreateFileStreamReader().
  virtual scoped_ptr<webkit_blob::FileStreamReader> CreateFileStreamReader(
      const fileapi::FileSystemURL& url,
      int64 offset,
      const base::Time& expected_modification_time,
      fileapi::FileSystemContext* context) = 0;

  // Called from FileSystemBackend::CreateFileStreamWriter().
  virtual scoped_ptr<fileapi::FileStreamWriter> CreateFileStreamWriter(
      const fileapi::FileSystemURL& url,
      int64 offset,
      fileapi::FileSystemContext* context) = 0;
};

}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_FILEAPI_FILE_SYSTEM_BACKEND_DELEGATE_H_


text:
module StylistsHelper
end


text:
__Version__ = "1.0.0"

import arcpy
import FileTransformations

# declare map
mxd = arcpy.mapping.MapDocument("CURRENT")

# Import data from ArcMap
fileToConvert = arcpy.GetParameterAsText(0)  # shapefile or GeoDatabase
listFieldValues = arcpy.GetParameterAsText(1)  # text file
outLocation = arcpy.GetParameterAsText(2)  # folder
fieldName = arcpy.GetParameterAsText(3)  # text field
spreadsheetType = arcpy.GetParameterAsText(4)  # text field -- Valid responses are dbf or csv

# translate file into layer
lyr = arcpy.mapping.Layer(fileToConvert)
lyr.name = "MyFile"

# declare arrays for this script
fieldValues = []
fileName = []
filePath = []

# declare the file to open
fin = open(listFieldValues)

# tell end user if there is an error
if fin.closed:
    arcpy.AddMessage("ERROR: File failed to open")

for line in fin:
    # Turn each line in the file into an entry to the array
    lineClear = str.strip(line)
    fieldValues.append(lineClear)

# make file names from UIDs
for i in range(len(fieldValues)):
        fileName.append(fieldValues[i] + ".dbf")

for y in range(len(fileName)):
        filePath.append(outLocation + "\\" + fileName[y])

for z in range(len(fieldValues)):
    # Extract out only the entries that are wanted
    arcpy.AddMessage("Currently extracting " + fieldValues[z] + " in " + fieldName)
    if lyr.name == "MyFile":
        lyr.definitionQuery = fieldName + " =" + "'" + fieldValues[z] + "'"
    arcpy.CopyRows_management(lyr, filePath[z])
fin.close()

if spreadsheetType == "csv":
    FileTransformations.dbf2csv(outLocation, fieldValues, filePath)
elif spreadsheetType == "tsv":
    FileTransformations.dbf2tsv(outLocation, fieldValues, filePath)


text:
define([
    'underscore',
    'web-utils',
    "core-basedir/reports/qe/ui/js/common/qe.utils"
], function (_, webUtils, qeUtils) {
    var CTGridConfig = function () {

        this.bgpRouterColumns = [
                {
                    field:"ip",
                    id:"ip",
                    name:"IP Address",
                    sortable: true,
                    sorter : comparatorIP
                },
                {
                    field:"role",
                    id:"role",
                    name:"Type",
                    sortable: true
                },
                {
                    field:"vendor",
                    id:"vendor",
                    name:"Vendor",
                    sortable: true
                },
                {
                    field:"name",
                    id:"name",
                    name:"HostName",
                    sortable: true
                }
        ];

        this.projectInstancesColumns = [
            {
                field: 'uuid',
                name: 'UUID',
                width: 100
            },
            {
                field: 'vmName',
                name: 'Instance Name',
                formatter: function (r, c, v, cd, dc) {
                    if(!contrail.checkIfExist(dc['vmName'])) {
                        return '-';
                    } else if(!contrail.checkIfExist(dc['vnFQN']) || ctwu.isServiceVN(dc['vnFQN'])){
                        return cowf.formatElementName({name: 'instance', value: dc['vmName'], cssClass: 'cell-no-link'});
                    } else {
                        return cowf.formatElementName({name: 'instance', value: dc['vmName'], cssClass: 'cell-hyperlink-blue'});
                    }
                },
                width: 150,
                searchable: true,
                events: {
                    onClick: ctwu.onClickNetworkMonitorGrid
                },
                exportConfig: {
                    allow: true,
                    stdFormatter: false
                }
            },
            {
                field: 'vn',
                name: 'Networks',
                formatter: function (r, c, v, cd, dc) {
                    return cowf.formatElementName({name: 'vn', value: dc['vn'], cssClass: 'cell-hyperlink-blue'});
                },
                width: 150,
                searchable: true,
                events: {
                    onClick: ctwu.onClickNetworkMonitorGrid
                },
            },
            {
                field: 'intfCnt',
                name: 'Interfaces',
                width: 80
            },
            {
                field: 'fipCnt',
                name: 'Floating IPs',
                width: 80
            },
            {
                field: 'vRouter',
                name: 'Virtual Router',
                formatter: function (r, c, v, cd, dc) {
                    return cowf.formatElementName({name: 'vRouter', value: dc['vRouter'], cssClass: 'cell-hyperlink-blue'});
                },
                width: 100,
                events: {
                    onClick: ctwu.onClickNetworkMonitorGrid
                },
                exportConfig: {
                    allow: true,
                    stdFormatter: false
                }
            },
            {
                field: 'ip',
                name: 'IP Address',
                formatter: function (r, c, v, cd, dc) {
                    return ctwu.formatIPArray(dc['ip']);
                },
                width: 110,
                exportConfig: {
                    allow: true,
                    stdFormatter: false
                }
            },
            {
                field: '',
                name: 'Aggr. Traffic In/Out (Last 1 Hr)',
                formatter: function (r, c, v, cd, dc) {
                    return cowu.addUnits2Bytes(dc['inBytes60'], true) + ' / ' + cowu.addUnits2Bytes(dc['outBytes60'], true);
                },
                width: 200
            },
            {
                field: '',
                name: '',
                width: 30,
                maxWidth: 30,
                formatter: function (r, c, v, cd, dc) {
                    var errorMessage = '', instanceHealthCheckStatus = null;

                    if (contrail.checkIfExist(dc.raw_json) && !contrail.checkIfKeyExistInObject(false, dc.raw_json.value, 'UveVirtualMachineAgent')) {
                        errorMessage = ctwm.INSTANCE_DATA_NOT_AVAILABLE;
                    } else if (contrail.checkIfKeyExistInObject(true, dc, 'ui_added_parameters.instance_health_check_status') && dc['ui_added_parameters']['instance_health_check_status'] === false) {
                        errorMessage = ctwm.HEALTH_CHECK_STATUS_INACTIVE;
                    }

                    return (errorMessage !== '') ? '' : '';
                 }
            }
        ];
        this.getVMInterfacesLazyRemoteConfig = function () {
            return [
                {
                    getAjaxConfig: function (responseJSON) {
                        var lazyAjaxConfig,
                            interfaceList = getValueByJsonPath(responseJSON, 'value;UveVirtualMachineAgent;interface_list', []);

                        lazyAjaxConfig = {
                            url: ctwc.URL_VM_INTERFACES,
                            type: 'POST',
                            data: JSON.stringify({kfilt: interfaceList.join(','), parentType: ctwc.TYPE_VIRTUAL_MACHINE})
                        };

                        return lazyAjaxConfig;
                    },
                    successCallback: function (response, contrailViewModel) {
                        var interfaceMap = ctwp.instanceInterfaceDataParser(response),
                            interfaceDetailsList = _.values(interfaceMap);

                        contrailViewModel.attributes['value']['UveVirtualMachineAgent']['interface_details'] = interfaceDetailsList;
                        if (interfaceDetailsList.length > 0) {
                            contrailViewModel.attributes.vm_name = interfaceDetailsList[0]['vm_name'];
                        }
                    }
                }
            ]
        };

        this.instanceInterfaceColumns = [
            {
                field: "name",
                name: "Name",
                minWidth: 100,
                searchable: true
            },
            {
                field: 'uuid',
                name: 'UUID',
                minWidth: 100,
                searchable: true
            },
            {
                field: 'ip',
                name: 'IP Address',
                minWidth: 100,
                searchable: true
            },
            {
                field: 'vm_name',
                name: 'Instance Name',
                minWidth: 250,
                searchable: true
            },
            {
                field: 'floatingIP',
                name: 'Floating IPs ( Agg Stats In/Out)',
                formatter: function (r, c, v, cd, dc) {
                    if (!contrail.checkIfExist(dc['floatingIP']) || dc['floatingIP'].length == 0) {
                        return '-';
                    } else {
                        return dc['floatingIP'].join(', ');
                    }
                },
                minWidth: 200
            },
            {
                field: '',
                name: 'Traffic In/Out (Last 1 Hr)',
                minWidth: 150,
                formatter: function (r, c, v, cd, dc) {
                    return contrail.format("{0} / {1}", cowu.addUnits2Bytes(dc['inBytes60'], true), cowu.addUnits2Bytes(dc['outBytes60'], true));
                }
            },
            {
                field: '',
                name: 'Throughput In/Out',
                minWidth: 150,
                formatter: function (r, c, v, cd, dc) {
                    return contrail.format("{0} / {1}", formatThroughput(dc['in_bw_usage'], true), formatThroughput(dc['out_bw_usage'], true));
                }
            },
            {
                name: 'Status',
                minWidth: 100,
                searchable: true,
                formatter: function (r, c, v, cd, dc) {
                    if (dc.active) {
                        return ('

 Active');
                    } else {
                        return ('

 Inactive');
                    }
                }
            },
            {
                field: '',
                name: '',
                minWidth: 30,
                maxWidth: 30,
                formatter: function (r, c, v, cd, dc) {
                    if (dc['is_health_check_active'] === false) {
                        return '';
                    }

                    return '';
                }
            }
        ];

        this.getAcknowledgeAction = function (onClickFunction, divider) {
            return {
                title: ctwl.TITLE_ACKNOWLEDGE,
                iconClass: 'fa fa-check-square',
                width: 80,
                disabled:true,
                divider: contrail.checkIfExist(divider) ? divider : false,
                onClick: onClickFunction
            };
        };
        this.getAlertHistoryAction = function (onClickFunction, divider) {
            return {
                title: ctwl.TITLE_ALARM_HISTORY,
                iconClass: 'fa fa-th',
                width: 80,
                divider: contrail.checkIfExist(divider) ? divider : false,
                onClick: onClickFunction
            };
        };
        this.getEditConfig = function (title, onClickFunction, divider) {
            return {
                title: title,
                iconClass: 'fa fa-pencil-square-o',
                width: 80,
                divider: contrail.checkIfExist(divider) ? divider : false,
                onClick: onClickFunction
            }
        };
        this.getDeleteConfig = function (title, onClickFunction, divider) {
            return {
                title: title,
                iconClass: 'fa fa-trash',
                width: 80,
                divider: contrail.checkIfExist(divider) ? divider : false,
                onClick: onClickFunction
            }
        };
        this.getEditAction = function (onClickFunction, title, divider) {
            return {
                title: title,
                iconClass: 'fa fa-pencil-square-o',
                width: 80,
                divider: contrail.checkIfExist(divider) ? divider : false,
                onClick: onClickFunction
            }
        };
        this.getListAction = function (onClickFunction, title, divider) {
            return {
                title: title,
                iconClass: 'fa fa-list-alt',
                width: 80,
                divider: contrail.checkIfExist(divider) ? divider : false,
                onClick: onClickFunction
            }
        };
        this.getDeleteAction = function (onClickFunction, divider) {
            return {
                title: ctwl.TITLE_DELETE_CONFIG,
                iconClass: 'fa fa-trash',
                width: 80,
                divider: contrail.checkIfExist(divider) ? divider : false,
                onClick: onClickFunction
            };
        };
        this.getActiveDnsConfig = function (title, onClickFunction, divider) {
            return {
                title: title,
               // iconClass: 'icon-trash',
                width: 80,
                divider: contrail.checkIfExist(divider) ? divider : false,
                onClick: onClickFunction
            }
        };
        this.getVMDetailsLazyRemoteConfig = function (type) {
            return [
                {
                    getAjaxConfig: function (responseJSON) {
                        var uuids = [], lazyAjaxConfig;
                        var whereClause = null;
                        var len = responseJSON.length;

                        for (var i = 0; i < len; i++) {
                            uuids.push(responseJSON[i].name);
                        }
                        var domCookie = ctwc.COOKIE_DOMAIN;
                        var projCookie = ctwc.COOKIE_PROJECT;
                        var vnCookie = ctwc.COOKIE_VIRTUAL_NETWORK;
                        whereClause = "(name Starts with " + domCookie + ":" + projCookie +
                            ":)";
                        if (ctwc.ALL_PROJECTS === projCookie) {
                            whereClause = "(name Starts with " + domCookie + ":)";
                        } else if (ctwc.ALL_NETWORKS == vnCookie) {
                            whereClause = "(name Starts with " + domCookie + ":" +
                                projCookie + ":)";
                        }
                        var whereClause =
                            qeUtils.formatUIWhereClauseConfigByUserRole(whereClause, "vm_uuid", uuids);
                        var qObj = {table: "StatTable.UveVMInterfaceAgent.if_stats",
                                where: whereClause};
                        var postData = qeUtils.formatQEUIQuery(qObj);

                        lazyAjaxConfig = {
                            url: cowc.URL_QE_QUERY,
                            type: 'POST',
                            data: JSON.stringify(postData)
                        }
                        return lazyAjaxConfig;
                    },
                    successCallback: function (response, contrailListModel) {
                        var statDataList = ctwp.parseInstanceStats(response.data, type),
                            dataItems = contrailListModel.getItems(),
                            updatedDataItems = [],
                            statData;

                        for (var j = 0; j < statDataList.length; j++) {
                            statData = statDataList[j];
                            for (var i = 0; i < dataItems.length; i++) {
                                var dataItem = dataItems[i];
                                if (statData['name'] == dataItem['name']) {
                                    dataItem['inBytes60'] = ifNull(statData['inBytes'], 0);
                                    dataItem['outBytes60'] = ifNull(statData['outBytes'], 0);
                                    updatedDataItems.push(dataItem);
                                    break;
                                }
                            }
                        }
                        contrailListModel.updateData(updatedDataItems);
                    }
                },
                {
                    getAjaxConfig: function (responseJSON) {
                        var lazyAjaxConfig,
                            interfaceList = [];

                        for (var i = 0; i < responseJSON.length; i++) {
                            var instance = responseJSON[i],
                                uveVirtualMachineAgent = contrail.handleIfNull(instance['value']['UveVirtualMachineAgent'], {}),
                                instanceInterfaces = contrail.handleIfNull(uveVirtualMachineAgent['interface_list'], []);
                            if(instanceInterfaces.length > 0) {
                                interfaceList.push(instanceInterfaces);
                            }
                        }

                        lazyAjaxConfig = {
                            url: ctwc.URL_VM_INTERFACES,
                            type: 'POST',
                            data: JSON.stringify({
                                parentType: ctwc.TYPE_VIRTUAL_MACHINE,
                                kfilt: interfaceList.join(','),
                                cfilt: ctwc.FILTERS_INSTANCE_LIST_INTERFACES.join(',')
                            })
                        };
                        return lazyAjaxConfig;
                    },
                    successCallback: function (response, contrailListModel) {
                        var interfaceMap = ctwp.instanceInterfaceDataParser(response),
                            dataItems = contrailListModel.getItems(),
                            updatedDataItems = [];

                        for (var i = 0; i < dataItems.length; i++) {
                            var dataItem = dataItems[i],
                                uveVirtualMachineAgent = contrail.handleIfNull(dataItem['value']['UveVirtualMachineAgent'], {}),
                                interfaceList = contrail.handleIfNull(uveVirtualMachineAgent['interface_list'], []),
                                interfaceDetailsList = [],
                                inThroughput = 0, outThroughput = 0, throughput = 0;

                            for (var j = 0; j < interfaceList.length; j++) {
                                var interfaceDetail = interfaceMap[interfaceList[j]],
                                    ifStats;

                                if (contrail.checkIfExist(interfaceDetail)) {
                                    ifStats = ifNull(interfaceDetail['if_stats'], {});
                                    inThroughput += ifNull(interfaceDetail['in_bw_usage'], 0);
                                    outThroughput += ifNull(interfaceDetail['out_bw_usage'], 0);
                                    interfaceDetailsList.push(interfaceDetail);
                                }
                            }

                            if(interfaceDetailsList.length > 0) {
                                throughput = inThroughput + outThroughput;
                                dataItem['throughput'] = throughput;
                                dataItem['fipCnt'] = 0;
                                dataItem['size'] = throughput;
                                uveVirtualMachineAgent['interface_details'] = interfaceDetailsList;
                                dataItem['vn'] = ifNull(jsonPath(interfaceDetailsList, '$...virtual_network'), [])

                                if (dataItem['vn'] != false) {
                                    if (dataItem['vn'].length != 0) {
                                        dataItem['vnFQN'] = dataItem['vn'][0];
                                    }
                                    dataItem['vn'] = ctwu.formatVNName(dataItem['vn'],
                                                                       cowc.COOKIE_DOMAIN + ":" +
                                                                       cowc.COOKIE_PROJECT);
                                } else {
                                    dataItem['vn'] = '-';
                                }

                                dataItem['ip'] = [];
                                dataItem['fipCnt'] = 0;
                                for (var k = 0; k < interfaceDetailsList.length; k++) {

                                    if (interfaceDetailsList[k]['is_health_check_active'] === false) {
                                        dataItem['ui_added_parameters']['instance_health_check_status'] = false;
                                    }

                                    if (interfaceDetailsList[k]['ip6_active'] == true) {
                                        if (interfaceDetailsList[k]['ip_address'] != '0.0.0.0')
                                            dataItem['ip'].push(interfaceDetailsList[k]['ip_address']);
                                        if (interfaceDetailsList[k]['ip6_address'] != null)
                                            dataItem['ip'].push(interfaceDetailsList[k]['ip6_address']);
                                    } else {
                                        if (interfaceDetailsList[k]['ip_address'] != '0.0.0.0')
                                            dataItem['ip'].push(interfaceDetailsList[k]['ip_address']);
                                    }
                                    dataItem['fipCnt'] += interfaceDetailsList[k]['count_floating_ips'];
                                }
                                /*
                                 if (interfaceDetailsList.length > 0) {
                                 dataItem['vmName'] = interfaceDetailsList[0]['vm_name'];
                                 }
                                 */
                                updatedDataItems.push(dataItem);
                            }
                        }
                        contrailListModel.updateData(updatedDataItems);
                    }
                }
            ];
        };
    };

    return CTGridConfig;
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Certificate.CertificateRep (Java Platform SE 6)
</TITLE>

<META NAME="date" CONTENT="2007-03-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

JavaTM Platform
Standard Ed. 6

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法

java.security.cert

类 Certificate.CertificateRep

java.lang.Object
  java.security.cert.Certificate.CertificateRep

所有已实现的接口:
Serializable

正在封闭类:
Certificate

protected static class Certificate.CertificateRep
extends Object
implements Serializable

用于序列化的替换 Certificate 类。

从以下版本开始:

1.3

另请参见:
序列化表格

构造方法摘要

protected
Certificate.CertificateRep(String type,
                           byte[] data)

          构造带有 Certificate 类型和 Certificate 编码字节的替代 Certificate 类。

方法摘要

protected  Object
readResolve()

          解析该 Certificate 对象。

从类 java.lang.Object 继承的方法

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

构造方法详细信息

Certificate.CertificateRep

protected Certificate.CertificateRep(String type,
                                     byte[] data)

构造带有 Certificate 类型和 Certificate 编码字节的替代 Certificate 类。

参数:
type - Certificate 类型的标准名称。

data - Certificate 数据。

方法详细信息

readResolve

protected Object readResolve()
                      throws ObjectStreamException

解析该 Certificate 对象。

返回:
解析后的 Certificate 对象

抛出:

ObjectStreamException - 如果无法解析该 Certificate

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

JavaTM Platform
Standard Ed. 6

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法

提交错误或意见
有关更多的 API 参考资料和开发人员文档,请参阅 Java SE 开发人员文档。该文档包含更详细的、面向开发人员的描述,以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 2007 Sun Microsystems, Inc. 保留所有权利。 请遵守许可证条款。另请参阅文档重新分发政策。


text:
<Type Name="TextViewEditable" FullName="Hyena.Widgets.TextViewEditable">
  <TypeSignature Language="C#" Value="public class TextViewEditable : Gtk.TextView, Gtk.Editable" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit TextViewEditable extends Gtk.TextView implements class GLib.IWrapper, class Gtk.Editable" />
  <AssemblyInfo>
    <AssemblyName>Hyena.Gui</AssemblyName>
    <AssemblyVersion>1.4.0.0</AssemblyVersion>
    <AssemblyVersion>1.5.0.0</AssemblyVersion>
    <AssemblyVersion>2.4.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>Gtk.TextView</BaseTypeName>
  </Base>
  <Interfaces>
    <Interface>
      <InterfaceName>Gtk.Editable</InterfaceName>
    </Interface>
  </Interfaces>
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public TextViewEditable ();" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor() cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Changed">
      <MemberSignature Language="C#" Value="public event EventHandler Changed;" />
      <MemberSignature Language="ILAsm" Value=".event class System.EventHandler Changed" />
      <MemberType>Event</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.EventHandler</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="DeleteSelection">
      <MemberSignature Language="C#" Value="public void DeleteSelection ();" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance void DeleteSelection() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="DeleteText">
      <MemberSignature Language="C#" Value="public void DeleteText (int start_pos, int end_pos);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance void DeleteText(int32 start_pos, int32 end_pos) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="start_pos" Type="System.Int32" />
        <Parameter Name="end_pos" Type="System.Int32" />
      </Parameters>
      <Docs>
        <param name="start_pos">To be added.</param>
        <param name="end_pos">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="GetChars">
      <MemberSignature Language="C#" Value="public string GetChars (int start_pos, int end_pos);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance string GetChars(int32 start_pos, int32 end_pos) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.String</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="start_pos" Type="System.Int32" />
        <Parameter Name="end_pos" Type="System.Int32" />
      </Parameters>
      <Docs>
        <param name="start_pos">To be added.</param>
        <param name="end_pos">To be added.</param>
        To be added.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="GetSelectionBounds">
      <MemberSignature Language="C#" Value="public bool GetSelectionBounds (out int start, out int end);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance bool GetSelectionBounds(int32 start, int32 end) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Boolean</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="start" Type="System.Int32&" RefType="out" />
        <Parameter Name="end" Type="System.Int32&" RefType="out" />
      </Parameters>
      <Docs>
        <param name="start">To be added.</param>
        <param name="end">To be added.</param>
        To be added.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Gtk.Editable.CopyClipboard">
      <MemberSignature Language="C#" Value="void Editable.CopyClipboard ();" />
      <MemberSignature Language="ILAsm" Value=".method hidebysig newslot virtual instance void Gtk.Editable.CopyClipboard() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Gtk.Editable.CutClipboard">
      <MemberSignature Language="C#" Value="void Editable.CutClipboard ();" />
      <MemberSignature Language="ILAsm" Value=".method hidebysig newslot virtual instance void Gtk.Editable.CutClipboard() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Gtk.Editable.PasteClipboard">
      <MemberSignature Language="C#" Value="void Editable.PasteClipboard ();" />
      <MemberSignature Language="ILAsm" Value=".method hidebysig newslot virtual instance void Gtk.Editable.PasteClipboard() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="InsertText">
      <MemberSignature Language="C#" Value="public void InsertText (string new_text, ref int position);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance void InsertText(string new_text, int32 position) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="new_text" Type="System.String" />
        <Parameter Name="position" Type="System.Int32&" RefType="ref" />
      </Parameters>
      <Docs>
        <param name="new_text">To be added.</param>
        <param name="position">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="IsEditable">
      <MemberSignature Language="C#" Value="public bool IsEditable { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance bool IsEditable" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Boolean</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Position">
      <MemberSignature Language="C#" Value="public int Position { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance int32 Position" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Int32</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="SelectRegion">
      <MemberSignature Language="C#" Value="public void SelectRegion (int start, int end);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance void SelectRegion(int32 start, int32 end) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="start" Type="System.Int32" />
        <Parameter Name="end" Type="System.Int32" />
      </Parameters>
      <Docs>
        <param name="start">To be added.</param>
        <param name="end">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="TextDeleted">
      <MemberSignature Language="C#" Value="public event Gtk.TextDeletedHandler TextDeleted;" />
      <MemberSignature Language="ILAsm" Value=".event class Gtk.TextDeletedHandler TextDeleted" />
      <MemberType>Event</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Gtk.TextDeletedHandler</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="TextInserted">
      <MemberSignature Language="C#" Value="public event Gtk.TextInsertedHandler TextInserted;" />
      <MemberSignature Language="ILAsm" Value=".event class Gtk.TextInsertedHandler TextInserted" />
      <MemberType>Event</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.4.0.0</AssemblyVersion>
        <AssemblyVersion>1.5.0.0</AssemblyVersion>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Gtk.TextInsertedHandler</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ideastormsoftware</groupId>
    <artifactId>presmedia</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <!-- put your configurations here -->
                    <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                            <manifestEntries>
                                <Main-Class>${app.main.class}</Main-Class>
                                <X-Compile-Source-JDK>${maven.compile.source}</X-Compile-Source-JDK>
                                <X-Compile-Target-JDK>${maven.compile.target}</X-Compile-Target-JDK>
                            </manifestEntries>
                        </transformer>
                    </transformers>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacpp-presets</artifactId>
            <version>0.10</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacv</artifactId>
            <version>0.10</version>
        </dependency>
        <dependency>
            <groupId>org.bytedeco.javacpp-presets</groupId>
            <artifactId>ffmpeg</artifactId>
            <version>2.5.1-0.10</version>
            <classifier>windows-x86_64</classifier>
        </dependency>
        <dependency>
            <groupId>org.bytedeco.javacpp-presets</groupId>
            <artifactId>opencv</artifactId>
            <version>2.4.10-0.10</version>
            <classifier>windows-x86_64</classifier>
        </dependency>
        <dependency>
            <groupId>org.bytedeco.javacpp-presets</groupId>
            <artifactId>ffmpeg</artifactId>
            <version>2.5.1-0.10</version>
            <classifier>macosx-x86_64</classifier>
        </dependency>
        <dependency>
            <groupId>org.bytedeco.javacpp-presets</groupId>
            <artifactId>opencv</artifactId>
            <version>2.4.10-0.10</version>
            <classifier>macosx-x86_64</classifier>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.imgscalr</groupId>
            <artifactId>imgscalr-lib</artifactId>
            <version>4.2</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>de.humatic</groupId>
            <artifactId>dsj</artifactId>
            <version>0.8.8</version>
        </dependency>
        <dependency>
            <groupId>org.fusesource</groupId>
            <artifactId>sigar</artifactId>
            <version>1.6.4</version>
            <classifier>native</classifier>
        </dependency>
        <dependency>
            <groupId>org.fusesource</groupId>
            <artifactId>sigar</artifactId>
            <version>1.6.4</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <app.main.class>com.ideastormsoftware.presmedia.ui.ControlView</app.main.class>
    </properties>
</project>