text:
[![Circle CI](https://circleci.com/gh/guillaumebreton/mqttcat.svg?style=svg)](https://circleci.com/gh/guillaumebreton/mqttcat)
# Install

The app is not available in any package manager.

~~~bash
go get
go build
~~~

# Credits

- MQTTcat is using [paho](http://www.eclipse.org/paho/clients/golang/)

# Feature

Mqttcat sends to mqtt broker formatted input from stdin
that should looks like topic:qos:hex_message.

~~~bash
usage: mqttcat [<flags>] <host> <port>

A netcat for mqtt.

Flags:
  --help               Show help.
  --id="mqtt-cat"      The id of the connected device
  --protocol="tcp"     The protocol to use (tcp, ssl, ws)
  --topics=TOPICS      List of topics
  --username=USERNAME  MQTT server username
  --password=PASSWORD  MQTT server password
  --clean              Set clean session flag
  --keepalive=10       Set the keep alive timer (in sec)

Args:
  <host>  IP address of the host
  <port>  Port of the server

~~~

#Usage

##Cat a file

cat data.dat |  mqttcat localhost 1883

##Read from stdin

~~~bash
./mqttcat localhost 1883 << EOF
a:1:48
a:1:46
b:1:45
EOF
~~~


text:
using namespace lldb_private;
using namespace lldb;

// Support ptrace extensions even when compiled without required kernel support
#ifndef NT_X86_XSTATE
#define NT_X86_XSTATE 0x202
#endif

#define REG_CONTEXT_SIZE (GetGPRSize() + sizeof(FPR))

static uint32_t size_and_rw_bits(size_t size, bool read, bool write) {
  uint32_t rw;

  if (read)
    rw = 0x3; // READ or READ/WRITE
  else if (write)
    rw = 0x1; // WRITE
  else
    assert(0 && "read and write cannot both be false");

  switch (size) {
  case 1:
    return rw;
  case 2:
    return (0x1 << 2) | rw;
  case 4:
    return (0x3 << 2) | rw;
  case 8:
    return (0x2 << 2) | rw;
  default:
    assert(0 && "invalid size, must be one of 1, 2, 4, or 8");
    return 0; // Unreachable. Just to silence compiler.
  }
}

RegisterContextPOSIXProcessMonitor_x86_64::
    RegisterContextPOSIXProcessMonitor_x86_64(
        Thread &thread, uint32_t concrete_frame_idx,
        lldb_private::RegisterInfoInterface *register_info)
    : RegisterContextPOSIX_x86(thread, concrete_frame_idx, register_info) {
  // Store byte offset of fctrl (i.e. first register of FPR) wrt 'UserArea'
  const RegisterInfo *reg_info_fctrl = GetRegisterInfoByName("fctrl");
  m_fctrl_offset_in_userarea = reg_info_fctrl->byte_offset;

  m_iovec.iov_base = &m_fpr.xsave;
  m_iovec.iov_len = sizeof(m_fpr.xsave);
}

ProcessMonitor &RegisterContextPOSIXProcessMonitor_x86_64::GetMonitor() {
  ProcessSP base = CalculateProcess();
  ProcessFreeBSD *process = static_cast<ProcessFreeBSD *>(base.get());
  return process->GetMonitor();
}

bool RegisterContextPOSIXProcessMonitor_x86_64::ReadGPR() {
  ProcessMonitor &monitor = GetMonitor();
  return monitor.ReadGPR(m_thread.GetID(), &m_gpr_x86_64, GetGPRSize());
}

bool RegisterContextPOSIXProcessMonitor_x86_64::ReadFPR() {
  ProcessMonitor &monitor = GetMonitor();
  if (GetFPRType() == eFXSAVE)
    return monitor.ReadFPR(m_thread.GetID(), &m_fpr.fxsave,
                           sizeof(m_fpr.fxsave));

  if (GetFPRType() == eXSAVE)
    return monitor.ReadRegisterSet(m_thread.GetID(), &m_iovec,
                                   sizeof(m_fpr.xsave), NT_X86_XSTATE);
  return false;
}

bool RegisterContextPOSIXProcessMonitor_x86_64::WriteGPR() {
  ProcessMonitor &monitor = GetMonitor();
  return monitor.WriteGPR(m_thread.GetID(), &m_gpr_x86_64, GetGPRSize());
}

bool RegisterContextPOSIXProcessMonitor_x86_64::WriteFPR() {
  ProcessMonitor &monitor = GetMonitor();
  if (GetFPRType() == eFXSAVE)
    return monitor.WriteFPR(m_thread.GetID(), &m_fpr.fxsave,
                            sizeof(m_fpr.fxsave));

  if (GetFPRType() == eXSAVE)
    return monitor.WriteRegisterSet(m_thread.GetID(), &m_iovec,
                                    sizeof(m_fpr.xsave), NT_X86_XSTATE);
  return false;
}

bool RegisterContextPOSIXProcessMonitor_x86_64::ReadRegister(
    const unsigned reg, RegisterValue &value) {
  ProcessMonitor &monitor = GetMonitor();

#if defined(__FreeBSD__)
  if (reg >= m_reg_info.first_dr)
    return monitor.ReadDebugRegisterValue(
        m_thread.GetID(), GetRegisterOffset(reg), GetRegisterName(reg),
        GetRegisterSize(reg), value);
#endif
  return monitor.ReadRegisterValue(m_thread.GetID(), GetRegisterOffset(reg),
                                   GetRegisterName(reg), GetRegisterSize(reg),
                                   value);
}

bool RegisterContextPOSIXProcessMonitor_x86_64::WriteRegister(
    const unsigned reg, const RegisterValue &value) {
  unsigned reg_to_write = reg;
  RegisterValue value_to_write = value;

  // Check if this is a subregister of a full register.
  const RegisterInfo *reg_info = GetRegisterInfoAtIndex(reg);
  if (reg_info->invalidate_regs &&
      (reg_info->invalidate_regs[0] != LLDB_INVALID_REGNUM)) {
    RegisterValue full_value;
    uint32_t full_reg = reg_info->invalidate_regs[0];
    const RegisterInfo *full_reg_info = GetRegisterInfoAtIndex(full_reg);

    // Read the full register.
    if (ReadRegister(full_reg_info, full_value)) {
      Status error;
      ByteOrder byte_order = GetByteOrder();
      uint8_t dst[RegisterValue::kMaxRegisterByteSize];

      // Get the bytes for the full register.
      const uint32_t dest_size = full_value.GetAsMemoryData(
          full_reg_info, dst, sizeof(dst), byte_order, error);
      if (error.Success() && dest_size) {
        uint8_t src[RegisterValue::kMaxRegisterByteSize];

        // Get the bytes for the source data.
        const uint32_t src_size = value.GetAsMemoryData(
            reg_info, src, sizeof(src), byte_order, error);
        if (error.Success() && src_size && (src_size < dest_size)) {
          // Copy the src bytes to the destination.
          memcpy(dst + (reg_info->byte_offset & 0x1), src, src_size);
          // Set this full register as the value to write.
          value_to_write.SetBytes(dst, full_value.GetByteSize(), byte_order);
          value_to_write.SetType(full_reg_info);
          reg_to_write = full_reg;
        }
      }
    }
  }

  ProcessMonitor &monitor = GetMonitor();
#if defined(__FreeBSD__)
  if (reg >= m_reg_info.first_dr)
    return monitor.WriteDebugRegisterValue(
        m_thread.GetID(), GetRegisterOffset(reg_to_write),
        GetRegisterName(reg_to_write), value_to_write);
#endif
  return monitor.WriteRegisterValue(
      m_thread.GetID(), GetRegisterOffset(reg_to_write),
      GetRegisterName(reg_to_write), value_to_write);
}

bool RegisterContextPOSIXProcessMonitor_x86_64::ReadRegister(
    const RegisterInfo *reg_info, RegisterValue &value) {
  if (!reg_info)
    return false;

  const uint32_t reg = reg_info->kinds[eRegisterKindLLDB];

  if (IsFPR(reg, GetFPRType())) {
    if (!ReadFPR())
      return false;
  } else {
    uint32_t full_reg = reg;
    bool is_subreg = reg_info->invalidate_regs &&
                     (reg_info->invalidate_regs[0] != LLDB_INVALID_REGNUM);

    if (is_subreg) {
      // Read the full aligned 64-bit register.
      full_reg = reg_info->invalidate_regs[0];
    }

    bool success = ReadRegister(full_reg, value);

    if (success) {
      // If our read was not aligned (for ah,bh,ch,dh), shift our returned
      // value one byte to the right.
      if (is_subreg && (reg_info->byte_offset & 0x1))
        value.SetUInt64(value.GetAsUInt64() >> 8);

      // If our return byte size was greater than the return value reg size,
      // then use the type specified by reg_info rather than the uint64_t
      // default
      if (value.GetByteSize() > reg_info->byte_size)
        value.SetType(reg_info);
    }
    return success;
  }

  if (reg_info->encoding == eEncodingVector) {
    ByteOrder byte_order = GetByteOrder();

    if (byte_order != ByteOrder::eByteOrderInvalid) {
      if (reg >= m_reg_info.first_st && reg <= m_reg_info.last_st)
        value.SetBytes(m_fpr.fxsave.stmm[reg - m_reg_info.first_st].bytes,
                       reg_info->byte_size, byte_order);
      if (reg >= m_reg_info.first_mm && reg <= m_reg_info.last_mm)
        value.SetBytes(m_fpr.fxsave.stmm[reg - m_reg_info.first_mm].bytes,
                       reg_info->byte_size, byte_order);
      if (reg >= m_reg_info.first_xmm && reg <= m_reg_info.last_xmm)
        value.SetBytes(m_fpr.fxsave.xmm[reg - m_reg_info.first_xmm].bytes,
                       reg_info->byte_size, byte_order);
      if (reg >= m_reg_info.first_ymm && reg <= m_reg_info.last_ymm) {
        // Concatenate ymm using the register halves in xmm.bytes and
        // ymmh.bytes
        if (GetFPRType() == eXSAVE && CopyXSTATEtoYMM(reg, byte_order))
          value.SetBytes(m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes,
                         reg_info->byte_size, byte_order);
        else
          return false;
      }
      return value.GetType() == RegisterValue::eTypeBytes;
    }
    return false;
  }

  // Get pointer to m_fpr.fxsave variable and set the data from it. Byte
  // offsets of all registers are calculated wrt 'UserArea' structure. However,
  // ReadFPR() reads fpu registers {using ptrace(PT_GETFPREGS,..)} and stores
  // them in 'm_fpr' (of type FPR structure). To extract values of fpu
  // registers, m_fpr should be read at byte offsets calculated wrt to FPR
  // structure.

  // Since, FPR structure is also one of the member of UserArea structure.
  // byte_offset(fpu wrt FPR) = byte_offset(fpu wrt UserArea) -
  // byte_offset(fctrl wrt UserArea)
  assert((reg_info->byte_offset - m_fctrl_offset_in_userarea) < sizeof(m_fpr));
  uint8_t *src =
      (uint8_t *)&m_fpr + reg_info->byte_offset - m_fctrl_offset_in_userarea;
  switch (reg_info->byte_size) {
  case 1:
    value.SetUInt8(*(uint8_t *)src);
    return true;
  case 2:
    value.SetUInt16(*(uint16_t *)src);
    return true;
  case 4:
    value.SetUInt32(*(uint32_t *)src);
    return true;
  case 8:
    value.SetUInt64(*(uint64_t *)src);
    return true;
  default:
    assert(false && "Unhandled data size.");
    return false;
  }
}

bool RegisterContextPOSIXProcessMonitor_x86_64::WriteRegister(
    const RegisterInfo *reg_info, const RegisterValue &value) {
  const uint32_t reg = reg_info->kinds[eRegisterKindLLDB];

  if (IsGPR(reg))
    return WriteRegister(reg, value);

  if (IsFPR(reg, GetFPRType())) {
    if (reg_info->encoding == eEncodingVector) {
      if (reg >= m_reg_info.first_st && reg <= m_reg_info.last_st)
        ::memcpy(m_fpr.fxsave.stmm[reg - m_reg_info.first_st].bytes,
                 value.GetBytes(), value.GetByteSize());

      if (reg >= m_reg_info.first_mm && reg <= m_reg_info.last_mm)
        ::memcpy(m_fpr.fxsave.stmm[reg - m_reg_info.first_mm].bytes,
                 value.GetBytes(), value.GetByteSize());

      if (reg >= m_reg_info.first_xmm && reg <= m_reg_info.last_xmm)
        ::memcpy(m_fpr.fxsave.xmm[reg - m_reg_info.first_xmm].bytes,
                 value.GetBytes(), value.GetByteSize());

      if (reg >= m_reg_info.first_ymm && reg <= m_reg_info.last_ymm) {
        if (GetFPRType() != eXSAVE)
          return false; // the target processor does not support AVX

        // Store ymm register content, and split into the register halves in
        // xmm.bytes and ymmh.bytes
        ::memcpy(m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes,
                 value.GetBytes(), value.GetByteSize());
        if (false == CopyYMMtoXSTATE(reg, GetByteOrder()))
          return false;
      }
    } else {
      // Get pointer to m_fpr.fxsave variable and set the data to it. Byte
      // offsets of all registers are calculated wrt 'UserArea' structure.
      // However, WriteFPR() takes m_fpr (of type FPR structure) and writes
      // only fpu registers using ptrace(PT_SETFPREGS,..) API. Hence fpu
      // registers should be written in m_fpr at byte offsets calculated wrt
      // FPR structure.

      // Since, FPR structure is also one of the member of UserArea structure.
      // byte_offset(fpu wrt FPR) = byte_offset(fpu wrt UserArea) -
      // byte_offset(fctrl wrt UserArea)
      assert((reg_info->byte_offset - m_fctrl_offset_in_userarea) <
             sizeof(m_fpr));
      uint8_t *dst = (uint8_t *)&m_fpr + reg_info->byte_offset -
                     m_fctrl_offset_in_userarea;
      switch (reg_info->byte_size) {
      case 1:
        *(uint8_t *)dst = value.GetAsUInt8();
        break;
      case 2:
        *(uint16_t *)dst = value.GetAsUInt16();
        break;
      case 4:
        *(uint32_t *)dst = value.GetAsUInt32();
        break;
      case 8:
        *(uint64_t *)dst = value.GetAsUInt64();
        break;
      default:
        assert(false && "Unhandled data size.");
        return false;
      }
    }

    if (WriteFPR()) {
      if (IsAVX(reg))
        return CopyYMMtoXSTATE(reg, GetByteOrder());
      return true;
    }
  }
  return false;
}

bool RegisterContextPOSIXProcessMonitor_x86_64::ReadAllRegisterValues(
    DataBufferSP &data_sp) {
  bool success = false;
  data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0));
  if (ReadGPR() && ReadFPR()) {
    uint8_t *dst = data_sp->GetBytes();
    success = dst != 0;

    if (success) {
      ::memcpy(dst, &m_gpr_x86_64, GetGPRSize());
      dst += GetGPRSize();
      if (GetFPRType() == eFXSAVE)
        ::memcpy(dst, &m_fpr.fxsave, sizeof(m_fpr.fxsave));
    }

    if (GetFPRType() == eXSAVE) {
      ByteOrder byte_order = GetByteOrder();

      // Assemble the YMM register content from the register halves.
      for (uint32_t reg = m_reg_info.first_ymm;
           success && reg <= m_reg_info.last_ymm; ++reg)
        success = CopyXSTATEtoYMM(reg, byte_order);

      if (success) {
        // Copy the extended register state including the assembled ymm
        // registers.
        ::memcpy(dst, &m_fpr, sizeof(m_fpr));
      }
    }
  }
  return success;
}

bool RegisterContextPOSIXProcessMonitor_x86_64::WriteAllRegisterValues(
    const DataBufferSP &data_sp) {
  bool success = false;
  if (data_sp && data_sp->GetByteSize() == REG_CONTEXT_SIZE) {
    uint8_t *src = data_sp->GetBytes();
    if (src) {
      ::memcpy(&m_gpr_x86_64, src, GetGPRSize());

      if (WriteGPR()) {
        src += GetGPRSize();
        if (GetFPRType() == eFXSAVE)
          ::memcpy(&m_fpr.fxsave, src, sizeof(m_fpr.fxsave));
        if (GetFPRType() == eXSAVE)
          ::memcpy(&m_fpr.xsave, src, sizeof(m_fpr.xsave));

        success = WriteFPR();
        if (success) {
          if (GetFPRType() == eXSAVE) {
            ByteOrder byte_order = GetByteOrder();

            // Parse the YMM register content from the register halves.
            for (uint32_t reg = m_reg_info.first_ymm;
                 success && reg <= m_reg_info.last_ymm; ++reg)
              success = CopyYMMtoXSTATE(reg, byte_order);
          }
        }
      }
    }
  }
  return success;
}

uint32_t RegisterContextPOSIXProcessMonitor_x86_64::SetHardwareWatchpoint(
    addr_t addr, size_t size, bool read, bool write) {
  const uint32_t num_hw_watchpoints = NumSupportedHardwareWatchpoints();
  uint32_t hw_index;

  for (hw_index = 0; hw_index < num_hw_watchpoints; ++hw_index) {
    if (IsWatchpointVacant(hw_index))
      return SetHardwareWatchpointWithIndex(addr, size, read, write, hw_index);
  }

  return LLDB_INVALID_INDEX32;
}

bool RegisterContextPOSIXProcessMonitor_x86_64::ClearHardwareWatchpoint(
    uint32_t hw_index) {
  if (hw_index < NumSupportedHardwareWatchpoints()) {
    RegisterValue current_dr7_bits;

    if (ReadRegister(m_reg_info.first_dr + 7, current_dr7_bits)) {
      uint64_t new_dr7_bits =
          current_dr7_bits.GetAsUInt64() & ~(3 << (2 * hw_index));

      if (WriteRegister(m_reg_info.first_dr + 7, RegisterValue(new_dr7_bits)))
        return true;
    }
  }

  return false;
}

bool RegisterContextPOSIXProcessMonitor_x86_64::HardwareSingleStep(
    bool enable) {
  enum { TRACE_BIT = 0x100 };
  uint64_t rflags;

  if ((rflags = ReadRegisterAsUnsigned(m_reg_info.gpr_flags, -1UL)) == -1UL)
    return false;

  if (enable) {
    if (rflags & TRACE_BIT)
      return true;

    rflags |= TRACE_BIT;
  } else {
    if (!(rflags & TRACE_BIT))
      return false;

    rflags &= ~TRACE_BIT;
  }

  return WriteRegisterFromUnsigned(m_reg_info.gpr_flags, rflags);
}

bool RegisterContextPOSIXProcessMonitor_x86_64::UpdateAfterBreakpoint() {
  // PC points one byte past the int3 responsible for the breakpoint.
  lldb::addr_t pc;

  if ((pc = GetPC()) == LLDB_INVALID_ADDRESS)
    return false;

  SetPC(pc - 1);
  return true;
}

unsigned RegisterContextPOSIXProcessMonitor_x86_64::GetRegisterIndexFromOffset(
    unsigned offset) {
  unsigned reg;
  for (reg = 0; reg < m_reg_info.num_registers; reg++) {
    if (GetRegisterInfo()[reg].byte_offset == offset)
      break;
  }
  assert(reg < m_reg_info.num_registers && "Invalid register offset.");
  return reg;
}

bool RegisterContextPOSIXProcessMonitor_x86_64::IsWatchpointHit(
    uint32_t hw_index) {
  bool is_hit = false;

  if (m_watchpoints_initialized == false) {
    // Reset the debug status and debug control registers
    RegisterValue zero_bits = RegisterValue(uint64_t(0));
    if (!WriteRegister(m_reg_info.first_dr + 6, zero_bits) ||
        !WriteRegister(m_reg_info.first_dr + 7, zero_bits))
      assert(false && "Could not initialize watchpoint registers");
    m_watchpoints_initialized = true;
  }

  if (hw_index < NumSupportedHardwareWatchpoints()) {
    RegisterValue value;

    if (ReadRegister(m_reg_info.first_dr + 6, value)) {
      uint64_t val = value.GetAsUInt64();
      is_hit = val & (1 << hw_index);
    }
  }

  return is_hit;
}

bool RegisterContextPOSIXProcessMonitor_x86_64::ClearWatchpointHits() {
  return WriteRegister(m_reg_info.first_dr + 6, RegisterValue((uint64_t)0));
}

addr_t RegisterContextPOSIXProcessMonitor_x86_64::GetWatchpointAddress(
    uint32_t hw_index) {
  addr_t wp_monitor_addr = LLDB_INVALID_ADDRESS;

  if (hw_index < NumSupportedHardwareWatchpoints()) {
    if (!IsWatchpointVacant(hw_index)) {
      RegisterValue value;

      if (ReadRegister(m_reg_info.first_dr + hw_index, value))
        wp_monitor_addr = value.GetAsUInt64();
    }
  }

  return wp_monitor_addr;
}

bool RegisterContextPOSIXProcessMonitor_x86_64::IsWatchpointVacant(
    uint32_t hw_index) {
  bool is_vacant = false;
  RegisterValue value;

  assert(hw_index < NumSupportedHardwareWatchpoints());

  if (m_watchpoints_initialized == false) {
    // Reset the debug status and debug control registers
    RegisterValue zero_bits = RegisterValue(uint64_t(0));
    if (!WriteRegister(m_reg_info.first_dr + 6, zero_bits) ||
        !WriteRegister(m_reg_info.first_dr + 7, zero_bits))
      assert(false && "Could not initialize watchpoint registers");
    m_watchpoints_initialized = true;
  }

  if (ReadRegister(m_reg_info.first_dr + 7, value)) {
    uint64_t val = value.GetAsUInt64();
    is_vacant = (val & (3 << 2 * hw_index)) == 0;
  }

  return is_vacant;
}

bool RegisterContextPOSIXProcessMonitor_x86_64::SetHardwareWatchpointWithIndex(
    addr_t addr, size_t size, bool read, bool write, uint32_t hw_index) {
  const uint32_t num_hw_watchpoints = NumSupportedHardwareWatchpoints();

  if (num_hw_watchpoints == 0 || hw_index >= num_hw_watchpoints)
    return false;

  if (!(size == 1 || size == 2 || size == 4 || size == 8))
    return false;

  if (read == false && write == false)
    return false;

  if (!IsWatchpointVacant(hw_index))
    return false;

  // Set both dr7 (debug control register) and dri (debug address register).

  // dr7{7-0} encodes the local/global enable bits:
  //  global enable --. .-- local enable
  //                  | |
  //                  v v
  //      dr0 -> bits{1-0}
  //      dr1 -> bits{3-2}
  //      dr2 -> bits{5-4}
  //      dr3 -> bits{7-6}
  //
  // dr7{31-16} encodes the rw/len bits:
  //  b_x+3, b_x+2, b_x+1, b_x
  //      where bits{x+1, x} => rw
  //            0b00: execute, 0b01: write, 0b11: read-or-write,
  //            0b10: io read-or-write (unused)
  //      and bits{x+3, x+2} => len
  //            0b00: 1-byte, 0b01: 2-byte, 0b11: 4-byte, 0b10: 8-byte
  //
  //      dr0 -> bits{19-16}
  //      dr1 -> bits{23-20}
  //      dr2 -> bits{27-24}
  //      dr3 -> bits{31-28}
  if (hw_index < num_hw_watchpoints) {
    RegisterValue current_dr7_bits;

    if (ReadRegister(m_reg_info.first_dr + 7, current_dr7_bits)) {
      uint64_t new_dr7_bits =
          current_dr7_bits.GetAsUInt64() |
          (1 << (2 * hw_index) |
           size_and_rw_bits(size, read, write) << (16 + 4 * hw_index));

      if (WriteRegister(m_reg_info.first_dr + hw_index, RegisterValue(addr)) &&
          WriteRegister(m_reg_info.first_dr + 7, RegisterValue(new_dr7_bits)))
        return true;
    }
  }

  return false;
}

uint32_t
RegisterContextPOSIXProcessMonitor_x86_64::NumSupportedHardwareWatchpoints() {
  // Available debug address registers: dr0, dr1, dr2, dr3
  return 4;
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace com\xcitestudios\Network\Server\Configuration\Test;

use com\xcitestudios\Network\Server\Configuration\UsernameAuthenticatedServerConfiguration;

class UsernameAuthenticatedServerConfigurationTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Check the JSON output adheres to the specified schema.
     */
    public function testSerializationAdheranceStandard()
    {
        $config = new UsernameAuthenticatedServerConfiguration();
        $config->setHost('192.168.5.1')
            ->setPort(32555)
            ->setSSL(true)
            ->setTLS(true)
            ->setUsername('abc')
            ->setPassword('123');

        $serialized = $config->serializeJSON();

        $retriever = new \JsonSchema\Uri\UriRetriever;
        $schema = $retriever->retrieve('file://' . realpath('vendor/xcitestudios/json-schemas/com/xcitestudios/schemas/Network/Server/Configuration/UsernameAuthenticatedServerConfiguration.json'));

        $refResolver = new \JsonSchema\RefResolver($retriever);
        $refResolver->resolve($schema, 'file://' . realpath('vendor/xcitestudios/json-schemas/com/xcitestudios/schemas/Network/Server/Configuration/.') . '/');

        $validator = new \JsonSchema\Validator();
        $validator->check(\json_decode($serialized), $schema);

        $message = 'Errors: ';
        if (!$validator->isValid()) {
            foreach ($validator->getErrors() as $error) {
                $message .= $error['property'] . ': ' . $error['message'] . "; ";
            }
        }

        $this->assertTrue($validator->isValid(), $message);
    }
}


text:
package org.k.controller;

import org.k.data.Location;
import org.k.dto.ErrorMessageDto;
import org.k.dto.TopicDto;
import org.k.service.AccuWeatherApiService;
import org.k.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.Optional;

@Controller
public class WeatherController {

    private final WeatherService weatherService;
    private final AccuWeatherApiService accuWeatherApiService;

    @Autowired
    public WeatherController(WeatherService weatherService,
                             AccuWeatherApiService accuWeatherApiService) {
        this.weatherService = weatherService;
        this.accuWeatherApiService = accuWeatherApiService;
    }

    @GetMapping(value = "/topic")
    public ResponseEntity<?> getTopic(@RequestParam("countryCode") String countryCode,
                                      @RequestParam("city") String city) throws IOException {
        Optional<Location> locationOptional = accuWeatherApiService.getLocation(countryCode, city);

        if (!locationOptional.isPresent()) {
            return new ResponseEntity<Object>(
                    new ErrorMessageDto(
                            "Can not find location of " + countryCode + " " + city),
                    HttpStatus.NOT_FOUND);
        }

        String topic = locationOptional.get().getLocationKey();
        weatherService.addNewTopicToMessageProcess(topic);

        return new ResponseEntity<Object>(new TopicDto(topic), HttpStatus.OK);
    }
}


text:
name = dstat
version = $(shell awk '/^Version: / {print $$2}' $(name).spec)

prefix = /usr
sysconfdir = /etc
bindir = $(prefix)/bin
datadir = $(prefix)/share
mandir = $(datadir)/man

.PHONY: all install docs clean

all: docs
	@echo "Nothing to be build."

docs:
	$(MAKE) -C docs docs

install:
#	-[ ! -f $(DESTDIR)$(sysconfdir)/dstat.conf ] && install -D -m0644 dstat.conf $(DESTDIR)$(sysconfdir)/dstat.conf
	install -Dp -m0755 dstat $(DESTDIR)$(bindir)/dstat
	install -d -m0755 $(DESTDIR)$(datadir)/dstat/
	install -Dp -m0755 dstat $(DESTDIR)$(datadir)/dstat/dstat.py
	install -Dp -m0644 plugins/dstat_*.py $(DESTDIR)$(datadir)/dstat/
#	install -d -m0755 $(DESTDIR)$(datadir)/dstat/examples/
#	install -Dp -m0755 examples/*.py $(DESTDIR)$(datadir)/dstat/examples/
	install -Dp -m0644 docs/dstat.1 $(DESTDIR)$(mandir)/man1/dstat.1

docs-install:
	$(MAKE) -C docs install

clean:
	rm -f examples/*.pyc plugins/*.pyc
	$(MAKE) -C docs clean

dist: clean
	$(MAKE) -C docs dist
	svn up
	svn list -R | pax -d -w -x ustar -s ,^,$(name)-$(version)/, | bzip2 >../$(name)-$(version).tar.bz2

rpm: dist
	rpmbuild -tb --clean --rmspec --define "_rpmfilename %%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm" --define "_rpmdir ../" ../$(name)-$(version).tar.bz2

srpm: dist
	rpmbuild -ts --clean --rmspec --define "_rpmfilename %%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm" --define "_srcrpmdir ../" ../$(name)-$(version).tar.bz2


text:
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using Inscribe.Common;

namespace Mystique.Views.Behaviors
{
    public class DragDropBehavior : Behavior<FrameworkElement>
    {
        protected override void OnAttached()
        {
            this.AssociatedObject.PreviewMouseDown += AssociatedObject_MouseDown;
            this.AssociatedObject.PreviewMouseMove += AssociatedObject_MouseMove;
            this.AssociatedObject.PreviewMouseUp += AssociatedObject_MouseUp;
        }

        protected override void OnDetaching()
        {
            this.AssociatedObject.PreviewMouseDown -= AssociatedObject_MouseDown;
            this.AssociatedObject.PreviewMouseMove -= AssociatedObject_MouseMove;
            this.AssociatedObject.PreviewMouseUp -= AssociatedObject_MouseUp;
        }

        public object DragDropData
        {
            get { return (object)GetValue(DragDropDataProperty); }
            set { SetValue(DragDropDataProperty, value); }
        }

        // Using a DependencyProperty as the backing store for DragDropData.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DragDropDataProperty =
            DependencyProperty.Register("DragDropData", typeof(object), typeof(DragDropBehavior), new UIPropertyMetadata(null));

        public DragDropEffects AllowedEffects
        {
            get { return (DragDropEffects)GetValue(AllowedEffectsProperty); }
            set { SetValue(AllowedEffectsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for AllowedEffects.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AllowedEffectsProperty =
            DependencyProperty.Register("AllowedEffects", typeof(DragDropEffects), typeof(DragDropBehavior), new UIPropertyMetadata(DragDropEffects.All));

        public ICommand BeforeDragDropCommand
        {
            get { return (ICommand)GetValue(BeforeDragDropCommandProperty); }
            set { SetValue(BeforeDragDropCommandProperty, value); }
        }

        // Using a DependencyProperty as the backing store for BeforeDragDropCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty BeforeDragDropCommandProperty =
            DependencyProperty.Register("BeforeDragDropCommand", typeof(ICommand), typeof(DragDropBehavior), new UIPropertyMetadata(null));

        public ICommand AfterDragDropCommand
        {
            get { return (ICommand)GetValue(AfterDragDropCommandProperty); }
            set { SetValue(AfterDragDropCommandProperty, value); }
        }

        // Using a DependencyProperty as the backing store for AfterDragDropCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AfterDragDropCommandProperty =
            DependencyProperty.Register("AfterDragDropCommand", typeof(ICommand), typeof(DragDropBehavior), new UIPropertyMetadata(null));

        public ICommand OnClickCommand
        {
            get { return (ICommand)GetValue(OnClickCommandProperty); }
            set { SetValue(OnClickCommandProperty, value); }
        }

        // Using a DependencyProperty as the backing store for OnClickCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty OnClickCommandProperty =
            DependencyProperty.Register("OnClickCommand", typeof(ICommand), typeof(DragDropBehavior), new UIPropertyMetadata(null));

        public bool OverrideClickEvent
        {
            get { return (bool)GetValue(OverrideClickEventProperty); }
            set { SetValue(OverrideClickEventProperty, value); }
        }

        // Using a DependencyProperty as the backing store for OverrideClickEvent.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty OverrideClickEventProperty =
            DependencyProperty.Register("OverrideClickEvent", typeof(bool), typeof(DragDropBehavior), new UIPropertyMetadata(false));

        Point oPoint = new Point(double.MinValue, double.MinValue);
        bool down = false;

        private void AssociatedObject_MouseDown(object sender, MouseButtonEventArgs e)
        {
            oPoint = e.GetPosition(this.AssociatedObject);
            down = true;
            if (OverrideClickEvent)
                e.Handled = true;
        }

        private void AssociatedObject_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed || !down) return;
            var point = e.GetPosition(this.AssociatedObject);
            var l = oPoint.DistanceDouble(point);
            if (l > 4)
            {
                if (this.BeforeDragDropCommand != null)
                    this.BeforeDragDropCommand.Execute(null);
                DragDrop.DoDragDrop(this.AssociatedObject, this.DragDropData, this.AllowedEffects);
                if (this.AfterDragDropCommand != null)
                    this.AfterDragDropCommand.Execute(null);
                down = false;
                e.Handled = true;
            }
            if (OverrideClickEvent)
                e.Handled = true;
        }

        private void AssociatedObject_MouseUp(object sender, MouseButtonEventArgs e)
        {
            down = false;
            var point = e.GetPosition(this.AssociatedObject);
            var l = oPoint.DistanceDouble(point);
            if (l <= 4 && OnClickCommand != null)
                OnClickCommand.Execute(null);
            if (OverrideClickEvent)
                e.Handled = true;
        }
    }
}


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */

#pragma once

#include <folly/futures/Future.h>
#include <folly/futures/Promise.h>
#include <folly/Unit.h>

#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <set>
#include <vector>

namespace a {
namespace different {
namespace ns {

} // namespace a
} // namespace different
} // namespace ns


text:
process.env.BABEL_ENV = 'test'
process.env.NODE_ENV = 'test'

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', error => {
  throw error
})

require('core-js/stable')
require('regenerator-runtime/runtime')

let options = require('yargs').argv
let getConfig = require('./config')
let config = getConfig(options)

require('@babel/register')({
  ...config.babel(true, config),
  extensions: ['.es6', '.es', '.jsx', '.js', '.mjs', '.ts', '.tsx']
})

let Mocha = require('mocha')
let fs = require('fs')
let path = require('path')

// Instantiate a Mocha instance.
let mocha = new Mocha({
  timeout: 20000,
  ...options
})

function travelDirectoryToAddTestFiles(dir) {
  fs.readdirSync(dir).forEach(file => {
    let filename = path.join(dir, file)
    // ignore node_modules
    if (
      filename.indexOf('node_modules') !== -1 ||
      filename.indexOf('publish') !== -1
    ) {
      return
    }
    // read file deeply
    if (fs.statSync(filename).isDirectory()) {
      return travelDirectoryToAddTestFiles(filename)
    }
    // add *test.js file to the mocha instance
    if (filename.substr(-8) === '-test.js') {
      return mocha.addFile(filename)
    }
  })
}

travelDirectoryToAddTestFiles(__dirname)

// Run the tests.
mocha.run(function(failures) {
  // exit with non-zero status if there were failures
  // Mocha Won't Force Exit
  process.exit(failures)
})


text:
using System;
using System.Collections.Generic;
using System.Linq;
using MongoFramework.Bson;
using MongoFramework.Infrastructure.Mapping;
using MongoFramework.Utilities;

namespace MongoFramework.Infrastructure
{
	public class EntityEntryContainer
	{
		private Dictionary<Type, List<EntityEntry>> EntryLookupByType { get; } = new Dictionary<Type, List<EntityEntry>>();

		public IEnumerable<EntityEntry> Entries()
		{
			return EntryLookupByType.Values.SelectMany(e => e);
		}

		private void RemoveEntry<TCollectionBase>(EntityEntry entry)
		{
			if (EntryLookupByType.TryGetValue(typeof(TCollectionBase), out var entries))
			{
				entries.Remove(entry);
			}
		}

		private void AddEntry<TCollectionBase>(EntityEntry entry)
		{
			if (!EntryLookupByType.TryGetValue(typeof(TCollectionBase), out var entries))
			{
				entries = new List<EntityEntry>();
				EntryLookupByType.Add(typeof(TCollectionBase), entries);
			}

			entries.Add(entry);
		}

		public EntityEntry GetEntry<TCollectionBase>(TCollectionBase entity)
		{
			Check.NotNull(entity, nameof(entity));

			var collectionType = typeof(TCollectionBase);

			if (EntryLookupByType.TryGetValue(collectionType, out var entries))
			{
				var entityDefinition = EntityMapping.GetOrCreateDefinition(collectionType);
				var entityId = entityDefinition.GetIdValue(entity);
				var defaultIdValue = entityDefinition.GetDefaultId();
				foreach (var entry in entries)
				{
					if (Equals(entityId, defaultIdValue) && ReferenceEquals(entry.Entity, entity))
					{
						return entry;
					}
					else
					{
						var entryEntityId = entityDefinition.GetIdValue(entry.Entity);
						if (!Equals(entryEntityId, defaultIdValue) && entryEntityId.Equals(entityId))
						{
							return entry;
						}
					}
				}
			}

			return null;
		}

		public EntityEntry GetEntryById<TCollectionBase>(object id)
		{
			var collectionType = typeof(TCollectionBase);

			if (EntryLookupByType.TryGetValue(collectionType, out var entries))
			{
				var entityDefinition = EntityMapping.GetOrCreateDefinition(collectionType);

				foreach (var entry in entries)
				{
					var entryEntityId = entityDefinition.GetIdValue(entry.Entity);
					if (entryEntityId.Equals(id))
					{
						return entry;
					}
				}
			}

			return null;
		}
		public EntityEntry SetEntityState<TCollectionBase>(TCollectionBase entity, EntityEntryState state) where TCollectionBase : class
		{
			Check.NotNull(entity, nameof(entity));

			var entry = GetEntry(entity);
			if (entry != null)
			{
				if (ReferenceEquals(entry.Entity, entity))
				{
					if ((entry.State == EntityEntryState.Added && state == EntityEntryState.Deleted) || state == EntityEntryState.Detached)
					{
						entry.State = EntityEntryState.Detached;
						RemoveEntry<TCollectionBase>(entry);
					}
					else
					{
						entry.State = state;
					}
				}
				else if (state != EntityEntryState.Detached)
				{
					RemoveEntry<TCollectionBase>(entry);
					entry = new EntityEntry(entity, typeof(TCollectionBase), state);
					AddEntry<TCollectionBase>(entry);
				}
			}
			else if (state != EntityEntryState.Detached)
			{
				entry = new EntityEntry(entity, typeof(TCollectionBase), state);
				AddEntry<TCollectionBase>(entry);
			}

			return entry;
		}

		/// <summary>
		/// Performed after saving, this resets the state of entries to align with the state in the database.
		/// </summary>
		public void CommitChanges()
		{
			foreach (var typeGroup in EntryLookupByType.Values)
			{
				for (var i = typeGroup.Count - 1; i >= 0; i--)
				{
					var entry = typeGroup[i];
					if (entry.State == EntityEntryState.Added || entry.State == EntityEntryState.Updated)
					{
						entry.ResetState();
					}
					else if (entry.State == EntityEntryState.Deleted)
					{
						typeGroup.Remove(entry);
					}
				}
			}
		}

		/// <summary>
		/// Performed prior to saving, this detect changes between the original and current state of entries, updating states where necessary.
		/// </summary>
		public void DetectChanges()
		{
			foreach (var typeGroup in EntryLookupByType.Values)
			{
				for (var i = typeGroup.Count - 1; i >= 0; i--)
				{
					var entry = typeGroup[i];
					if (entry.State == EntityEntryState.NoChanges || entry.State == EntityEntryState.Updated)
					{
						if (BsonDiff.HasDifferences(entry.OriginalValues, entry.CurrentValues))
						{
							entry.State = EntityEntryState.Updated;
						}
						else
						{
							entry.State = EntityEntryState.NoChanges;
						}
					}
				}
			}
		}

		public void EnforceMultiTenant(string tenantId)
		{
			foreach (var pair in EntryLookupByType)
			{
				if (!typeof(IHaveTenantId).IsAssignableFrom(pair.Key))
				{
					continue;
				}

				if (string.IsNullOrEmpty(tenantId))
				{
					throw new MultiTenantException($"Entity type {pair.Key.Name} is in the context, but no tenant ID was provided.");
				}

				var typeGroup = pair.Value;
				for (var i = typeGroup.Count - 1; i >= 0; i--)
				{
					var entry = typeGroup[i];
					var tenantItem = entry.Entity as IHaveTenantId;
					if (tenantItem.TenantId != tenantId)
					{
						throw new MultiTenantException($"Entity type {entry.EntityType.Name}, tenant ID does not match. Expected: {tenantId}, entity has: {tenantItem.TenantId}");
					}

				}

			}
		}

		public void Clear()
		{
			EntryLookupByType.Clear();
		}
	}
}


text:
<?php
	Class CUser
	{
		// Const Members.
		const FIELD_USER_ID 		= "user_id" ;
		const FIELD_FIRST_NAME 		= "firstname" ;
		const FIELD_LAST_NAME	 	= "lastname" ;
		const FIELD_PASSWORD 		= "passwd" ;
		const FIELD_EMAIL 			= "email" ;
		const FIELD_GENDER			= "gender" ;
		const FIELD_CITY			= "city" ;
		const FIELD_STATE			= "state" ;
		const FIELD_COUNTRY			= "country" ;
		const FIELD_DOB				= "dob" ;
		const FIELD_SECURITY_QUES 	= "security_ques" ;
		const FIELD_SECURITY_ANS	= "security_ans" ;
		const FIELD_SIGNUP_DATE		= "signup_date" ;
		const FIELD_REG_STATUS		= "reg_status" ;
		const FIELD_ONLINE			= "online" ;

		// Class Members.
		private $user_id ;
		private $first_name ;
  		private $last_name ;
  		private $password ;
  		private $email ;
  		private $gender ;
  		private $city ;
  		private $state ;
  		private $country ;
  		private $dob ;
  		private $security_question ;
  		private $security_answer ;
  		private $signup_date ;
  		private $reg_status ;
  		private $online ;

		function __construct()
		{

		}
		public function __destruct()
		{

		}

	    public function GetUserID()
	    {
			return $this->user_id ;
	    }
	    public function SetUserID($user_id)
	    {
	    	$this->user_id = $user_id;
	    }

	    public function GetFirstName()
	    {
	    	return $this->first_name ;
	    }
		public function SetFirstName($first_name)
		{
			$this->first_name = $first_name ;
		}

		public function GetLastName()
	    {
	    	return $this->last_name ;
	    }
		public function SetLastName($last_name)
		{
			$this->last_name = $last_name ;
		}

	    public function GetPassword()
	    {
	    	return $this->password ;
	    }
	    public function SetPassword($password)
	    {
	    	$this->password = $password ;
	    }

	    public function GetEmail()
	    {
	    	return $this->email ;
	    }
	    public function SetEmail($email)
	    {
	    	$this->email = $email ;
	    }

	    public function GetGender()
	    {
	    	return $this->gender ;
	    }
	    public function SetGender($gender)
	    {
	    	$this->gender = $gender ;
	    }

	    public function GetCity()
	    {
	    	return $this->city ;
	    }
	    public function SetCity($city)
	    {
			$this->city = $city ;
	    }

  		public function GetState()
  		{
  			return $this->state ;
  		}
  		public function SetState($state)
  		{
  			$this->state = $state ;
  		}

  		public function GetCountry()
  		{
  			return $this->country ;
  		}
  		public function SetCountry($country)
  		{
  			$this->country = $country ;
  		}

  		public function GetDOB()
  		{
  			return $this->dob ;
  		}
  		public function SetDOB($dob)
  		{
  			$this->dob = $dob ;
  		}

  		public function GetSecQues()
  		{
  			return $this->security_question ;
  		}
  		public function SetSecQues($security_question)
  		{
			$this->security_question = $security_question ;
  		}

  		public function GetSecAns()
  		{
  			return $this->security_answer ;
  		}
  		public function SetSecAns($security_answer)
  		{
			$this->security_answer = $security_answer ;
  		}

	    public function GetSignupDate()
	    {
	    	return $this->signup_date ;
	    }
	    public function SetSignupDate($signup_date)
	    {
	    	$this->signup_date = $signup_date;
	    }

	    public function GetRegStatus()
	    {
	    	return $this->reg_status ;
	    }
	    public function SetRegStatus($reg_status)
	    {
	    	$this->reg_status = $reg_status ;
	    }

	    public function GetOnline()
	    {
	    	return $this->online ;
	    }
	    public function SetOnline($online)
	    {
	    	$this->online = $online ;
	    }
	}
?>


text:
 	var question = 'Who is this?'
    	choices = ['Joe','Cordell', 'Scott'],
    	answer0 = 'Joe'

    var question = 'Who is shown here?'
    	choices = ['Cordell','Joe','Scott'],
    	answer1 = 'Cordell'

    var question = 'Who do you think this is?'
    	choices = ['Cordell','Joe','Scott'],
    	answer2 = 'Scott'
    ;


text:
YUI.add('gallery-zui-rascroll', function (Y, NAME) {

/**
 * The RAScrollPlugin help to handle scrollView behaviors.
 * When a Horizontal scrollView is placed inside a Vertical scrollView,
 * user can do only x or y direction slick.
 *
 * @module gallery-zui-rascroll
 */
var dragging = 0,
    dragStart = false,
    onlyX = false,
/**
 * RAScrollPlugin is a ScrollView plugin that adds right angle flick behaviors.
 *
 * @class RAScrollPlugin
 * @namespace zui
 * @extends Plugin.Base
 * @constructor
 */
    RAScrollPlugin = function () {
        RAScrollPlugin.superclass.constructor.apply(this, arguments);
    };

RAScrollPlugin.NAME = 'pluginRAScroll';
RAScrollPlugin.NS = 'zras';
RAScrollPlugin.ATTRS = {
    /**
     * make the scrollView as horizontal or not.
     *
     * @attribute horizontal
     * @default true
     * @type Boolean
     */
    horizontal: {
        value: true,
        lazyAdd: false,
        validator: Y.Lang.isBoolean,
        setter: function (V) {
            this._hori = V;
            return V;
        }
    },

    /**
     * A boolean decides the right angle behavior should started when other scrollView is also dragged.
     *
     * @attribute cooperation
     * @default false
     * @type Boolean
     */
    cooperation: {
        value: false,
        lazyAdd: false,
        validator: Y.Lang.isBoolean,
        setter: function (V) {
            this._coop = V;
            return V;
        }
    }
};

Y.namespace('zui').RAScroll = Y.extend(RAScrollPlugin, Y.Plugin.Base, {
    initializer: function () {
        this._host = this.get('host');
        this._node = this._host.get('boundingBox');
        this._cnt = this._host.get('contentBox');
        this._start = false;

        if (!this._hori) {
            this._cnt.setStyles({
                overflowX: 'hidden',
                height: 'auto'
            });
        }

        this._handles.push(new Y.EventHandle([
            this._node.on('gesturemovestart', this.handleGestureMoveStart),
            this._node.on('gesturemove', Y.bind(this.handleGestureMove, this)),
            this._cnt.on('gesturemoveend', Y.bind(this.handleGestureMoveEnd, this), {standAlone: true})
        ]));

        this.syncScroll();
    },

    /**
     * internal gesturemovestart event handler
     *
     * @method handleGestureMoveStart
     * @protected
     */
    handleGestureMoveStart: function () {
        dragging++;
    },

    /**
     * internal gesturemove event handler
     *
     * @method handleGestureMove
     * @protected
     */
    handleGestureMove: function (E) {
        if (this._start) {
            return;
        }

        this._start = true;

        if (!dragStart) {
            onlyX = Math.abs(this._host._gesture.startClientX - E.clientX) > Math.abs(this._host._gesture.startClientY - E.clientY);
            dragStart = true;
        }

        if (this._coop && dragging < 2) {
            return;
        }

        if (this._hori ? !onlyX : onlyX) {
            this._host.set('disabled', true);
        } else {
            E.preventDefault();
        }
    },

    /**
     * internal gesturemoveend event handler
     *
     * @method handleGestureMoveEnd
     * @protected
     */
    handleGestureMoveEnd: function () {
        this._start = false;
        dragStart = false;
        dragging = 0;

        if (this._hori ? !onlyX : onlyX) {
            // IOS6 setTimeout bug fix
            if (Y.UA.ipad + Y.UA.iphone + Y.UA.ipod >= 6) {
                this._host.set('disabled', false);
            } else {
                // Use later to make multi scrollview more stable when
                // user finger off
                Y.later(1, this._host, this._host.set, ['disabled', false]);
            }

        }
    },

    /**
     * sync width or height for vertical scroll or horizontal scroll
     *
     * @method syncScroll
     */
    syncScroll: function () {
        if (this._hori) {
            this._node.set('offsetHeight', this._node.get('scrollHeight'));
        } else {
            this.syncWidth();
        }
    },

    /**
     * make the scrollView become vertical scrolling
     *
     * @method syncWidth
     */
    syncWidth: function () {
        var c = this._cnt,
            sw = this._node.get('scrollWidth'),
            pw = this._node.get('offsetWidth'),
            cw = c.get('offsetWidth');

        if (cw && (sw > pw)) {
            c.set('offsetWidth', cw + pw - sw);
        }
    }
});

}, 'gallery-2013.02.07-15-27', {"skinnable": false, "requires": ["scrollview"]});


text:
<?xml version="1.0" ?>
<tei>
	<teiHeader>
		<fileDesc xml:id="55011353"/>
	</teiHeader>
	<text xml:lang="en">
		<front>
<lb/>
	<docTitle>
	<titlePart>Material Safety Data Sheet<lb/></titlePart>
	</docTitle>

	<note type="submission">acc. to OSHA and ANSI<lb/> </note>

	<date type="publication">Printing date 08/16/2002<lb/> Reviewed on 10/06/1999<lb/></date>

1 Identification of substance:<lb/> Product details:<lb/>Trade name: Manganese (II) 2-ethylhexanoate, 40% w/w in<lb/> mineral spirits<lb/>

	<note>Stock number: 38607<lb/> </note>

	<note type="other">Manufacturer/Supplier:<lb/></note>

	<byline>
	<docAuthor>Alfa Aesar, A Johnson Matthey </docAuthor>
	</byline>

	<byline>
	<affiliation>company<lb/> Johnson Matthey Catalog Company, Inc.<lb/></affiliation>
	</byline>

	<address>30 Bond Street<lb/> Ward Hill, MA 01835-8099<lb/></address>

	<phone>Emergency Phone: (978) 521-6300<lb/> CHEMTREC: (800) 424-9300<lb/> </phone>

	<ptr>Web Site: www.alfa.com<lb/> </ptr>

	<note type="other">Information department: Health, Safety and Environmental<lb/> Department<lb/> Emergency information:<lb/> During normal hours the Health, Safety and Environmental<lb/> Department. After normal hours call Chemtrec at </note>

	<phone>(800) 424-<lb/>9300.</phone>

		</front>
	</text>
</tei>


text:
SAEFACTO - Sistema de Acompanhamento de Estágio da FACTO
=========================================================

Sistema desenvolvido como requisito parcial para a disciplina de Interface Interface homem-máquina

LICENÇA
=======

Este projeto inclui software ADQUIRIDO e LICENCIADO especificamente para o mesmo.

Caso queira utilizar esse projeto, você deve COMPRAR a licença em:

https://wrapbootstrap.com/theme/smartadmin-responsive-webapp-WB0573SK0

Desenvolvido por Fábio C. Barrionuevo da Luz e outros (vide commits)


text:
/**
 * @fileoverview Provides data persistence using HTML5 local storage
 * mechanism. Local storage must be available under window.localStorage,
 * see: http://www.w3.org/TR/webstorage/#the-localstorage-attribute.
 */

goog.provide('goog.storage.mechanism.HTML5LocalStorage');

goog.require('goog.storage.mechanism.HTML5WebStorage');

/**
 * Provides a storage mechanism that uses HTML5 local storage.
 *
 * @constructor
 * @struct
 * @extends {goog.storage.mechanism.HTML5WebStorage}
 */
goog.storage.mechanism.HTML5LocalStorage = function() {
  'use strict';
  var storage = null;

  try {
    // May throw an exception in cases where the local storage object
    // is visible but access to it is disabled.
    storage = window.localStorage || null;
  } catch (e) {
  }
  goog.storage.mechanism.HTML5LocalStorage.base(this, 'constructor', storage);
};
goog.inherits(
    goog.storage.mechanism.HTML5LocalStorage,
    goog.storage.mechanism.HTML5WebStorage);


text:
var express = require('express');
var app = express();
var Schema = require('validate');
var xml2json = require('xml2json');
var util = require('util');
var Page = new Schema();

Page.path('title').type('string').required(); //<co id="web-middleware-5-1"/>

function ValidatorError(errors) { //<co id="web-middleware-5-2"/>
  this.statusCode = 400;
  this.message = errors.join(', ');
}
util.inherits(ValidatorError, Error);

function xmlMiddleware(req, res, next) { //<co id="web-middleware-5-3"/>
  if (!req.is('xml')) return next();

  var body = '';
  req.on('data', function(str) { //<co id="web-middleware-5-4"/>
    body += str;
  });

  req.on('end', function() {
    req.body = xml2json.toJson(body.toString(), {
      object: true,
      sanitize: false
    });
    next();
  });
}

function checkValidXml(req, res, next) { //<co id="web-middleware-5-5"/>
  var page = Page.validate(req.body.page);
  if (page.errors.length) {
    next(new ValidatorError(page.errors)); //<co id="web-middleware-5-6"/>
  } else {
    next();
  }
}

function errorHandler(err, req, res, next) { //<co id="web-middleware-5-7"/>
  console.error('errorHandler', err);
  res.send(err.statusCode || 500, err.message);
}

app.use(xmlMiddleware); //<co id="web-middleware-5-8"/>

app.post('/pages', checkValidXml, function(req, res) { //<co id="web-middleware-5-9"/>
  console.log('Valid page:', req.body.page);
  res.send(req.body);
});

app.use(errorHandler); //<co id="web-middleware-5-10"/>

app.listen(3000);


text:
package org.kbac.spring.app.dao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.kbac.spring.app.entities.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *
 */
@Repository
public class PersonDAOImpl implements PersonDAO {

    public static final int SLEEP_TIME = 200;

    private static final Log logger = LogFactory.getLog(PersonDAOImpl.class);

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public List<Person> getPersons() {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Person p");
        return query.list();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public List<Person> getPersonsLong() {
        sleep();
        return getPersons();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void addPerson(Person toAdd) {
        Session session = sessionFactory.getCurrentSession();
        session.save(toAdd);
    }

    private void sleep() {
        try {
            Thread.sleep(SLEEP_TIME);
        } catch (InterruptedException e) {
            logger.error(e);
        }
    }
}


text:
from copy import copy

from django.conf.urls import include as django_include
from django.conf.urls import url
from django.views.generic import View
from django_js_reverse.tests.helper import is_django_ver_gte_2
from django_js_reverse.views import urls_js

try:
    from django.urls import path
except ImportError:
    pass

dummy_view = View.as_view()

basic_patterns = [
    url(r'^jsreverse/$', urls_js, name='js_reverse'),

    # test urls
    url(r'^test_no_url_args/$', dummy_view, name='test_no_url_args'),
    url(r'^test_script/$', dummy_view, name='</script><script>console.log(&)</script><!--'),
    url(r'^test_one_url_args/(?P<arg_one>[-\w]+)/$', dummy_view, name='test_one_url_args'),
    url(r'^test_two_url_args/(?P<arg_one>[-\w]+)-(?P<arg_two>[-\w]+)/$', dummy_view, name='test_two_url_args'),
    url(r'^test_optional_url_arg/(?:1_(?P<arg_one>[-\w]+)-)?2_(?P<arg_two>[-\w]+)/$', dummy_view,
        name='test_optional_url_arg'),
    url(r'^test_unicode_url_name/$', dummy_view, name=u'test_unicode_url_name'),
    url(r'^test_duplicate_name/(?P<arg_one>[-\w]+)/$', dummy_view, name='test_duplicate_name'),
    url(r'^test_duplicate_name/(?P<arg_one>[-\w]+)-(?P<arg_two>[-\w]+)/$', dummy_view, name='test_duplicate_name'),
    url(r'^test_duplicate_argcount/(?P<arg_one>[-\w]+)?-(?P<arg_two>[-\w]+)?/$', dummy_view,
        name='test_duplicate_argcount'),
]

if is_django_ver_gte_2():
    basic_patterns.append(
        path('test_django_gte_2_path_syntax/<int:arg_one>/<str:arg_two>/', dummy_view,
             name='test_django_gte_2_path_syntax'),
    )

urlpatterns = copy(basic_patterns)

# test exclude namespaces urls
urlexclude = [
    url(r'^test_exclude_namespace/$', dummy_view,
        name='test_exclude_namespace_url1')
]

def include(v, **kwargs):
    if not is_django_ver_gte_2():
        return django_include(v, **kwargs)

    return django_include((v, 'django_js_reverse'), **kwargs)

# test namespace
pattern_ns_1 = [
    url(r'', django_include(basic_patterns))
]

pattern_ns_2 = [
    url(r'', django_include(basic_patterns))
]

pattern_ns = [
    url(r'', django_include(basic_patterns))
]

pattern_nested_ns = [
    url(r'^ns1/', include(pattern_ns_1, namespace='ns1'))
]

pattern_dubble_nested2_ns = [
    url(r'^ns1/', include(pattern_ns_1, namespace='ns1'))]

pattern_dubble_nested_ns = [
    url(r'^ns1/', include(pattern_ns_1, namespace='ns1')),
    url(r'^nsdn2/', include(pattern_dubble_nested2_ns, namespace='nsdn2'))]

pattern_only_nested_ns = [
    url(r'^ns1/', django_include(pattern_ns_1)),
    url(r'^nsdn0/', include(pattern_dubble_nested2_ns, namespace='nsdn0'))]

urlpatterns += [
    url(r'^ns1/', include(pattern_ns_1, namespace='ns1')),
    url(r'^ns2/', include(pattern_ns_2, namespace='ns2')),
    url(r'^ns_ex/', include(urlexclude, namespace='exclude_namespace')),
    url(r'^ns(?P<ns_arg>[^/]*)/', include(pattern_ns, namespace='ns_arg')),
    url(r'^nestedns/', include(pattern_nested_ns, namespace='nestedns')),
    url(r'^nsdn/', include(pattern_dubble_nested_ns, namespace='nsdn')),
    url(r'^nsno/', include(pattern_only_nested_ns, namespace='nsno'))
]


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace COGOLineFeatures {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.0")]
    internal sealed partial class COGOLineDialog : global::System.Configuration.ApplicationSettingsBase {

        private static COGOLineDialog defaultInstance = ((COGOLineDialog)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new COGOLineDialog())));

        public static COGOLineDialog Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string LastUsedParams {
            get {
                return ((string)(this["LastUsedParams"]));
            }
            set {
                this["LastUsedParams"] = value;
            }
        }
    }
}


text:
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	    <title>方法封装</title>
	    <meta name="keywords" content="">
	    <meta name="description" content="">
		<script type="text/javascript" src="<?php echo config_item('PUBLICRES'); ?>/js/require.js"></script>
		<script type="text/javascript" src="<?php echo config_item('PUBLICRES'); ?>/js/config.js"></script>
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
			require(["cqdewei_dialog"], function(cqdewei_dialog) {
			    cqdewei_dialog.success('234');
			});
		</script>
	</body>
</html>


text:
layout: post
title: Splat and double splat in Ruby
summary:
date: 2016-06-01
published: false
categories: ruby
---

Outline:
1. Destructing of arrays
2. Destructing of hashes(?)
3. Calling methods


text:
namespace iv {
namespace core {
namespace thread {

class WinMutex : private Noncopyable<> {
 public:
  WinMutex() {
    ::InitializeCriticalSection(&mutex_);
  }

  ~WinMutex() {
    ::DeleteCriticalSection(&mutex_);
  }

  int Lock() {
    ::EnterCriticalSection(&mutex_);
    return 0;
  }

  int Unlock() {
    ::LeaveCriticalSection(&mutex_);
    return 0;
  }

  bool TryLock() {
    return ::TryEnterCriticalSection(&mutex_);
  }

 private:
  CRITICAL_SECTION mutex_;
};

typedef WinMutex Mutex;

inline void YieldCPU() {
  ::YieldProcessor();
}

} } }  // namespace iv::core::thread
#endif  // IV_THREAD_WIN_H_


text:
class HelloWorld : public cocos2d::Layer
{
public:
    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::Scene* createScene();

    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();

    // a selector callback
    void menuCloseCallback(cocos2d::Ref* pSender);
    void menuRequestCallback(cocos2d::Ref* pSender);
	void onHttpResponseComplete(cocos2d::network::HttpClient* client, cocos2d::network::HttpResponse* response);

    // implement the "static create()" method manually
    CREATE_FUNC(HelloWorld);
};

#endif // __HELLOWORLD_SCENE_H__


text:
class ModuleRender : public Module
{
public:
	ModuleRender(Application* app, bool start_enabled = true);
	~ModuleRender();

	bool Init();
	update_status PreUpdate();
	update_status Update();
	update_status PostUpdate();
	bool CleanUp();

	bool Blit(SDL_Texture* texture, int x, int y, SDL_Rect* section = NULL, float scale = 1.0f, float speed = 1.0f, double angle = 0, int pivot_x = INT_MAX, int pivot_y = INT_MAX);
	bool DrawQuad(const SDL_Rect& rect, Uint8 r, Uint8 g, Uint8 b, Uint8 a = 255, bool filled = true, bool use_camera = true);
	bool DrawLine(int x1, int y1, int x2, int y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a = 255, bool use_camera = true);
	bool DrawCircle(int x1, int y1, int redius, Uint8 r, Uint8 g, Uint8 b, Uint8 a = 255, bool use_camera = true);

public:
	SDL_Renderer* renderer;
	SDL_Rect camera;
};


text:
package org.apache.wicket.extensions.markup.html.repeater.tree.nested;

import java.util.Iterator;

import org.apache.wicket.Component;
import org.apache.wicket.extensions.markup.html.repeater.tree.AbstractTree.State;
import org.apache.wicket.extensions.markup.html.repeater.tree.ITreeProvider;
import org.apache.wicket.extensions.markup.html.repeater.tree.NestedTree;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.IItemFactory;
import org.apache.wicket.markup.repeater.IItemReuseStrategy;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.RefreshingView;
import org.apache.wicket.model.IModel;

/**
 * A subtree handles all children of a single node (or the root nodes if a null node
 * was given to the constructor).
 *
 * @see ITreeProvider#getChildren(Object)
 * @see ITreeProvider#getRoots()
 *
 * @author svenmeier
 */
public class Subtree<T> extends Panel
{

	private static final long serialVersionUID = 1L;

	private NestedTree<T> tree;

	/**
	 * Create a subtree for the children of the node contained in the given model or the root nodes
	 * if the model contains null.
	 *
	 * @param id
	 *            component id
	 * @param tree
	 *            the containing tree
	 * @param model
	 */
	public Subtree(String id, final NestedTree<T> tree, final IModel<T> model)
	{
		super(id, model);

		if (tree == null)
		{
			throw new IllegalArgumentException("argument [tree] cannot be null");
		}
		this.tree = tree;

		RefreshingView<T> branches = new RefreshingView<T>("branches")
		{
			private static final long serialVersionUID = 1L;

			@Override
			protected Iterator<IModel<T>> getItemModels()
			{
				return new ModelIterator();
			}

			@Override
			protected Item<T> newItem(String id, int index, IModel<T> model)
			{
				return newBranchItem(id, index, model);
			}

			@Override
			protected void populateItem(Item<T> item)
			{
				IModel<T> model = item.getModel();

				Component node = tree.newNodeComponent("node", model);
				item.add(node);

				item.add(tree.newSubtree("subtree", model));
			}
		};
		branches.setItemReuseStrategy(new IItemReuseStrategy()
		{
			private static final long serialVersionUID = 1L;

			public <S> Iterator<Item<S>> getItems(IItemFactory<S> factory,
				Iterator<IModel<S>> newModels, Iterator<Item<S>> existingItems)
			{
				return tree.getItemReuseStrategy().getItems(factory, newModels, existingItems);
			}
		});
		add(branches);
	}

	@SuppressWarnings("unchecked")
	public IModel<T> getModel()
	{
		return (IModel<T>)getDefaultModel();
	}

	public T getModelObject()
	{
		return getModel().getObject();
	}

	protected BranchItem<T> newBranchItem(String id, int index, IModel<T> model)
	{
		return new BranchItem<T>(id, index, model);
	}

	@Override
	public boolean isVisible()
	{
		T t = getModel().getObject();
		if (t == null)
		{
			// roots always visible
			return true;
		}
		else
		{
			return tree.getState(t) == State.EXPANDED;
		}
	}

	private final class ModelIterator implements Iterator<IModel<T>>
	{
		private Iterator<? extends T> children;

		public ModelIterator()
		{
			T t = getModel().getObject();
			if (t == null)
			{
				children = tree.getProvider().getRoots();
			}
			else
			{
				children = tree.getProvider().getChildren(t);
			}
		}

		public void remove()
		{
			throw new UnsupportedOperationException();
		}

		public boolean hasNext()
		{
			return children.hasNext();
		}

		public IModel<T> next()
		{
			return tree.getProvider().model(children.next());
		}
	}
}


text:
"""drafting and designing a manager for python written modules.
the current plan is that there'll be a Manager that the PythonScriptModule
instanciates, and which then loads the python modules that are to be autoloaded,
and handles their event registrations, passing incoming events to them etc.
that will be prototyped here in pure py, and perhaps reused in the actual
impl if it seems that a py written manager makes sense within the c++ framework too.

currently here is only test code for modules and handelers that would
use the manager, nothing of the Manager itself yet.
"""

import circuits

class RealxtendViewer(pyglet.event.EventDispatcher):
    def run(self, deltatime):
        print ".",
        self.dispatch_event('update', deltatime)

RealxtendViewer.register_event_type('update')

viewer = RealxtendViewer()

class TestModule:
    """A wish of how a py written module might like to have the system.
    This could for example be the CommunicationsModule, right?
    Or something that implements as a custom control type..
    Now attempting a generic test thing."""

    def __init__(self):
        self.data = 1

    @viewer.event
    def update(self):
        if self.data == 1:
            self.data == 0
        else:
            self.data == 1
        print self.data,

"""
why not allow plain functions as event handlers too,
the python module of it, i.e. the file, can be considered as the module,
so no classes are required.
"""

@viewer.event
def dosomething():
    pass #e.g. move an object w.r.t to something (like time?)

"""
update may be nice as a method, but the real thing are the events.
"""

#~ @e.communication.PRESENCE_STATUS_UPDATE
#~ def sparkle_presence_updates():
    #~ """a custom visual thing: some local sparkles upon IM presence updates.
    #~ what data do we have in these events? the im participant id?
    #~ is that associated to an avatar anywhere? so could e.g. get the location..
    #~ """
    #~ create_sparkle((0,2, 0,2), 0.5) #in upper right corner, for half a sec

if __name__ == '__main__':
    pyglet.clock.schedule_interval(viewer.run, 0.1)


text:
package com.github.cjm0000000.shared.test.weather;

import java.io.IOException;

import static org.junit.Assert.assertNotNull;

import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.github.cjm0000000.mmt.shared.weather.City;
import com.github.cjm0000000.mmt.shared.weather.Weather;
import com.github.cjm0000000.mmt.shared.weather.WeatherInfo;
import com.github.cjm0000000.mmt.shared.weather.persistence.CityRepository;
import com.github.cjm0000000.shared.test.AbstractTester;

/**
 * Unit test case for weather
 * @author lemon
 * @version 1.0
 *
 */
public class Weather_Test extends AbstractTester {
	@Autowired
	private CityRepository cityMapper;
	@Autowired
	private Weather weather;

	@Override
	public void defaultCase() {
		searchWeather();
	}

	@Test
	@Ignore
	public void initCity() throws IOException{
		weather.initCity();
	}

	@Test
	@Ignore
	public void addCity(){
		City c = new City();
		c.setCity_name("AAS");
		c.setCitycode("asdq");
		c.setProvince("B");
		cityMapper.add(c);
	}

	//FIXME 获取城市名称   http://maps.google.com/maps/api/geocode/json?latlng=23.149207,113.256196&language=zh-CN&sensor=true
	private void searchWeather(){
		String city = "杭州";
		WeatherInfo result = weather.searchWeather(city);
		assertNotNull(result);
	}

}


text:
function Invoke-LabResourceDownload {
<#
    .SYNOPSIS
        Starts a download of all required lab resources.
    .DESCRIPTION
        When a lab configuration is started, Lability will attempt to download all the required media and resources.

        In some scenarios you many need to download lab resources in advance, e.g. where internet access is not
        readily available or permitted. The `Invoke-LabResourceDownload` cmdlet can be used to manually download
        all required resources or specific media/resources as needed.
    .PARAMETER ConfigurationData
        Specifies a PowerShell DSC configuration document (.psd1) containing the lab configuration.
    .PARAMETER All
        Specifies all media, custom and DSC resources should be downloaded.
    .PARAMETER MediaId
        Specifies the specific media IDs to download.
    .PARAMETER ResourceId
        Specifies the specific custom resource IDs to download.
    .PARAMETER Media
        Specifies all media IDs should be downloaded.
    .PARAMETER Resources
        Specifies all custom resource IDs should be downloaded.
    .PARAMETER DSCResources
        Specifies all defined DSC resources should be downloaded.
    .PARAMETER Moduless
        Specifies all defined PowerShell modules should be downloaded.
    .PARAMETER Force
        Forces a download of all resources, overwriting any existing resources.
    .PARAMETER DestinationPath
        Specifies the target destination path of downloaded custom resources (not media or DSC resources).
    .EXAMPLE
        Invoke-LabResourceDownload -ConfigurationData ~\Documents\MyLab.psd1 -All

        Downloads all required lab media, any custom resources and DSC resources defined in the 'MyLab.psd1' configuration.
    .EXAMPLE
        Invoke-LabResourceDownload -ConfigurationData ~\Documents\MyLab.psd1 -MediaId 'WIN10_x64_Enterprise_EN_Eval'

        Downloads only the 'WIN10_x64_Enterprise_EN_Eval' media.
    .EXAMPLE
        Invoke-LabResourceDownload -ConfigurationData ~\Documents\MyLab.psd1 -ResourceId 'MyCustomResource'

        Downloads only the 'MyCustomResource' resource defined in the 'MyLab.psd1' configuration.
    .EXAMPLE
        Invoke-LabResourceDownload -ConfigurationData ~\Documents\MyLab.psd1 -Media

        Downloads only the media defined in the 'MyLab.psd1' configuration.
    .EXAMPLE
        Invoke-LabResourceDownload -ConfigurationData ~\Documents\MyLab.psd1 -Resources -DSCResources

        Downloads only the custom file resources and DSC resources defined in the 'MyLab.psd1' configuration.
#>
    [CmdletBinding(DefaultParameterSetName = 'All')]
    param (
        [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [System.Collections.Hashtable]
        [Microsoft.PowerShell.DesiredStateConfiguration.ArgumentToConfigurationDataTransformationAttribute()]
         $ConfigurationData = @{ },

        [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'All')]
        [System.Management.Automation.SwitchParameter] $All,

        [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'MediaId')]
        [System.String[]] $MediaId,

        [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ResourceId')]
        [System.String[]] $ResourceId,

        [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Media')]
        [System.Management.Automation.SwitchParameter] $Media,

        [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Resources')]
        [System.Management.Automation.SwitchParameter] $Resources,

        [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DSCResources')]
        [System.Management.Automation.SwitchParameter] $DSCResources,

        [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Modules')]
        [System.Management.Automation.SwitchParameter] $Modules,

        [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Resources')]
        [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ResourceId')]
        [ValidateNotNullOrEmpty()]
        [System.String] $DestinationPath,

        [Parameter(ValueFromPipelineByPropertyName)]
        [System.Management.Automation.SwitchParameter] $Force
    )
    begin {

        $hostDefaults = Get-ConfigurationData -Configuration Host;
        if (-not $DestinationPath) {
            $DestinationPath = $hostDefaults.ResourcePath;
        }

    }
    process {

        if ($PSCmdlet.ParameterSetName -in 'MediaId','Media','All') {

            if (-not $MediaId) {

                Write-Verbose -Message ($Localized.DownloadingAllRequiredMedia);
                $uniqueMediaIds = @();
                $ConfigurationData.AllNodes.Where({ $_.NodeName -ne '*' }) | ForEach-Object {
                    $id = (Resolve-NodePropertyValue -NodeName $_.NodeName -ConfigurationData $ConfigurationData).Media;
                    if ($uniqueMediaIds -notcontains $id) { $uniqueMediaIds += $id; }
                }
                $MediaId = $uniqueMediaIds;
            }

            if ($MediaId) {

                foreach ($id in $MediaId) {

                    $labMedia = Resolve-LabMedia -ConfigurationData $ConfigurationData -Id $id;
                    Invoke-LabMediaImageDownload -Media $labMedia -Force:$Force;

                    Write-Verbose -Message $Localized.DownloadingAllRequiredHotfixes;
                    if ($labMedia.Hotfixes.Count -gt 0) {
                        foreach ($hotfix in $labMedia.Hotfixes) {
                            Invoke-LabMediaDownload -Id $hotfix.Id -Uri $hotfix.Uri;
                        }
                    }
                    else {
                        Write-Verbose -Message ($localized.NoHotfixesSpecified);
                    }
                }

            }
            else {
                Write-Verbose -Message ($localized.NoMediaDefined);
            }

        } #end if MediaId or MediaOnly

        if ($PSCmdlet.ParameterSetName -in 'ResourceId','Resources','All') {

            if (-not $ResourceId) {

                Write-Verbose -Message ($Localized.DownloadingAllDefinedResources);
                $ResourceId = $ConfigurationData.NonNodeData.$($labDefaults.ModuleName).Resource.Id;
            }

            if (($ResourceId.Count -gt 0) -and (-not $MediaOnly)) {

                foreach ($id in $ResourceId) {

                    $resource = Resolve-LabResource -ConfigurationData $ConfigurationData -ResourceId $id;
                    if (($null -eq $resource.IsLocal) -or ($resource.IsLocal -eq $false)) {

                        $fileName = $resource.Id;
                        if ($resource.Filename) { $fileName = $resource.Filename; }
                        $resourceDestinationPath = Join-Path -Path $DestinationPath -ChildPath $fileName;
                        $invokeResourceDownloadParams = @{
                            DestinationPath = $resourceDestinationPath;
                            Uri = $resource.Uri;
                            Checksum = $resource.Checksum;
                            Force = $Force;
                        }
                        [ref] $null = Invoke-ResourceDownload @invokeResourceDownloadParams;
                        Write-Output (Get-Item -Path $resourceDestinationPath);
                    }
                }
            }
            else {

                Write-Verbose -Message ($localized.NoResourcesDefined);
            }

        } #end if ResourceId or ResourceOnly

        if ($PSCmdlet.ParameterSetName -in 'DSCResources','All') {

            $dscResourceDefinitions = $ConfigurationData.NonNodeData.$($labDefaults.ModuleName).DSCResource;
            if (($null -ne $dscResourceDefinitions) -and ($dscResourceDefinitions.Count -gt 0)) {

                ## Invokes download of DSC resource modules into the module cache
                Write-Verbose -Message ($Localized.DownloadingAllDSCResources);
                Invoke-LabModuleCacheDownload -Module $dscResourceDefinitions -Force:$Force;
            }
            else {
                Write-Verbose -Message ($localized.NoDSCResourcesDefined);
            }
        } #end if DSC resource

        if ($PSCmdlet.ParameterSetName -in 'Modules','All') {

            $moduleDefinitions = $ConfigurationData.NonNodeData.$($labDefaults.ModuleName).Module;
            if (($null -ne $moduleDefinitions) -and ($moduleDefinitions.Count -gt 0)) {

                ## Invokes download of PowerShell modules into the module cache
                Write-Verbose -Message ($Localized.DownloadingAllPowerShellModules);
                Invoke-LabModuleCacheDownload -Module $moduleDefinitions -Force:$Force;
            }
            else {
                Write-Verbose -Message ($localized.NoPowerShellModulesDefined);
            }

        } #end PowerShell module

    } #end process
} #end function


text:
from jinja2 import Environment, FileSystemLoader, TemplateNotFound
from webob import Request as WebObRequest, Response as WebObResponse
from webob.static import DirectoryApp as WebObDirectoryApp
import traceback
import os.path

from gunstar.session import Session
from gunstar.template import linebreaks, linebreaksbr
from gunstar.signals import template_rendered_signal

PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
GUNSTAR_TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates')

Request = WebObRequest
Response = WebObResponse
DirectoryApp = WebObDirectoryApp

class RequestHandler(object):

    http_method_names = [
        'get', 'post', 'put', 'delete', 'head', 'options', 'trace'
    ]

    def __init__(self, app, request, response):
        self.app = app
        self.request = request
        self.response = response
        self.session = Session(self.app, self.request, self.response)
        self.template_env = self.create_template_env()

    def before_dispatch(self):
        pass

    def dispatch(self, *args, **kwargs):
        # call before dispatch
        self.before_dispatch()

        # flag to control method not allowed error
        handler_executed = False

        if self.request.method.lower() in self.http_method_names:
            handler = getattr(self, self.request.method.lower(), None)
            if handler:
                handler_executed = True
                handler(*args, **kwargs)

        if not handler_executed:
            self.abort(405, 'Method Not Allowed.')

        # call after dispatch
        self.after_dispatch()

    def after_dispatch(self):
        pass

    def abort(self, code, message=None):
        self.response.status_code = code
        if not message:
            message = 'Returned Status Code = {0}'.format(code)
        self.response.write(message)

    def redirect(self, redirect_url, permanent=False, status_code=302):
        message = 'The resource has been moved to {0}'.format(redirect_url)
        if permanent:
            status_code = 301
        self.response.status_code = status_code
        self.response.location = redirect_url
        self.response.write(message)

    def get_template_globals(self):
        template_globals = {
            'handler': self,
            'config': self.app.config,
            'request': self.request,
            'reverse_route': self.reverse_route,
        }
        return template_globals

    def get_template_filters(self):
        template_filters = {
            'linebreaks': linebreaks,
            'linebreaksbr': linebreaksbr
        }
        return template_filters

    def create_template_env(self):
        template_dirs = []
        if self.app.config.get('TEMPLATE_PATH', None):
            template_dirs.append(self.app.config['TEMPLATE_PATH'])
        template_dirs.append(GUNSTAR_TEMPLATE_PATH)
        template_env = Environment(
            loader=FileSystemLoader(template_dirs),
            extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_'],
            autoescape=True
        )
        template_env.globals.update(self.get_template_globals())
        template_env.filters.update(self.get_template_filters())
        return template_env

    def render_template(self, template_name, **kwargs):
        try:
            template = self.template_env.get_template(template_name)
        except TemplateNotFound:
            raise TemplateNotFound(template_name)
        template_rendered = template.render(kwargs)
        template_rendered_signal.send(
            self.app, handler=self, template=template_rendered, context=kwargs
        )
        self.response.text = template_rendered

    def reverse_route(self, name, *args):
        url = ''
        route = self.app.router.find_route_by_name(name)
        if route:
            reverse = route.reverse_route(*args)
            if reverse:
                url = reverse
        return url

class NotFoundHandler(RequestHandler):

    def get(self):
        self.response.status = 404
        self.render_template('404.html', path=self.request.path_info)

class ErrorHandler(RequestHandler):

    def get(self, exc_info):
        self.response.status = 500
        self.render_template(
            '500.html', traceback=traceback.format_exception(*exc_info)
        )


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using NSwag.Annotations;
using MediatR;
using System.Net.Http;
using Newtonsoft.Json;
using Microsoft.AspNetCore.WebUtilities;

namespace DataReaver.Framework
{

    public interface IRestClient : IDisposable
    {
        Task<RestResponse<T>> Execute<T>(RestRequest request);
        Task<RestResponse<T>> Get<T>(string resource);
    }

    public class RestClient : IRestClient
    {
        private HttpClient httpClient;

        public List<Parameter> Parameters { get; } = new List<Parameter>();

        public RestClient()
        {
            this.httpClient = new HttpClient();
        }

        public RestClient(Uri baseAddress)
        {
            this.httpClient = new HttpClient
            {
                BaseAddress = baseAddress
            };
        }

        public RestClient(string baseAddress) : this(new Uri(baseAddress))
        {
        }

        public Uri BaseAddress
        {
            get
            {
                return this.httpClient.BaseAddress;
            }
            set
            {
                this.httpClient.BaseAddress = value;
            }
        }

        public TimeSpan Timeout
        {
            get
            {
                return this.httpClient.Timeout;
            }
            set
            {
                this.httpClient.Timeout = value;
            }
        }

        public void Dispose()
        {
            this.httpClient.Dispose();
        }

        public async Task<RestResponse<T>> Execute<T>(RestRequest request)
        {
            var requestUri = this.BuildUri(request);

            var httpRequestMessage = new HttpRequestMessage(request.Method, requestUri);

            var httpResponseMessage = await this.httpClient.SendAsync(httpRequestMessage);

            return new RestResponse<T>(httpResponseMessage);
        }

        public async Task<RestResponse<T>> Get<T>(string resource)
        {
            return await this.Execute<T>(new RestRequest(HttpMethod.Get, resource));
        }

        private List<Parameter> GetParameters(RestRequest request)
        {
            var parameters = new List<Parameter>(this.Parameters);
            foreach (var parameter in request.Parameters)
            {
                var existingParameter = parameters.SingleOrDefault(p => p.Name.Equals(parameter.Name) && p.Type == parameter.Type);
                if (existingParameter != null)
                {
                    parameters.Remove(existingParameter);
                }
                parameters.Add(parameter);
            }
            return parameters;
        }

        public Uri BuildUri(RestRequest request)
        {
            Uri uri;

            if(this.BaseAddress == null)
            {
                uri = new Uri(request.Resource);
            }
            else if(!string.IsNullOrEmpty(request.Resource))
            {
                uri = new Uri(this.BaseAddress, request.Resource);
            }
            else
            {
                uri = this.BaseAddress;
            }

            var builder = new UriBuilder(uri);

            builder.Path = this.GetPath(request, builder.Path);

            builder.Query = this.GetQuery(request, builder.Query);

            return builder.Uri;
        }

        private string GetQuery(RestRequest request, string originalQuery)
        {
            if (string.IsNullOrEmpty(originalQuery))
            {
                return originalQuery;
            }

            var dictionary = QueryHelpers.ParseQuery(originalQuery);

            foreach (var parameter in this.GetParameters(request).Where(p => p.Type == ParameterType.QueryString || (request.Method == HttpMethod.Get && p.Type == ParameterType.GetOrPost)))
            {
                if(dictionary.ContainsKey(parameter.Name))
                {
                    dictionary.Remove(parameter.Name);
                }

                dictionary.Add(parameter.Name, parameter.Value?.ToString());
            }

            return string.Join("&", dictionary.Select(x => $"{Uri.EscapeUriString(x.Key)}={Uri.EscapeUriString(x.Value.ToString())}"));
        }

        private string GetPath(RestRequest request, string originalPath)
        {
            if (string.IsNullOrEmpty(originalPath))
            {
                return originalPath;
            }

            var path = Uri.UnescapeDataString(originalPath);

            foreach (var parameter in this.GetParameters(request).Where(p => p.Type == ParameterType.UrlSegment))
            {
                path = path.Replace($"{{{parameter.Name}}}", Uri.EscapeUriString(parameter.Value?.ToString() ?? string.Empty));
            }

            return path;
        }

    }

    public class RestRequest
    {
        public HttpMethod Method { get; set; }
        public string Resource { get; set; }

        public List<Parameter> Parameters { get; } = new List<Parameter>();

        public RestRequest(HttpMethod method, string resource)
        {
            this.Method = method;
            this.Resource = resource;
        }

        public RestRequest AddParameter(Parameter parameter)
        {
            this.Parameters.Add(parameter);

            return this;
        }

        public RestRequest AddParameter(string name, object value, ParameterType type)
        {
            return this.AddParameter(new Parameter
            {
                Name = name,
                Value = value,
                Type = type
            });
        }
    }

    public class RestResponse<T>
    {
        private readonly HttpResponseMessage httpResponseMessage;

        public RestResponse(HttpResponseMessage httpResponseMessage)
        {
            this.httpResponseMessage = httpResponseMessage;
        }

        public void EnsureSuccessStatusCode()
        {
            this.httpResponseMessage.EnsureSuccessStatusCode();
        }

        public async Task<T> GetData()
        {
            return await this.GetData<T>(x => x);
        }

        public async Task<TOutput> GetData<TOutput>(Func<T, TOutput> getDataFunction)
        {
            var content = await this.GetContent();

            var data = JsonConvert.DeserializeObject<T>(content);

            return getDataFunction(data);
        }

        public async Task<string> GetContent()
        {
            return await this.httpResponseMessage.Content.ReadAsStringAsync();
        }
    }

    public enum ParameterType
    {
        Cookie,
        GetOrPost,
        UrlSegment,
        HttpHeader,
        RequestBody,
        QueryString
    }

    public class Parameter
    {
        public string Name { get; set; }
        public object Value { get; set; }
        public ParameterType Type { get; set; }
        public string ContentType { get; set; }
    }
}


text:
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

require 'rubygems'

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara-screenshot/rspec'
require 'capybara/webkit/matchers'
require 'codeclimate-test-reporter'

CodeClimate::TestReporter.start

Capybara.javascript_driver = :webkit

Capybara.save_and_open_page_path = '/tmp/capybara-screenshot'
Capybara::Screenshot.register_filename_prefix_formatter(:rspec) do |example|
  "screen_#{example.full_description.gsub(' ', '-').gsub(/^.*\/spec\//, '')}"
end

Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.include Rails.application.routes.url_helpers
  config.fail_fast = false
  config.include FactoryGirl::Syntax::Methods
  config.include Capybara::DSL
  config.use_transactional_fixtures = false
  config.infer_base_class_for_anonymous_controllers = false
  config.order = 'random'
  config.include AbstractController::Translation
  config.include Devise::TestHelpers, type: :controller
  config.extend ControllerMacros, type: :controller
  config.before :suite do
    DatabaseRewinder.clean_all
  end

  config.after :each do
    DatabaseRewinder.clean
  end
end


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

// Network topology
//
// Normally, the use case for emulated net devices is in collections of
// small simulations that connect to the outside world through specific
// interfaces.  For example, one could construct a number of virtual
// machines and connect them via a host-only network.  To use the emulated
// net device, you would need to set all of the host-only interfaces in
// promiscuous mode and provide an appropriate device name (search for "eth1"
// below).  One could also use the emulated net device in a testbed situation
// where the host on which the simulation is running has a specific interface
// of interested.  You would also need to set this specific interface into
// promiscuous mode and provide an appropriate device name.
//
// This philosophy carries over to this simple example.
//
// We don't assume any special configuration and all of the ns-3 emulated net
// devices will actually talk to the same underlying OS device.  We rely on
// the fact that the OS will deliver copies of our packets to the other ns-3
// net devices since we operate in promiscuous mode.
//
// Packets will be sent out over the device, but we use MAC spoofing.  The
// MAC addresses will be generated using the Organizationally Unique Identifier
// (OUI) 00:00:00 as a base.  This vendor code is not assigned to any
// organization and so should not conflict with any real hardware.  We'll use
// the first n of these addresses, where n is the number of nodes, in this
// simualtion.  It is up to you to determine that using these MAC addresses is
// okay on your network and won't conflict with anything else (including another
// simulation using emu devices) on your network.  Once you have made this
// determination, you need to put the interface you chose into promiscuous mode.
// We don't do it for you since you need to think about it first.
//
// This simulation uses the real-time simulator and so will consume ten seconds
// of real time.
//
// By default, we create the following topology
//
//       n0    n1   n2   n3
//       |     |    |    |
//       -----------------
//             "eth1"
//
// - UDP flows from n0 to n1 and back
// - DropTail queues
// - Tracing of queues and packet receptions to file "udp-echo.tr"
// - pcap tracing on all devices
//

#include <fstream>
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/applications-module.h"
#include "ns3/emu-helper.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("EmulatedUdpEchoExample");

int
main (int argc, char *argv[])
{
  std::string deviceName ("eth1");
  std::string encapMode ("Dix");
  uint32_t nNodes = 4;

  //
  // Allow the user to override any of the defaults at run-time, via command-line
  // arguments
  //
  CommandLine cmd;
  cmd.AddValue ("deviceName", "device name", deviceName);
  cmd.AddValue ("encapsulationMode", "encapsulation mode of emu device (\"Dix\" [default] or \"Llc\")", encapMode);
  cmd.AddValue ("nNodes", "number of nodes to create (>= 2)", nNodes);

  cmd.Parse (argc, argv);

  GlobalValue::Bind ("SimulatorImplementationType",
                     StringValue ("ns3::RealtimeSimulatorImpl"));

  //
  // need at least two nodes
  //
  nNodes = nNodes < 2 ? 2 : nNodes;

  //
  // Explicitly create the nodes required by the topology (shown above).
  //
  NS_LOG_INFO ("Create nodes.");
  NodeContainer n;
  n.Create (nNodes);

  InternetStackHelper internet;
  internet.Install (n);

  //
  // Explicitly create the channels required by the topology (shown above).
  //
  NS_LOG_INFO ("Create channels.");
  EmuHelper emu;
  emu.SetAttribute ("DeviceName", StringValue (deviceName));
  emu.SetAttribute ("EncapsulationMode", StringValue (encapMode));

  NetDeviceContainer d = emu.Install (n);

  //
  // We've got the "hardware" in place.  Now we need to add IP addresses.
  //
  Ipv4AddressHelper ipv4;
  NS_LOG_INFO ("Assign IP Addresses.");
  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer i = ipv4.Assign (d);

  //
  // Create a UdpEchoServer application on node one.
  //
  NS_LOG_INFO ("Create Applications.");
  UdpEchoServerHelper server (9);
  ApplicationContainer apps = server.Install (n.Get (1));
  apps.Start (Seconds (1.0));
  apps.Stop (Seconds (10.0));

  //
  // Create a UdpEchoClient application to send UDP datagrams from node zero to node one.
  //
  uint32_t packetSize = 1024;
  uint32_t maxPacketCount = 20;
  Time interPacketInterval = Seconds (0.1);
  UdpEchoClientHelper client (i.GetAddress (1), 9);
  client.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
  client.SetAttribute ("Interval", TimeValue (interPacketInterval));
  client.SetAttribute ("PacketSize", UintegerValue (packetSize));
  apps = client.Install (n.Get (0));
  apps.Start (Seconds (2.0));
  apps.Stop (Seconds (10.0));

  std::ofstream ascii;
  ascii.open ("emu-udp-echo.tr");
  emu.EnablePcapAll ("emu-udp-echo", true);

  //
  // Now, do the actual simulation.
  //
  NS_LOG_INFO ("Run Simulation.");
  Simulator::Run ();
  Simulator::Destroy ();
  NS_LOG_INFO ("Done.");
}


text:
package org.codegist.crest.config.annotate;

import org.codegist.crest.CRestConfig;
import org.codegist.crest.annotate.Produces;
import org.codegist.crest.config.InterfaceConfigBuilder;
import org.codegist.crest.config.MethodConfigBuilder;

/**
 * @author laurent.gilles@codegist.org
 */
class ProducesAnnotationHandler extends StringBasedAnnotationHandler<Produces> {

    ProducesAnnotationHandler(CRestConfig crestConfig) {
        super(crestConfig);
    }

    @Override
    public void handleInterfaceAnnotation(Produces annotation, InterfaceConfigBuilder builder) {
        builder.setMethodsProduces(ph(annotation.value()));
    }

    @Override
    public void handleMethodAnnotation(Produces annotation, MethodConfigBuilder builder) {
        builder.setProduces(ph(annotation.value()));
    }

}


text:
require('./mapperregistry');
var mapregister = global.MapRegistry; // ÒÀÀµ×¢²áÀà
require('./cache');
var cacheclient = global.CACHE; // ÒÀÀµ»º´æ

var UnitOfWork = require('./unitofwork').UnitOfWork; // Session¹¤×÷µ¥Ôª
var Mapper = require('./map').Mapper; // MapperÓ³ÉäÀà
// ¹¹ÔìORMÒýÇæ
function ORM() {
    //console.log(".newOrm");
    return this;
}
exports.ORM = ORM;

ORM.prototype.setCache = function(table, obj) {
    cacheclient.set(table, obj);
}
ORM.prototype.getCache = function(table, id) {
    return cacheclient.get(table, id);
}

ORM.prototype.createMapper = function(table, columns) {
	return new Mapper(table, columns);
}
ORM.prototype.registerMapper = function(key, mapper) {
	mapregister.registerMapper(key, mapper);
}
ORM.prototype.getMapper = function(key) {
	return mapregister.getMapper(key);
}

ORM.prototype.registerREDIS = function(host,port) {
	mapregister.registerREDIS(host,port);
}
ORM.prototype.getREDIS = function() {
	return mapregister.getREDIS();
}

ORM.prototype.registerJDBC = function(host,port,user,pass,database) {
	mapregister.registerJDBC(host,port,user,pass,database);
}
ORM.prototype.getJDBC = function() {
	return mapregister.getJDBC();
}

ORM.prototype.end = function(sessionid) {
	var worker = mapregister.getUnitOfWork(sessionid);
	try {
		worker.commit();
	}
	catch(E) {
		worker.rollback();
		throw E;
	}
	finally{
		mapregister.unregisterUnitOfWork(sessionid);
	}
}
ORM.prototype.transaction = function(sessionid,callback) {
	var worker = new UnitOfWork(sessionid);
	try {
		mapregister.registerUnitOfWork(sessionid, worker);
		callback(sessionid, worker);
	}
	catch(E){
		worker.rollback();
		mapregister.unregisterUnitOfWork(sessionid);
		throw E;
	}
}


text:
<title>SpriteHeight</title>

SpriteHeight()

Syntax

Result = SpriteHeight(#Sprite)

Description

Returns the height (in pixels) of the specified sprite.

Parameters

#Sprite

The sprite to use.

Return value

The height (in pixels) of the specified sprite.

See Also

SpriteWidth(), SpriteDepth()

Supported OS
All

<- SpriteDepth() - Sprite Index - SpriteID() ->