text:
from copy import copy

from blu import Config
from commander import Commander, Response

class HandbrakeSettins(object):
    def __init__(self,
                 preset: str,
                 frameRate: float,
                 quality: int,
                 encoder: str,
                 encoderPreset: str,
                 encoderTune: str,
                 options: str):
        self.preset: str = preset
        self.preset: str = preset
        self.frameRate: str = frameRate
        self.quality: str = quality
        self.encoder: str = encoder
        self.encoderPreset: str = encoderPreset
        self.encoderTune: str = encoderTune
        self.options: str = options

class HandbrakeCLI(object):
    config: Config = Config()

    def __init__(self, commander: Commander):
        self.commander: Commander = commander
        self.executable: str = self.config.cfg['handbrake']['executable']
        self.defaultSettings = HandbrakeSettins(
            preset=self.config.cfg['handbrake']['preset'],
            frameRate=self.config.cfg['handbrake']['frame_rate'],
            quality=self.config.cfg['handbrake']['quality']['default'],
            encoder=self.config.cfg['handbrake']['encoder']['encoder'],
            encoderPreset=self.config.cfg['handbrake']['encoder']['preset'],
            encoderTune=self.config.cfg['handbrake']['encoder']['tune'],
            options=self.config.cfg['handbrake']['options']
        )

    def compressFile(self, input_file: str, output_file: str, **kwargs):
        settings: HandbrakeSettins = copy(self.defaultSettings)

        if kwargs.get('frame_rate') is not None:
            settings.frameRate = kwargs.get('frame_rate')

        if kwargs.get('quality') is not None:
            settings.quality = kwargs.get('quality')

        if kwargs.get('height') is not None:
            settings.options = "{} --height {}".format(settings.options, kwargs.get('height'))

        if kwargs.get('width') is not None:
            settings.options = "{} --width {}".format(settings.options, kwargs.get('width'))

        response: Response = self.commander.call(
            '{executable} --input="{input}" --output="{output}" --preset="{preset}" --rate={frameRate} --quality={quality} --encoder={encoder} --encoder-preset={encoderPreset} --encoder-tune={encoderTune} {options}'
                .format(executable=self.executable,
                        input=input_file,
                        output=output_file,
                        preset=settings.preset,
                        frameRate=settings.frameRate,
                        quality=settings.quality,
                        encoder=settings.encoder,
                        encoderPreset=settings.encoderPreset,
                        encoderTune=settings.encoderTune,
                        options=settings.options))

        if response.return_code != 0:
            print(response.std_err)
            raise Exception(response.return_code)


text:
namespace util {
namespace win {

namespace {

struct PressureSettings {
  int phys_left_mb;
  base::MemoryPressureListener::MemoryPressureLevel level;
};

}  // namespace

// This is outside of the anonymous namespace so that it can be seen as a friend
// to the evaluator class.
class TestSystemMemoryPressureEvaluator : public SystemMemoryPressureEvaluator {
 public:
  using SystemMemoryPressureEvaluator::CalculateCurrentPressureLevel;
  using SystemMemoryPressureEvaluator::CheckMemoryPressure;

  static const DWORDLONG kMBBytes = 1024 * 1024;

  explicit TestSystemMemoryPressureEvaluator(
      bool large_memory,
      std::unique_ptr<MemoryPressureVoter> voter)
      : SystemMemoryPressureEvaluator(std::move(voter)), mem_status_() {
    // Generate a plausible amount of memory.
    mem_status_.ullTotalPhys =
        static_cast<DWORDLONG>(GenerateTotalMemoryMb(large_memory)) * kMBBytes;

    // Rerun InferThresholds using the test fixture's GetSystemMemoryStatus.
    InferThresholds();
    // Stop the timer.
    StopObserving();
  }

  TestSystemMemoryPressureEvaluator(int system_memory_mb,
                                    int moderate_threshold_mb,
                                    int critical_threshold_mb)
      : SystemMemoryPressureEvaluator(moderate_threshold_mb,
                                      critical_threshold_mb,
                                      nullptr),
        mem_status_() {
    // Set the amount of system memory.
    mem_status_.ullTotalPhys =
        static_cast<DWORDLONG>(system_memory_mb * kMBBytes);

    // Stop the timer.
    StopObserving();
  }

  MOCK_METHOD1(OnMemoryPressure,
               void(base::MemoryPressureListener::MemoryPressureLevel level));

  // Generates an amount of total memory that is consistent with the requested
  // memory model.
  int GenerateTotalMemoryMb(bool large_memory) {
    int total_mb = 64;
    while (total_mb < SystemMemoryPressureEvaluator::kLargeMemoryThresholdMb)
      total_mb *= 2;
    if (large_memory)
      return total_mb * 2;
    return total_mb / 2;
  }

  // Sets up the memory status to reflect the provided absolute memory left.
  void SetMemoryFree(int phys_left_mb) {
    // ullTotalPhys is set in the constructor and not modified.

    // Set the amount of available memory.
    mem_status_.ullAvailPhys = static_cast<DWORDLONG>(phys_left_mb) * kMBBytes;
    DCHECK_LT(mem_status_.ullAvailPhys, mem_status_.ullTotalPhys);

    // These fields are unused.
    mem_status_.dwMemoryLoad = 0;
    mem_status_.ullTotalPageFile = 0;
    mem_status_.ullAvailPageFile = 0;
    mem_status_.ullTotalVirtual = 0;
    mem_status_.ullAvailVirtual = 0;
  }

  void SetNone() { SetMemoryFree(moderate_threshold_mb() + 1); }

  void SetModerate() { SetMemoryFree(moderate_threshold_mb() - 1); }

  void SetCritical() { SetMemoryFree(critical_threshold_mb() - 1); }

 private:
  bool GetSystemMemoryStatus(MEMORYSTATUSEX* mem_status) override {
    // Simply copy the memory status set by the test fixture.
    *mem_status = mem_status_;
    return true;
  }

  MEMORYSTATUSEX mem_status_;

  DISALLOW_COPY_AND_ASSIGN(TestSystemMemoryPressureEvaluator);
};

class WinSystemMemoryPressureEvaluatorTest : public testing::Test {
 protected:
  void CalculateCurrentMemoryPressureLevelTest(
      TestSystemMemoryPressureEvaluator* evaluator) {
    int mod = evaluator->moderate_threshold_mb();
    evaluator->SetMemoryFree(mod + 1);
    EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE,
              evaluator->CalculateCurrentPressureLevel());

    evaluator->SetMemoryFree(mod);
    EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE,
              evaluator->CalculateCurrentPressureLevel());

    evaluator->SetMemoryFree(mod - 1);
    EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE,
              evaluator->CalculateCurrentPressureLevel());

    int crit = evaluator->critical_threshold_mb();
    evaluator->SetMemoryFree(crit + 1);
    EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE,
              evaluator->CalculateCurrentPressureLevel());

    evaluator->SetMemoryFree(crit);
    EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL,
              evaluator->CalculateCurrentPressureLevel());

    evaluator->SetMemoryFree(crit - 1);
    EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL,
              evaluator->CalculateCurrentPressureLevel());
  }

  base::test::SingleThreadTaskEnvironment task_environment_{
      base::test::SingleThreadTaskEnvironment::MainThreadType::UI};
};

// Tests the fundamental direct calculation of memory pressure with automatic
// small-memory thresholds.
TEST_F(WinSystemMemoryPressureEvaluatorTest,
       CalculateCurrentMemoryPressureLevelSmall) {
  static const int kModerateMb =
      SystemMemoryPressureEvaluator::kSmallMemoryDefaultModerateThresholdMb;
  static const int kCriticalMb =
      SystemMemoryPressureEvaluator::kSmallMemoryDefaultCriticalThresholdMb;

  // Small-memory model.
  TestSystemMemoryPressureEvaluator evaluator(false, nullptr);

  EXPECT_EQ(kModerateMb, evaluator.moderate_threshold_mb());
  EXPECT_EQ(kCriticalMb, evaluator.critical_threshold_mb());

  ASSERT_NO_FATAL_FAILURE(CalculateCurrentMemoryPressureLevelTest(&evaluator));
}

// Tests the fundamental direct calculation of memory pressure with automatic
// large-memory thresholds.
TEST_F(WinSystemMemoryPressureEvaluatorTest,
       CalculateCurrentMemoryPressureLevelLarge) {
  static const int kModerateMb =
      SystemMemoryPressureEvaluator::kLargeMemoryDefaultModerateThresholdMb;
  static const int kCriticalMb =
      SystemMemoryPressureEvaluator::kLargeMemoryDefaultCriticalThresholdMb;

  // Large-memory model.
  TestSystemMemoryPressureEvaluator evaluator(true, nullptr);

  EXPECT_EQ(kModerateMb, evaluator.moderate_threshold_mb());
  EXPECT_EQ(kCriticalMb, evaluator.critical_threshold_mb());

  ASSERT_NO_FATAL_FAILURE(CalculateCurrentMemoryPressureLevelTest(&evaluator));
}

// Tests the fundamental direct calculation of memory pressure with manually
// specified threshold levels.
TEST_F(WinSystemMemoryPressureEvaluatorTest,
       CalculateCurrentMemoryPressureLevelCustom) {
  static const int kSystemMb = 512;
  static const int kModerateMb = 256;
  static const int kCriticalMb = 128;

  TestSystemMemoryPressureEvaluator evaluator(kSystemMb, kModerateMb,
                                              kCriticalMb);

  EXPECT_EQ(kModerateMb, evaluator.moderate_threshold_mb());
  EXPECT_EQ(kCriticalMb, evaluator.critical_threshold_mb());

  ASSERT_NO_FATAL_FAILURE(CalculateCurrentMemoryPressureLevelTest(&evaluator));
}

// This test tests the various transition states from memory pressure, looking
// for the correct behavior on event reposting as well as state updates.
TEST_F(WinSystemMemoryPressureEvaluatorTest, CheckMemoryPressure) {
  MultiSourceMemoryPressureMonitor monitor;
  monitor.ResetSystemEvaluatorForTesting();

  // Large-memory.
  testing::StrictMock<TestSystemMemoryPressureEvaluator> evaluator(
      true, monitor.CreateVoter());

  base::MemoryPressureListener listener(
      base::BindRepeating(&TestSystemMemoryPressureEvaluator::OnMemoryPressure,
                          base::Unretained(&evaluator)));

  // Checking the memory pressure at 0% load should not produce any
  // events.
  evaluator.SetNone();
  evaluator.CheckMemoryPressure();
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE,
            evaluator.current_vote());

  // Setting the memory level to 80% should produce a moderate pressure level.
  EXPECT_CALL(
      evaluator,
      OnMemoryPressure(
          base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE));
  evaluator.SetModerate();
  evaluator.CheckMemoryPressure();
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE,
            evaluator.current_vote());
  testing::Mock::VerifyAndClearExpectations(&evaluator);

  // Check that the event gets reposted after a while.
  const int kModeratePressureCooldownCycles =
      evaluator.kModeratePressureCooldownMs /
      base::MemoryPressureMonitor::kUMAMemoryPressureLevelPeriod
          .InMilliseconds();

  for (int i = 0; i < kModeratePressureCooldownCycles; ++i) {
    if (i + 1 == kModeratePressureCooldownCycles) {
      EXPECT_CALL(
          evaluator,
          OnMemoryPressure(
              base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE));
    }
    evaluator.CheckMemoryPressure();
    base::RunLoop().RunUntilIdle();
    EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE,
              evaluator.current_vote());
    testing::Mock::VerifyAndClearExpectations(&evaluator);
  }

  // Setting the memory usage to 99% should produce critical levels.
  EXPECT_CALL(
      evaluator,
      OnMemoryPressure(
          base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL));
  evaluator.SetCritical();
  evaluator.CheckMemoryPressure();
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL,
            evaluator.current_vote());
  testing::Mock::VerifyAndClearExpectations(&evaluator);

  // Calling it again should immediately produce a second call.
  EXPECT_CALL(
      evaluator,
      OnMemoryPressure(
          base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL));
  evaluator.CheckMemoryPressure();
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL,
            evaluator.current_vote());
  testing::Mock::VerifyAndClearExpectations(&evaluator);

  // When lowering the pressure again there should be a notification and the
  // pressure should go back to moderate.
  EXPECT_CALL(
      evaluator,
      OnMemoryPressure(
          base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE));
  evaluator.SetModerate();
  evaluator.CheckMemoryPressure();
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE,
            evaluator.current_vote());
  testing::Mock::VerifyAndClearExpectations(&evaluator);

  // Check that the event gets reposted after a while.
  for (int i = 0; i < kModeratePressureCooldownCycles; ++i) {
    if (i + 1 == kModeratePressureCooldownCycles) {
      EXPECT_CALL(
          evaluator,
          OnMemoryPressure(
              base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE));
    }
    evaluator.CheckMemoryPressure();
    base::RunLoop().RunUntilIdle();
    EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE,
              evaluator.current_vote());
    testing::Mock::VerifyAndClearExpectations(&evaluator);
  }

  // Going down to no pressure should not produce an notification.
  evaluator.SetNone();
  evaluator.CheckMemoryPressure();
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE,
            evaluator.current_vote());
  testing::Mock::VerifyAndClearExpectations(&evaluator);
}

}  // namespace win
}  // namespace util

redpajama_set_name: RedPajamaGithub


text:
"""FNode are the building blocks of formulae."""
import collections

import pysmt.environment
from pysmt.operators import (FORALL, EXISTS, AND, OR, NOT, IMPLIES, IFF,
                             SYMBOL, FUNCTION,
                             REAL_CONSTANT, BOOL_CONSTANT, INT_CONSTANT,
                             PLUS, MINUS, TIMES,
                             LE, LT, EQUALS,
                             ITE,
                             TOREAL,
                             BV_CONSTANT, BV_NOT, BV_AND, BV_OR, BV_XOR,
                             BV_CONCAT, BV_EXTRACT,
                             BV_ULT, BV_NEG, BV_ADD, BV_SUB,
                             BV_MUL, BV_UDIV, BV_UREM,
                             BV_LSHL, BV_LSHR,
                             BV_ROL, BV_ROR,
                             BV_ZEXT, BV_SEXT,
                             BV_SLT, BV_SLE,
                             BV_COMP,
                             BV_SDIV, BV_SREM,
                             BV_ASHR)
from pysmt.operators import  (BOOL_OPERATORS, THEORY_OPERATORS,
                              BV_OPERATORS, LIRA_OPERATORS,
                              RELATIONS, CONSTANTS)
from pysmt.typing import BOOL, REAL, INT, BVType
from pysmt.decorators import deprecated
from pysmt.utils import is_python_integer, is_python_rational, is_python_boolean
from pysmt.utils import twos_complement

FNodeContent = collections.namedtuple("FNodeContent",
                                      ["node_type", "args", "payload"])

class FNode(object):
    r"""FNode represent the basic structure for representing a formula.

    FNodes are built using the FormulaManager, and should not be
    explicitely instantiated, since the FormulaManager takes care of
    memoization, thus guaranteeing that equivalent are represented by
    the same object.

    An FNode is a wrapper to the structure FNodeContent. FNodeContent
    defines the type of the node (see operators.py), its arguments
    (e.g., for the formula A /\ B, args=(A,B)) and its payload,
    content of the node that is not an FNode (e.g., for an integer
    constant, the payload might be the python value 1).

    The node_id is an integer uniquely identifying the node within the
    FormulaManager it belongs.
    """

    def __init__(self, content, node_id):
        self._content = content
        self._node_id = node_id
        return

    # __eq__ is left as default while __hash__ uses the node id. This
    # is because we always have shared FNodes, hence in a single
    # environment two nodes have always different ids, but in
    # different environments they can have the same id. This is not an
    # issue since, by default, equality coincides with identity.
    def __hash__(self):
        return self._node_id

    def node_id(self):
        return self._node_id

    def node_type(self):
        return self._content.node_type

    def args(self):
        """Returns the subformulae."""
        return self._content.args

    def arg(self, idx):
        """Return the given subformula at the given position."""
        return self._content.args[idx]

    @deprecated("get_free_variables")
    def get_dependencies(self):
        return self.get_free_variables()

    def get_free_variables(self):
        """Return the set of Symbols that are free in the formula."""
        return _env().fvo.get_free_variables(self)

    def get_atoms(self):
        """Return the set of atoms appearing in the formula."""
        return _env().ao.get_atoms(self)

    @deprecated("args")
    def get_sons(self):
        return self.args()

    def simplify(self):
        """Return a simplified version of the formula."""
        return _env().simplifier.simplify(self)

    def substitute(self, subs):
        """Return a formula in which subformula have been substituted.

        subs is a dictionary mapping terms to be subtituted with their
        substitution.
        """
        return _env().substituter.substitute(self, subs=subs)

    def size(self, measure=None):
        """Return the size of the formula according to the given metric.

        See :py:class:`SizeOracle`
        """
        return _env().sizeo.get_size(self, measure)

    def get_type(self):
        """Return the type of the formula by calling the Type-Checker.

        See :py:class:`SimpleTypeChecker`
        """
        return _env().stc.get_type(self)

    def is_constant(self, _type=None, value=None):
        """Test whether the formula is a constant.

        Optionally, check that the constant is of the given type and value.
        """
        if self.node_type() not in CONSTANTS:
            return False
        if _type is not None:
            if _type.is_int_type() and self.node_type() != INT_CONSTANT:
                return False
            if _type.is_real_type() and self.node_type() != REAL_CONSTANT:
                return False
            if _type.is_bool_type() and self.node_type() != BOOL_CONSTANT:
                return False
            if _type.is_bv_type():
                if self.node_type() != BV_CONSTANT:
                    return False
                if self._content.payload[1] != _type.width:
                    return False

        if value is not None:
            return value == self.constant_value()
        return True

    def is_bool_constant(self, value=None):
        """Test whether the formula is a Boolean constant.

        Optionally, check that the constant has the given value.
        """
        return self.is_constant(BOOL, value)

    def is_real_constant(self, value=None):
        """Test whether the formula is a Real constant.

        Optionally, check that the constant has the given value.
        """
        return self.is_constant(REAL, value)

    def is_int_constant(self, value=None):
        """Test whether the formula is an Integer constant.

        Optionally, check that the constant has the given value.
        """
        return self.is_constant(INT, value)

    def is_bv_constant(self, value=None, width=None):
        """Test whether the formula is a BitVector constant.

        Optionally, check that the constant has the given value.
        """
        if value is None and width is None:
            return self.node_type() == BV_CONSTANT

        if width is None:
            return self.is_constant(value=value)
        else:
            return self.is_constant(_type=BVType(width=width),
                                    value=value)

    def is_symbol(self, type_=None):
        """Test whether the formula is a Symbol.

        Optionally, check that the symbol has the given type.
        """
        if type_:
            return self.node_type() == SYMBOL and \
                   self.symbol_type() == type_
        return self.node_type() == SYMBOL

    def is_literal(self):
        """Test whether the formula is a literal.

        A literal is a positive or negative Boolean symbol.
        """
        if self.is_symbol(BOOL):
            return True
        if self.is_not():
            return self.arg(0).is_symbol(BOOL)

    def is_true(self):
        """Test whether the formula is the True Boolean constant."""
        return self.is_bool_constant(True)

    def is_false(self):
        """Test whether the formula is the False Boolean constant."""
        return self.is_bool_constant(False)

    def is_one(self):
        return self.is_real_constant(1) or self.is_int_constant(1)

    def is_zero(self):
        return self.is_real_constant(0) or self.is_int_constant(0)

    def is_toreal(self):
        """Test whether the node is the ToReal operator."""
        return self.node_type() == TOREAL

    def is_forall(self):
        """Test whether the node is the ForAll operator."""
        return self.node_type() == FORALL

    def is_exists(self):
        """Test whether the node is the Exists operator."""
        return self.node_type() == EXISTS

    def is_quantifier(self):
        """Test whether the node is a Quantifier."""
        return self.is_exists() or self.is_forall()

    def is_and(self):
        """Test whether the node is the And operator."""
        return self.node_type() == AND

    def is_or(self):
        """Test whether the node is the Or operator."""
        return self.node_type() == OR

    def is_not(self):
        """Test whether the node is the Not operator."""
        return self.node_type() == NOT

    def is_plus(self):
        """Test whether the node is the Plus operator."""
        return self.node_type() == PLUS

    def is_minus(self):
        """Test whether the node is the Minus operator."""
        return self.node_type() == MINUS

    def is_times(self):
        """Test whether the node is the Times operator."""
        return self.node_type() == TIMES

    def is_implies(self):
        """Test whether the node is the Implies operator."""
        return self.node_type() == IMPLIES

    def is_iff(self):
        """Test whether the node is the Iff operator."""
        return self.node_type() == IFF

    def is_ite(self):
        """Test whether the node is the Ite operator."""
        return self.node_type() == ITE

    def is_equals(self):
        """Test whether the node is the Equals operator."""
        return self.node_type() == EQUALS

    def is_le(self):
        """Test whether the node is the LE (less than equal) relation."""
        return self.node_type() == LE

    def is_lt(self):
        """Test whether the node is the LT (less than) relation."""
        return self.node_type() == LT

    def is_bool_op(self):
        """Test whether the node is a Boolean operator."""
        return self.node_type() in BOOL_OPERATORS

    def is_theory_relation(self):
        """Test whether the node is a theory relation."""
        return self.node_type() in RELATIONS

    def is_theory_op(self):
        """Test whether the node is a theory operator."""
        return self.node_type() in THEORY_OPERATORS

    def is_lira_op(self):
        """Test whether the node is a LIRA operator."""
        return self.node_type() in LIRA_OPERATORS

    def is_bv_op(self):
        """Test whether the node is a BitVector operator."""
        return self.node_type() in BV_OPERATORS

    def is_bv_not(self):
        """Test whether the node is the BVNot operator."""
        return self.node_type() == BV_NOT

    def is_bv_and(self):
        """Test whether the node is the BVAnd operator."""
        return self.node_type() == BV_AND

    def is_bv_or(self):
        """Test whether the node is the BVOr operator."""
        return self.node_type() == BV_OR

    def is_bv_xor(self):
        """Test whether the node is the BVXor operator."""
        return self.node_type() == BV_XOR

    def is_bv_concat(self):
        """Test whether the node is the BVConcat operator."""
        return self.node_type() == BV_CONCAT

    def is_bv_extract(self):
        """Test whether the node is the BVConcat operator."""
        return self.node_type() == BV_EXTRACT

    def is_bv_ult(self):
        """Test whether the node is the BVULT (unsigned less than) relation."""
        return self.node_type() == BV_ULT

    def is_bv_neg(self):
        """Test whether the node is the BVNeg operator."""
        return self.node_type() == BV_NEG

    def is_bv_add(self):
        """Test whether the node is the BVAdd operator."""
        return self.node_type() == BV_ADD

    def is_bv_mul(self):
        """Test whether the node is the BVMul operator."""
        return self.node_type() == BV_MUL

    def is_bv_udiv(self):
        """Test whether the node is the BVUDiv operator."""
        return self.node_type() == BV_UDIV

    def is_bv_urem(self):
        """Test whether the node is the BVURem operator."""
        return self.node_type() == BV_UREM

    def is_bv_lshl(self):
        """Test whether the node is the BVLShl (logical shift left) operator."""
        return self.node_type() == BV_LSHL

    def is_bv_lshr(self):
        """Test whether the node is the BVLShr (logical shift right) operator."""
        return self.node_type() == BV_LSHR

    def is_bv_rol(self):
        """Test whether the node is the BVRol (rotate left) operator."""
        return self.node_type() == BV_ROL

    def is_bv_ror(self):
        """Test whether the node is the BVRor (rotate right) operator."""
        return self.node_type() == BV_ROR

    def is_bv_zext(self):
        """Test whether the node is the BVZext (zero extension) operator."""
        return self.node_type() == BV_ZEXT

    def is_bv_sext(self):
        """Test whether the node is the BVSext (signed extension) operator."""
        return self.node_type() == BV_SEXT

    def is_bv_sub(self):
        """Test whether the node is the BVSub (subtraction) operator."""
        return self.node_type() == BV_SUB

    def is_bv_slt(self):
        """Test whether the node is the BVSLT (signed less-than) operator."""
        return self.node_type() == BV_SLT

    def is_bv_sle(self):
        """Test whether the node is the BVSLE (signed less-than-or-equal-to) operator."""
        return self.node_type() == BV_SLE

    def is_bv_comp(self):
        """Test whether the node is the BVComp (comparison) operator."""
        return self.node_type() == BV_COMP

    def is_bv_sdiv(self):
        """Test whether the node is the BVSDiv (signed division) operator."""
        return self.node_type() == BV_SDIV

    def is_bv_srem(self):
        """Test whether the node is the BVSRem (signed reminder) operator."""
        return self.node_type() == BV_SREM

    def is_bv_ashr(self):
        """Test whether the node is the BVAshr (arithmetic shift right) operator."""
        return self.node_type() == BV_ASHR

    def bv_width(self):
        """Return the BV width of the formula."""
        if self.is_bv_constant():
            return self._content.payload[1]
        elif self.is_symbol():
            assert self.symbol_type().is_bv_type()
            return self.symbol_type().width
        elif self.is_function_application():
            # Return width defined in the declaration
            return self.function_name().symbol_type().return_type.width
        elif self.is_ite():
            # Recursively call bv_width on the left child
            # (The right child has the same width if the node is well-formed)
            width_l = self.arg(1).bv_width()
            return width_l
        else:
            # BV Operator
            assert self.is_bv_op(), "Unsupported method bv_width on %s" % self
            return self._content.payload[0]

    def bv_extract_start(self):
        """Return the starting index for BVExtract."""
        assert self.is_bv_extract()
        return self._content.payload[1]

    def bv_extract_end(self):
        """Return the ending index for BVExtract."""
        assert self.is_bv_extract()
        return self._content.payload[2]

    def bv_rotation_step(self):
        """Return the rotation step for BVRor and BVRol."""
        assert self.is_bv_ror() or self.is_bv_rol()
        return self._content.payload[1]

    def bv_extend_step(self):
        """Return the extension step for BVZext and BVSext."""
        assert self.is_bv_zext() or self.is_bv_sext()
        return self._content.payload[1]

    def __str__(self):
        return self.serialize(threshold=5)

    def __repr__(self):
        return str(self)

    def serialize(self, threshold=None):
        """Returns a human readable representation of the formula.

        The threshold parameter can be used to limit the amount of the
        formula that will be printed.
        See :py:class:`HRSerializer`
        """
        return _env().serializer.serialize(self, threshold=threshold)

    def is_function_application(self):
        """Test whether the node is a Function application."""
        return self.node_type() == FUNCTION

    @deprecated("is_bool_op")
    def is_boolean_operator(self):
        return self.is_bool_op()

    def is_term(self):
        """Test whether the node is a term.

        All nodes are terms, except for function definitions.
        """
        return not (self.is_symbol() and self.symbol_type().is_function_type())

    def symbol_type(self):
        """Return the type of the Symbol."""
        return self._content.payload[1]

    def symbol_name(self):
        """Return the name of the Symbol."""
        return self._content.payload[0]

    def constant_value(self):
        """Return the value of the Constant."""
        if self.node_type() == BV_CONSTANT:
            return self._content.payload[0]
        return self._content.payload

    def constant_type(self):
        """Return the type of the Constant."""
        if self.node_type() == INT_CONSTANT:
            return INT
        elif self.node_type() == REAL_CONSTANT:
            return REAL
        elif self.node_type() == BOOL_CONSTANT:
            return BOOL
        else:
            assert self.node_type() == BV_CONSTANT,\
                "Unsupported method constant_type '%s'" % self
            return BVType(width=self.bv_width())

    def bv2nat(self):
        """Return the unsigned value encoded by the BitVector."""
        return self.bv_unsigned_value()

    def bv_unsigned_value(self):
        """Return the unsigned value encoded by the BitVector."""
        return self.constant_value()

    def bv_signed_value(self):
        """Return the signed value encoded by the BitVector."""
        return twos_complement(self.constant_value(), self.bv_width())

    def bv_bin_str(self, reverse=False):
        """Return the binary representation of the BitVector as string.

        The reverse option is provided to deal with MSB/LSB.
        """
        fstr = '{0:0%db}' % self.bv_width()
        bitstr = fstr.format(self.constant_value())
        if reverse:
            bitstr = bitstr[::-1]
        return bitstr

    def function_name(self):
        """Return the Function name."""
        return self._content.payload

    def quantifier_vars(self):
        """Return the list of quantified variables."""
        return self._content.payload

    # Infix Notation
    def _apply_infix(self, right, function):
        if _env().enable_infix_notation:
            mgr = _mgr()
            if is_python_boolean(right):
                right = mgr.Bool(right)
            elif is_python_integer(right):
                ty = self.get_type()
                if ty.is_real_type():
                    right = mgr.Real(right)
                else:
                    right = mgr.Int(right)
            elif is_python_rational(right):
                right = mgr.Real(right)
            return function(self, right)
        else:
            raise Exception("Cannot use infix notation")

    def Implies(self, right):
        return self._apply_infix(right, _mgr().Implies)

    def Iff(self, right):
        return self._apply_infix(right, _mgr().Iff)

    def Equals(self, right):
        return self._apply_infix(right, _mgr().Equals)

    def Ite(self, right):
        return self._apply_infix(right, _mgr().Ite)

    def And(self, right):
        return self._apply_infix(right, _mgr().And)

    def Or(self, right):
        return self._apply_infix(right, _mgr().Or)

    def __add__(self, right):
        return self._apply_infix(right, _mgr().Plus)

    def __radd__(self, right):
        return self._apply_infix(right, _mgr().Plus)

    def __sub__(self, right):
        return self._apply_infix(right, _mgr().Minus)

    def __rsub__(self, right):
        minus_self = -self
        return minus_self._apply_infix(right, _mgr().Plus)

    def __mul__(self, right):
        return self._apply_infix(right, _mgr().Times)

    def __rmul__(self, right):
        return self._apply_infix(right, _mgr().Times)

    def __div__(self, right):
        return self._apply_infix(right, _mgr().Div)

    def __truediv__(self, right):
        return self.__div__(right)

    def __gt__(self, right):
        return self._apply_infix(right, _mgr().GT)

    def __ge__(self, right):
        return self._apply_infix(right, _mgr().GE)

    def __lt__(self, right):
        return self._apply_infix(right, _mgr().LT)

    def __le__(self, right):
        return self._apply_infix(right, _mgr().LE)

    def __and__(self, other):
        return self.And(other)

    def __rand__(self, other):
        return self.And(other)

    def __or__(self, other):
        return self.Or(other)

    def __ror__(self, other):
        return self.Or(other)

    def __xor__(self, other):
        return self._apply_infix(other, _mgr().Xor)

    def __neg__(self):
        return self._apply_infix(-1, _mgr().Times)

    def __invert__(self):
        if not _env().enable_infix_notation:
            raise Exception("Cannot use infix notation")
        return _mgr().Not(self)

    def __int__(self):
        if self.is_int_constant():
            return self.constant_value()
        raise NotImplementedError("Cannot convert `%s` to integer" % str(self))

    def __long__(self):
        if self.is_int_constant():
            return self.constant_value()
        raise NotImplementedError("Cannot convert `%s` to integer" % str(self))

    def __float__(self):
        if self.is_int_constant() or self.is_real_constant():
            return float(self.constant_value())
        raise NotImplementedError("Cannot convert `%s` to float" % str(self))

# EOC FNode

def _env():
    """Aux function to obtain the environment."""
    return pysmt.environment.get_env()

def _mgr():
    """Aux function to obtain the formula manager."""
    return pysmt.environment.get_env().formula_manager


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using Microsoft.Azure.WebJobs.Host;

namespace Microsoft.Azure.WebJobs
{
    /// <summary>
    /// Attribute that can be applied at the class or function level to specify a retry
    /// strategy for failed function invocations.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public abstract class RetryAttribute : Attribute, IRetryStrategy
    {
        public RetryAttribute(int maxRetryCount)
        {
            if (maxRetryCount < -1)
            {
                throw new ArgumentOutOfRangeException(nameof(maxRetryCount));
            }
            MaxRetryCount = maxRetryCount;
        }

        /// <summary>
        /// Gets the maximum number of retries allowed.
        /// </summary>
        public int MaxRetryCount { get; }

        /// <summary>
        /// Returns delay between function invocation retries. This is when number of retries < MaxRetryCount
        /// </summary>
        /// <param name="context"><see cref="RetryContext"/>)</param>
        /// <returns></returns>
        public abstract TimeSpan GetNextDelay(RetryContext context);
    }
}


text:
layout: simple
---

# Bulldogs Racing

The Yale Bulldogs Racing team built a gas-electric hybrid racecar
that [won first place](https://seas.yale.edu/news-events/news/bulldogs-racing-roars-big-win) at the 2013 Formula Hybrid International competition.

I worked on low-voltage electronics, and wrote large portions of the code for the Arduino microcontroller ([Github link](https://github.com/BulldogsRacing/Yale-Formula-Hybrid)) that handled functions like:

* core driving functions: mapping the gas pedal to the throttle, activating the brake light
* displaying data to the driver on a control panel
* managing a power-saving "endurance mode"
* monitoring the high voltage battery system
* wirelessly sending telemetry data
* safety cutoffs in dangerous situations

![](/images/project_images/formula-hybrid/team.jpg)


text:
var PORT = 4444;
var HOST = '127.0.0.1';

var dgram = require('dgram');
var message = new Buffer('dia dhuit');

var client = dgram.createSocket('udp4');
client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
    if (err) throw err;
    console.log('UDP message sent to ' + HOST +':'+ PORT);
    client.close();
});


text:
import * as React from 'react';
import { expect } from 'chai';
import { SinonFakeTimers, useFakeTimers } from 'sinon';
import { fireEvent, screen, describeConformanceV5 } from 'test/utils';
import CalendarPicker, { calendarPickerClasses as classes } from '@material-ui/lab/CalendarPicker';
import {
  adapterToUse,
  wrapPickerMount,
  createPickerRender,
  getAllByMuiTest,
} from '../internal/pickers/test-utils';

describe('<CalendarPicker />', () => {
  let clock: SinonFakeTimers;
  beforeEach(() => {
    clock = useFakeTimers();
  });
  afterEach(() => {
    clock.restore();
  });

  // StrictModeViolation: Uses StrictMode incompatible API of `react-transition-group`
  const render = createPickerRender({ strict: false });

  describeConformanceV5(<CalendarPicker date={adapterToUse.date()} onChange={() => {}} />, () => ({
    classes,
    inheritComponent: 'div',
    render,
    muiName: 'MuiCalendarPicker',
    wrapMount: wrapPickerMount,
    refInstanceof: window.HTMLDivElement,
    // cannot test reactTestRenderer because of required context
    skip: [
      'componentProp',
      'componentsProp',
      'propsSpread',
      'reactTestRenderer',
      // TODO: Fix CalendarPicker is not spreading props on root
      'themeDefaultProps',
      'themeVariants',
    ],
  }));

  it('renders calendar standalone', () => {
    render(
      <CalendarPicker date={adapterToUse.date('2019-01-01T00:00:00.000')} onChange={() => {}} />,
    );

    expect(screen.getByText('January')).toBeVisible();
    expect(screen.getByText('2019')).toBeVisible();
    expect(getAllByMuiTest('day')).to.have.length(31);
    // It should follow https://www.w3.org/TR/wai-aria-practices/examples/dialog-modal/datepicker-dialog.html
    expect(
      document.querySelector('[role="grid"] > [role="row"] > [role="cell"] > button'),
    ).to.have.text('1');
  });

  // Flaky, it match 201 instead of 200 in the CI
  // eslint-disable-next-line mocha/no-skipped-tests
  it.skip('renders year selection standalone', () => {
    render(
      <CalendarPicker
        date={adapterToUse.date('2019-01-01T00:00:00.000')}
        openTo="year"
        onChange={() => {}}
      />,
    );

    expect(getAllByMuiTest('year')).to.have.length(200);
  });

  it('switches between views uncontrolled', () => {
    render(
      <CalendarPicker date={adapterToUse.date('2019-01-01T00:00:00.000')} onChange={() => {}} />,
    );

    fireEvent.click(screen.getByLabelText(/switch to year view/i));

    expect(screen.queryByLabelText(/switch to year view/i)).to.equal(null);
    expect(screen.getByLabelText('year view is open, switch to calendar view')).toBeVisible();
  });

  // eslint-disable-next-line mocha/no-skipped-tests -- TODO: test without implementation details
  it.skip('should skip the header', () => {
    render(
      <CalendarPicker
        views={['year']}
        date={adapterToUse.date('2019-01-01T00:00:00.000')}
        onChange={() => {}}
      />,
    );
    expect(document.querySelector('.MuiPickersCalendarHeader-root')).to.equal(null);
  });
});


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AnaglyphView3D.xaml.cs" company="Helix 3D Toolkit">
//   http://helixtoolkit.codeplex.com, license: MIT
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace HelixToolkit.Wpf
{
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Markup;

    /// <summary>
    /// An anaglyph viewer control.
    /// </summary>
    /// <remarks>
    /// Petzold's anaglyph space station (using opacity)
    /// http://www.charlespetzold.com/3D/
    /// Greg Schechter multi input shader effects (for the AnaglyphEffect)
    /// http://blogs.msdn.com/greg_schechter/archive/2008/09/27/a-more-useful-multi-input-effect.aspx
    /// Barcinski and Jean-Jean: Making of Part III - Anaglyph
    /// http://blog.barcinski-jeanjean.com/2008/10/17/making-of-part-iii-anaglyph/
    /// </remarks>
    [ContentProperty("Children")]
    [Localizability(LocalizationCategory.NeverLocalize)]
    public partial class AnaglyphView3D : StereoControl
    {
        /// <summary>
        /// Identifies the <see cref="HorizontalOffset"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty HorizontalOffsetProperty =
            DependencyProperty.Register(
                "HorizontalOffset",
                typeof(double),
                typeof(AnaglyphView3D),
                new UIPropertyMetadata(0.0, HorizontalOffsetChanged));

        /// <summary>
        /// Identifies the <see cref="Method"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty MethodProperty = DependencyProperty.Register(
            "Method", typeof(AnaglyphMethod), typeof(AnaglyphView3D), new UIPropertyMetadata(AnaglyphMethod.Gray));

        /// <summary>
        /// Initializes a new instance of the <see cref = "AnaglyphView3D" /> class.
        /// </summary>
        public AnaglyphView3D()
        {
            this.InitializeComponent();
            this.BindViewports(this.LeftView, this.RightView);
        }

        /// <summary>
        /// Gets or sets the horizontal offset.
        /// </summary>
        /// <value>The horizontal offset.</value>
        public double HorizontalOffset
        {
            get
            {
                return (double)this.GetValue(HorizontalOffsetProperty);
            }

            set
            {
                this.SetValue(HorizontalOffsetProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the method.
        /// </summary>
        /// <value>The method.</value>
        public AnaglyphMethod Method
        {
            get
            {
                return (AnaglyphMethod)this.GetValue(MethodProperty);
            }

            set
            {
                this.SetValue(MethodProperty, value);
            }
        }

        /// <summary>
        /// Invoked when an unhandled <see cref="E:System.Windows.Input.Keyboard.KeyDown"/> attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
        /// </summary>
        /// <param name="e">
        /// The <see cref="T:System.Windows.Input.KeyEventArgs"/> that contains the event data.
        /// </param>
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            switch (e.Key)
            {
                case Key.Left:
                    this.HorizontalOffset -= 0.001f;
                    break;
                case Key.Right:
                    this.HorizontalOffset += 0.001f;
                    break;
            }
        }

        /// <summary>
        /// Invoked when an unhandled <see cref="E:System.Windows.Input.Mouse.MouseDown"/> attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
        /// </summary>
        /// <param name="e">
        /// The <see cref="T:System.Windows.Input.MouseButtonEventArgs"/> that contains the event data. This event data reports details about the mouse button that was pressed and the handled state.
        /// </param>
        protected override void OnMouseDown(MouseButtonEventArgs e)
        {
            base.OnMouseDown(e);
            this.Focus();
        }

        /// <summary>
        /// The horizontal offset changed.
        /// </summary>
        /// <param name="d">
        /// The d.
        /// </param>
        /// <param name="e">
        /// The event arguments.
        /// </param>
        private static void HorizontalOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((AnaglyphView3D)d).OnHorizontalOffsetChanged();
        }

        /// <summary>
        /// The on horizontal offset changed.
        /// </summary>
        private void OnHorizontalOffsetChanged()
        {
            // RightView.Margin=new Thickness(HorizontalOffset,0,-HorizontalOffset,0);
        }

    }
}


text:
using System;

namespace FluentNHibernate.MappingModel.ClassBased
{
    /// <summary>
    /// A component that is declared external to a class mapping.
    /// </summary>
    [Serializable]
    public class ExternalComponentMapping : ComponentMapping
    {
        public ExternalComponentMapping(ComponentType componentType): this(componentType, new AttributeStore(), null)
        {}

        public ExternalComponentMapping(ComponentType componentType, AttributeStore underlyingStore, Member member)
            : base(componentType, underlyingStore, member)
        {}
    }
}


text:
from office365.runtime.queries.service_operation import ServiceOperationQuery
from office365.runtime.paths.resource_path import ResourcePath
from office365.sharepoint.alerts.collection import AlertCollection
from office365.sharepoint.principal.principal import Principal
from office365.sharepoint.principal.user_id_info import UserIdInfo

class User(Principal):
    """Represents a user in Microsoft SharePoint Foundation. A user is a type of SP.Principal."""

    def get_personal_site(self):
        """Get Personal Site"""
        from office365.sharepoint.sites.site import Site
        return_type = Site(self.context)

        def _user_loaded():
            from office365.sharepoint.userprofiles.people_manager import PeopleManager
            people_manager = PeopleManager(self.context)
            person_props = people_manager.get_properties_for(self.login_name)

            def _person_props_loaded(resp):
                return_type.set_property("__siteUrl", person_props.personal_url)
            self.context.after_execute(_person_props_loaded)

        self.ensure_property("LoginName", _user_loaded)
        return return_type

    def get_user_profile_properties(self, property_names=None):
        """
        :param list[str] property_names:
        """
        from office365.sharepoint.userprofiles.properties_for_user import UserProfilePropertiesForUser
        return_type = UserProfilePropertiesForUser(self.context)

        def _user_loaded():
            return_type.set_property("PropertyNames", property_names)
            return_type.set_property("AccountName", self.user_principal_name)
        self.ensure_property("UserPrincipalName", _user_loaded)
        return return_type

    @property
    def groups(self):
        """Gets a collection of group objects that represents all of the groups for the user."""
        from office365.sharepoint.principal.group_collection import GroupCollection
        return self.properties.get('Groups',
                                   GroupCollection(self.context, ResourcePath("Groups", self.resource_path)))

    @property
    def alerts(self):
        """Gets site alerts for this user."""
        return self.properties.get('Alerts',
                                   AlertCollection(self.context, ResourcePath("Alerts", self.resource_path)))

    @property
    def is_site_admin(self):
        """Gets a Boolean value that specifies whether the user is a site collection administrator."""
        return self.properties.get('IsSiteAdmin', None)

    @property
    def user_id(self):
        """Gets the information of the user that contains the user's name identifier and the issuer of the
         user's name identifier."""
        return self.properties.get('UserId', UserIdInfo())

    @property
    def email(self):
        """
        Specifies the e-mail address of the user.
        It MUST NOT be NULL. Its length MUST be equal to or less than 255.

        :rtype: str or None
        """
        return self.properties.get('Email', None)

    def expire(self):
        qry = ServiceOperationQuery(self, "Expire")
        self.context.add_query(qry)
        return self

    def get_property(self, name, default_value=None):
        if default_value is None:
            property_mapping = {
                "UserId": self.user_id,
            }
            default_value = property_mapping.get(name, None)
        return super(User, self).get_property(name, default_value)


text:
package net.opengis.gml.impl;
/**
 * A document containing one target(@http://www.opengis.net/gml) element.
 *
 * This is a complex type.
 */
public class TargetDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements net.opengis.gml.TargetDocument
{
    private static final long serialVersionUID = 1L;

    public TargetDocumentImpl(org.apache.xmlbeans.SchemaType sType)
    {
        super(sType);
    }

    private static final javax.xml.namespace.QName TARGET$0 =
        new javax.xml.namespace.QName("http://www.opengis.net/gml", "target");
    private static final org.apache.xmlbeans.QNameSet TARGET$1 = org.apache.xmlbeans.QNameSet.forArray( new javax.xml.namespace.QName[] {
        new javax.xml.namespace.QName("http://www.opengis.net/gml", "target"),
        new javax.xml.namespace.QName("http://www.opengis.net/gml", "subject"),
    });

    /**
     * Gets the "target" element
     */
    public net.opengis.gml.TargetPropertyType getTarget()
    {
        synchronized (monitor())
        {
            check_orphaned();
            net.opengis.gml.TargetPropertyType target = null;
            target = (net.opengis.gml.TargetPropertyType)get_store().find_element_user(TARGET$1, 0);
            if (target == null)
            {
                return null;
            }
            return target;
        }
    }

    /**
     * Sets the "target" element
     */
     public void setTarget(net.opengis.gml.TargetPropertyType targetValue)
    {
        synchronized (monitor())
        {
            check_orphaned();
            net.opengis.gml.TargetPropertyType target = null;
            target = (net.opengis.gml.TargetPropertyType)get_store().find_element_user(TARGET$1, 0);
            if (target == null)
            {
                target = (net.opengis.gml.TargetPropertyType)get_store().add_element_user(TARGET$0);
            }
            target.set(targetValue);
        }
    }

    /**
     * Appends and returns a new empty "target" element
     */
    public net.opengis.gml.TargetPropertyType addNewTarget()
    {
        synchronized (monitor())
        {
            check_orphaned();
            net.opengis.gml.TargetPropertyType target = null;
            target = (net.opengis.gml.TargetPropertyType)get_store().add_element_user(TARGET$0);
            return target;
        }
    }
}


text:
package org.drools.workbench.screens.scenariosimulation.client.editor.menu;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

@RunWith(GwtMockitoTestRunner.class)
public class ExpectedContextMenuTest extends AbstractMenuTest {

    @Before
    public void setup() {
        abstractColumnMenuPresenter = new ExpectedContextMenu();
        super.setup();
    }

    @Test
    public void initMenu() {
        assertNull(abstractColumnMenuPresenter.COLUMNCONTEXTMENU_COLUMN);
        assertNull(abstractColumnMenuPresenter.COLUMNCONTEXTMENU_INSERT_COLUMN_LEFT);
        assertNull(abstractColumnMenuPresenter.COLUMNCONTEXTMENU_INSERT_COLUMN_RIGHT);
        assertNull(abstractColumnMenuPresenter.COLUMNCONTEXTMENU_DELETE_COLUMN);
        assertNull(abstractColumnMenuPresenter.COLUMNCONTEXTMENU_DELETE_INSTANCE);
        assertNull(abstractColumnMenuPresenter.COLUMNCONTEXTMENU_DUPLICATE_INSTANCE);
        assertNull(abstractColumnMenuPresenter.COLUMNCONTEXTMENU_LABEL);
        assertNull(abstractColumnMenuPresenter.COLUMNCONTEXTMENU_I18N);
        abstractColumnMenuPresenter.initMenu();
        assertEquals(ExpectedContextMenu.EXPECTCONTEXTMENU_EXPECT, abstractColumnMenuPresenter.COLUMNCONTEXTMENU_COLUMN);
        assertEquals(ExpectedContextMenu.EXPECTCONTEXTMENU_INSERT_COLUMN_LEFT, abstractColumnMenuPresenter.COLUMNCONTEXTMENU_INSERT_COLUMN_LEFT);
        assertEquals(ExpectedContextMenu.EXPECTCONTEXTMENU_INSERT_COLUMN_RIGHT, abstractColumnMenuPresenter.COLUMNCONTEXTMENU_INSERT_COLUMN_RIGHT);
        assertEquals(ExpectedContextMenu.EXPECTCONTEXTMENU_DELETE_COLUMN, abstractColumnMenuPresenter.COLUMNCONTEXTMENU_DELETE_COLUMN);
        assertEquals(ExpectedContextMenu.EXPECTCONTEXTMENU_DELETE_INSTANCE, abstractColumnMenuPresenter.COLUMNCONTEXTMENU_DELETE_INSTANCE);
        assertEquals(abstractColumnMenuPresenter.constants.expect().toUpperCase(), abstractColumnMenuPresenter.COLUMNCONTEXTMENU_LABEL);
        assertEquals("expect", abstractColumnMenuPresenter.COLUMNCONTEXTMENU_I18N);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Interfaces
{
    public interface IPluginMetadata
    {
        string Name { get; }
        string Version { get; }
    }
}


text:
package quasar.ejson

import slamdata.Predef._

import quasar.fp._
import quasar.pkg.tests._

import scala.Predef.$conforms

import scalaz.Equal
import scalaz.std.list._

trait EqMapArbitrary {
  implicit def arbitraryEqMap[K: Arbitrary: Equal, V: Arbitrary]: Arbitrary[EqMap[K, V]] =
    Arbitrary(arbitrary[List[(K, V)]] map (EqMap.fromFoldable(_)))
}

object EqMapArbitrary extends EqMapArbitrary


text:
PRIMARY_OS = 'Ubuntu-16.04'
PRIMARY = '''#!/bin/sh
#
FQDN="{fqdn}"

# hostname
hostnamectl set-hostname $FQDN

{dinfo}
'''

def pre_process():
    """Anything added to this function is executed before launching the instances"""
    pass

def post_process():
    """Anything added to this function is executed after launching the instances"""
    pass


text:
require 'test_helper'
require 'timeout'

class ProjectWizardRepoAccessFlowFeatureTest< Capybara::Rails::TestCase
  let(:user_without_svc_access) { FactoryGirl.create(:user, :without_svc_access) }
  let(:github_user_public_repos) { FactoryGirl.create(:user, :with_github_public_repo_access) }
  let(:user) { FactoryGirl.create(:user) } # with private repo access by default

  describe 'when user has not given any svc access' do
    before do
      login_as user_without_svc_access, scope: :user
    end

    it 'displays a helping text explaining that he is going to be redirected', js: true do
      VCR.use_cassette (self.class.name + "::" + self.__name__) do
        visit project_wizard_path(:select_repository)
        help_blocks = page.all('.help-block')
        help_blocks[0].text.must_equal("You will be redirected to authorize public repository access "\
                                      "Note: You can upgrade access to private repositories later")
        help_blocks[1].text.must_equal("You will be redirected to authorize public & private repository access "\
                                      "Note: Bitbucket authorises access to both public and "\
                                      "private repositories without distinction. This is not a Testributor limitation.")
      end
    end
  end

  describe 'when user has given github public repo access' do
    before do
      login_as github_user_public_repos, scope: :user
    end

    it 'displays a helping text explaining that he provided access', js: true do
      VCR.use_cassette (self.class.name + "::" + self.__name__) do
        visit project_wizard_path(:select_repository)
        help_blocks = page.all('.help-block')
        help_blocks[0].text.must_equal 'Access to public repositories granted'
        help_blocks[1].text.must_equal("You will be redirected to authorize public & private repository access "\
                                      "Note: Bitbucket authorises access to both public and "\
                                      "private repositories without distinction. This is not a Testributor limitation.")
      end
    end

    it 'displays a button to upgrade access to private repos', js: true do
      VCR.use_cassette (self.class.name + "::" + self.__name__) do
        visit project_wizard_path(:select_repository)
        find('label', text: "GITHUB").click
        page.must_have_selector('.private-repo-access .btn')
      end
    end

    it 'does not display private repositories', js: true do
      VCR.use_cassette (self.class.name + "::" + self.__name__) do
        visit project_wizard_path(:select_repository)
        find('label', text: "GITHUB").click
        page.must_have_selector('.private-repo-access .btn')
        list_group = page.find('.list-group')
        within list_group do
          page.wont_have_content('PRIVATE')
        end
      end
    end
  end

  describe 'when user has given github private repo access' do
    before do
      login_as user, scope: :user
    end

    it 'does not display any button to upgrade access', js: true do
      VCR.use_cassette (self.class.name + "::" + self.__name__), allow_playback_repeats: true do
        visit project_wizard_path(:select_repository)
        find('label', text: "GITHUB").click
        page.must_have_content('Select a GitHub repository:')
        page.wont_have_selector('.private-repo-access .btn')
        page.must_have_content 'ispyropoulos/aroma-kouzinas'
      end
    end

    it 'displays private repositories', js: true do
      VCR.use_cassette (self.class.name + "::" + self.__name__) do
        visit project_wizard_path(:select_repository)
          find('label', text: "GITHUB").click
          page.must_have_content 'ispyropoulos/aroma-kouzinas'
        list_group = page.find('.list-group')
        within list_group do
          page.must_have_content('PRIVATE')
        end
      end
    end
  end
end


text:
/* ========================================================================== */
/*! @file avm/detect/architecture.h Auto-detects the current architecture
      based on various pre-processor defines.                                 */
/* ========================================================================== */

#ifndef _AVM_DETECT_ARCHITECTURE_H_
#define _AVM_DETECT_ARCHITECTURE_H_

#include <avm/config.h>
#include <avm/architecture.h>

#ifdef AVM_DONT_AUTODETECT_ARCHITECTURE
  #ifndef AVM_ARCHITECTURE
    #error ("Architecture auto-detection is disabled, but no architecture is defined!")
  #else
    #if (AVM_ARCHITECTURE != AVM_ARCHITECTURE_X86) || \
        (AVM_ARCHITECTURE != AVM_ARCHITECTURE_X86_64) || \
        (AVM_ARCHITECTURE != AVM_ARCHITECTURE_ARM)
      #define AVM_ARCHITECTURE AVM_ARCHITECTURE_UNKNOWN_OR_UNSUPPORTED
    #endif
  #endif
#else /* #ifndef AVM_DONT_AUTODETECT_ARCHITECTURE */
  #if (defined(_M_IX86) || defined(__i386__))
    #define AVM_ARCHITECTURE AVM_ARCHITECTURE_X86
  #elif (defined(_M_X64) || defined(__x86_64__))
    #define AVM_ARCHITECTURE AVM_ARCHITECTURE_X86_64
  #elif defined(__ARMEL__)
    #define AVM_ARCHITECTURE AVM_ARCHITECTURE_ARM
  #else
    #define AVM_ARCHITECTURE AVM_ARCHITECTURE_UNKNOWN_OR_UNSUPPORTED
  #endif
#endif /* #ifndef AVM_DONT_AUTODETECT_ARCHITECTURE */

#if (AVM_ARCHITECTURE == AVM_ARCHITECTURE_UNKNOWN_OR_UNSUPPORTED)
  #error ("Unknown or unsupported architecture!")
#endif /* (AVM_ARCHITECTURE == AVM_ARCHITECTURE_UNKNOWN_OR_UNSUPPORTED) */

#endif /* _AVM_DETECT_ARCHITECTURE_H_ */


text:
namespace predictors {

// static
AutocompleteActionPredictor* AutocompleteActionPredictorFactory::GetForProfile(
    Profile* profile) {
  return static_cast<AutocompleteActionPredictor*>(
      GetInstance()->GetServiceForBrowserContext(profile, true));
}

// static
AutocompleteActionPredictorFactory*
    AutocompleteActionPredictorFactory::GetInstance() {
  return base::Singleton<AutocompleteActionPredictorFactory>::get();
}

AutocompleteActionPredictorFactory::AutocompleteActionPredictorFactory()
    : ProfileKeyedServiceFactory(
          "AutocompleteActionPredictor",
          ProfileSelections::BuildForRegularAndIncognito()) {
  DependsOn(HistoryServiceFactory::GetInstance());
  DependsOn(PredictorDatabaseFactory::GetInstance());
}

AutocompleteActionPredictorFactory::~AutocompleteActionPredictorFactory() {}

KeyedService* AutocompleteActionPredictorFactory::BuildServiceInstanceFor(
    content::BrowserContext* profile) const {
  return new AutocompleteActionPredictor(static_cast<Profile*>(profile));
}

}  // namespace predictors


text:
using UnityEngine;
using System.Collections;

public class BulletScript : MonoBehaviour {
	public int bulletSpeed;
	public int cullingDistance;
	private Vector3 initalPos;

	void Start() {
		initalPos = transform.position;
	}

	void Update() {
		transform.Translate(new Vector3(0, bulletSpeed, 0) * Time.deltaTime);
		if ((initalPos - transform.position).magnitude > cullingDistance) {
			Destroy(gameObject);
		}
	}

	void OnTriggerEnter(Collider other) {
		if (other.gameObject.CompareTag("Target")) {
			Destroy(other.gameObject);
			Destroy(gameObject);
		}
	}
}


text:
import { HttpClient } from "@angular/common/http";
import { HTTP } from "@ionic-native/http/ngx";
import { IContest } from "../interfaces";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Platform } from "@ionic/angular";
import "rxjs/add/observable/fromPromise";
import "rxjs/add/operator/map";
import "rxjs/add/operator/publishReplay";

interface IContestsCache {
    contests?: Observable<IContest[]>;
}

@Injectable()
export class ContestsService {
    private static BASE_URL = "http://mcubed.ddns.net:60002"; // Keep in sync with proxy.config.json
    private cache: IContestsCache = { };

    constructor(private nativeHttp: HTTP, private ngHttp: HttpClient, private platform: Platform) {
    }

    getContests(): Observable<IContest[]> {
        if (!this.cache.contests) {
            if (this.platform.is("android") || this.platform.is("ios")) {
                this.cache.contests = Observable.fromPromise(this.platform.ready().then(() => {
                    return this.nativeHttp.get(ContestsService.BASE_URL, {}, {});
                }).then((response) => {
                    return <IContest[]>JSON.parse(response.data);
                }));
            } else {
                this.cache.contests = this.ngHttp.get<IContest[]>("/api").publishReplay(1).refCount();
            }
        }
        return this.cache.contests;
    }
}


text:
module DataObjects

  module Mysql

    class Transaction < DataObjects::Transaction

      def begin_prepared
        cmd = "XA START '#{id}'"
        connection.create_command(cmd).execute_non_query
      end

      def commit_prepared
        cmd = "XA COMMIT '#{id}'"
        connection.create_command(cmd).execute_non_query
      end

      def rollback_prepared
        cmd = "XA ROLLBACK '#{id}'"
        connection.create_command(cmd).execute_non_query
      end

      def prepare
        finalize_transaction
        cmd = "XA PREPARE '#{id}'"
        connection.create_command(cmd).execute_non_query
      end

      private

      def finalize_transaction
        cmd = "XA END '#{id}'"
        connection.create_command(cmd).execute_non_query
      end

    end

  end

end


text:
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Layers</title>
  <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
  <link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="manifest.json">
  <link rel="mask-icon" href="safari-pinned-tab.svg" color="#151517">
  <meta name="theme-color" content="#ffffff">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Roboto+Slab|Roboto:300,400,700" rel="stylesheet">

3D Layers

        LAYER 1
        done
        code

LOREM IPSUM DOLOR

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum
          sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies
          nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel,
          aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam
          dictum felis eu pede mollis pretium.

        LAYER 2
        done
        code

LOREM IPSUM DOLOR

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum
          sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies
          nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel,
          aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam
          dictum felis eu pede mollis pretium.

Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo
          ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis,
          feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam
          ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus.

        LAYER 3
        done
        code

LOREM IPSUM DOLOR

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum
          sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies
          nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel,
          aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam
          dictum felis eu pede mollis pretium.

Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo
          ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis,
          feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam
          ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus.

Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed
          ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt
          tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros
          faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna.

Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce
          vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam
          accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in
          faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium
          turpis et arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum.

Carlos Coves Prieto 2017


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.datafactory.fluent.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Informix table dataset properties. */
@Fluent
public final class InformixTableDatasetTypeProperties {
    /*
     * The Informix table name. Type: string (or Expression with resultType string).
     */
    @JsonProperty(value = "tableName")
    private Object tableName;

    /** Creates an instance of InformixTableDatasetTypeProperties class. */
    public InformixTableDatasetTypeProperties() {
    }

    /**
     * Get the tableName property: The Informix table name. Type: string (or Expression with resultType string).
     *
     * @return the tableName value.
     */
    public Object tableName() {
        return this.tableName;
    }

    /**
     * Set the tableName property: The Informix table name. Type: string (or Expression with resultType string).
     *
     * @param tableName the tableName value to set.
     * @return the InformixTableDatasetTypeProperties object itself.
     */
    public InformixTableDatasetTypeProperties withTableName(Object tableName) {
        this.tableName = tableName;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
<resources>
    <string name="date_format">dd.MM. EEEE</string>
    <string name="today">Данас</string>
    <string name="tomorrow">Сутра</string>
    <string name="aqi_pure"/>
    <string name="aqi_good"/>
    <string name="aqi_moderate"/>
    <string name="aqi_pollution"/>
    <string name="aqi_unhealthy"/>
    <string name="aqi_dangerous"/>
    <string name="aqi_hazardous"/>
    <string name="aqi_break"/>
    <string name="weather_type_0">Ведро - Roaming Electronics</string>
    <string name="weather_type_1">Облачно - Roaming Electronics</string>
    <string name="weather_type_2">Магловито - Roaming Electronics</string>
    <string name="weather_type_3">Магла - Roaming Electronics</string>
    <string name="weather_type_4">Олуја - Roaming Electronics</string>
    <string name="weather_type_5">Кишна олуја - Roaming Electronics</string>
    <string name="weather_type_6">Пљусак - Roaming Electronics</string>
    <string name="weather_type_7">Олуја - Roaming Electronics</string>
    <string name="weather_type_8">Пљусак - Roaming Electronics</string>
    <string name="weather_type_9">Пљусак - Roaming Electronics</string>
    <string name="weather_type_10">Киша - Roaming Electronics</string>
    <string name="weather_type_11">Слаба киша - Roaming Electronics</string>
    <string name="weather_type_12">Суснежица - Roaming Electronics</string>
    <string name="weather_type_13">Мећава - Roaming Electronics</string>
    <string name="weather_type_14">Снег - Roaming Electronics</string>
    <string name="weather_type_15">Снег - Roaming Electronics</string>
    <string name="weather_type_16">Снег - Roaming Electronics</string>
    <string name="weather_type_17">Снег - Roaming Electronics</string>
    <string name="weather_type_18">Пешчана олуја - Roaming Electronics</string>
    <string name="weather_type_19">Пешчана олуја - Roaming Electronics</string>
    <string name="weather_type_20">Пешчана олуја - Roaming Electronics</string>
    <string name="weather_type_21">Пешчана олуја - Roaming Electronics</string>
    <string name="weather_type_22">Град - Roaming Electronics</string>
    <string name="weather_type_23">Прашина - Roaming Electronics</string>
    <string name="weather_type_24">Ледена киша - Roaming Electronics</string>
</resources>


text:
'use strict';

angular.module('users').controller('SettingsController', ['$scope', 'Authentication',
  function ($scope, Authentication) {
    $scope.user = Authentication.user;

    // document.body.style.background = 'none';

    document.body.style.background = 'url(modules/core/img/brand/green.jpg) no-repeat center center fixed';
    document.body.style.backgroundSize = 'cover';
  }
]);


text:
namespace IECore
{

class MPlayDisplayDriver : public DisplayDriver
{
	public :

		IE_CORE_DECLARERUNTIMETYPED( MPlayDisplayDriver, DisplayDriver );

		MPlayDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, ConstCompoundDataPtr parameters );
		virtual ~MPlayDisplayDriver();

		virtual void imageData( const Imath::Box2i &box, const float *data, size_t dataSize );
		virtual void imageClose();
		virtual bool scanLineOrderOnly() const;
		virtual bool acceptsRepeatedData() const;

	private :

		static const DisplayDriverDescription<MPlayDisplayDriver> g_description;

		struct ImageHeader;
		struct PlaneHeader;
		struct TileHeader;

		struct Plane
		{
			Plane( const std::string &n ) : name( n ) {}
			std::string name;
			std::vector<std::string> channelNames;
			std::vector<size_t> channelIndices;
		};

		typedef std::vector<Plane> PlaneVector;

		FILE *m_imDisplayStdIn;
		PlaneVector m_planes;

};

IE_CORE_DECLAREPTR( MPlayDisplayDriver )

}  // namespace IECore

#endif // IECORE_MPLAYDISPLAYDRIVER_H


text:
{-# LANGUAGE GADTs #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE TemplateHaskell #-}

module Main where

import Control.Concurrent
import Control.Event.Handler
import Control.Monad
import Reactive.Banana.Internal.Combinators
import System.Mem

main :: IO ()
main =
  do (ah,tick) <- newAddHandler
     network <-
       compile (do render <- fromAddHandler ah
                   addReactimate
                     (applyE (mapB (\x _ ->
                                      return (print x))
                                   (stepperB 0 render))
                             render))
     actuate network
     performGC
     tick 1
     putStrLn "GC"
     putStrLn "Done"
     tick 2
     mapM_ tick [3 .. 10]


text:
import java.io.File;
public class DecodeMain{
	public static void main(String[] args){
		System.out.println("解析结果如下:");
		String content= QrDecode.decodeImage(new File("./qr.png"));
		System.out.println(content);
	}
}


text:
#pragma once
#include <aws/events/CloudWatchEvents_EXPORTS.h>
#include <aws/events/CloudWatchEventsRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace CloudWatchEvents
{
namespace Model
{

  /**
   *
Container for the parameters to the ListRules operation.

   */
  class AWS_CLOUDWATCHEVENTS_API ListRulesRequest : public CloudWatchEventsRequest
  {
  public:
    ListRulesRequest();
    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The prefix matching the rule name.

     */
    inline const Aws::String& GetNamePrefix() const{ return m_namePrefix; }

    /**
     *
The prefix matching the rule name.

     */
    inline void SetNamePrefix(const Aws::String& value) { m_namePrefixHasBeenSet = true; m_namePrefix = value; }

    /**
     *
The prefix matching the rule name.

     */
    inline void SetNamePrefix(Aws::String&& value) { m_namePrefixHasBeenSet = true; m_namePrefix = value; }

    /**
     *
The prefix matching the rule name.

     */
    inline void SetNamePrefix(const char* value) { m_namePrefixHasBeenSet = true; m_namePrefix.assign(value); }

    /**
     *
The prefix matching the rule name.

     */
    inline ListRulesRequest& WithNamePrefix(const Aws::String& value) { SetNamePrefix(value); return *this;}

    /**
     *
The prefix matching the rule name.

     */
    inline ListRulesRequest& WithNamePrefix(Aws::String&& value) { SetNamePrefix(value); return *this;}

    /**
     *
The prefix matching the rule name.

     */
    inline ListRulesRequest& WithNamePrefix(const char* value) { SetNamePrefix(value); return *this;}

    /**
     *
The token returned by a previous call to indicate that there is more data
     * available.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The token returned by a previous call to indicate that there is more data
     * available.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
The token returned by a previous call to indicate that there is more data
     * available.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
The token returned by a previous call to indicate that there is more data
     * available.

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
The token returned by a previous call to indicate that there is more data
     * available.

     */
    inline ListRulesRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The token returned by a previous call to indicate that there is more data
     * available.

     */
    inline ListRulesRequest& WithNextToken(Aws::String&& value) { SetNextToken(value); return *this;}

    /**
     *
The token returned by a previous call to indicate that there is more data
     * available.

     */
    inline ListRulesRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

    /**
     *
The maximum number of results to return.

     */
    inline int GetLimit() const{ return m_limit; }

    /**
     *
The maximum number of results to return.

     */
    inline void SetLimit(int value) { m_limitHasBeenSet = true; m_limit = value; }

    /**
     *
The maximum number of results to return.

     */
    inline ListRulesRequest& WithLimit(int value) { SetLimit(value); return *this;}

  private:
    Aws::String m_namePrefix;
    bool m_namePrefixHasBeenSet;
    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet;
    int m_limit;
    bool m_limitHasBeenSet;
  };

} // namespace Model
} // namespace CloudWatchEvents
} // namespace Aws


text: A repo for things and stuff


text:
package edu.isi.karma.modeling.semantictypes;

public class SemanticTypeLabel {

	private String label;
	private float score;

	public SemanticTypeLabel(String label, float score) {
		this.label = label;
		this.score = score;
	}

	public String getLabel() {
		return this.label;
	}

	public float getScore() {
		return this.score;
	}
}


text:
import { replication as replicationConfig } from '../config.json'

class ProductsService {
  constructor ($injector, pouchDB, angularNavDataUtilsService) {
    let dataModuleRemoteDB

    const pouchDBOptions = {
      ajax: {
        timeout: replicationConfig.timeout
      },
      skip_setup: true
    }

    try {
      dataModuleRemoteDB = $injector.get('dataModuleRemoteDB')
    } catch (e) {
      throw new Error('dataModuleRemoteDB should be provided in the data module configuration')
    }

    this.pouchDB = pouchDB
    this.angularNavDataUtilsService = angularNavDataUtilsService

    this.remoteDB = this.pouchDB(dataModuleRemoteDB, pouchDBOptions)
    this.replicationFrom
    this.localDB
    this.onChangeCompleteCallbacks = {}
    this.onReplicationCompleteCallbacks = {}
  }

  startReplication () {
    const onComplete = (handler, res) => {
      Object.keys(this[handler])
        .forEach(id => this[handler][id](res))
    }

    const onChangeComplete = res => onComplete('onChangeCompleteCallbacks', res)
    const onReplicationComplete = () => onComplete('onReplicationCompleteCallbacks')

    const onReplicationPaused = (err) => {
      if (!err) {
        onReplicationComplete()
        this.stopReplication()
      }
    }

    var options = {
      filter: 'products/all',
      live: true,
      retry: true
    }

    if (!this.localDB) {
      this.localDB = this.pouchDB('navIntProductsDB')
    }

    if (!this.replicationFrom || this.replicationFrom.state === 'cancelled') {
      this.replicationFrom = this.localDB.replicate.from(this.remoteDB, options)

      this.replicationFrom
        .on('paused', onReplicationPaused)
    }

    const changeOpts = {
      conflicts: true,
      include_docs: true
    }

    const handleConflicts = change => {
      this.angularNavDataUtilsService
        .checkAndResolveConflicts(change, this.localDB)
        .then(onChangeComplete)
        .catch(onChangeComplete)
    }

    this.localDB.changes(changeOpts).$promise
      .then(null, null, handleConflicts)
  }

  stopReplication () {
    if (this.replicationFrom && this.replicationFrom.cancel) {
      this.replicationFrom.cancel()
    }
  }

  callOnReplicationComplete (id, callback) {
    if (this.onReplicationCompleteCallbacks[id]) {
      return
    }
    this.onReplicationCompleteCallbacks[id] = callback
  }

  unregisterOnReplicationComplete (id) {
    delete this.onReplicationCompleteCallbacks[id]
  }

  callOnChangeComplete (id, callback) {
    if (this.onChangeCompleteCallbacks[id]) {
      return
    }
    this.onChangeCompleteCallbacks[id] = callback
  }

  unregisterOnChangeComplete (id) {
    delete this.onReplicationCompleteCallbacks[id]
  }

  allDocs (options) {
    const db = this.localDB || this.remoteDB
    return this.angularNavDataUtilsService.allDocs(db, options)
  }
}

ProductsService.$inject = ['$injector', 'pouchDB', 'angularNavDataUtilsService']

export default ProductsService


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>nodeAttributes</key>
	<dict>
		<key>categories</key>
		<array>
			<string>Kineme FileTools</string>
		</array>
		<key>copyright</key>
		<string>Copyright 2007 Kosada Incorporated. All rights reserved.</string>
		<key>description</key>
		<string>This patch downloads an image from a URL.

http://kineme.net/</string>
		<key>name</key>
		<string>Image Downloader (Blocking)</string>
	</dict>
	<key>inputAttributes</key>
	<dict>
		<key>inputURL</key>
		<dict>
			<key>description</key>
			<string>Image URL</string>
			<key>name</key>
			<string>Image URL</string>
		</dict>
		<key>inputAsynchronous</key>
		<dict>
			<key>description</key>
			<string>Load image asynchronously (don't block)</string>
			<key>name</key>
			<string>Asynchronous</string>
		</dict>

		<key>inputUseProxyCache</key>
		<dict>
			<key>description</key>
			<string>Cache and use smaller cached proxy images</string>
			<key>name</key>
			<string>Use Proxy Cache</string>
		</dict>
		<key>inputProxyThresholdWidth</key>
		<dict>
			<key>description</key>
			<string>Width where images are rescaled for the proxy cache</string>
			<key>name</key>
			<string>Proxy Threshold Width</string>
		</dict>
		<key>inputInterpolation</key>
		<dict>
			<key>description</key>
			<string>Interpolation method used when downsampling</string>
			<key>name</key>
			<string>Interpolation</string>
			<key>menu</key>
			<array>
				<string>Bilinear</string>
				<string>Lanczos</string>
			</array>
		</dict>
	</dict>
	<key>outputAttributes</key>
	<dict>
		<key>outputImage</key>
		<dict>
			<key>description</key>
			<string>Image</string>
			<key>name</key>
			<string>Image</string>
		</dict>
		<key>outputEXIFData</key>
		<dict>
			<key>description</key>
			<string>Output structure containing image metadata, if available</string>
			<key>name</key>
			<string>MetaData</string>
		</dict>
		<key>outputFinished</key>
		<dict>
			<key>description</key>
			<string>True if loading has finished</string>
			<key>name</key>
			<string>Finished</string>
		</dict>
	</dict>
</dict>
</plist>


text:
#ifndef NANAKA_GUI_COUNTER_H
#define NANAKA_GUI_COUNTER_H

#include "gui/Widget.h"
#include "gui/DigitField.h"
#include "gui/StaticChar.h"

class Font;
class RenderData;

class Counter final : public Widget
{
public:

	Counter(
		const Font& font,
		float textSize,
		GUISizeUnit sizeUnit,
		unsigned int maxDigits,
		unsigned int decimals,
		char fillChar);

	void SetNumber(float num);
	void UpdateDigitFields();

protected:

	/**
	 * Widget implementation
	 */
	void OnPlacementUpdated() override;
	void OnDraw(RenderData& renderData) const override;

private:

	StaticChar m_dotChar;
	StaticChar m_subChar;
	bool m_printSub;

	DigitField m_NPart;
	DigitField m_FPart;
	bool m_hasFPart;

	int m_decPow;
};

inline void Counter::OnPlacementUpdated()
{
	UpdateDigitFields();
}

#endif // NANAKA_GUI_COUNTER_H


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.ServiceModel.Security
{
  abstract public partial class BasicSecurityProfileVersion
  {
    #region Methods and constructors
    internal BasicSecurityProfileVersion()
    {
    }
    #endregion

    #region Properties and indexers
    public static System.ServiceModel.Security.BasicSecurityProfileVersion BasicSecurityProfile10
    {
      get
      {
        return default(System.ServiceModel.Security.BasicSecurityProfileVersion);
      }
    }
    #endregion
  }
}


text:
The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash's](https://lodash.com/) `_.where` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module.

## Installation

Using npm:

```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash.where
```

In Node.js/io.js:

```js
var where = require('lodash.where');
```

See the [documentation](https://lodash.com/docs#where) or [package source](https://github.com/lodash/lodash/blob/3.1.0-npm-packages/lodash.where) for more details.


text:
<?xml version = '1.0' encoding = 'UTF-8'?>
<TableProxyOraclev12c class="oracle.dbtools.crest.model.design.storage.oracle.v12c.TableProxyOraclev12c" name="AMB_OBJECT" directorySegmentName="seg_0" id="F42E4401-8E3B-4FD4-C69F-4E3C575EEB4F">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
<logging>YES</logging>
<partitionedRowMovement>DISABLE</partitionedRowMovement>
<temporaryChanged>false</temporaryChanged>
<accessDriverType>oracle_loader</accessDriverType>
<rejectLimit></rejectLimit>
<columnProxies itemClass="oracle.dbtools.crest.model.design.storage.oracle.v12c.ColumnProxyOraclev12c">
<ColumnProxy name="REFERENCE" id="1CBF54ED-65A6-93B1-3B8A-448F01500F35">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="UPDATE_DATE" id="3709235D-E08C-D251-10DB-A76854C6CBA9">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="NAME" id="46E14032-3EC0-05E0-2FF4-59F7B8C0B645">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="VERSION_ID" id="5A1987F5-80B8-611A-6692-079829796831">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="CREATE_DATE" id="6A68706E-CDBC-939C-4BF2-3A04DED834CF">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="ID" id="7A2EEDD3-549F-13F6-FB93-EAC7D18BB909">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="UPDATE_BY" id="929C54A9-F302-B24E-BE53-A774370C8721">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="CREATE_BY" id="B7EABAEF-A77D-C126-9382-ED5519F8C531">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="TYPE" id="C63689BE-9CEB-234F-29E6-7F7A8F980306">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="COMPILED" id="EFE45AA3-65A8-4744-B33C-3350B3566CFE">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="DESCRIPTION" id="FCC044E6-FF60-8520-FAAA-66BD21231519">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="CONTENT" id="FF67C0E4-8CC3-9324-7F4A-DB34AA32233F">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ColumnProxy>
</columnProxies>
<foreignKeys>
<ForeignKey class="oracle.dbtools.crest.model.design.storage.oracle.v10g.FKProxyOraclev10g" name="AMB_OBJECT_AMB_VERSION_FK" id="8128D935-4E6F-7B54-8C93-732E8445E2BD">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
</ForeignKey>
</foreignKeys>
<primaryKeys>
<PrimaryKey class="oracle.dbtools.crest.model.design.storage.oracle.v10g.PKProxyOraclev10g" name="AMB_OBJECT_PK" id="06CD8FCD-8070-645B-84EF-0145EE343523">
<createdBy>openthinks-pc</createdBy>
<createdTime>2016-03-23 13:26:52 UTC</createdTime>
<ownerDesignName>AMB</ownerDesignName>
<indexSort>SORTED</indexSort>
</PrimaryKey>
</primaryKeys>
</TableProxyOraclev12c>


text:
A Kefir.js adapter and run function for CycleJS

## Install

`npm i cyclejs-kefir --save`


text: {{labelValue}}


text:
package com.facebook.buck.shell;

import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.util.FakeProcessExecutor;
import com.facebook.buck.util.ProcessExecutorParams;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import java.io.IOException;
import java.nio.file.Paths;

public class FakeWorkerProcess extends WorkerProcess {

  private ImmutableMap<String, WorkerJobResult> jobArgsToJobResultMap;
  private boolean isAlive;

  public FakeWorkerProcess(
      ImmutableMap<String, WorkerJobResult> jobArgsToJobResultMap) throws IOException {
    super(
        new FakeProcessExecutor(),
        ProcessExecutorParams.builder()
            .setCommand(ImmutableList.of())
            .build(),
        new FakeProjectFilesystem(),
        Paths.get("tmp").toAbsolutePath().normalize());
    this.jobArgsToJobResultMap = jobArgsToJobResultMap;
    this.isAlive = false;
    this.setProtocol(new FakeWorkerProcessProtocol());
  }

  @Override
  public boolean isAlive() {
    return isAlive;
  }

  @Override
  public synchronized void ensureLaunchAndHandshake() throws IOException {
    isAlive = true;
  }

  @Override
  public synchronized WorkerJobResult submitAndWaitForJob(String jobArgs) throws IOException {
    WorkerJobResult result = this.jobArgsToJobResultMap.get(jobArgs);
    if (result == null) {
      throw new IllegalArgumentException(String.format(
          "No fake WorkerJobResult found for job arguments '%s'",
          jobArgs));
    }
    return result;
  }

  @Override
  public void close() {
    Preconditions.checkState(isAlive, "Closing a dead process?");
    isAlive = false;
  }
}


text:
package org.apache.camel.component.jms;

import javax.jms.ConnectionFactory;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.camel.util.StopWatch;
import org.junit.Test;

import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge;

/**
 * Using exclusive fixed replyTo queues should be faster as there is no need for
 * JMSMessage selectors.
 */
public class JmsRequestReplyExclusiveReplyToComponentTest extends CamelTestSupport {

    @Test
    public void testJmsRequestReplyExclusiveFixedReplyTo() throws Exception {
        StopWatch watch = new StopWatch();

        assertEquals("Hello A", template.requestBody("activemq:queue:foo?replyTo=bar", "A"));
        assertEquals("Hello B", template.requestBody("activemq:queue:foo?replyTo=bar", "B"));
        assertEquals("Hello C", template.requestBody("activemq:queue:foo?replyTo=bar", "C"));
        assertEquals("Hello D", template.requestBody("activemq:queue:foo?replyTo=bar", "D"));
        assertEquals("Hello E", template.requestBody("activemq:queue:foo?replyTo=bar", "E"));

        long delta = watch.taken();
        assertTrue("Should be faster than about 4 seconds, was: " + delta, delta < 4200);
    }

    @Override
    protected CamelContext createCamelContext() throws Exception {
        CamelContext camelContext = super.createCamelContext();
        ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory();
        // mark the reply to type as exclusive on the component
        JmsComponent jms = jmsComponentAutoAcknowledge(connectionFactory);
        jms.setReplyToType(ReplyToType.Exclusive);
        camelContext.addComponent("activemq", jms);
        return camelContext;
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("activemq:queue:foo")
                    .transform(body().prepend("Hello "));
            }
        };
    }
}