text:
namespace base {

namespace {

struct CheckOnDestroy {
  ~CheckOnDestroy() { CHECK(false); }
};

TEST(NoDestructorTest, SkipsDestructors) {
  NoDestructor<CheckOnDestroy> destructor_should_not_run;
}

struct CopyOnly {
  CopyOnly() = default;

  CopyOnly(const CopyOnly&) = default;
  CopyOnly& operator=(const CopyOnly&) = default;

  CopyOnly(CopyOnly&&) = delete;
  CopyOnly& operator=(CopyOnly&&) = delete;
};

struct MoveOnly {
  MoveOnly() = default;

  MoveOnly(const MoveOnly&) = delete;
  MoveOnly& operator=(const MoveOnly&) = delete;

  MoveOnly(MoveOnly&&) = default;
  MoveOnly& operator=(MoveOnly&&) = default;
};

struct ForwardingTestStruct {
  ForwardingTestStruct(const CopyOnly&, MoveOnly&&) {}
};

TEST(NoDestructorTest, ForwardsArguments) {
  CopyOnly copy_only;
  MoveOnly move_only;

  static NoDestructor<ForwardingTestStruct> test_forwarding(
      copy_only, std::move(move_only));
}

TEST(NoDestructorTest, Accessors) {
  static NoDestructor<std::string> awesome("awesome");

  EXPECT_EQ("awesome", *awesome);
  EXPECT_EQ(0, awesome->compare("awesome"));
  EXPECT_EQ(0, awesome.get()->compare("awesome"));
}

// Passing initializer list to a NoDestructor like in this test
// is ambiguous in GCC.
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84849
#if !defined(COMPILER_GCC) && !defined(__clang__)
TEST(NoDestructorTest, InitializerList) {
  static NoDestructor<std::vector<std::string>> vector({"a", "b", "c"});
}
#endif
}  // namespace

namespace {

// A class whose constructor busy-loops until it is told to complete
// construction.
class BlockingConstructor {
 public:
  BlockingConstructor() {
    EXPECT_FALSE(WasConstructorCalled());
    subtle::NoBarrier_Store(&constructor_called_, 1);
    EXPECT_TRUE(WasConstructorCalled());
    while (!subtle::NoBarrier_Load(&complete_construction_))
      PlatformThread::YieldCurrentThread();
    done_construction_ = true;
  }

  ~BlockingConstructor() = delete;

  // Returns true if BlockingConstructor() was entered.
  static bool WasConstructorCalled() {
    return subtle::NoBarrier_Load(&constructor_called_);
  }

  // Instructs BlockingConstructor() that it may now unblock its construction.
  static void CompleteConstructionNow() {
    subtle::NoBarrier_Store(&complete_construction_, 1);
  }

  bool done_construction() { return done_construction_; }

 private:
  // Use Atomic32 instead of AtomicFlag for them to be trivially initialized.
  static subtle::Atomic32 constructor_called_;
  static subtle::Atomic32 complete_construction_;

  bool done_construction_ = false;

  DISALLOW_COPY_AND_ASSIGN(BlockingConstructor);
};

// static
subtle::Atomic32 BlockingConstructor::constructor_called_ = 0;
// static
subtle::Atomic32 BlockingConstructor::complete_construction_ = 0;

// A SimpleThread running at |thread_priority| which invokes |before_get|
// (optional) and then invokes thread-safe
// scoped-static-initializationconstruction on its NoDestructor instance.
class BlockingConstructorThread : public SimpleThread {
 public:
  BlockingConstructorThread(ThreadPriority thread_priority,
                            OnceClosure before_get)
      : SimpleThread("BlockingConstructorThread", Options(thread_priority)),
        before_get_(std::move(before_get)) {}

  void Run() override {
    if (before_get_)
      std::move(before_get_).Run();

    static NoDestructor<BlockingConstructor> instance;
    EXPECT_TRUE(instance->done_construction());
  }

 private:
  OnceClosure before_get_;

  DISALLOW_COPY_AND_ASSIGN(BlockingConstructorThread);
};

}  // namespace

// Tests that if the thread assigned to construct the local-static
// initialization of the NoDestructor runs at background priority : the
// foreground threads will yield to it enough for it to eventually complete
// construction. While local-static thread-safe initialization isn't specific to
// NoDestructor, it is tested here as NoDestructor is set to replace
// LazyInstance and this is an important regression test for it
// (https://crbug.com/797129).
TEST(NoDestructorTest, PriorityInversionAtStaticInitializationResolves) {
  TimeTicks test_begin = TimeTicks::Now();

  // Construct BlockingConstructor from a background thread.
  BlockingConstructorThread background_getter(ThreadPriority::BACKGROUND,
                                              OnceClosure());
  background_getter.Start();

  while (!BlockingConstructor::WasConstructorCalled())
    PlatformThread::Sleep(TimeDelta::FromMilliseconds(1));

  // Spin 4 foreground thread per core contending to get the already under
  // construction NoDestructor. When they are all running and poking at it :
  // allow the background thread to complete its work.
  const int kNumForegroundThreads = 4 * SysInfo::NumberOfProcessors();
  std::vector<std::unique_ptr<SimpleThread>> foreground_threads;
  RepeatingClosure foreground_thread_ready_callback =
      BarrierClosure(kNumForegroundThreads,
                     BindOnce(&BlockingConstructor::CompleteConstructionNow));
  for (int i = 0; i < kNumForegroundThreads; ++i) {
    foreground_threads.push_back(std::make_unique<BlockingConstructorThread>(
        ThreadPriority::NORMAL, foreground_thread_ready_callback));
    foreground_threads.back()->Start();
  }

  // This test will hang if the foreground threads become stuck in
  // NoDestructor's construction per the background thread never being scheduled
  // to complete construction.
  for (auto& foreground_thread : foreground_threads)
    foreground_thread->Join();
  background_getter.Join();

  // Fail if this test takes more than 5 seconds (it takes 5-10 seconds on a
  // Z840 without r527445 but is expected to be fast (~30ms) with the fix).
  EXPECT_LT(TimeTicks::Now() - test_begin, TimeDelta::FromSeconds(5));
}

}  // namespace base


text:
var $$ = require('ui/styles').prop;

var exports = {
  init:function(option){
    var tableViewStyle = option||tableView;
    var tableView = Ti.UI.createTableView($$[tableViewStyle]);

    tableView.addEventListener('click',function(e){
      var index = e.index;
      var row = myApps.ui.createComposeRow();
      row.rowNum =  index;
      myApps.ui.tableView.insertRowAfter(index,row,{animationStyle:Titanium.UI.iPhone.RowAnimationStyle.DOWN});
      row.addEventListener('click',function(e){
        myApps.ui.tableView.deleteRow(index+1,{animationStyle:Titanium.UI.iPhone.RowAnimationStyle.UP});
      });

      // if(row.sourceNum){
      //   row.sourceNum = index;
      // }else{
      //   myApps.ui.tableView.deleteRow(index+1,{animationStyle:Titanium.UI.iPhone.RowAnimationStyle.UP});
      //   row.sourceNum =  null;
      // }

    });
    tableView.addEventListener('scrollEnd',function(e){
      var last_index = tableView.data[0].rows.length - 1;
      var post_date = tableView.data[0].rows[last_index].data.post_date;

      myApps.entries.findLocalJSONDB(post_date,function(cached){

        for(var i=0;i<cached.length;i++){
          var rows = [];
          var entry = cached[i];
          Ti.API.info('読み込まれたエントリタイトル:'+cached[i].title);
          var row = myApps.ui.createEntryRow(entry);
          tableView.appendRow(row,{
            animationStyle:Titanium.UI.iPhone.RowAnimationStyle.DOWN
          });
        }
      });
    });
    return tableView;
  },

  setTableData:function(table,/*array*/ data){
    return table.setData(data,{
      animated:true,
      animationStyle:Titanium.UI.iPhone.RowAnimationStyle.DOWN
    });
  }
};

redpajama_set_name: RedPajamaGithub


text:
.. _str: https://docs.python.org/2/library/stdtypes.html

.. _vim.fault.VimFault: ../../vim/fault/VimFault.rst

vim.fault.PatchNotApplicable
============================
    :extends:

        `vim.fault.VimFault`_

  This fault is thrown if a patch install fails because the patch is not applicable to the host. Typically, a subclass of this exception is thrown, indicating a problem such as the patch is superseded, already installed, or has dependencies missing, and so on.

Attributes:

    patchID (`str`_)


text:
<?php
	declare(strict_types=1);

	namespace Edde\Common\Strings;

	use Edde\Common\Callback\CallbackUtils;
	use Edde\Common\Object;

	/**
	 * StringsUtils are set of independent methods for UTF-8 string manipulation.
	 */
	class StringUtils extends Object {
		private static $SEPARATOR_LIST = [
			'|',
			':',
			'.',
			'-',
			'_',
			'/',
			' ',
		];

		/**
		 * try to capitalize input string
		 *
		 * @param string $string
		 *
		 * @return string
		 */
		static public function capitalize(string $string): string {
			return mb_convert_case($string, MB_CASE_TITLE, 'UTF-8');
		}

		/**
		 * compare two strings
		 *
		 * @param string   $left
		 * @param string   $right
		 * @param int|null $length
		 *
		 * @return bool
		 */
		static public function compare(string $left, string $right, int $length = null): bool {
			if ($length !== null) {
				$left = self::substring($left, 0, $length);
				$right = self::substring($right, 0, $length);
			}
			return self::lower($left) === self::lower($right);
		}

		/**
		 * return subset of the given string
		 *
		 * @param string   $string
		 * @param int      $start
		 * @param int|null $length
		 *
		 * @return string
		 */
		static public function substring(string $string, int $start, int $length = null): string {
			return mb_substr($string, $start, $length, 'UTF-8');
		}

		/**
		 * @param string $string
		 *
		 * @return string
		 */
		static public function lower(string $string): string {
			return mb_strtolower($string, 'UTF-8');
		}

		/**
		 * ensure that input string is unicode; if not exception is thrown
		 *
		 * @param string $string
		 *
		 * @return string
		 * @throws StringException
		 */
		static public function checkUnicode(string $string): string {
			if (strpos($string, "\xEF\xBB\xBF", 0) !== false) {
				$string = substr($string, 3);
			}
			if (preg_match('~~u', $string) !== 1) {
				throw new StringException('String is not valid UTF-8 stream.');
			}
			return str_replace("\r\n", "\n", $string);
		}

		/**
		 * @param int $code
		 *
		 * @return string
		 * @throws StringException
		 */
		static public function chr(int $code): string {
			if ($code < 0 || ($code >= 0xD800 && $code <= 0xDFFF) || $code > 0x10FFFF) {
				throw new StringException('Code point must be in range 0x0 to 0xD7FF or 0xE000 to 0x10FFFF.');
			}
			return iconv('UTF-32BE', 'UTF-8//IGNORE', pack('N', $code));
		}

		/**
		 * return true if the given string is utf-8
		 *
		 * @param string $string
		 *
		 * @return bool
		 */
		static public function isEncoding(string $string): bool {
			return $string === self::fixEncoding($string);
		}

		/**
		 * convert given string into utf-8
		 *
		 * @param string $string
		 *
		 * @return string
		 */
		static public function fixEncoding(string $string): string {
			return htmlspecialchars_decode(htmlspecialchars($string, ENT_NOQUOTES | ENT_IGNORE, 'UTF-8'), ENT_NOQUOTES);
		}

		/**
		 * translate given size to the human readable form
		 *
		 * @param int $size
		 * @param int $decimal
		 *
		 * @return string
		 */
		static public function toHumanSize(int $size, int $decimal = 2): string {
			static $sizeList = [
				'B',
				'kB',
				'MB',
				'GB',
				'TB',
				'PB',
				'EB',
				'ZB',
				'YB',
			];
			$factor = (int)floor((strlen((string)$size) - 1) / 3);
			/** @noinspection PhpUsageOfSilenceOperatorInspection */
			return sprintf('%.' . $decimal . 'f %s', $size / pow(1024, $factor), @$sizeList[$factor]);
		}

		/**
		 * split given string by capital letters and glue them by the given glue - e.g. FooBar will became foo-bar
		 *
		 * @param string $string
		 * @param string $glue
		 * @param int    $index
		 *
		 * @return string
		 */
		static public function recamel(string $string, string $glue = '-', int $index = 0): string {
			$camel = self::fromCamelCase($string, $index);
			return mb_strtolower(implode($glue, $camel));
		}

		/**
		 * split the given string by capital letters (e.g. FooBar will became [Foo, Bar])
		 *
		 * @param string $string
		 * @param int    $index
		 *
		 * @return array
		 */
		static public function fromCamelCase(string $string, int $index = null): array {
			$camel = preg_split('~(?=[A-Z])~', $string, -1, PREG_SPLIT_NO_EMPTY);
			if ($index !== null) {
				return array_slice($camel, $index);
			}
			return $camel;
		}

		/**
		 * convert input string to camelHumpCase
		 *
		 * @param array|string $input
		 *
		 * @return string
		 */
		static public function toCamelHump($input): string {
			return self::firstLower(self::toCamelCase($input));
		}

		/**
		 * convert first character to lower case
		 *
		 * @param string $string
		 *
		 * @return string
		 */
		static public function firstLower(string $string): string {
			return self::lower(self::substring($string, 0, 1)) . self::substring($string, 1);
		}

		/**
		 * return the given input as CamelCase
		 *
		 * @param string|array $input
		 *
		 * @return string
		 */
		static public function toCamelCase($input): string {
			return str_replace('~', null, mb_convert_case(str_replace(self::$SEPARATOR_LIST, '~', mb_strtolower(implode('~', is_array($input) ? $input : preg_split('~(?=[A-Z])~', $input, -1, PREG_SPLIT_NO_EMPTY)))), MB_CASE_TITLE, 'UTF-8'));
		}

		/**
		 * remove invalid character from an "url" string
		 *
		 * @param string      $string
		 * @param string|null $charlist
		 * @param bool        $lower
		 *
		 * @return string
		 */
		static public function webalize(string $string, string $charlist = null, bool $lower = true): string {
			$string = self::toAscii($string);
			if ($lower) {
				$string = strtolower($string);
			}
			$string = preg_replace('~[^a-z0-9' . ($charlist ? preg_quote($charlist, '~') : '') . ']+~i', '-', $string);
			$string = trim($string, '-');
			return $string;
		}

		/**
		 * convert the input string to an ascii only string
		 *
		 * @param string $string
		 *
		 * @return string
		 */
		static public function toAscii(string $string): string {
			$string = preg_replace('~[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]~u', '', $string);
			$string = strtr($string, '`\'"^~?', "\x01\x02\x03\x04\x05\x06");
			$string = str_replace([
				"\xE2\x80\x9E",
				"\xE2\x80\x9C",
				"\xE2\x80\x9D",
				"\xE2\x80\x9A",
				"\xE2\x80\x98",
				"\xE2\x80\x99",
				"\xC2\xB0",
			], [
				"\x03",
				"\x03",
				"\x03",
				"\x02",
				"\x02",
				"\x02",
				"\x04",
			], $string);
			/** @noinspection PhpUsageOfSilenceOperatorInspection */
			$string = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string); // intentionally @
			$string = str_replace([
				'`',
				"'",
				'"',
				'^',
				'~',
				'?',
			], '', $string);
			return strtr($string, "\x01\x02\x03\x04\x05\x06", '`\'"^~?');
		}

		/**
		 * preg_match
		 *
		 * @param string           $string
		 * @param string           $pattern
		 * @param bool|false       $named return only named parameters from token
		 * @param array|bool|false $trim  if array is provided, its used for named parameters defaults
		 *
		 * @return array|null
		 * @throws StringException
		 */
		static public function match(string $string, string $pattern, bool $named = false, bool $trim = false) {
			$match = null;
			$match = self::pcre('preg_match', [
				$pattern,
				$string,
				&$match,
			]) ? $match : null;
			if ($match === null) {
				return null;
			}
			if ($named && is_array($match)) {
				/** @noinspection ForeachSourceInspection */
				foreach ($match as $k => $v) {
					if (is_int($k) || ((is_array($trim) || $trim) && empty($v))) {
						unset($match[$k]);
					}
				}
			}
			if (is_array($trim)) {
				$match = array_merge($trim, $match);
			}
			return $match;
		}

		/**
		 * @param $func
		 * @param $args
		 *
		 * @return mixed
		 * @throws StringException
		 */
		static private function pcre($func, $args) {
			static $messages = [
				PREG_INTERNAL_ERROR        => 'Internal error',
				PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit was exhausted',
				PREG_RECURSION_LIMIT_ERROR => 'Recursion limit was exhausted',
				PREG_BAD_UTF8_ERROR        => 'Malformed UTF-8 data',
				5                          => 'Offset didn\'t correspond to the begin of a valid UTF-8 code point',
				// PREG_BAD_UTF8_OFFSET_ERROR
			];
			/** @noinspection ExceptionsAnnotatingAndHandlingInspection */
			$res = CallbackUtils::invoke($func, $args, function ($message) use ($args) {
				// compile-time error, not detectable by preg_last_error
				throw new StringException($message . ' in pattern: ' . implode(' or ', (array)$args[0]));
			});
			if (($code = preg_last_error()) // run-time error, but preg_last_error & return code are liars
				&& ($res === null || in_array($func, [
						'preg_filter',
						'preg_replace_callback',
						'preg_replace',
					], true) === false)) {
				throw new StringException(($messages[$code] ?? 'Unknown error') . ' (pattern: ' . implode(' or ', (array)$args[0]) . ')', $code);
			}
			return $res;
		}

		/**
		 * @param string           $string
		 * @param string           $pattern
		 * @param bool|false       $named return only named parameters from token
		 * @param array|bool|false $trim  if array is provided, its used for named parameters defaults
		 *
		 * @return array|null
		 * @throws StringException
		 */
		static public function matchAll(string $string, string $pattern, bool $named = false, $trim = false): array {
			$match = null;
			$match = self::pcre('preg_match_all', [
				$pattern,
				$string,
				&$match,
			]) ? $match : null;
			if ($match === null) {
				return [];
			}
			if ($named) {
				/** @noinspection ForeachSourceInspection */
				foreach ($match as $k => $v) {
					if (is_int($k) || ((is_array($trim) || $trim) && empty($v))) {
						unset($match[$k]);
					}
				}
			}
			if (is_array($trim)) {
				$match = array_merge($trim, $match);
			}
			return $match;
		}

		/**
		 * preg_replace
		 *
		 * @param string      $subject
		 * @param string      $pattern
		 * @param string|null $replacement
		 * @param int         $limit
		 *
		 * @return string
		 * @throws StringException
		 */
		static public function replace(string $subject, string $pattern, string $replacement = null, int $limit = -1): string {
			return self::pcre('preg_replace', [
				$pattern,
				$replacement,
				$subject,
				$limit,
			]);
		}

		/**
		 * break down the given string by the given pattern
		 *
		 * @param string $subject
		 * @param string $pattern
		 * @param int    $flags
		 *
		 * @return array
		 * @throws StringException
		 */
		static public function split(string $subject, string $pattern, int $flags = 0): array {
			return self::pcre('preg_split', [
				$pattern,
				$subject,
				-1,
				$flags | PREG_SPLIT_DELIM_CAPTURE,
			]);
		}

		/**
		 * convert first character to upper case
		 *
		 * @param string $string
		 *
		 * @return string
		 */
		static public function firstUpper(string $string): string {
			return self::upper(self::substring($string, 0, 1)) . self::substring($string, 1);
		}

		/**
		 * convert to upper case
		 *
		 * @param string $string
		 *
		 * @return string
		 */
		static public function upper(string $string): string {
			return mb_strtoupper($string, 'UTF-8');
		}

		/**
		 * create an iterator over the given string
		 *
		 * @param string $string
		 *
		 * @return \Generator
		 */
		static public function createIterator(string $string): \Generator {
			$length = mb_strlen($string = self::normalizeNewLines($string));
			while ($length) {
				yield mb_substr($string, 0, 1);
				$string = mb_substr($string, 1, $length);
				$length = mb_strlen($string);
			}
		}

		/**
		 * normalize input string, trim newlines, ...
		 *
		 * @param string $string
		 *
		 * @return string
		 */
		static public function normalize(string $string): string {
			$string = self::normalizeNewLines($string);
			$string = preg_replace('~[\x00-\x08\x0B-\x1F\x7F-\x9F]+~u', '', $string);
			$string = preg_replace('~[\t ]+$~m', '', $string);
			$string = trim($string, "\n");
			return $string;
		}

		/**
		 * translate an iconsistent newlines to the standard "\n"
		 *
		 * @param string $string
		 *
		 * @return string
		 */
		static public function normalizeNewLines(string $string): string {
			return str_replace([
				"\r\n",
				"\r",
			], "\n", $string);
		}

		/**
		 * extract particular string from another simply formatted string (for example class name from namespace, ...)
		 *
		 * @param string $source
		 * @param string $separator
		 * @param int    $index
		 *
		 * @return string
		 */
		static public function extract(string $source, string $separator = '\\', int $index = -1): string {
			$sourceList = explode($separator, $source);
			return isset($sourceList[$index = $index < 0 ? count($sourceList) + $index : $index]) ? $sourceList[$index] : '';
		}

		/**
		 * @param string $string
		 *
		 * @return int
		 */
		static public function length(string $string): int {
			return mb_strlen($string);
		}
	}


text:
use Config::Simple;
use Getopt::Long;
use Pod::Usage;
our $VERSION = "0.1.0";

GetOptions ('h',    \$help,
	    'help', \$help,
	    'a',    \$abort_on_conflict,
	    't=s',    \$target,
	   );
pod2usage(-exitstatus => 0, -verbose => 2) if $help;

# we need to assume that some environment variables are available
# it is not clear to me if this program should assume the location
# of deployment.cfg under TARGET or if it should check the TARGET
# variable. For now, I think we'll not use the TARGET variable.
# die "envionment variable TARGET not defined" unless $ENV{TARGET};

my $global_cfg = Config::Simple->new( syntax => 'ini' );
my $local_cfg  = Config::Simple->new( syntax => 'ini' );

# if there is a global deployment.cfg file, read it
if (defined $target && $target ne "") {
	# then use the command line provided target
	die "$target is not a valid directory" unless -d $target;
	die "$target is not a writable directory" unless -w $target;
	$ENV{TARGET} = $target;
}
if (-e "$ENV{TARGET}/deployment.cfg" ) {
	$global_cfg->read("$ENV{TARGET}/deployment.cfg")
	  or die "can not read $ENV{TARGET}/deployment.cfg\n", $global_cfg->error();
	$global_cfg->save("$ENV{TARGET}/deployment.cfg.bak");
}

# if there is a module deploy.cfg available, read it
if (-e './deploy.cfg') {
	$local_cfg->read('./deploy.cfg')
	  or die "can not read ./deploy.cfg", $local_cfg->error();
}

# merge the two configs, issueing a warning if the same key exists with
# different values between the two config files
foreach my $key (keys $local_cfg->vars() ) {
    my $global_val = $global_cfg->param($key);
    my $local_val = $local_cfg->param($key);

    if ($global_val && !cfg_values_equal($global_val, $local_val))
    {
	my $gstr = ref($global_val) ? join(", ", @$global_val) : $global_val;
	my $lstr = ref($local_val) ? join(", ", @$local_val) : $local_val;
	warn "key conflict: global $key, $gstr\n",
		"key conflict: local  $key, $lstr\n",
		"keeping global config\n";
	die "and aborting -  on conflict is set to true" if defined $abort_on_conflict;
    }
    else {
	$global_cfg->param($key, $local_val);
    }
}

# write out the resulting global deployment config
$global_cfg->param('dev_container.version', $VERSION);
$global_cfg->write("$ENV{TARGET}/deployment.cfg") if $global_cfg->param();

sub cfg_values_equal
{
    my($v1, $v2) = @_;

    if (ref($v1) && !ref($v2))
    {
	$v2 = [$v2];
    }
    elsif (!ref($v1) && ref($v2))
    {
	$v1 = [$v1];
    }
    if (ref($v1))
    {
	if (@$v1 != @$v2)
	{
	    return 0;
	}
	for my $i (0..$#$v1)
	{
	    return 0 if $v1->[$i] ne $v2->[$i];
	}
	return 1;
    }
    else
    {
	return $v1 eq $v2;
    }
}

=pod

=head1  NAME

mkcfg

=head1  SYNOPSIS

=over

=item mkcfg -h, --help

=back

=head1  DESCRIPTION

The mkcfg command appends the module deploy.cfg file in the module
top level directory to the deployment.cfg file in the deployment top
level directory directory.

The deployment directory is specified by the $TARGET environment variable.

If neither file exists, then an empty deployment.cfg file is created.

If deploy.cfg exists but not deployment.cfg, then a deployment.cfg
is created that contains the contents of deploy.cfg.

If deployment.cfg exists but not deploy.cfg, then deployment.cfg
remains unchanged, but due to the write a new timestamp on the file
will occur.

If both files exist, a merge of the files will be attempted, and
as long as there are no conflicts between the values of a given key
in a given block the merge will succeed and a new deployment.cfg file
will be written.

If both files exist and there is a conflict between the values of
a given key in a given block, the program will issue a warning and
keep the global setting.

No order is assumed on the blocks in the output file.

If the deployment.cfg exists, under all cases a deployment.cfg.bak
file will be created as a backup.

=head1  COMMAND-LINE OPTIONS

=over

=item   -h, --help
This documentation

=item   -a
When set, the progam will abort with a non-zero return
value if a convlict exists betweeen the deploy.cfg and the existing
deployment.cfg files

=back

=head1  AUTHORS

Thomas Brettin
Shane Canon
Dan Olson


text:
(function() {
  define(['subtitles.controls.view', 'youtube.sync.subtitles.view', 'backbone', 'handlebars', 'templates'], function(SubtitlesControlsView, YoutubeSubtitlesSyncView, Backbone, Handlebars) {
    var YoutubeSyncView;
    YoutubeSyncView = Backbone.View.extend({
      className: 'youtube-sync',
      initialize: function() {
        var _this = this;
        this.playerId = 'ytPlayerSync';
        this.subtitlesControlsView = new SubtitlesControlsView({
          model: this.model,
          allowToggleVideo: true
        });
        this.youtubeSubtitlesSyncView = new YoutubeSubtitlesSyncView({
          model: this.model
        });
        this.subtitlesControlsView.on('hideVideo', function() {
          return _this.$('.video-container').hide();
        });
        this.subtitlesControlsView.on('showVideo', function() {
          return _this.$('.video-container').show();
        });
        return this.listenTo(this.model, 'change:syncing', function() {
          return _this.renderSyncButton();
        });
      },
      render: function() {
        var postRender,
          _this = this;
        this.$el.html(Handlebars.templates['youtube-sync'](this.model.toJSON()));
        this.$('.controls-container').html(this.subtitlesControlsView.render().el);
        this.$('.subtitles-container').html(this.youtubeSubtitlesSyncView.render().el);
        this.$('.toggleSync').on('click', function() {
          if (_this.model.get('syncing')) {
            return _this.model.set({
              syncing: false
            });
          } else {
            return _this.model.set({
              syncing: true
            });
          }
        });
        this.renderSyncButton();
        postRender = function() {
          return _this.postRender();
        };
        setTimeout(postRender);
        return this;
      },
      renderSyncButton: function(syncing) {
        var toggleSync;
        toggleSync = this.$('.toggleSync');
        if (this.model.get('syncing')) {
          toggleSync.addClass('btn-primary');
          toggleSync.removeClass('btn-default');
          toggleSync.attr('title', 'Sync Off');
          return toggleSync.html('Sync Off');
        } else {
          toggleSync.removeClass('btn-primary');
          toggleSync.addClass('btn-default');
          toggleSync.attr('title', 'Sync On');
          return toggleSync.html('Sync On');
        }
      },
      calculateYTPlayerHeight: function() {
        var ytPlayerHeight, ytPlayerWidth;
        ytPlayerWidth = this.$('#' + this.playerId).width();
        ytPlayerHeight = ytPlayerWidth * 0.75;
        return this.$('#' + this.playerId).height(ytPlayerHeight + 'px');
      },
      postRender: function() {
        var onAPIReady, onReady, onStateChange,
          _this = this;
        onReady = function() {
          _this.model.set({
            ytPlayerReady: true
          });
          return _this.model.trigger('change:currentSong');
        };
        onStateChange = function(state) {
          var fn;
          fn = function() {
            return _this.model.onStateChange(state);
          };
          return setTimeout(fn);
        };
        onAPIReady = function() {
          var height, params, width;
          height = _this.$el.height();
          width = height * (4 / 3);
          params = {
            height: height,
            width: width,
            playerVars: {
              modestbranding: 1,
              fs: 0,
              showInfo: 0,
              rel: 0,
              controls: 0
            },
            events: {
              'onReady': onReady,
              'onStateChange': onStateChange
            }
          };
          return _this.model.ytPlayer = new YT.Player(_this.playerId, params);
        };
        if (typeof YT === 'undefined' || typeof YT.Player === 'undefined') {
          window.onYouTubeIframeAPIReady = onAPIReady;
          return $.getScript('//www.youtube.com/iframe_api?noext');
        } else {
          return onAPIReady();
        }
      }
    });
    return YoutubeSyncView;
  });

}).call(this);

/*
//@ sourceMappingURL=youtube-sync-view.js.map
*/


text:
package com.intellij.find;

import com.intellij.openapi.components.ServiceManager;
import org.jetbrains.annotations.NotNull;

public abstract class FindSettings{

  public static FindSettings getInstance() {
    return ServiceManager.getService(FindSettings.class);
  }

  public abstract boolean isSkipResultsWithOneUsage();

  public abstract void setSkipResultsWithOneUsage(boolean skip);

  public abstract String getDefaultScopeName();

  public abstract void setDefaultScopeName(String scope);

  public abstract boolean isSearchOverloadedMethods();

  public abstract void setSearchOverloadedMethods (boolean search);

  public abstract boolean isForward();

  public abstract void setForward(boolean findDirectionForward);

  public abstract boolean isFromCursor();

  public abstract void setFromCursor(boolean findFromCursor);

  public abstract boolean isGlobal();

  public abstract void setGlobal(boolean findGlobalScope);

  public abstract boolean isCaseSensitive();

  public abstract void setCaseSensitive(boolean caseSensitiveSearch);

  public abstract boolean isLocalCaseSensitive();

  public abstract void setLocalCaseSensitive(boolean caseSensitiveSearch);

  public abstract boolean isPreserveCase();

  public abstract void setPreserveCase(boolean preserveCase);

  public abstract boolean isWholeWordsOnly();

  public abstract void setWholeWordsOnly(boolean wholeWordsOnly);

  public abstract boolean isLocalWholeWordsOnly();

  public abstract void setLocalWholeWordsOnly(boolean wholeWordsOnly);

  public abstract boolean isRegularExpressions();

  public abstract void setRegularExpressions(boolean regularExpressions);

  public abstract boolean isLocalRegularExpressions();

  public abstract void setLocalRegularExpressions(boolean regularExpressions);

  /**
   * FindInProjectSettings.addDirectory
   */
  @Deprecated
  public abstract void addStringToFind(@NotNull String s);

  /**
   * Use FindInProjectSettings.addDirectory
   */
  @Deprecated
  public abstract void addStringToReplace(@NotNull String s);

  /**
   * FindInProjectSettings.addDirectory
   */
  @NotNull
  public abstract String[] getRecentFindStrings();

  /**
   * FindInProjectSettings.addDirectory
   */
  @NotNull
  public abstract String[] getRecentReplaceStrings();

  /**
   * Returns the list of file masks used by the user in the "File name filter"
   * group box.
   *
   * @return the recent file masks list
   * @since 5.0.2
   */
  @NotNull
  public abstract String[] getRecentFileMasks();

  public abstract void setWithSubdirectories(boolean b);

  public abstract void initModelBySetings(@NotNull FindModel model);

  public abstract String getFileMask();

  public abstract void setFileMask(String fileMask);
  public abstract void setCustomScope(String scopeName);
  public abstract String getCustomScope();

  public abstract boolean isInStringLiteralsOnly();
  public abstract void setInStringLiteralsOnly(boolean selected);

  public abstract boolean isInCommentsOnly();
  public abstract void setInCommentsOnly(boolean selected);

  public abstract boolean isExceptStringLiterals();
  public abstract void setExceptStringLiterals(boolean selected);

  public abstract boolean isExceptComments();
  public abstract void setExceptComments(boolean selected);

  public abstract boolean isExceptCommentsAndLiterals();
  public abstract void setExceptCommentsAndLiterals(boolean selected);

  public abstract boolean isShowResultsInSeparateView();
  public abstract void setShowResultsInSeparateView(boolean selected);
}


text:
require 'doorkeeper/orm/active_record/application'

Doorkeeper::Application.class_eval do
  enum trust_level: [:insecure, :secure, :first_party]

  def scopes
    scope = default_scope.blank? ? 'public' : default_scope
    Doorkeeper::OAuth::Scopes.from_array(scope)
  end

  def allowed_grants
    if secure?
      %w(client_credentials authorization_code refresh_token)
    elsif insecure?
      %w(refresh_token)
    else
      %w(client_credentials authorization_code password refresh_token)
    end
  end

  def allowed_authorizations
    if secure? || first_party?
      %w(token code)
    else
      %w(token)
    end
  end
end


text:
from django.shortcuts import get_object_or_404

import django_filters
from funfactory.urlresolvers import reverse
from rest_framework import viewsets, serializers
from rest_framework.response import Response

from mozillians.common.helpers import absolutify
from mozillians.groups.models import Group, GroupMembership, Skill
from mozillians.users.models import UserProfile

class GroupMemberSerializer(serializers.HyperlinkedModelSerializer):
    privacy = serializers.CharField(source='get_privacy_groups_display')
    username = serializers.Field(source='user.username')

    class Meta:
        model = UserProfile
        fields = ('privacy', 'username', '_url')

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    member_count = serializers.Field()
    url = serializers.SerializerMethodField('get_url')

    class Meta:
        model = Group
        fields = ('id', 'url', 'name', 'member_count', '_url')

    def get_url(self, obj):
        return absolutify(reverse('groups:show_group', kwargs={'url': obj.url}))

class GroupDetailedSerializer(GroupSerializer):
    members = GroupMemberSerializer(many=True, source='_members')
    curator = serializers.SerializerMethodField('get_curator')

    class Meta:
        # The curator field is only listed here for compatibility reasons
        # The curators field returns all the curators of a group
        model = Group
        fields = ('id', 'name', 'description', 'curator', 'curators',
                  'irc_channel', 'website', 'wiki',
                  'members_can_leave', 'accepting_new_members',
                  'new_member_criteria', 'functional_area', 'members', 'url')

    def get_curator(self, obj):
        return obj.curators.all().first()

class SkillSerializer(serializers.HyperlinkedModelSerializer):
    member_count = serializers.Field()
    url = serializers.SerializerMethodField('get_url')

    class Meta:
        model = Skill
        fields = ('id', 'url', 'name', 'member_count', '_url')

    def get_url(self, obj):
        return absolutify(reverse('groups:show_skill', kwargs={'url': obj.url}))

class SkillDetailedSerializer(SkillSerializer):
    members = GroupMemberSerializer(many=True, source='_members')

    class Meta:
        model = Skill
        fields = ('id', 'name', 'members', 'url')

class GroupFilter(django_filters.FilterSet):
    curator = django_filters.MethodFilter(action='filter_curator')

    class Meta:
        model = Group
        fields = ('name', 'functional_area', 'curators', 'curator',
                  'members_can_leave', 'accepting_new_members',)

    def filter_curator(self, queryset, value):
        return queryset.filter(curators=value)

class SkillFilter(django_filters.FilterSet):

    class Meta:
        model = Skill
        fields = ('name',)

class GroupViewSet(viewsets.ReadOnlyModelViewSet):
    """
    Returns a list of Mozillians groups respecting authorization
    levels and privacy settings.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    ordering = 'name'
    ordering_fields = ('name', 'member_count')
    filter_class = GroupFilter

    def get_queryset(self):
        queryset = Group.objects.filter(visible=True)
        return queryset

    def retrieve(self, request, pk):
        group = get_object_or_404(self.get_queryset(), pk=pk)

        # Exclude members in 'pending' state
        group._members = group.members.filter(privacy_groups__gte=self.request.privacy_level,
                                              groupmembership__status=GroupMembership.MEMBER)
        serializer = GroupDetailedSerializer(group, context={'request': self.request})
        return Response(serializer.data)

class SkillViewSet(viewsets.ReadOnlyModelViewSet):
    """
    Returns a list of Mozillians skills respecting authorization
    levels and privacy settings.
    """
    queryset = Skill.objects.all()
    serializer_class = SkillSerializer
    ordering_fields = ('name',)
    filter_class = SkillFilter

    def retrieve(self, request, pk):
        skill = get_object_or_404(self.queryset, pk=pk)
        skill._members = skill.members.filter(privacy_groups__gte=self.request.privacy_level)
        serializer = SkillDetailedSerializer(skill, context={'request': self.request})
        return Response(serializer.data)


text:
/*!
 * reveal.js Mermaid plugin
 */

import mermaid from "mermaid";

mermaid.mermaidAPI.initialize({
  // The node size will be calculated incorrectly if set `startOnLoad: start`,
  // so we need to manually render.
  startOnLoad: false,
});

const Plugin = {
  id: "mermaid",

  init: function (reveal) {
    const mermaidEls = reveal.getRevealElement().querySelectorAll(".mermaid");

    Array.from(mermaidEls).forEach(function (el) {
      var insertSvg = function (svgCode, bindFunctions) {
        el.innerHTML = svgCode;
      };

      var graphDefinition = el.textContent.trim();

      try {
        mermaid.mermaidAPI.render(
          `mermaid-${Math.random().toString(36).substring(2)}`,
          graphDefinition,
          insertSvg
        );
      } catch (error) {
        console.error(error, { graphDefinition, el });
        el.innerHTML = error.message;
      }
    });
  },
};

export default () => Plugin;


text:
DataTorrent Front
=================

Open-source, web-based user interface for use with [DataTorrent](http://datatorrent.com), a stream-processing platform for developing real-time, big data applications in Hadoop.

Contributing
------------
This project welcomes new contributors!

You acknowledge that your submissions to DataTorrent on this repository are made pursuant the terms of the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html) and constitute "Contributions," as defined therein, and you represent and warrant that you have the right and authority to do so.

When **adding new javascript files**, please prepend the Apache v2.0 license header, which can be found in [CONTRIBUTING.md file](https://github.com/DataTorrent/malhar-ui-console/blob/master/CONTRIBUTING.md).

Installation/Building
---------------------

After cloning the [Malhar](https://github.com/DataTorrent/Malhar) repository from Github:

    cd front
    npm install .
    make build

This creates a `dist` folder whose contents should be copied into the static file server root on the DataTorrent Gateway.

Browser Compatibility
---------------------

The following browsers are currently supported:
- Chrome
- Firefox
- Safari

Tests
-----

Tests are written using the [Mocha Framework](http://visionmedia.github.io/mocha/), the [Chai Assertion Library](http://chaijs.com/), and the [Sinon Library](http://sinonjs.org/). The `suite.js` file which is located in `front/test/` includes all the tests to be run. The individual test files are located in the same directory of the file under test, and by convention end in `.spec.js`.

### CLI

To run tests via command line, run `make clitest` (or `npm test`, which proxies to the make target).

### Browser

To run the tests in the browser, run `make test`, then go to `http://localhost:3334/test/runner.html` to view the test results.

Development
-----------

To start development on the DataTorrent UI, you will need to set up a ssh tunnel to the node in a DataTorrent cluster that has the DT Gateway successfully configured and running.

### Configure

By default, the ui assumes that you have set up a tunnel that is listening on port 3390 of your local machine that is connected to the Gateway node. If you are using another port, change the assignment of `config.gateway.port` in `config.js` to the appropriate port.

### Starting Dev Server

Run the command:

	node server

Then, open `http://localhost:3333/` in your browser and you should see the dashboard. Chrome is best when developing.

### The DT Global Variable

At runtime, the variable DT is available on the global namespace and contains all the base components that the Front relies on, such as classes that model aspects of your datatorrent applications and views that are common throughout the project. To view what is on this module, take a look at the file located at `front/js/datatorent/index.js`.

### Pages

The file located at `front/js/app/pages.js` acts as an index for all registered pages, and contains more information therein about how to set up a page. The actual page definitions are located in `front/js/app/lib/pages/` and specify a page name, the widgets that can be instantiated, the default widget configurations (called dashboards), and the page-wide models that will be instantiated. The best way to get familiar with these is to review the code.

### Widgets

Widgets are simply enhanced backbone views. It is recommended (but not necessarily required) to have all widgets extend from DT.widgets.Widget, which maps to the base backbone view located at `front/js/datatorrent/WidgetView.js`.

#### Location

Widgets live in `/js/App/lib/widgets`.

#### Creation

To create a boilerplate for a widget, run

    ./bin/createWidget [-c] _WIDGET_NAME_

This will append "Widget" to the end of your widget name, so it is not necessary to include it here. The new folder that is created will be located at `front/js/app/lib/widgets/_WIDGET_NAME_Widget`.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Multi-head Support Overview</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="index.html" title="GDK Reference Manual">
<link rel="up" href="reference.html" title="API Reference">
<link rel="prev" href="gdk-General.html" title="General">
<link rel="next" href="GdkDisplay.html" title="GdkDisplay">
<meta name="generator" content="GTK-Doc V1.15 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GDK Reference Manual

Multi-head Support Overview

Multi-head Support Overview — Overview of GdkDisplay and GdkScreen

Overview

	Multihead support is based around two main object types:

GdkDisplay

GdkScreen

	GdkDisplay objects are the GDK
	representation of the X Display which can be described as a
	workstation consisting of a keyboard a pointing device (such as a
	  mouse) and one or more screens.
	It is used to open and keep track of various GdkScreen objects currently
	instanciated by the application. It is also used to grab and release
	the keyboard and the mouse pointer.

	GdkScreen objects are the GDK
	representation of a physical screen. It is used throughout GDK and GTK+
	to specify which screen the top level windows are to be displayed on.
	It is also used to query the screen specification and default settings such as
	the default colormap (gdk_screen_get_default_colormap()),
	the screen width (gdk_screen_get_width()), etc.

	The following code samples demonstrate common usage of the objects described above.

Example 2. Testing the number of screen on the current display

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

gint num_screen = 0;
gchar *displayname = NULL;
GdkScreen **screen_list;
GdkDisplay *display;

gtk_init (&argc, &argv);

display = gdk_display_get_default ();
num_screen = gdk_display_get_n_screens (display);
displayname = gdk_display_get_name (display);
if (num_screen <= 1)
  {
    printf ("This Xserver (%s) manages only one screen. exiting...\n",
            displayname);
    exit (1);
  }
else
  {
    printf ("This Xserver (%s) manages %d screens.\n", displayname,
            num_screen);
  }

Example 3. Opening a second display

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

gchar *second_screen_name;
GdkDisplay *second_display;
GdkScreen *second_screen;
GtkWidget *window;

gtk_init (&argc, &argv);

/* screen2_name needs to be initialized before calling
/* gdk_display_new() */
second_display = gdk_display_new (&argc, &argv, second_screen_name);
if (second_display)
    second_screen = gdk_display_get_default_screen (second_display);
else
  {
    g_print ("Can't open display :\n\t%s\n\n",
          second_screen_name);
    exit (1);
  }
/* now GdkScreen can be assigned to GtkWindows */

window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_screen (window, second_screen);

See Also

<col align="left" valign="top">

GdkDisplay

the GDK Object used to represent and manipulate display
		related data

GdkScreen

the GDK Object used to represent and query screen related
		data

          Generated by GTK-Doc V1.15


text:
import { EG, p } from '@web-companions/gfc';
import { setProp } from '@web-companions/gfc/utils';
import { css, setStyle } from '@web-companions/h';
import { render } from 'lit-html2';
import { snippetRoundNode } from './snippetRound.node';

const SnippetRoundNode = snippetRoundNode();

export const preloaderElement = EG({
  props: {
    loading: p.opt<boolean>('loading'),
  },
  mapper,
})(function* (params) {
  const $ = this.attachShadow({ mode: 'open' });
  let loading = params.loading;
  let showSpinner = true;

  setStyle(require('./style.scss'), $);

  while (true) {
    if (loading !== params.loading) {
      loading = params.loading;

      // remove spinner with animation from DOM
      if (!loading) {
        setTimeout(() => {
          showSpinner = false;
          this.next();
        }, 600);
      } else {
        showSpinner = true;
      }
    }

    params = yield render(
      <div class="um-preloader">
        {showSpinner ? (
          <div
            class="um-preloader__loader um-preloader__loader_fixed"
            style={css`
              opacity: ${loading ? 1 : 0};
            `}
          >
            <SnippetRoundNode/>
          </div>
        ) : (
          ''
        )}
        <slot></slot>
      </div>,
      $
    );
  }
});

function mapper<P>(key: keyof P, value: any) {
  if (key === 'loading') {
    value = typeof value === 'string' ? true : Boolean(value);
  }

  return setProp.apply(this, [key, value]);
}


text:
import setup
import time
import sys
import glob
import errorhandling

def serial_ports():
    """Lists serial ports

    :raises EnvironmentError:
        On unsupported or unknown platforms
    :returns:
        A list of available serial ports
    """
    if sys.platform.startswith('win'):
        ports = ['COM' + str(i + 1) for i in range(256)]

    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this is to exclude your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*')

    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')

    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result

def make_recipe(drink_order):
    try:
        arduino = serial.Serial(serial_ports()[0], 9600, timeout=1)
    except IndexError:
        errorhandling.create_error_popup('No Arduino Detected')
        return

    arduino.setDTR(level=False)

    try:
        arduino.open()
    except serial.serialutil.SerialException:
        arduino.close()
        arduino.open()

    while True:
        arduinoread = arduino.readline()
        print 'Arduino: ' + arduinoread
        if 'Ready' in arduinoread:
            break;

    for ingredient in drink_order:
        ingredient_name = ingredient[1].lower()
        ingredient_amount = ingredient[0]

        setup_pos = setup.get_setup_drinks()[0]
        setup_type = setup.get_setup_drinks()[1]

        xpos = setup_pos[ingredient_name]

        print 'Moving to %s' % xpos

        arduino.write('x%s' % xpos)  # Send X axis movement command
        while True:  # Wait until x axis in position
            arduinoread = arduino.readline()
            print 'Arduino: ' + arduinoread
            if 'Moved' in arduinoread:
                break;

        if setup_type[ingredient_name] == 'spirit':

            # Spirit Behaviour

            presses = ingredient_amount / 25  # Convert ml into optic presses

            arduino.write('y\n20')  # Move Y axis up into dispense position.

            while presses > 0:
                print 'Pressing'

                arduino.write('y\n10')  # Write command to Y axis to raise
                time.sleep(2.500)  # wait for y axis to raise, dispense liquid, and stop dripping.
                arduino.write('y\n-10')
                time.sleep(1)  # Wait for y axis to retract
                presses = presses - 1

            arduino.write('y\n-20')  # Move Y axis into travelling position.

        else:

            # Mixer behaviour

            ml_per_second = 50
            solenoid_id = setup.get_solenoid(ingredient_name)  # Get reference number of solenoid valve.
            arduino.write('s\n%s' % solenoid_id)  # Cycle Solenoid Valve.
            print 'Solenoid %s Open' % solenoid_id

            delay_amount = ingredient_amount / ml_per_second

            time.sleep(delay_amount)  # Leave solenoid open for enough liquid to pass.

            arduino.write('s\n%s' % solenoid_id)  # Cycle Solenoid Valve.
            print 'Solenoid %s Closed' % solenoid_id

        time.sleep(0.5)  # Delay half a second to catch drips.

    arduino.write('x\n0')  # Return X axis to zero.


text:
/*************************************************************************/
/*  gd_mono_field.cpp                                                    */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "gd_mono_field.h"

#include <mono/metadata/attrdefs.h>

#include "gd_mono_class.h"
#include "gd_mono_marshal.h"

void GDMonoField::set_value_raw(MonoObject *p_object, void *p_ptr) {
	mono_field_set_value(p_object, mono_field, &p_ptr);
}

void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_value) {
#define SET_FROM_STRUCT(m_type)                                                               \
	{                                                                                \
		GDMonoMarshal::M_##m_type from = MARSHALLED_OUT(m_type, p_value.operator ::m_type()); \
		mono_field_set_value(p_object, mono_field, &from);                                    \
	}

#define SET_FROM_ARRAY(m_type)                                                                   \
	{                                                                                \
		MonoArray *managed = GDMonoMarshal::m_type##_to_mono_array(p_value.operator ::m_type()); \
		mono_field_set_value(p_object, mono_field, managed);                                     \
	}

	switch (type.type_encoding) {
		case MONO_TYPE_BOOLEAN: {
			MonoBoolean val = p_value.operator bool();
			mono_field_set_value(p_object, mono_field, &val);
		} break;

		case MONO_TYPE_CHAR: {
			int16_t val = p_value.operator unsigned short();
			mono_field_set_value(p_object, mono_field, &val);
		} break;

		case MONO_TYPE_I1: {
			int8_t val = p_value.operator signed char();
			mono_field_set_value(p_object, mono_field, &val);
		} break;
		case MONO_TYPE_I2: {
			int16_t val = p_value.operator signed short();
			mono_field_set_value(p_object, mono_field, &val);
		} break;
		case MONO_TYPE_I4: {
			int32_t val = p_value.operator signed int();
			mono_field_set_value(p_object, mono_field, &val);
		} break;
		case MONO_TYPE_I8: {
			int64_t val = p_value.operator int64_t();
			mono_field_set_value(p_object, mono_field, &val);
		} break;

		case MONO_TYPE_U1: {
			uint8_t val = p_value.operator unsigned char();
			mono_field_set_value(p_object, mono_field, &val);
		} break;
		case MONO_TYPE_U2: {
			uint16_t val = p_value.operator unsigned short();
			mono_field_set_value(p_object, mono_field, &val);
		} break;
		case MONO_TYPE_U4: {
			uint32_t val = p_value.operator unsigned int();
			mono_field_set_value(p_object, mono_field, &val);
		} break;
		case MONO_TYPE_U8: {
			uint64_t val = p_value.operator uint64_t();
			mono_field_set_value(p_object, mono_field, &val);
		} break;

		case MONO_TYPE_R4: {
			float val = p_value.operator float();
			mono_field_set_value(p_object, mono_field, &val);
		} break;

		case MONO_TYPE_R8: {
			double val = p_value.operator double();
			mono_field_set_value(p_object, mono_field, &val);
		} break;

		case MONO_TYPE_STRING: {
			MonoString *mono_string = GDMonoMarshal::mono_string_from_godot(p_value);
			mono_field_set_value(p_object, mono_field, mono_string);
		} break;

		case MONO_TYPE_VALUETYPE: {
			GDMonoClass *tclass = type.type_class;

			if (tclass == CACHED_CLASS(Vector2)) {
				SET_FROM_STRUCT(Vector2);
				break;
			}

			if (tclass == CACHED_CLASS(Rect2)) {
				SET_FROM_STRUCT(Rect2);
				break;
			}

			if (tclass == CACHED_CLASS(Transform2D)) {
				SET_FROM_STRUCT(Transform2D);
				break;
			}

			if (tclass == CACHED_CLASS(Vector3)) {
				SET_FROM_STRUCT(Vector3);
				break;
			}

			if (tclass == CACHED_CLASS(Basis)) {
				SET_FROM_STRUCT(Basis);
				break;
			}

			if (tclass == CACHED_CLASS(Quat)) {
				SET_FROM_STRUCT(Quat);
				break;
			}

			if (tclass == CACHED_CLASS(Transform)) {
				SET_FROM_STRUCT(Transform);
				break;
			}

			if (tclass == CACHED_CLASS(AABB)) {
				SET_FROM_STRUCT(AABB);
				break;
			}

			if (tclass == CACHED_CLASS(Color)) {
				SET_FROM_STRUCT(Color);
				break;
			}

			if (tclass == CACHED_CLASS(Plane)) {
				SET_FROM_STRUCT(Plane);
				break;
			}

			if (mono_class_is_enum(tclass->get_mono_ptr())) {
				MonoType *enum_basetype = mono_class_enum_basetype(tclass->get_mono_ptr());
				switch (mono_type_get_type(enum_basetype)) {
					case MONO_TYPE_BOOLEAN: {
						MonoBoolean val = p_value.operator bool();
						mono_field_set_value(p_object, mono_field, &val);
						break;
					}
					case MONO_TYPE_CHAR: {
						uint16_t val = p_value.operator unsigned short();
						mono_field_set_value(p_object, mono_field, &val);
						break;
					}
					case MONO_TYPE_I1: {
						int8_t val = p_value.operator signed char();
						mono_field_set_value(p_object, mono_field, &val);
						break;
					}
					case MONO_TYPE_I2: {
						int16_t val = p_value.operator signed short();
						mono_field_set_value(p_object, mono_field, &val);
						break;
					}
					case MONO_TYPE_I4: {
						int32_t val = p_value.operator signed int();
						mono_field_set_value(p_object, mono_field, &val);
						break;
					}
					case MONO_TYPE_I8: {
						int64_t val = p_value.operator int64_t();
						mono_field_set_value(p_object, mono_field, &val);
						break;
					}
					case MONO_TYPE_U1: {
						uint8_t val = p_value.operator unsigned char();
						mono_field_set_value(p_object, mono_field, &val);
						break;
					}
					case MONO_TYPE_U2: {
						uint16_t val = p_value.operator unsigned short();
						mono_field_set_value(p_object, mono_field, &val);
						break;
					}
					case MONO_TYPE_U4: {
						uint32_t val = p_value.operator unsigned int();
						mono_field_set_value(p_object, mono_field, &val);
						break;
					}
					case MONO_TYPE_U8: {
						uint64_t val = p_value.operator uint64_t();
						mono_field_set_value(p_object, mono_field, &val);
						break;
					}
					default: {
						ERR_EXPLAIN(String() + "Attempted to convert Variant to a managed enum value of unmarshallable base type.");
						ERR_FAIL();
					}
				}

				break;
			}

			ERR_EXPLAIN(String() + "Attempted to set the value of a field of unmarshallable type: " + tclass->get_name());
			ERR_FAIL();
		} break;

		case MONO_TYPE_ARRAY:
		case MONO_TYPE_SZARRAY: {
			MonoArrayType *array_type = mono_type_get_array_type(type.type_class->get_mono_type());

			if (array_type->eklass == CACHED_CLASS_RAW(MonoObject)) {
				SET_FROM_ARRAY(Array);
				break;
			}

			if (array_type->eklass == CACHED_CLASS_RAW(uint8_t)) {
				SET_FROM_ARRAY(PoolByteArray);
				break;
			}

			if (array_type->eklass == CACHED_CLASS_RAW(int32_t)) {
				SET_FROM_ARRAY(PoolIntArray);
				break;
			}

			if (array_type->eklass == REAL_T_MONOCLASS) {
				SET_FROM_ARRAY(PoolRealArray);
				break;
			}

			if (array_type->eklass == CACHED_CLASS_RAW(String)) {
				SET_FROM_ARRAY(PoolStringArray);
				break;
			}

			if (array_type->eklass == CACHED_CLASS_RAW(Vector2)) {
				SET_FROM_ARRAY(PoolVector2Array);
				break;
			}

			if (array_type->eklass == CACHED_CLASS_RAW(Vector3)) {
				SET_FROM_ARRAY(PoolVector3Array);
				break;
			}

			if (array_type->eklass == CACHED_CLASS_RAW(Color)) {
				SET_FROM_ARRAY(PoolColorArray);
				break;
			}

			ERR_EXPLAIN(String() + "Attempted to convert Variant to a managed array of unmarshallable element type.");
			ERR_FAIL();
		} break;

		case MONO_TYPE_CLASS: {
			GDMonoClass *type_class = type.type_class;

			// GodotObject
			if (CACHED_CLASS(GodotObject)->is_assignable_from(type_class)) {
				MonoObject *managed = GDMonoUtils::unmanaged_get_managed(p_value.operator Object *());
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			if (CACHED_CLASS(NodePath) == type_class) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator NodePath());
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			if (CACHED_CLASS(RID) == type_class) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator RID());
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			if (CACHED_CLASS(Dictionary) == type_class) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), CACHED_CLASS(Dictionary));
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			if (CACHED_CLASS(Array) == type_class) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array));
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			// The order in which we check the following interfaces is very important (dictionaries and generics first)

			MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type_class->get_mono_type());

			MonoReflectionType *key_reftype, *value_reftype;
			if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype, &key_reftype, &value_reftype)) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(),
						GDMonoUtils::Marshal::make_generic_dictionary_type(key_reftype, value_reftype));
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			if (type_class->implements_interface(CACHED_CLASS(System_Collections_IDictionary))) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), CACHED_CLASS(Dictionary));
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			MonoReflectionType *elem_reftype;
			if (GDMonoUtils::Marshal::generic_ienumerable_is_assignable_from(reftype, &elem_reftype)) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(),
						GDMonoUtils::Marshal::make_generic_array_type(elem_reftype));
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			if (type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) {
				if (GDMonoUtils::tools_godot_api_check()) {
					MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array));
					mono_field_set_value(p_object, mono_field, managed);
					break;
				} else {
					MonoObject *managed = (MonoObject *)GDMonoMarshal::Array_to_mono_array(p_value.operator Array());
					mono_field_set_value(p_object, mono_field, managed);
					break;
				}
			}

			ERR_EXPLAIN(String() + "Attempted to set the value of a field of unmarshallable type: " + type_class->get_name());
			ERR_FAIL();
		} break;

		case MONO_TYPE_OBJECT: {
			// Variant
			switch (p_value.get_type()) {
				case Variant::BOOL: {
					MonoBoolean val = p_value.operator bool();
					mono_field_set_value(p_object, mono_field, &val);
				} break;
				case Variant::INT: {
					int32_t val = p_value.operator signed int();
					mono_field_set_value(p_object, mono_field, &val);
				} break;
				case Variant::REAL: {
#ifdef REAL_T_IS_DOUBLE
					double val = p_value.operator double();
					mono_field_set_value(p_object, mono_field, &val);
#else
					float val = p_value.operator float();
					mono_field_set_value(p_object, mono_field, &val);
#endif
				} break;
				case Variant::STRING: {
					MonoString *mono_string = GDMonoMarshal::mono_string_from_godot(p_value);
					mono_field_set_value(p_object, mono_field, mono_string);
				} break;
				case Variant::VECTOR2: {
					SET_FROM_STRUCT(Vector2);
				} break;
				case Variant::RECT2: {
					SET_FROM_STRUCT(Rect2);
				} break;
				case Variant::VECTOR3: {
					SET_FROM_STRUCT(Vector3);
				} break;
				case Variant::TRANSFORM2D: {
					SET_FROM_STRUCT(Transform2D);
				} break;
				case Variant::PLANE: {
					SET_FROM_STRUCT(Plane);
				} break;
				case Variant::QUAT: {
					SET_FROM_STRUCT(Quat);
				} break;
				case Variant::AABB: {
					SET_FROM_STRUCT(AABB);
				} break;
				case Variant::BASIS: {
					SET_FROM_STRUCT(Basis);
				} break;
				case Variant::TRANSFORM: {
					SET_FROM_STRUCT(Transform);
				} break;
				case Variant::COLOR: {
					SET_FROM_STRUCT(Color);
				} break;
				case Variant::NODE_PATH: {
					MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator NodePath());
					mono_field_set_value(p_object, mono_field, managed);
				} break;
				case Variant::_RID: {
					MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator RID());
					mono_field_set_value(p_object, mono_field, managed);
				} break;
				case Variant::OBJECT: {
					MonoObject *managed = GDMonoUtils::unmanaged_get_managed(p_value.operator Object *());
					mono_field_set_value(p_object, mono_field, managed);
					break;
				}
				case Variant::DICTIONARY: {
					MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), CACHED_CLASS(Dictionary));
					mono_field_set_value(p_object, mono_field, managed);
				} break;
				case Variant::ARRAY: {
					MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array));
					mono_field_set_value(p_object, mono_field, managed);
				} break;
				case Variant::POOL_BYTE_ARRAY: {
					SET_FROM_ARRAY(PoolByteArray);
				} break;
				case Variant::POOL_INT_ARRAY: {
					SET_FROM_ARRAY(PoolIntArray);
				} break;
				case Variant::POOL_REAL_ARRAY: {
					SET_FROM_ARRAY(PoolRealArray);
				} break;
				case Variant::POOL_STRING_ARRAY: {
					SET_FROM_ARRAY(PoolStringArray);
				} break;
				case Variant::POOL_VECTOR2_ARRAY: {
					SET_FROM_ARRAY(PoolVector2Array);
				} break;
				case Variant::POOL_VECTOR3_ARRAY: {
					SET_FROM_ARRAY(PoolVector3Array);
				} break;
				case Variant::POOL_COLOR_ARRAY: {
					SET_FROM_ARRAY(PoolColorArray);
				} break;
				default: break;
			}
		} break;

		case MONO_TYPE_GENERICINST: {
			MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type.type_class->get_mono_type());

			if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), type.type_class);
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), type.type_class);
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			// The order in which we check the following interfaces is very important (dictionaries and generics first)

			MonoReflectionType *key_reftype, *value_reftype;
			if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype, &key_reftype, &value_reftype)) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(),
						GDMonoUtils::Marshal::make_generic_dictionary_type(key_reftype, value_reftype));
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			if (type.type_class->implements_interface(CACHED_CLASS(System_Collections_IDictionary))) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), CACHED_CLASS(Dictionary));
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			MonoReflectionType *elem_reftype;
			if (GDMonoUtils::Marshal::generic_ienumerable_is_assignable_from(reftype, &elem_reftype)) {
				MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(),
						GDMonoUtils::Marshal::make_generic_array_type(elem_reftype));
				mono_field_set_value(p_object, mono_field, managed);
				break;
			}

			if (type.type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) {
				if (GDMonoUtils::tools_godot_api_check()) {
					MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array));
					mono_field_set_value(p_object, mono_field, managed);
					break;
				} else {
					MonoObject *managed = (MonoObject *)GDMonoMarshal::Array_to_mono_array(p_value.operator Array());
					mono_field_set_value(p_object, mono_field, managed);
					break;
				}
			}
		} break;

		default: {
			ERR_PRINTS(String() + "Attempted to set the value of a field of unexpected type encoding: " + itos(type.type_encoding));
		} break;
	}

#undef SET_FROM_ARRAY_AND_BREAK
#undef SET_FROM_STRUCT_AND_BREAK
}

MonoObject *GDMonoField::get_value(MonoObject *p_object) {
	return mono_field_get_value_object(mono_domain_get(), mono_field, p_object);
}

bool GDMonoField::get_bool_value(MonoObject *p_object) {
	return (bool)GDMonoMarshal::unbox<MonoBoolean>(get_value(p_object));
}

int GDMonoField::get_int_value(MonoObject *p_object) {
	return GDMonoMarshal::unbox<int32_t>(get_value(p_object));
}

String GDMonoField::get_string_value(MonoObject *p_object) {
	MonoObject *val = get_value(p_object);
	return GDMonoMarshal::mono_string_to_godot((MonoString *)val);
}

bool GDMonoField::has_attribute(GDMonoClass *p_attr_class) {
	ERR_FAIL_NULL_V(p_attr_class, false);

	if (!attrs_fetched)
		fetch_attributes();

	if (!attributes)
		return false;

	return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr());
}

MonoObject *GDMonoField::get_attribute(GDMonoClass *p_attr_class) {
	ERR_FAIL_NULL_V(p_attr_class, NULL);

	if (!attrs_fetched)
		fetch_attributes();

	if (!attributes)
		return NULL;

	return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr());
}

void GDMonoField::fetch_attributes() {
	ERR_FAIL_COND(attributes != NULL);
	attributes = mono_custom_attrs_from_field(owner->get_mono_ptr(), mono_field);
	attrs_fetched = true;
}

bool GDMonoField::is_static() {
	return mono_field_get_flags(mono_field) & MONO_FIELD_ATTR_STATIC;
}

IMonoClassMember::Visibility GDMonoField::get_visibility() {
	switch (mono_field_get_flags(mono_field) & MONO_FIELD_ATTR_FIELD_ACCESS_MASK) {
		case MONO_FIELD_ATTR_PRIVATE:
			return IMonoClassMember::PRIVATE;
		case MONO_FIELD_ATTR_FAM_AND_ASSEM:
			return IMonoClassMember::PROTECTED_AND_INTERNAL;
		case MONO_FIELD_ATTR_ASSEMBLY:
			return IMonoClassMember::INTERNAL;
		case MONO_FIELD_ATTR_FAMILY:
			return IMonoClassMember::PROTECTED;
		case MONO_FIELD_ATTR_PUBLIC:
			return IMonoClassMember::PUBLIC;
		default:
			ERR_FAIL_V(IMonoClassMember::PRIVATE);
	}
}

GDMonoField::GDMonoField(MonoClassField *p_mono_field, GDMonoClass *p_owner) {
	owner = p_owner;
	mono_field = p_mono_field;
	name = mono_field_get_name(mono_field);
	MonoType *field_type = mono_field_get_type(mono_field);
	type.type_encoding = mono_type_get_type(field_type);
	MonoClass *field_type_class = mono_class_from_mono_type(field_type);
	type.type_class = GDMono::get_singleton()->get_class(field_type_class);

	attrs_fetched = false;
	attributes = NULL;
}

GDMonoField::~GDMonoField() {
	if (attributes) {
		mono_custom_attrs_free(attributes);
	}
}


text:
package it.f2informatica.pagination.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.NoRepositoryBean;

import java.io.Serializable;

/**
 *
Extend this repository in order to use the server-side pagination.

 *

 * This interface works with {@link org.springframework.data.jpa.domain.Specification}
 * and {@link QueryDslPredicateExecutor} of QueryDsl.
 *

 *
 * @param <T>  Entity Type
 * @param <ID> ID - PK Type
 * @author Fernando Aspiazu
 */
@NoRepositoryBean
public interface PaginationRepository<T, ID extends Serializable>
	extends JpaRepository<T, ID>, JpaSpecificationExecutor<T>, QueryDslPredicateExecutor<T> {

}


text:
/*
 * Base structure
 */

.img100 {
  width: 100%;

  z-index: 0;
}

.imgSmall {
  width: 100px;
  height: 100px;
  position: relative;
  margin-top:-60px;
  padding: 0;
}

.inline-Buell li {
  display: inline-block;
}

.onehundred {
  width: 100%;
}

.cookieItem {
  width: 200px;
  height: auto;
}

table.center {
  margin-left: auto;
  margin-right: auto;
}
.thumbnailBuell {
display: inline-table;
margin-right: auto;
margin-right: auto;
padding: 10px;
max-width: 200px;
min-width: 200px;
min-height: 290px;
margin-bottom: 20px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: border .2s ease-in-out;

}

ul.evenMargin {
  margin-left: 3%;
  margin-right: 1%;
  padding: 1px;
}

.thumbnailBuell img {
width: 100%;

}

img.displayed {
    display: block;
    margin-left: 38px;
    margin-right: auto; }

.pUnderImg {
  display: inline-block;
  margin: .5em;
  padding: 0px;
  font-size: 1.4em;
}

.sub-header {
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

/*
 * Top navigation
 * Hide default border to remove 1px line.
 */
.navbar-fixed-top {
  border: 0;
}

/*
 * Sidebar
 */

/* Hide for mobile, show later */
.sidebar {
  display: none;
}
@media (min-width: 768px) {
  .sidebar {
    position: fixed;
    top: 51px;
    bottom: 0;
    left: 0;
    z-index: 1000;
    display: block;
    padding: 20px;
    overflow-x: hidden;
    overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
    background-color: #f5f5f5;
    border-right: 1px solid #eee;
  }
}

/* Sidebar navigation */
.nav-sidebar {
  margin-right: -21px; /* 20px padding + 1px border */
  margin-bottom: 20px;
  margin-left: -20px;
}
.nav-sidebar > li > a {
  padding-right: 20px;
  padding-left: 20px;
}
.nav-sidebar > .active > a,
.nav-sidebar > .active > a:hover,
.nav-sidebar > .active > a:focus {
  color: #fff;
  background-color: #428bca;
}

/*
 * Placeholder dashboard ideas
 */

.placeholders {
  margin-bottom: 30px;
  text-align: center;
}
.placeholders h4 {
  margin-bottom: 0;
}
.placeholder {
  margin-bottom: 20px;
}
.placeholder img {
  display: inline-block;
  border-radius: 50%;
}


text:
var index = 0;
var books = Alloy.createCollection("book");
// carica la collezione dalla memoria (database)
books.fetch();

function save(e) {

	// Crea un modello di tipo 'book'
	var book = Alloy.createModel('book', {
		title : $.title.value,
		author : $.author.value,
		isbn : $.isbn.value
	});

	if (!book.isValid())
	{
		alert("titolo o autore mancanti");
		return;
	}

	// aggiungi un modello alla collezione
	books.add(book);

	// salva il modello
	book.save();
	index++;

	$.title.value = "";
	$.author.value = "";
	$.isbn.value = "";

	alert("inserimento completato");

}

function prev() {
	index--;
	if (index <= 0) {
		index = 0;
	}
	showModel(index);
}

function next() {
	index++;
	if (index >= books.length) {
		index = books.length - 1;
	}
	showModel(index);
}

function showModel(index) {

	var model = books.at(index);
	displayModel(model);
}

function showModelWithID(id) {

	var model = books.get(id);
	displayModel(model);
}

function displayModel(model) {
	Ti.API.info(JSON.stringify(model));

	$.title.value = model.get("title") || "";
	$.author.value = model.get("author") || "";
	$.isbn.value = model.get("isbn") || "";
}

function list() {
	var list = Alloy.createController('list', {
		onRowClickCallback : showModelWithID
	}).getView();
	list.open();
}

$.index.open();


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using VisaCheckout.VisaHelper.Options;

namespace VisaCheckout.Tests
{
    [TestClass]
    public class ShippingOptionsTests
    {
        [TestMethod]
        public void GetHtmlTest()
        {
            IOptions options = new ShippingOptions();

            string result = options.GetOptionString();

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Contains("\"shipping\":{"));
        }

        [TestMethod]
        public void GetHtmlWithOptionsTest()
        {
            IOptions options = new ShippingOptions
            {
                AcceptedRegions = new List<string>() { "US" },
                CollectShipping = true
            };

            string result = options.GetOptionString();

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Contains("\"shipping\":{"));
            Assert.IsTrue(result.Contains("\"acceptedRegions\":[\"US\"]"));
            Assert.IsTrue(result.Contains("\"collectShipping\":\"true\""));
        }

        [TestInitialize]
        public void TestInitialize()
        {
            VisaCheckout.VisaHelper.Environment.IsSandbox = false;
        }
    }
}


text:
#ifndef _DATE_H_
#define _DATE_H_
//start
class Date {
public:
    Date(int d = 0, int m = 0, int y = 0);

    /** @param eoln if true, output end of line
        character after the date.
    */
    void display(bool eoln = true) const;
//end

//start
private:
    int m_Day, m_Month, m_Year;
};
//end
#endif


text:
import Ember from 'ember';

export default Ember.Route.extend({
  meta: Ember.inject.service(),
  setupController(controller, model) {
    this._super(controller, model);
    this.set('meta.title', 'Quizzes from Wordset');
  },
  model() {
    return this.store.find('quiz');
  },
});


text:
import time
from datetime import datetime, timedelta
from settings import UR

class Scheduler:
    """
    Execute job on schedule.

    Keeps per-hour schedule constant.
    E.g. if job is set to run every 20 minutes, it will always be
    executed at HH:00, HH:20 and HH:40.
    """

    def __init__(self, period, job):
        period_minutes = period.m_as('min')
        if not isinstance(period_minutes, int):
            raise Exception('Period must be an integer')
        if period_minutes == 0:
            raise Exception('Period must be greater than zero')
        if 60 % period_minutes != 0:
            raise Exception('Period must be a divider of 60')

        self.period_minutes = period_minutes
        self.job = job

    @staticmethod
    def round_int(value, base):
        return int(value) - int(value) % int(base)

    def round_date(self, date):
        minute = self.round_int(date.minute, self.period_minutes)
        return date.replace(minute=minute, second=0)

    def next_run(self, last_run):
        return self.round_date(last_run) + timedelta(minutes=self.period_minutes)

    def run(self):
        next_run = self.next_run(datetime.utcnow())
        while True:
            now = datetime.utcnow()
            if now > next_run:
                next_run = self.next_run(now)
                self.job()
            time.sleep(1)

def main():
    s = Scheduler(3 * UR.min, None)

    last_run = datetime.now()
    for n in range(1, 3600):
        next_run = s.next_run(last_run)
        print('%s %s' % (last_run.strftime('%H:%M:%S'), next_run.strftime('%H:%M:%S')))
        last_run += timedelta(seconds=1)

if __name__ == '__main__':
    main()


text:
define(['lodash'], function(_){
    tagUtils = function () {
        this.fetchVMIDetails =  function (dataItems, listModel) {
            var vmiIdList = [],
                ajaxConfig = {}, tagVmiListMap = {};
            _.forEach(dataItems, function(data) {
                var currentTagVmis =
                    _.map(_.get(data, 'virtual_machine_interface_back_refs', []),'uuid');
                vmiIdList = vmiIdList.concat(currentTagVmis);
            });
            vmiIdList = _.uniq(vmiIdList);
            if(vmiIdList.length === 0) {
                return dataItems;
            }
            ajaxConfig.type = 'POST';
            ajaxConfig.url = ctwc.URL_GET_PORT;
            ajaxConfig.data = JSON.stringify({type: "virtual-machine-interfaces",
                uuidList: vmiIdList})
            contrail.ajaxHandler(ajaxConfig, null,
                function (vmiDetails) {
                _.forEach(vmiDetails, function (vmiData) {
                    var vmi =
                        _.get(vmiData, 'virtual-machine-interface', {}),
                        tags = _.get(vmi, 'tag_refs', []);
                    _.forEach(tags, function (tag) {
                        var tagId = _.get(tag, 'uuid', '');
                        if(!(tagVmiListMap[tagId] instanceof Array)) {
                            tagVmiListMap[tagId] = [];
                        }
                        tagVmiListMap[tagId].push(vmi);
                    });
                });
                //update vmi details in tag object
                _.forEach(dataItems, function (tagDetails) {
                    tagDetails.virtual_machine_interface_back_refs =
                        tagVmiListMap[tagDetails.uuid];
                });
                listModel.setData(dataItems);

            },  function (error) {
                listModel.setData(dataItems);
            });
            return [];
        };
    };
    return new tagUtils();
});