text:
#ifndef SRC_TRACE_PROCESSOR_IMPORTERS_COMMON_CLOCK_TRACKER_H_
#define SRC_TRACE_PROCESSOR_IMPORTERS_COMMON_CLOCK_TRACKER_H_

#include <stdint.h>

#include <array>
#include <cinttypes>
#include <map>
#include <random>
#include <set>
#include <vector>

#include "perfetto/base/logging.h"
#include "perfetto/ext/base/optional.h"
#include "perfetto/ext/base/string_utils.h"
#include "src/trace_processor/storage/trace_storage.h"

namespace perfetto {
namespace trace_processor {

class TraceProcessorContext;

// This class handles synchronization of timestamps across different clock
// domains. This includes multi-hop conversions from two clocks A and D, e.g.
// A->B -> B->C -> C->D, even if we never saw a snapshot that contains A and D
// at the same time.
// The API is fairly simple (but the inner operation is not):
// - AddSnapshot(map<clock_id, timestamp>): pushes a set of clocks that have
//   been snapshotted at the same time (within technical limits).
// - Convert(src_clock_id, src_timestamp, target_clock_id):
//   converts a timestamp between two clock domains.
//
// Concepts:
// - Snapshot hash:
//   As new snapshots are pushed via AddSnapshot() we compute a snapshot hash.
//   Such hash is the hash(clock_ids) (only IDs, not their timestamps) and is
//   used to find other snapshots that involve the same clock domains.
//   Two clock snapshots have the same hash iff they snapshot the same set of
//   clocks (the order of clocks is irrelevant).
//   This hash is used to efficiently go from the clock graph pathfinder to the
//   time-series obtained by appending the various snapshots.
// - Snapshot id:
//   A simple monotonic counter that is incremented on each AddSnapshot() call.
//
// Data structures:
//  - For each clock domain:
//    - For each snapshot hash:
//      - A logic vector of (snapshot_id, timestamp) tuples (physically stored
//        as two vectors of the same length instead of a vector of pairs).
// This allows to efficiently binary search timestamps within a clock domain
// that were obtained through a particular snapshot.
//
// - A graph of edges (source_clock, target_clock) -> snapshot hash.
//
// Operation:
// Upon each AddSnapshot() call, we incrementally build an unweighted, directed
// graph, which has clock domains as nodes.
// The graph is timestamp-oblivious. As long as we see one snapshot that
// connects two clocks, we assume we'll always be able to convert between them.
// This graph is queried by the Convert() function to figure out the shortest
// path between clock domain, possibly involving hopping through snapshots of
// different type (i.e. different hash).
//
// Example:

// We see a snapshot, with hash S1, for clocks (A,B,C). We build the edges in
// the graph: A->B, B->C, A->C (and the symmetrical ones). In other words we
// keep track of the fact that we can convert between any of them using S1.
// Later we get another snapshot containing (C,E), this snapshot will have a
// different hash (S2, because Hash(C,E) != Hash(A,B,C)) and will add the edges
// C->E, E->C [via S2] to the graph.
// At this point when we are asked to convert a timestamp from A to E, or
// viceversa, we use a simple BFS to figure out a conversion path that is:
// A->C [via S1] + C->E [via S2].
//
// Visually:
// Assume we make the following calls:
//  - AddSnapshot(A:10, B:100)
//  - AddSnapshot(A:20, C:2000)
//  - AddSnapshot(B:400, C:5000)
//  - AddSnapshot(A:30, B:300)

// And assume Hash(A,B) = S1, H(A,C) = S2, H(B,C) = S3
// The vectors in the tracker will look as follows:
// Clock A:
//   S1        {t:10, id:1}                                      {t:30, id:4}
//   S2        |               {t:20, id:2}                      |
//             |               |                                 |
// Clock B:    |               |                                 |
//   S1        {t:100, id:1}   |                                 {t:300, id:4}
//   S3                        |                  {t:400, id:3}
//                             |                  |
// Clock C:                    |                  |
//   S2                        {t: 2000, id: 2}   |
//   S3                                           {t:5000, id:3}

class ClockTracker {
 public:
  using ClockId = uint64_t;

  // IDs in the range [64, 128) are reserved for sequence-scoped clock ids.
  // They can't be passed directly in ClockTracker calls and must be resolved
  // to 64-bit global clock ids by calling SeqScopedClockIdToGlobal().
  static bool IsReservedSeqScopedClockId(ClockId clock_id) {
    return clock_id >= 64 && clock_id < 128;
  }

  // Converts a sequence-scoped clock ids to a global clock id that can be
  // passed as argument to ClockTracker functions.
  static ClockId SeqScopedClockIdToGlobal(uint32_t seq_id, uint32_t clock_id) {
    PERFETTO_DCHECK(IsReservedSeqScopedClockId(clock_id));
    return (static_cast<uint64_t>(seq_id) << 32) | clock_id;
  }

  // Returns whether |global_clock_id| represents a sequence-scoped clock, i.e.
  // a ClockId returned by SeqScopedClockIdToGlobal().
  static bool ClockIsSeqScoped(ClockId global_clock_id) {
    // If the id is > 2**32, this is a sequence-scoped clock id translated into
    // the global namespace.
    return (global_clock_id >> 32) > 0;
  }

  explicit ClockTracker(TraceStorage*);
  virtual ~ClockTracker();

  // Clock description and its value in a snapshot.
  struct ClockValue {
    ClockValue(ClockId id, int64_t ts) : clock_id(id), absolute_timestamp(ts) {}
    ClockValue(ClockId id, int64_t ts, int64_t unit, bool incremental)
        : clock_id(id),
          absolute_timestamp(ts),
          unit_multiplier_ns(unit),
          is_incremental(incremental) {}

    ClockId clock_id;
    int64_t absolute_timestamp;
    int64_t unit_multiplier_ns = 1;
    bool is_incremental = false;
  };

  // Appends a new snapshot for the given clock domains.
  // This is typically called by the code that reads the ClockSnapshot packet.
  // Returns the internal snapshot id of this set of clocks.
  uint32_t AddSnapshot(const std::vector<ClockValue>&);

  // Converts a timestamp between two clock domains. Tries to use the cache
  // first (only for single-path resolutions), then falls back on path finding
  // as described in the header.
  base::Optional<int64_t> Convert(ClockId src_clock_id,
                                  int64_t src_timestamp,
                                  ClockId target_clock_id) {
    if (PERFETTO_LIKELY(!cache_lookups_disabled_for_testing_)) {
      for (const auto& ce : cache_) {
        if (ce.src != src_clock_id || ce.target != target_clock_id)
          continue;
        int64_t ns = ce.src_domain->ToNs(src_timestamp);
        if (ns >= ce.min_ts_ns && ns < ce.max_ts_ns)
          return ns + ce.translation_ns;
      }
    }
    return ConvertSlowpath(src_clock_id, src_timestamp, target_clock_id);
  }

  base::Optional<int64_t> ConvertSlowpath(ClockId src_clock_id,
                                          int64_t src_timestamp,
                                          ClockId target_clock_id);

  base::Optional<int64_t> ToTraceTime(ClockId clock_id, int64_t timestamp) {
    trace_time_clock_id_used_for_conversion_ = true;
    if (clock_id == trace_time_clock_id_)
      return timestamp;
    return Convert(clock_id, timestamp, trace_time_clock_id_);
  }

  base::Optional<int64_t> FromTraceTime(ClockId to_clock_id,
                                        int64_t timestamp) {
    trace_time_clock_id_used_for_conversion_ = true;
    if (to_clock_id == trace_time_clock_id_)
      return timestamp;
    return Convert(trace_time_clock_id_, timestamp, to_clock_id);
  }

  base::Optional<std::string> FromTraceTimeAsISO8601(int64_t timestamp);

  void SetTraceTimeClock(ClockId clock_id) {
    PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));
    if (trace_time_clock_id_used_for_conversion_ &&
        trace_time_clock_id_ != clock_id) {
      PERFETTO_ELOG("Not updating trace time clock from %" PRIu64 " to %" PRIu64
                    " because the old clock was already used for timestamp "
                    "conversion - ClockSnapshot too late in trace?",
                    trace_time_clock_id_, clock_id);
      return;
    }
    trace_time_clock_id_ = clock_id;
  }

  void set_cache_lookups_disabled_for_testing(bool v) {
    cache_lookups_disabled_for_testing_ = v;
  }

 private:
  using SnapshotHash = uint32_t;

  // 0th argument is the source clock, 1st argument is the target clock.
  using ClockGraphEdge = std::tuple<ClockId, ClockId, SnapshotHash>;

  // A value-type object that carries the information about the path between
  // two clock domains. It's used by the BFS algorithm.
  struct ClockPath {
    static constexpr size_t kMaxLen = 4;
    ClockPath() = default;
    ClockPath(const ClockPath&) = default;

    // Constructs an invalid path with just a source node.
    explicit ClockPath(ClockId clock_id) : last(clock_id) {}

    // Constructs a path by appending a node to |prefix|.
    // If |prefix| = [A,B] and clock_id = C, then |this| = [A,B,C].
    ClockPath(const ClockPath& prefix, ClockId clock_id, SnapshotHash hash) {
      PERFETTO_DCHECK(prefix.len < kMaxLen);
      len = prefix.len + 1;
      path = prefix.path;
      path[prefix.len] = ClockGraphEdge{prefix.last, clock_id, hash};
      last = clock_id;
    }

    bool valid() const { return len > 0; }
    const ClockGraphEdge& at(uint32_t i) const {
      PERFETTO_DCHECK(i < len);
      return path[i];
    }

    uint32_t len = 0;
    ClockId last = 0;
    std::array<ClockGraphEdge, kMaxLen> path;  // Deliberately uninitialized.
  };

  struct ClockSnapshots {
    // Invariant: both vectors have the same length.
    std::vector<uint32_t> snapshot_ids;
    std::vector<int64_t> timestamps_ns;
  };

  struct ClockDomain {
    // One time-series for each hash.
    std::map<SnapshotHash, ClockSnapshots> snapshots;

    // Multiplier for timestamps given in this domain.
    int64_t unit_multiplier_ns = 1;

    // Whether this clock domain encodes timestamps as deltas. This is only
    // supported on sequence-local domains.
    bool is_incremental = false;

    // If |is_incremental| is true, this stores the most recent absolute
    // timestamp in nanoseconds.
    int64_t last_timestamp_ns = 0;

    // Treats |timestamp| as delta timestamp if the clock uses incremental
    // encoding, and as absolute timestamp otherwise.
    int64_t ToNs(int64_t timestamp) {
      if (!is_incremental)
        return timestamp * unit_multiplier_ns;

      int64_t delta_ns = timestamp * unit_multiplier_ns;
      last_timestamp_ns += delta_ns;
      return last_timestamp_ns;
    }

    const ClockSnapshots& GetSnapshot(uint32_t hash) const {
      auto it = snapshots.find(hash);
      PERFETTO_DCHECK(it != snapshots.end());
      return it->second;
    }
  };

  // Holds data for cached entries. At the moment only single-path resolution
  // are cached.
  struct CachedClockPath {
    ClockId src;
    ClockId target;
    ClockDomain* src_domain;
    int64_t min_ts_ns;
    int64_t max_ts_ns;
    int64_t translation_ns;
  };

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

  ClockPath FindPath(ClockId src, ClockId target);

  ClockDomain* GetClock(ClockId clock_id) {
    auto it = clocks_.find(clock_id);
    PERFETTO_DCHECK(it != clocks_.end());
    return &it->second;
  }

  TraceStorage* const storage_;
  ClockId trace_time_clock_id_ = 0;
  std::map<ClockId, ClockDomain> clocks_;
  std::set<ClockGraphEdge> graph_;
  std::set<ClockId> non_monotonic_clocks_;
  std::array<CachedClockPath, 2> cache_{};
  bool cache_lookups_disabled_for_testing_ = false;
  std::minstd_rand rnd_;  // For cache eviction.
  uint32_t cur_snapshot_id_ = 0;
  bool trace_time_clock_id_used_for_conversion_ = false;
};

}  // namespace trace_processor
}  // namespace perfetto

#endif  // SRC_TRACE_PROCESSOR_IMPORTERS_COMMON_CLOCK_TRACKER_H_

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>CoffeeDigg Comment System</title>

        <link type="text/css" rel="stylesheet" href="css/style.css">
        <link type="text/css" rel="stylesheet" href="css/example.css">

<?php
// Connect to the database
include('config.php');
$id_post = "1"; //the post or the page id
?>

    <?php
    $sql = mysql_query("SELECT * FROM comment WHERE id_post = '$id_post'") or die(mysql_error());;
    while($affcom = mysql_fetch_assoc($sql)){
        $name = $affcom['name'];
        $email = $affcom['email'];
        $comment = $affcom['comment'];
        $date = $affcom['date'];

        // Get gravatar Image
        // https://fr.gravatar.com/site/implement/images/php/
        $default = "mm";
        $size = 35;
        $grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;

    ?>

        <img src="<?php echo $grav_url; ?>" />

<?php echo $name; ?>
<?php echo $date; ?>

                <?php echo $comment; ?>

    <?php } ?>

        Write a comment ...

        <input type="text" id="name-com" name="name-com" value="" placeholder="Your name" />
        <input type="text" id="mail-com" name="mail-com" value="" placeholder="Your e-mail adress" />
        <textarea class="the-new-com"></textarea>

Post comment

Cancel


text:
best practice npm TypeScript modules

## Availabililty

[![npm](https://gitzone.gitlab.io/assets/repo-button-npm.svg)](https://www.npmjs.com/package/@gitzone/npmts)
[![git](https://gitzone.gitlab.io/assets/repo-button-git.svg)](https://GitLab.com/gitzone/npmts)
[![git](https://gitzone.gitlab.io/assets/repo-button-mirror.svg)](https://github.com/gitzone/npmts)
[![docs](https://gitzone.gitlab.io/assets/repo-button-docs.svg)](https://gitzone.gitlab.io/npmts/)

## Status for master

[![build status](https://GitLab.com/gitzone/npmts/badges/master/build.svg)](https://GitLab.com/gitzone/npmts/commits/master)
[![coverage report](https://GitLab.com/gitzone/npmts/badges/master/coverage.svg)](https://GitLab.com/gitzone/npmts/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/@gitzone/npmts.svg)](https://www.npmjs.com/package/npmts)
[![bitHound Dependencies](https://www.bithound.io/github/gitzonetools/npmts/badges/dependencies.svg)](https://www.bithound.io/github/gitzonetools/npmts/master/dependencies/npm)
[![bitHound Code](https://www.bithound.io/github/gitzonetools/npmts/badges/code.svg)](https://www.bithound.io/github/gitzonetools/npmts)
[![Known Vulnerabilities](https://snyk.io/test/npm/@gitzone/npmts/badge.svg)]
[![TypeScript](https://img.shields.io/badge/TypeScript-2.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%206.x.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)

## Quick Demo

[![asciicast](https://asciinema.org/a/9c3assmh21i49qhe5lmi48sze.png)](https://asciinema.org/a/9c3assmh21i49qhe5lmi48sze?speed=2&t=0)

## Usage

NPMTS is your friend when writing, testing, publishing and documenting npm modules written in TypeScript.

npmts will

1.  check your dependencies and package.json (unused, missing, updates, security)
1.  transpile your code with tsc,
1.  test your code with tap (supports the fancy stuff like Promises, Generators, async/await, sourcemaps, parallel test execution in child processes)
1.  create coverage with istanbul (supports tracing of the originating TypeScript)

For more information on how tests are run check out the [tapbuffer module](https://www.npmjs.com/package/tapbuffer).

For more information about how to best write tap tests check out the [tapbundle module's linked docs](https://www.npmjs.com/package/tapbundle).

This works on your machine and in CI. There is a prebuild docker image available that includes npmts to make CI a breeze:
[hosttoday/ht-docker-node:npmts on Dockerhub](https://hub.docker.com/r/hosttoday/ht-docker-node/)

## Changelog

For breaking changes please see the [changelog](https://gitzone.gitlab.io/npmts/changelog.html).

For further information read the linked docs at the top of this README.

> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
> | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html)

[![repo-footer](https://gitzone.gitlab.io/assets/repo-footer.svg)](https://push.rocks)


text:
class CreateUsersRoles < ActiveRecord::Migration
  def change
    create_table :users_roles do |t|
      t.belongs_to :user, index: true
      t.belongs_to :role, index: true

      t.timestamps
    end
  end
end


text:
/**
 *
 */
package cn.aposoft.wechat.access;

import cn.aposoft.wechat.account.AccountId;

/**
 * 公众号访问授权码存储
 *
 * @author Jann Liu
 * @since 1.0
 */
public interface MpAccessTokenStore extends AccessToken, AccountId {

}


text:
//================================================================================
// All pages
//================================================================================

// Constants
var $HOSTNAME_PRODUCTION 	=	'www.staffdna.com';
var $STAFFDNA_PRODUCTION	=	'https://secure.staffdna.com/sd-web';
var $STAFFDNA_UAT			=	'http://uat.staffdna.com:8080/sd-web';
var $AJAX_URL				=	'';

// Setting ajax url for requests
if (window.location.hostname == $HOSTNAME_PRODUCTION) {
	$AJAX_URL = $STAFFDNA_PRODUCTION;
} else {
	$AJAX_URL = $STAFFDNA_UAT;
}

// Collapse generic
$('[data-collapse]').on('click', function() {
	var $this = $(this);
	var $target = $('#' + $this.attr('data-collapse'));

	var $icon = $this.find('i');
	var $dataChangeIcon = $icon.attr('data-change-icon');

	if ($dataChangeIcon) {
		var $originalIcons = $icon.attr('class');
		$icon.attr('class', $dataChangeIcon);
		$icon.attr('data-change-icon', $originalIcons);
	}

	$this.toggleClass('active');
	$target.toggle();
});

// Menu
$('#btn-menu').on('click', function() {
	$('.menu').toggleClass('active');
});

// Menu > Styling Login
$('.menu li:last').each(function() {
	var $this = $(this);
	var $a = $this.find('a');

	if ($a.text().toUpperCase() == "LOGIN" ) {
		$a.addClass('btn');
	}
});

// Social share links
$('[data-social]').on('click', function() {
	var $url = $(this).attr('data-social') + window.location.href;
	window.open($url, "socialWindow", "height=450,width=750");
});

// Auto resize iframe
window.addEventListener("message", function(event) {
    var iframe = document.getElementById(event.data.id)
	var newHeight = event.data.height;

	if (iframe) {
		iframe.height = parseInt(newHeight) + "px";
	} else {
		console.error("Not found element id for #"  + event.data.id);
	}
});

//================================================================================
// Home
//================================================================================
if ($('.home').length >= 1) {

	// Fetch total count from server for jobs and profiles
	function getTotalCount() {

		var $jobsUrl = $AJAX_URL + '/candidate/getProfileCountForWebsite.srvc';

		$.when( $.post($jobsUrl) ).done(function($initial) {
			var $loadingCounter = $('.loading-counter');
			var $counters = $('.counter');

			$loadingCounter.fadeOut('slow', function() {

				$counterContainer = $('.counter > span');
				$initial = parseInt($initial);

				$counterContainer.counter({
					format: '999999',
					direction: 'up',
					initial: $initial,
					stop: $initial,
					interval: 1000,
				});

				function incrementByOne() {

					$initial = parseInt($counterContainer.text());
					$randomStop = $initial + 1;

					$counterContainer.counter({
						format: '999999',
						direction: 'up',
						initial: $initial,
						stop: $randomStop,
						interval: 1000,
					});
				}

				(function loop() {
				    var rand = Math.round(Math.random() * (10000 - 3000)) + 3000;
				    setTimeout(function() {
				    	incrementByOne();
				            loop();
				    }, rand);
				}());

				$('.home #bg .active-text').hide().removeClass('hide').fadeIn('slow', function() {
					$counters.hide().removeClass('hide').fadeIn('slow');
				});

			});

		});

	}

	getTotalCount();

	// Browse Jobs > Lazy load enable custom scroll
	function enableBrowseJobsScroll(event) {
        $('#job-list:in-viewport').each(function () {

        	$(window).off('scroll', enableBrowseJobsScroll);

        	populateBrowseJob(null, null, function () {

        		/*
        		$.mCustomScrollbar.defaults.scrollButtons.enable = true; //enable scrolling buttons by default
				$.mCustomScrollbar.defaults.axis="yx"; //enable 2 axis scrollbars by default

				$("#job-list").mCustomScrollbar({
					callbacks: {
						onTotalScroll : loadMoreJobs,
				        onTotalScrollOffset:350,
					    alwaysTriggerOffsets:false
				    }
				});
				*/
			 });

        });
    }

	$(window).on('scroll', enableBrowseJobsScroll);

	// Browse Jobs > Lazy load pagination
	var $currentPage = 1;

	function loadMoreJobs() {

		var $nextPage = $currentPage + 1;

		populateBrowseJob($nextPage, null, function() {
			$currentPage++;
		});
	}

  //Browse Jobs > Populating
  function populateBrowseJob(page, rows, callback) {
  	var page = page || 1;
  	var rows = rows || 15;
  	var jobList = $("#job-list");
  	var loadingIcon = $(".home #browse_jobs .loading");

  	loadingIcon.fadeIn('slow');

	$.ajax({
		method: 'POST',
		url: $AJAX_URL + '/candidate/listJobBoardEntries.srvc?page=' + page + '&rows=' + rows + '&sidx=modifiedDate&filterRequest=0'
	  })
	.done(function( data ) {

		var keys = [];

		$.each(data.data, function(key, value) {
			var h3Class = '';
			var firstTime = (jobList.html() == "");

			if(firstTime)
				jobList.hide();

			// CSS business rule
			if (value.profession.length > 13)
				h3Class = 'bigh3';

			// Element to append
			var jobCard = '
' +
						'' +
							'
' + value.specialty + '
' +
							'
' + value.profession + '
' +
							'
' + value.zipcodeData + ', ' + value.state + '' + value.jobLength + ' week' +  ((value.jobLength > 1) ? 's' : '' ) +
							' , ' + value.employmentType.toLowerCase() + '
' +
						'' +
					'
';
			var blankJobCard = '

' ;

			// Appending
			if (key == 2) {
				jobList.append(blankJobCard);
				jobList.append(blankJobCard);
				jobList.append(jobCard);
			} else {
				var scrollContainer = jobList.find('.mCSB_container');

				if(scrollContainer.length >= 1) {
					scrollContainer.append(jobCard);
				} else {
					jobList.append(jobCard);
				}
			}

			// Showing
			if(firstTime)
				jobList.fadeIn('slow');

		});

		loadingIcon.fadeOut('slow');

		if (typeof callback === "function") {
			callback();
		}

	});

  }

  // Viewport fix
  if ($(window).width() <= 736) {
	  $('.nurse-girl').insertAfter($('#browse_jobs p:nth-child(2)'));
  };

}

//================================================================================
// Clients
//================================================================================
if ($('.clients').length >= 1) {
	$('.btn-register').on('click', function(e) {
		var $this = $(this);
		var $divIframe = '

';
		var $main = $('main[role="main"]');

		$this.off();
		$this.html(' Loading client application');
		$main.prepend($divIframe);

		$('#clients-div-iframe iframe').on('load', function() {
			var $this = $(this);
			var $mainChild = $main.find('main[role="page"]');

			$mainChild.fadeOut('slow', function () {
				$('#clients-div-iframe').fadeIn('slow', function () {
					$mainChild.remove();
				});
			});

		});

		e.preventDefault();

	});
}

//================================================================================
// Contact Us
//================================================================================
if ($('.contact-us').length >= 1) {
	var $this = $('.contact-us > main');
	var $form = $this.find('form');
	var $submitInput = $this.find('input[type="submit"]');

	$submitInput.on('click', function(e) {

		if(!$form[0].checkValidity || $form[0].checkValidity()) {
			var name = $form.find('input[type="text"]').val();
			var email = $form.find('input[type="email"]').val();
			var message = $form.find('textarea').val();

			$form.hide();

			$.post( "/send-" + "email.php", { name: name, email: email, message: message } );

			var responseMessage = '

Thank You ' + name + '

Your message was sent to our Team. ' +
									'You should receive a reply from a representative of our web site by the end of the next business day by email at ' + email + '.

'

			$form.html(responseMessage).show('slow');
			$this.off();
		}
	});
}

//================================================================================
// Blog > Single Post > Comments
//================================================================================
if ($('#respond').length >= 1) {

	function fadeInCommentForm(event) {
        $('#respond:in-viewport').each(function () {
        	$(window).off('scroll', fadeInCommentForm);
        	$(this).addClass('visible');
        	$('#comment')
        		.attr('placeholder', 'Write here');
        });
    }

	$(window).on('scroll', fadeInCommentForm);

}


text:
    (_M_IX86_FP >= 2) || defined(OZZ_SIMD_SSE2)
#include <emmintrin.h>
#define OZZ_SIMD_SSE2
#define OZZ_SIMD_SSEx  // OZZ_SIMD_SSEx is the generic flag for SSE support
#endif

// End of SIMD instruction detection
#endif  // !OZZ_BUILD_SIMD_REF

// SEE* intrinsics available
#if defined(OZZ_SIMD_SSEx)

namespace ozz {
namespace math {

// Vector of four floating point values.
typedef __m128 SimdFloat4;

// Argument type for Float4.
typedef const __m128 _SimdFloat4;

// Vector of four integer values.
typedef __m128i SimdInt4;

// Argument type for Int4.
typedef const __m128i _SimdInt4;
}  // namespace math
}  // namespace ozz

#else  // No builtin simd available

// No simd instruction set detected, switch back to reference implementation.
// OZZ_SIMD_REF is the generic flag for SIMD reference implementation.
#define OZZ_SIMD_REF

// Declares reference simd float and integer vectors outside of ozz::math, in
// order to match non-reference implementation details.

// Vector of four floating point values.
struct SimdFloat4Def {
  OZZ_ALIGN(16) float x;
  float y;
  float z;
  float w;
};

// Vector of four integer values.
struct SimdInt4Def {
  OZZ_ALIGN(16) int x;
  int y;
  int z;
  int w;
};

namespace ozz {
namespace math {

// Vector of four floating point values.
typedef SimdFloat4Def SimdFloat4;

// Argument type for SimdFloat4
typedef const SimdFloat4& _SimdFloat4;

// Vector of four integer values.
typedef SimdInt4Def SimdInt4;

// Argument type for SimdInt4.
typedef const SimdInt4& _SimdInt4;

}  // namespace math
}  // namespace ozz

#endif  // OZZ_SIMD_x
#endif  // OZZ_OZZ_BASE_MATHS_INTERNAL_SIMD_MATH_CONFIG_H_


text:
package opennlp.tools.postag;

import java.util.Arrays;

import opennlp.tools.util.SequenceValidator;

public class DefaultPOSSequenceValidator implements SequenceValidator<String> {

  private TagDictionary tagDictionary;

  public DefaultPOSSequenceValidator(TagDictionary tagDictionary) {
    this.tagDictionary = tagDictionary;
  }

  public boolean validSequence(int i, String[] inputSequence,
      String[] outcomesSequence, String outcome) {
    if (tagDictionary == null) {
      return true;
    } else {
      String[] tags = tagDictionary.getTags(inputSequence[i].toString());
      if (tags == null) {
        return true;
      } else {
        return Arrays.asList(tags).contains(outcome);
      }
    }
  }
}


text:
class RestData
  def initialize(name = 'default')
    @name = name
    @storage = {}
  end

  def add(path, message)
    @storage[path] = message
  end

  def get(path)
    return @storage[path] unless @storage[path].nil?
    file = "data/#{path}.txt"
    return File.read(file) if File.exist?(file)
    ''
  end

  def delete(path)
    @storage.delete(path)
  end
end


text:
package server

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"fmt"
	stdlog "log"
	"net"
	"net/http"
	"sync"
	"time"

	"github.com/armon/go-proxyproto"
	"github.com/containous/traefik/config/static"
	"github.com/containous/traefik/h2c"
	"github.com/containous/traefik/ip"
	"github.com/containous/traefik/log"
	"github.com/containous/traefik/middlewares"
	"github.com/containous/traefik/middlewares/forwardedheaders"
	"github.com/containous/traefik/old/configuration"
	traefiktls "github.com/containous/traefik/tls"
	"github.com/containous/traefik/tls/generate"
	"github.com/containous/traefik/types"
	"github.com/sirupsen/logrus"
	"github.com/xenolf/lego/challenge/tlsalpn01"
)

// EntryPoints map of EntryPoint
type EntryPoints map[string]*EntryPoint

// NewEntryPoint creates a new EntryPoint
func NewEntryPoint(ctx context.Context, configuration *static.EntryPoint) (*EntryPoint, error) {
	var err error

	switcher := middlewares.NewHandlerSwitcher(buildDefaultHTTPRouter())
	handler, err := forwardedheaders.NewXForwarded(
		configuration.ForwardedHeaders.Insecure,
		configuration.ForwardedHeaders.TrustedIPs,
		switcher)
	if err != nil {
		return nil, err
	}

	tracker := newHijackConnectionTracker()

	listener, err := buildListener(ctx, configuration)
	if err != nil {
		return nil, fmt.Errorf("error preparing server: %v", err)
	}

	var tlsConfig *tls.Config
	var certificateStore *traefiktls.CertificateStore
	if configuration.TLS != nil {
		certificateStore, err = buildCertificateStore(*configuration.TLS)
		if err != nil {
			return nil, fmt.Errorf("error creating certificate store: %v", err)
		}

		tlsConfig, err = buildTLSConfig(*configuration.TLS)
		if err != nil {
			return nil, fmt.Errorf("error creating TLS config: %v", err)
		}
	}

	entryPoint := &EntryPoint{
		switcher:                switcher,
		transportConfiguration:  configuration.Transport,
		hijackConnectionTracker: tracker,
		listener:                listener,
		httpServer:              buildServer(ctx, configuration, tlsConfig, handler, tracker),
		Certs:                   certificateStore,
	}

	if tlsConfig != nil {
		tlsConfig.GetCertificate = entryPoint.getCertificate
	}

	return entryPoint, nil
}

// EntryPoint holds everything about the entry point (httpServer, listener etc...)
type EntryPoint struct {
	RouteAppenderFactory    RouteAppenderFactory
	httpServer              *h2c.Server
	listener                net.Listener
	switcher                *middlewares.HandlerSwitcher
	Certs                   *traefiktls.CertificateStore
	OnDemandListener        func(string) (*tls.Certificate, error)
	TLSALPNGetter           func(string) (*tls.Certificate, error)
	hijackConnectionTracker *hijackConnectionTracker
	transportConfiguration  *static.EntryPointsTransport
}

// Start starts listening for traffic
func (s *EntryPoint) Start(ctx context.Context) {
	logger := log.FromContext(ctx)
	logger.Infof("Starting server on %s", s.httpServer.Addr)

	var err error
	if s.httpServer.TLSConfig != nil {
		err = s.httpServer.ServeTLS(s.listener, "", "")
	} else {
		err = s.httpServer.Serve(s.listener)
	}

	if err != http.ErrServerClosed {
		logger.Error("Cannot start server: %v", err)
	}
}

// Shutdown handles the entrypoint shutdown process
func (s EntryPoint) Shutdown(ctx context.Context) {
	logger := log.FromContext(ctx)

	reqAcceptGraceTimeOut := time.Duration(s.transportConfiguration.LifeCycle.RequestAcceptGraceTimeout)
	if reqAcceptGraceTimeOut > 0 {
		logger.Infof("Waiting %s for incoming requests to cease", reqAcceptGraceTimeOut)
		time.Sleep(reqAcceptGraceTimeOut)
	}

	graceTimeOut := time.Duration(s.transportConfiguration.LifeCycle.GraceTimeOut)
	ctx, cancel := context.WithTimeout(ctx, graceTimeOut)
	logger.Debugf("Waiting %s seconds before killing connections.", graceTimeOut)

	var wg sync.WaitGroup
	if s.httpServer != nil {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if err := s.httpServer.Shutdown(ctx); err != nil {
				if ctx.Err() == context.DeadlineExceeded {
					logger.Debugf("Wait server shutdown is overdue to: %s", err)
					err = s.httpServer.Close()
					if err != nil {
						logger.Error(err)
					}
				}
			}
		}()
	}

	if s.hijackConnectionTracker != nil {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if err := s.hijackConnectionTracker.Shutdown(ctx); err != nil {
				if ctx.Err() == context.DeadlineExceeded {
					logger.Debugf("Wait hijack connection is overdue to: %s", err)
					s.hijackConnectionTracker.Close()
				}
			}
		}()
	}

	wg.Wait()
	cancel()
}

// getCertificate allows to customize tlsConfig.GetCertificate behavior to get the certificates inserted dynamically
func (s *EntryPoint) getCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
	domainToCheck := types.CanonicalDomain(clientHello.ServerName)

	if s.TLSALPNGetter != nil {
		cert, err := s.TLSALPNGetter(domainToCheck)
		if err != nil {
			return nil, err
		}

		if cert != nil {
			return cert, nil
		}
	}

	bestCertificate := s.Certs.GetBestCertificate(clientHello)
	if bestCertificate != nil {
		return bestCertificate, nil
	}

	if s.OnDemandListener != nil && len(domainToCheck) > 0 {
		// Only check for an onDemandCert if there is a domain name
		return s.OnDemandListener(domainToCheck)
	}

	if s.Certs.SniStrict {
		return nil, fmt.Errorf("strict SNI enabled - No certificate found for domain: %q, closing connection", domainToCheck)
	}

	log.WithoutContext().Debugf("Serving default certificate for request: %q", domainToCheck)
	return s.Certs.DefaultCertificate, nil
}

func newHijackConnectionTracker() *hijackConnectionTracker {
	return &hijackConnectionTracker{
		conns: make(map[net.Conn]struct{}),
	}
}

type hijackConnectionTracker struct {
	conns map[net.Conn]struct{}
	lock  sync.RWMutex
}

// AddHijackedConnection add a connection in the tracked connections list
func (h *hijackConnectionTracker) AddHijackedConnection(conn net.Conn) {
	h.lock.Lock()
	defer h.lock.Unlock()
	h.conns[conn] = struct{}{}
}

// RemoveHijackedConnection remove a connection from the tracked connections list
func (h *hijackConnectionTracker) RemoveHijackedConnection(conn net.Conn) {
	h.lock.Lock()
	defer h.lock.Unlock()
	delete(h.conns, conn)
}

// Shutdown wait for the connection closing
func (h *hijackConnectionTracker) Shutdown(ctx context.Context) error {
	ticker := time.NewTicker(500 * time.Millisecond)
	defer ticker.Stop()
	for {
		h.lock.RLock()
		if len(h.conns) == 0 {
			return nil
		}
		h.lock.RUnlock()
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-ticker.C:
		}
	}
}

// Close close all the connections in the tracked connections list
func (h *hijackConnectionTracker) Close() {
	for conn := range h.conns {
		if err := conn.Close(); err != nil {
			log.WithoutContext().Errorf("Error while closing Hijacked connection: %v", err)
		}
		delete(h.conns, conn)
	}
}

// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections.
type tcpKeepAliveListener struct {
	*net.TCPListener
}

func (ln tcpKeepAliveListener) Accept() (net.Conn, error) {
	tc, err := ln.AcceptTCP()
	if err != nil {
		return nil, err
	}

	if err = tc.SetKeepAlive(true); err != nil {
		return nil, err
	}

	if err = tc.SetKeepAlivePeriod(3 * time.Minute); err != nil {
		return nil, err
	}

	return tc, nil
}

func buildProxyProtocolListener(ctx context.Context, entryPoint *static.EntryPoint, listener net.Listener) (net.Listener, error) {
	var sourceCheck func(addr net.Addr) (bool, error)
	if entryPoint.ProxyProtocol.Insecure {
		sourceCheck = func(_ net.Addr) (bool, error) {
			return true, nil
		}
	} else {
		checker, err := ip.NewChecker(entryPoint.ProxyProtocol.TrustedIPs)
		if err != nil {
			return nil, err
		}

		sourceCheck = func(addr net.Addr) (bool, error) {
			ipAddr, ok := addr.(*net.TCPAddr)
			if !ok {
				return false, fmt.Errorf("type error %v", addr)
			}

			return checker.ContainsIP(ipAddr.IP), nil
		}
	}

	log.FromContext(ctx).Infof("Enabling ProxyProtocol for trusted IPs %v", entryPoint.ProxyProtocol.TrustedIPs)

	return &proxyproto.Listener{
		Listener:    listener,
		SourceCheck: sourceCheck,
	}, nil
}

func buildServerTimeouts(entryPointsTransport static.EntryPointsTransport) (readTimeout, writeTimeout, idleTimeout time.Duration) {
	readTimeout = time.Duration(0)
	writeTimeout = time.Duration(0)
	if entryPointsTransport.RespondingTimeouts != nil {
		readTimeout = time.Duration(entryPointsTransport.RespondingTimeouts.ReadTimeout)
		writeTimeout = time.Duration(entryPointsTransport.RespondingTimeouts.WriteTimeout)
	}

	if entryPointsTransport.RespondingTimeouts != nil {
		idleTimeout = time.Duration(entryPointsTransport.RespondingTimeouts.IdleTimeout)
	} else {
		idleTimeout = configuration.DefaultIdleTimeout
	}

	return readTimeout, writeTimeout, idleTimeout
}

func buildListener(ctx context.Context, entryPoint *static.EntryPoint) (net.Listener, error) {
	listener, err := net.Listen("tcp", entryPoint.Address)
	if err != nil {
		return nil, fmt.Errorf("error opening listener: %v", err)
	}

	listener = tcpKeepAliveListener{listener.(*net.TCPListener)}

	if entryPoint.ProxyProtocol != nil {
		listener, err = buildProxyProtocolListener(ctx, entryPoint, listener)
		if err != nil {
			return nil, fmt.Errorf("error creating proxy protocol listener: %v", err)
		}
	}
	return listener, nil
}

func buildCertificateStore(tlsOption traefiktls.TLS) (*traefiktls.CertificateStore, error) {
	certificateStore := traefiktls.NewCertificateStore()
	certificateStore.DynamicCerts.Set(make(map[string]*tls.Certificate))

	certificateStore.SniStrict = tlsOption.SniStrict

	if tlsOption.DefaultCertificate != nil {
		cert, err := buildDefaultCertificate(tlsOption.DefaultCertificate)
		if err != nil {
			return nil, err
		}
		certificateStore.DefaultCertificate = cert
	} else {
		cert, err := generate.DefaultCertificate()
		if err != nil {
			return nil, err
		}
		certificateStore.DefaultCertificate = cert
	}
	return certificateStore, nil
}

func buildServer(ctx context.Context, configuration *static.EntryPoint, tlsConfig *tls.Config, router http.Handler, tracker *hijackConnectionTracker) *h2c.Server {
	logger := log.FromContext(ctx)

	readTimeout, writeTimeout, idleTimeout := buildServerTimeouts(*configuration.Transport)
	logger.
		WithField("readTimeout", readTimeout).
		WithField("writeTimeout", writeTimeout).
		WithField("idleTimeout", idleTimeout).
		Infof("Preparing server")

	return &h2c.Server{
		Server: &http.Server{
			Addr:         configuration.Address,
			Handler:      router,
			TLSConfig:    tlsConfig,
			ReadTimeout:  readTimeout,
			WriteTimeout: writeTimeout,
			IdleTimeout:  idleTimeout,
			ErrorLog:     stdlog.New(logger.WriterLevel(logrus.DebugLevel), "", 0),
			ConnState: func(conn net.Conn, state http.ConnState) {
				switch state {
				case http.StateHijacked:
					tracker.AddHijackedConnection(conn)
				case http.StateClosed:
					tracker.RemoveHijackedConnection(conn)
				}
			},
		},
	}
}

// creates a TLS config that allows terminating HTTPS for multiple domains using SNI
func buildTLSConfig(tlsOption traefiktls.TLS) (*tls.Config, error) {
	conf := &tls.Config{}

	// ensure http2 enabled
	conf.NextProtos = []string{"h2", "http/1.1", tlsalpn01.ACMETLS1Protocol}

	if len(tlsOption.ClientCA.Files) > 0 {
		pool := x509.NewCertPool()
		for _, caFile := range tlsOption.ClientCA.Files {
			data, err := caFile.Read()
			if err != nil {
				return nil, err
			}
			ok := pool.AppendCertsFromPEM(data)
			if !ok {
				return nil, fmt.Errorf("invalid certificate(s) in %s", caFile)
			}
		}
		conf.ClientCAs = pool
		if tlsOption.ClientCA.Optional {
			conf.ClientAuth = tls.VerifyClientCertIfGiven
		} else {
			conf.ClientAuth = tls.RequireAndVerifyClientCert
		}
	}

	// Set the minimum TLS version if set in the config TOML
	if minConst, exists := traefiktls.MinVersion[tlsOption.MinVersion]; exists {
		conf.PreferServerCipherSuites = true
		conf.MinVersion = minConst
	}

	// Set the list of CipherSuites if set in the config TOML
	if tlsOption.CipherSuites != nil {
		// if our list of CipherSuites is defined in the entryPoint config, we can re-initialize the suites list as empty
		conf.CipherSuites = make([]uint16, 0)
		for _, cipher := range tlsOption.CipherSuites {
			if cipherConst, exists := traefiktls.CipherSuites[cipher]; exists {
				conf.CipherSuites = append(conf.CipherSuites, cipherConst)
			} else {
				// CipherSuite listed in the toml does not exist in our listed
				return nil, fmt.Errorf("invalid CipherSuite: %s", cipher)
			}
		}
	}

	return conf, nil
}


text:
package itsyouonline

import (
	"gopkg.in/validator.v2"
)

type GetOrganizationUsersResponseBody struct {
	Haseditpermissions bool               `json:"haseditpermissions"`
	Users              []OrganizationUser `json:"users" validate:"nonzero"`
}

func (s GetOrganizationUsersResponseBody) Validate() error {

	return validator.Validate(s)
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Dominion.Rules;
using Dominion.Rules.Activities;
using Dominion.Rules.CardTypes;

namespace Dominion.Cards.Actions
{
    public class Adventurer : Card, IActionCard
    {
        public Adventurer() : base(6)
        {

        }

        public void Play(TurnContext context)
        {
            context.AddEffect(this, new AdventurerEffect());
        }

        private class AdventurerEffect : CardEffectBase
        {
            private IEnumerable<ITreasureCard> MatchingCards(RevealZone zone)
            {
                return zone.OfType<ITreasureCard>();
            }

            public override void Resolve(TurnContext context, ICard source)
            {
                var deck = context.ActivePlayer.Deck;
                var revealZone = new RevealZone(context.ActivePlayer);

                while (deck.TopCard != null && MatchingCards(revealZone).Count() < 2)
                    deck.TopCard.MoveTo(revealZone);

                revealZone.LogReveal(context.Game.Log);
                var revealedTreasure = MatchingCards(revealZone).ToList();

                var discards = revealZone.Where(c => !revealedTreasure.Cast<ICard>().Contains(c)).ToList();

                foreach(var card in discards)
                    card.MoveTo(context.ActivePlayer.Discards);

                foreach (var card in revealedTreasure)
                    card.MoveTo(context.ActivePlayer.Hand);

            }
        }
    }
}


text:
<?php

namespace Wallabag\CoreBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Wallabag\CoreBundle\Form\Type\NewTagType;
use Wallabag\CoreBundle\Entity\Tag;
use Wallabag\CoreBundle\Entity\Entry;

class TagController extends Controller
{
    /**
     * @param Request $request
     *
     * @Route("/new-tag/{entry}", requirements={"entry" = "\d+"}, name="new_tag")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function addTagFormAction(Request $request, Entry $entry)
    {
        $tag = new Tag($this->getUser());
        $form = $this->createForm(new NewTagType(), $tag);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $existingTag = $this->getDoctrine()
                ->getRepository('WallabagCoreBundle:Tag')
                ->findOneByLabelAndUserId($tag->getLabel(), $this->getUser()->getId());

            $em = $this->getDoctrine()->getManager();

            if (is_null($existingTag)) {
                $entry->addTag($tag);
                $em->persist($tag);
            } else {
                if (!$existingTag->hasEntry($entry)) {
                    $entry->addTag($existingTag);
                    $em->persist($existingTag);
                }
            }

            $em->flush();

            $this->get('session')->getFlashBag()->add(
                'notice',
                'Tag added'
            );

            return $this->redirect($this->generateUrl('view', array('id' => $entry->getId())));
        }

        return $this->render('WallabagCoreBundle:Tag:new_form.html.twig', array(
            'form' => $form->createView(),
            'entry' => $entry,
        ));
    }

    /**
     * Shows tags for current user.
     *
     * @Route("/tag/list", name="tag")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function showTagAction()
    {
        $tags = $this->getDoctrine()
            ->getRepository('WallabagCoreBundle:Tag')
            ->findTags($this->getUser()->getId());

        return $this->render(
            'WallabagCoreBundle:Tag:tags.html.twig',
            array(
                'tags' => $tags,
            )
        );
    }
}


text:
{% extends 'pybb/base.html' %}

{% load i18n pybb_tags %}

{% block title %}{% trans "Profile editing" %}{% endblock title %}

{% block content %}
{% comment %}
--- disabled at this place and integrated into userena profile! ---

{% trans "Profile editing" %}

    {% include 'pybb/avatar.html' with user=user %}
    <form method="post" enctype="multipart/form-data" class="profile-edit">
        {% csrf_token %}
        <fieldset>
            <legend>{% trans "Profile editing" %}</legend>
            {% include "pybb/form.html" %}

{% include "pybb/_button_save.html" %}

        </fieldset>
    </form>

{% trans "Subscriptions on topics" %}

        {% for sub in user.subscriptions.all %}

                {% pybb_link sub %}
                —

                    {% trans "delete" %}

        {% endfor %}

{% endcomment %}
{% endblock content %}


text:
int main(int argc, char *argv[])
{

#ifdef _UNIX
  setlocale(LC_ALL,"");
#endif

  InitConsole();
  ErrHandler.SetSignalHandlers(true);

#ifdef SFX_MODULE
  wchar ModuleName[NM];
#ifdef _WIN_ALL
  GetModuleFileName(NULL,ModuleName,ASIZE(ModuleName));
#else
  CharToWide(argv[0],ModuleName,ASIZE(ModuleName));
#endif
#endif

#ifdef _WIN_ALL
  SetErrorMode(SEM_NOALIGNMENTFAULTEXCEPT|SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);

#endif

#if defined(_WIN_ALL) && !defined(SFX_MODULE)
  // Must be initialized, normal initialization can be skipped in case of
  // exception.
  POWER_MODE ShutdownOnClose=POWERMODE_KEEP;
#endif

  try
  {

    CommandData *Cmd=new CommandData;
#ifdef SFX_MODULE
    wcsncpyz(Cmd->Command,L"X",ASIZE(Cmd->Command));
    char *Switch=argc>1 ? argv[1]:NULL;
    if (Switch!=NULL && Cmd->IsSwitch(Switch[0]))
    {
      int UpperCmd=etoupper(Switch[1]);
      switch(UpperCmd)
      {
        case 'T':
        case 'V':
          Cmd->Command[0]=UpperCmd;
          break;
        case '?':
          Cmd->OutHelp(RARX_SUCCESS);
          break;
      }
    }
    Cmd->AddArcName(ModuleName);
    Cmd->ParseDone();
    Cmd->AbsoluteLinks=true; // If users runs SFX, he trusts an archive source.
#else // !SFX_MODULE
    Cmd->ParseCommandLine(true,argc,argv);
    if (!Cmd->ConfigDisabled)
    {
      Cmd->ReadConfig();
      Cmd->ParseEnvVar();
    }
    Cmd->ParseCommandLine(false,argc,argv);
#endif

#if defined(_WIN_ALL) && !defined(SFX_MODULE)
    ShutdownOnClose=Cmd->Shutdown;
    if (ShutdownOnClose)
      ShutdownCheckAnother(true);
#endif

    uiInit(Cmd->Sound);
    InitLogOptions(Cmd->LogName,Cmd->ErrlogCharset);
    ErrHandler.SetSilent(Cmd->AllYes || Cmd->MsgStream==MSG_NULL);

    Cmd->OutTitle();
    Cmd->ProcessCommand();
    delete Cmd;
  }
  catch (RAR_EXIT ErrCode)
  {
    ErrHandler.SetErrorCode(ErrCode);
  }
  catch (std::bad_alloc&)
  {
    ErrHandler.MemoryErrorMsg();
    ErrHandler.SetErrorCode(RARX_MEMORY);
  }
  catch (...)
  {
    ErrHandler.SetErrorCode(RARX_FATAL);
  }

#if defined(_WIN_ALL) && !defined(SFX_MODULE)
  if (ShutdownOnClose!=POWERMODE_KEEP && ErrHandler.IsShutdownEnabled() &&
      !ShutdownCheckAnother(false))
    Shutdown(ShutdownOnClose);
#endif
  ErrHandler.MainExit=true;
  return ErrHandler.GetErrorCode();
}
#endif


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('confess', '0004_post_liked'),
        ('likes', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='MtmLike2Conf',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('confession', models.ForeignKey(to='confess.Post')),
                ('like', models.ForeignKey(to='likes.Like')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
package com.tale.hooks;

import com.blade.ioc.annotation.Bean;
import com.blade.mvc.hook.Signature;
import com.blade.mvc.hook.WebHook;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.tale.init.TaleConst;
import com.tale.model.entity.Users;
import com.tale.utils.TaleUtils;
import lombok.extern.slf4j.Slf4j;

@Bean
@Slf4j
public class BaseWebHook implements WebHook {

    @Override
    public boolean before(Signature signature) {
        Request  request  = signature.request();
        Response response = signature.response();

        String uri = request.uri();
        String ip  = request.address();

        // 禁止该ip访问
        if (TaleConst.BLOCK_IPS.contains(ip)) {
            response.text("You have been banned, brother");
            return false;
        }

        log.info("UserAgent: {}", request.userAgent());
        log.info("用户访问地址: {}, 来路地址: {}", uri, ip);

        if (uri.startsWith(TaleConst.STATIC_URI)) {
            return true;
        }

        if (!TaleConst.INSTALLED && !uri.startsWith(TaleConst.INSTALL_URI)) {
            response.redirect(TaleConst.INSTALL_URI);
            return false;
        }

        if (TaleConst.INSTALLED) {
            return isRedirect(request, response);
        }
        return true;
    }

    private boolean isRedirect(Request request, Response response) {
        Users  user = TaleUtils.getLoginUser();
        String uri  = request.uri();
        if (null == user) {
            Integer uid = TaleUtils.getCookieUid(request);
            if (null != uid) {
                user = new Users().find(uid);
                request.session().attribute(TaleConst.LOGIN_SESSION_KEY, user);
            }
        }
        if (uri.startsWith(TaleConst.ADMIN_URI) && !uri.startsWith(TaleConst.LOGIN_URI)) {
            if (null == user) {
                response.redirect(TaleConst.LOGIN_URI);
                return false;
            }
            request.attribute(TaleConst.PLUGINS_MENU_NAME, TaleConst.PLUGIN_MENUS);
        }
        return true;
    }

}


text:
DROP TABLE IF EXISTS judge_token;
DROP TABLE IF EXISTS map_user_power;
DROP TABLE IF EXISTS map_group_user;
DROP TABLE IF EXISTS map_group_user_power;
DROP TABLE IF EXISTS map_problem_execute;
DROP TABLE IF EXISTS map_contest_problem;
DROP TABLE IF EXISTS map_contest_user;
DROP TABLE IF EXISTS bulletins;
DROP TABLE IF EXISTS wait_submissions;
DROP TABLE IF EXISTS map_submission_testdata;
DROP TABLE IF EXISTS submissions;
DROP TABLE IF EXISTS map_verdict_string;
DROP TABLE IF EXISTS contests;
DROP TABLE IF EXISTS testdata;
DROP TABLE IF EXISTS map_problem_tag;
DROP TABLE IF EXISTS tags;
DROP TABLE IF EXISTS problems;
DROP TABLE IF EXISTS verdicts;
DROP TABLE IF EXISTS score_types;
DROP TABLE IF EXISTS execute_steps;
DROP TABLE IF EXISTS execute_types;
DROP TABLE IF EXISTS map_inpublic_group_user;
DROP TABLE IF EXISTS groups;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS schools;

CREATE OR REPLACE FUNCTION updated_row()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = date_trunc('second', now());
    RETURN NEW;
END;
$$ language 'plpgsql';

-- CREATE TABLE table_name (
    --     id              serial          NOT NULL    PRIMARY KEY,
    --     created_at      timestamp       DEFAULT now(),
    --     updated_at      timestamp       DEFAULT now()
    -- );
-- CREATE TRIGGER table_name_updated_at_column BEFORE UPDATE ON table_name FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column_column();

--DROP TABLE IF EXISTS users;
CREATE TABLE schools(
    id              serial          NOT NULL    PRIMARY KEY,
    name            varchar(255)    NOT NULL,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER schools_update_row BEFORE UPDATE ON schools FOR EACH ROW EXECUTE PROCEDURE updated_row();
INSERT INTO schools (name) VALUES('NCTU');

CREATE TABLE users (
    id              serial          NOT NULL    PRIMARY KEY,
    account         varchar(32)     NOT NULL,
    passwd          varchar(32)     NOT NULL,
    email           varchar(255)    NOT NULL,
    name            varchar(32)     DEFAULT '',
    student_id      varchar(32)     DEFAULT '',
    school_id       integer         DEFAULT 1   REFERENCES schools(id)  ON DELETE CASCADE,
    token           varchar(64)     NOT NULL,
    created_at      timestamp       DEFAULT date_trunc('second', now()),
    updated_at      timestamp       DEFAULT date_trunc('second', now())
);
CREATE TRIGGER users_updated_row BEFORE UPDATE ON users FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE UNIQUE INDEX on users (token);
CREATE UNIQUE INDEX on users (account);
CREATE INDEX on users (name);
CREATE INDEX on users (student_id);
INSERT INTO users (account, passwd, email, student_id, school_id, token) VALUES ('admin', '21232f297a57a5a743894a0e4a801fc3', 'admin@gmail.com', '0000000', '1', 'P8AWkMjJFcEjsc7rpVfBk9XkBt99H4KjyHSHBwPtzXtyl3LtUeA6CQl8EVcdZrhr');

--DROP TABLE IF EXISTS map_user_power;
CREATE TABLE map_user_power (
    id              serial          NOT NULL    PRIMARY KEY,
    user_id         integer         NOT NULL    REFERENCES users(id)    ON DELETE CASCADE,
    power           integer         NOT NULL,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER map_user_power_updated_row BEFORE UPDATE ON map_user_power FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON map_user_power (power);
CREATE INDEX ON map_user_power (user_id);
INSERT INTO map_user_power (user_id, power) VALUES (1, 1);
INSERT INTO map_user_power (user_id, power) VALUES (1, 2);
INSERT INTO map_user_power (user_id, power) VALUES (1, 3);
INSERT INTO map_user_power (user_id, power) VALUES (1, 4);

--DROP TABLE IF EXISTS groups;
CREATE TABLE groups (
    id              serial          NOT NULL    PRIMARY KEY,
    name            varchar(255)    NOT NULL,
	type			integer			NOT NULL DEFAULT 0,
    description     varchar(255)    NOT NULL,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER groups_updated_row BEFORE UPDATE ON groups FOR EACH ROW EXECUTE PROCEDURE updated_row();
INSERT INTO groups (name, description) VALUES ('Group1', 'For Group1');

--DROP TABLE IF EXISTS map_group_user;
CREATE TABLE map_group_user (
    id              serial          NOT NULL    PRIMARY KEY,
    group_id        integer         NOT NULL    REFERENCES groups(id)   ON DELETE CASCADE,
    user_id         integer         NOT NULL    REFERENCES users(id)    ON DELETE CASCADE,
    priority        integer         NOt NULL    DEFAULT 999,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE INDEX on map_group_user (group_id);
CREATE INDEX on map_group_user (user_id);
CREATE UNIQUE INDEX ON map_group_user(group_id, user_id);
CREATE TRIGGER map_group_user_updated_row BEFORE UPDATE ON map_group_user FOR EACH ROW EXECUTE PROCEDURE updated_row();
INSERT INTO map_group_user (group_id, user_id) VALUES (1, 1);

CREATE TABLE map_inpublic_group_user (
    id              serial          NOT NULL    PRIMARY KEY,
    group_id        integer         NOT NULL    REFERENCES groups(id)   ON DELETE CASCADE,
    user_id         integer         NOT NULL    REFERENCES users(id)    ON DELETE CASCADE,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE INDEX ON map_inpublic_group_user (group_id);
CREATE INDEX ON map_inpublic_group_user (user_id);
CREATE UNIQUE INDEX ON map_inpublic_group_user (user_id, group_id);
CREATE TRIGGER map_inpublic_group_user_updated_row BEFORE UPDATE ON map_inpublic_group_user FOR EACH ROW EXECUTE PROCEDURE updated_row();

--DROP TABLE IF EXISTS map_group_user_power;
CREATE TABLE map_group_user_power (
    id              serial          NOT NULL    PRIMARY KEY,
    group_id        integer         NOT NULL    REFERENCES groups(id)   ON DELETE CASCADE,
    user_id         integer         NOT NULL    REFERENCES users(id)    ON DELETE CASCADE,
    power           integer         NOT NULL,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER map_group_user_power_updated_row BEFORE UPDATE ON map_group_user_power FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON map_group_user_power (group_id);
CREATE INDEX ON map_group_user_power (user_id);
CREATE INDEX ON map_group_user_power (power);
CREATE UNIQUE INDEX ON map_group_user_power (group_id, user_id, power);
INSERT INTO map_group_user_power (group_id, user_id, power) VALUES (1, 1, 1);
INSERT INTO map_group_user_power (group_id, user_id, power) VALUES (1, 1, 2);
INSERT INTO map_group_user_power (group_id, user_id, power) VALUES (1, 1, 3);
INSERT INTO map_group_user_power (group_id, user_id, power) VALUES (1, 1, 4);
INSERT INTO map_group_user_power (group_id, user_id, power) VALUES (1, 1, 5);

--DROP TABLE IF EXISTS bulletins;
CREATE TABLE bulletins (
    id              serial          NOT NULL    PRIMARY KEY,
    group_id        integer         NOT NULL    REFERENCES groups(id)   ON DELETE CASCADE,
    setter_user_id  integer         NOT NULL    REFERENCES users(id)    ON DELETE CASCADE,
    title           varchar(255)    DEFAULT '',
    content         text            DEFAULT '',
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER bulletins_updated_row BEFORE UPDATE ON bulletins FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON bulletins (group_id);
INSERT INTO bulletins (group_id, setter_user_id, title, content) VALUES (1, 1, 'Public', 'New Group Public');

--DROP TABLE IF EXISTS execute_types;
CREATE TABLE execute_types (
    id              serial          NOT NULL    PRIMARY KEY,
    description     varchar(255)    NOT NULL    DEFAULT '',
    lang            integer         NOT NULL,
    recompile       integer         NOT NULL    DEFAULT 0   CHECK(recompile = ANY('{0,1}')),
    setter_user_id  integer         NOT NULL    REFERENCES users(id)    ON DELETE CASCADE,
    priority        integer         NOT NULL    DEFAULT 999,
	cm_mode			varchar(255)	DEFAULT '',
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER execute_types_updated_row BEFORE UPDATE ON execute_types FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX on execute_types (priority);
INSERT INTO execute_types (description, lang, setter_user_id, priority, cm_mode) values ('Basic C', 0, 1, 1, 'text/x-csrc');
INSERT INTO execute_types (description, lang, setter_user_id, priority, cm_mode) values ('Basic C++', 1, 1, 2, 'text/x-c++src');
INSERT INTO execute_types (description, lang, setter_user_id, priority, cm_mode) values ('Basic C++11', 1, 1, 3, 'text/x-c++src');
INSERT INTO execute_types (description, lang, setter_user_id, priority, cm_mode) values ('Basic Java', 2, 1, 4, 'text/x-java');
INSERT INTO execute_types (description, lang, setter_user_id, priority, cm_mode) values ('Basic Python2', 3, 1, 5, 'text/x-python');
INSERT INTO execute_types (description, lang, setter_user_id, priority, cm_mode) values ('Basic Python3', 4, 1, 6, 'text/x-python');
INSERT INTO execute_types (description, lang, setter_user_id, priority, cm_mode) values ('Basic Go', 5, 1, 7, 'text/x-go');
INSERT INTO execute_types (description, lang, setter_user_id, priority, cm_mode) values ('Basic Perl', 6, 1, 8, 'text/x-perl');
INSERT INTO execute_types (description, lang, setter_user_id, priority, cm_mode) values ('Basic Javascript', 7, 1, 9, 'text/javascript');
INSERT INTO execute_types (description, lang, setter_user_id, priority, cm_mode) values ('Basic Ruby', 9, 1, 10, 'text/x-ruby');
INSERT INTO execute_types (description, lang, setter_user_id, priority, cm_mode) values ('Basic shell', 10, 1, 11, 'text/x-sh');
--map_lang = {
--0: "C",
--1: "C++",
--2: "Java",
--3: "Python2",
--4: "Python3",
--5: "Go",
--6: "Perl",
--7: "Javascript",
--8: "Haskell",
--9: "ruby",
--10:"sh",
--}

--DROP TABLE IF EXISTS execute_steps;
CREATE TABLE execute_steps (
    id              serial          NOT NULL    PRIMARY KEY,
    execute_type_id integer         NOT NULL    REFERENCES execute_types(id)    ON DELETE CASCADE,
    command         varchar(255)    NOT NULL    DEFAULT '',
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER execute_steps_updated_row BEFORE UPDATE ON execute_steps FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON execute_steps (execute_type_id);
INSERT INTO execute_steps (execute_type_id, command) values (1, 'gcc __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (1, './a.out');
INSERT INTO execute_steps (execute_type_id, command) values (2, 'g++ __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (2, './a.out');
INSERT INTO execute_steps (execute_type_id, command) values (3, 'g++ -std=c++11  __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (3, './a.out');
INSERT INTO execute_steps (execute_type_id, command) values (4, 'javac __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (4, 'java -Xmx__MEMORY_LIMIT__k -Xss8m __MAIN_FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (5, 'python2 -m py_compile __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (5, 'python2 __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (6, 'python3 -m py_compile __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (6, 'python3 __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (7, 'TMPDIR="." go build -o a.out __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (7, './a.out');
INSERT INTO execute_steps (execute_type_id, command) values (8, 'perl __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (9, 'd8 __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (10, 'ruby __FILE__');
INSERT INTO execute_steps (execute_type_id, command) values (11, 'sh __FILE__');

--INSERT INTO execute_types (description, lang, setter_user_id, priority) values ('Basic C', 0, 1, 1);
--INSERT INTO execute_types (description, lang, setter_user_id, priority) values ('Basic C++', 1, 1, 2);
--INSERT INTO execute_types (description, lang, setter_user_id, priority) values ('Basic C++11', 1, 1, 3);
--INSERT INTO execute_types (description, lang, setter_user_id, priority) values ('Basic Java', 2, 1, 4);
--INSERT INTO execute_types (description, lang, setter_user_id, priority) values ('Basic Python2', 3, 1, 5);
--INSERT INTO execute_types (description, lang, setter_user_id, priority) values ('Basic Python3', 4, 1, 6);
--INSERT INTO execute_types (description, lang, setter_user_id, priority) values ('Basic Go', 5, 1, 7);

--DROP TABLE IF EXISTS verdicts;
CREATE TABLE verdicts(
    id              serial          NOT NULL    PRIMARY KEY,
    title           varchar(255)    ,
    execute_type_id integer         NOT NULL    DEFAULT 0   REFERENCES execute_types(id)    ON DELETE CASCADE,
    problem_id      integer         NOT NULL    DEFAULT 0,
    file_name       varchar(255)    NOT NULL,
    setter_user_id  integer         NOT NULL    REFERENCES users(id)    ON DELETE CASCADE,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER verdicts_update_row BEFORE UPDATE ON verdicts FOR EACH ROW EXECUTE PROCEDURE updated_row();
INSERT INTO verdicts (title, execute_type_id, file_name, setter_user_id) VALUES ('Token By Character(Ignore Lines)', 2, 'main.cpp', 1);

CREATE TABLE score_types (
    id              serial          NOT NULL    PRIMARY KEY,
    name            varchar(255)    NOT NULL,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER score_types_update_row BEFORE UPDATE ON score_types FOR EACH ROW EXECUTE PROCEDURE updated_row();
INSERT INTO score_types (name) VALUES ('sum');
INSERT INTO score_types (name) VALUES ('min');

--DROP TABLE IF EXISTS problems;
CREATE TABLE problems (
    id              serial          NOT NULL    PRIMARY KEY,
    title           varchar(255)    NOT NULL DEFAULT '',
    pdf             boolean         NOT NULL DEFAULT FALSE,
    description     text            NOT NULL DEFAULT '',
    input           text            NOT NULL DEFAULT '',
    output          text            NOT NULL DEFAULT '',
    sample_input    text            NOT NULL DEFAULT '',
    sample_output   text            NOT NULL DEFAULT '',
    hint            text            NOT NULL DEFAULT '',
    source          text            NOT NULL DEFAULT '',
    group_id        integer         NOT NULL    REFERENCES groups(id)   ON DELETE CASCADE,
    setter_user_id  integer         NOT NULL    REFERENCES users(id)    ON DELETE CASCADE,
    visible         integer         NOT NULL DEFAULT 0 CHECK (visible = ANY('{0, 1}')),
    interactive     integer         NOT NULL DEFAULT 0 CHECK (interactive = ANY('{0, 1}')),
    verdict_id      integer         DEFAULT 1   REFERENCES verdicts(id) ON DELETE CASCADE,
    score_type_id   integer         DEFAULT 1   REFERENCES score_types(id) ON DELETE CASCADE,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
ALTER SEQUENCE problems_id_seq RESTART WITH 10001;
CREATE TRIGGER problems_updated_row BEFORE UPDATE ON problems FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON problems (visible);
CREATE INDEX ON problems (group_id);

--DROP TABLE IF EXISTS map_problem_execute;
CREATE TABLE map_problem_execute (
    id              serial          NOT NULL    PRIMARY KEY,
    problem_id      integer         NOT NULL    REFERENCES problems(id) ON DELETE CASCADE,
    execute_type_id integer         NOT NULL    REFERENCES execute_types(id)    ON DELETE CASCADE,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER map_problem_execute_updated_row BEFORE UPDATE ON map_problem_execute FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON map_problem_execute (problem_id);
CREATE INDEX ON map_problem_execute (execute_type_id);
CREATE UNIQUE INDEX ON map_problem_execute (problem_id, execute_type_id);

--DROP TABLE IF EXISTS testdata;
CREATE TABLE testdata(
    id              serial          NOT NULL    PRIMARY KEY,
    problem_id      integer         NOT NULL    REFERENCES problems(id) ON DELETE CASCADE,
    time_limit      integer         NOT NULL    DEFAULT 1000,
    memory_limit    integer         NOT NULL    DEFAULT 262144,
    output_limit    integer         NOT NULL    DEFAULT 64,
    score           integer         NOT NULL    DEFAULT 0,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER testdata_updated_row BEFORE UPDATE ON testdata FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON testdata (problem_id);

CREATE TABLE map_verdict_string (
    id              serial          NOT NULL    PRIMARY KEY,
    abbreviation    varchar(15)     NOT NULL,
    description     varchar(31)     NOT NULL,
    priority        integer         NOT NULL,
    color           varchar(32)     NOT NULL    DEFAULT '#000',
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER map_verdict_string_updated_row BEFORE UPDATE ON map_verdict_string FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON map_verdict_string(priority);
INSERT INTO map_verdict_string (abbreviation,description,priority,color) VALUES('Pending', 'In Queue', 1, '#000');
INSERT INTO map_verdict_string (abbreviation,description,priority,color) VALUES('SE', 'System Error', 2, '#000');
INSERT INTO map_verdict_string (abbreviation,description,priority,color) VALUES('CE', 'Compile Error', 3, 'rgb(51, 122, 183)');
INSERT INTO map_verdict_string (abbreviation,description,priority,color) VALUES('RE', 'Runtime Error', 4, 'rgb(163, 188, 0)');
INSERT INTO map_verdict_string (abbreviation,description,priority,color) VALUES('MLE', 'Memory Limit Exceed', 5, '#000');
INSERT INTO map_verdict_string (abbreviation,description,priority,color) VALUES('TLE', 'Time Limit Exceed', 6, 'rgb(156, 39, 176)');
INSERT INTO map_verdict_string (abbreviation,description,priority,color) VALUES('OLE', 'Output Limit Exceed', 7, '#000');
INSERT INTO map_verdict_string (abbreviation,description,priority,color) VALUES('WA', 'Wrong Answer', 8, 'rgb(244, 67, 54)');
INSERT INTO map_verdict_string (abbreviation,description,priority,color) VALUES('AC', 'Accepted', 9, 'rgb(76, 175, 80)');

--DROP TABLE IF EXISTS submissions;
CREATE TABLE submissions(
    id              serial          NOT NULL    PRIMARY KEY,
    user_id         integer         NOT NULL    REFERENCES users(id)    ON DELETE CASCADE,
    problem_id      integer         NOT NULL    REFERENCES problems(id) ON DELETE CASCADE,
    execute_type_id integer         NOT NULL    REFERENCES execute_types(id)    ON DELETE CASCADE,
    time_usage      integer         ,
    memory_usage    integer         ,
    verdict         integer         NOT NULL    DEFAULT 1   REFERENCES map_verdict_string(id)   ON DELETE CASCADE,
    score           integer         ,
    length          integer         NOT NULL,
    file_name       varchar(255)    NOT NULL,
    ip              inet            NOT NULL,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
ALTER SEQUENCE submissions_id_seq RESTART WITH 10001;
CREATE TRIGGER submissions_updated_row BEFORE UPDATE ON submissions FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON submissions (user_id);
CREATE INDEX ON submissions (problem_id);
CREATE INDEX ON submissions (execute_type_id);
CREATE INDEX ON submissions (memory_usage);
CREATE INDEX ON submissions (time_usage);
CREATE INDEX ON submissions (verdict);
CREATE INDEX ON submissions (length);
CREATE INDEX ON submissions (created_at);

CREATE TABLE map_submission_testdata (
    id              serial          NOT NULL    PRIMARY KEY,
    testdata_id     integer         NOT NULL    REFERENCES testdata(id)     ON DELETE CASCADE,
    submission_id   integer         NOT NULL    REFERENCES submissions(id)  ON DELETE CASCADE,
    time_usage      integer,
    memory_usage    integer,
    score           integer,
    verdict         integer         DEFAULT 1   REFERENCES map_verdict_string(id)   ON DELETE CASCADE,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER map_submission_testdata_updated_row BEFORE UPDATE ON map_submission_testdata FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON map_submission_testdata(submission_id);
CREATE INDEX ON map_submission_testdata(time_usage);
CREATE INDEX ON map_submission_testdata(memory_usage);
CREATE INDEX ON map_submission_testdata(verdict);

--DROP TABLE IF EXISTS contests;
CREATE TABLE contests(
    id              serial          NOT NULL    PRIMARY KEY,
    group_id        integer         NOT NULL    REFERENCES groups(id)   ON DELETE CASCADE,
    visible         integer         NOT NULL    DEFAULT 0 CHECK (visible = ANY('{0, 1}')),
    setter_user_id  integer         NOT NULL    REFERENCES users(id)    ON DELETE CASCADE,
    title           varchar(255)    ,
    description     text            ,
    register_start  timestamp       NOT NULL    DEFAULT date_trunc('second', now()),
    register_end    timestamp       NOT NULL    DEFAULT date_trunc('second', now()),
    "start"         timestamp       NOT NULL    DEFAULT date_trunc('second', now()),
    "freeze"        integer         NOT NULL    DEFAULT 0 CHECK ("freeze" * interval '1 minute' <= "end"-"start"),
    "end"           timestamp       NOT NULL    DEFAULT date_trunc('second', now()),
    "type"          integer         NOT NULL    DEFAULT 0,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
ALTER SEQUENCE contests_id_seq RESTART WITH 1001;
CREATE TRIGGER contests_update_row BEFORE UPDATE ON contests FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON contests (group_id);
CREATE INDEX ON contests (visible);

--DROP TABLE IF EXISTS map_contest_problem;
CREATE TABLE map_contest_problem (
    id              serial          NOT NULL    PRIMARY KEY,
    contest_id      integer         NOT NULL    REFERENCES contests(id) ON DELETE CASCADE,
    problem_id      integer         NOT NULL    REFERENCES problems(id) ON DELETE CASCADE,
    score           varchar(255)    NOT NULL    DEFAULT '',
    penalty         integer         NOT NULL    DEFAULT 20,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER map_conteset_problem_update_row BEFORE UPDATE ON map_contest_problem FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON map_contest_problem (contest_id);
CREATE INDEX ON map_contest_problem (problem_id);
CREATE UNIQUE INDEX ON map_contest_problem (contest_id, problem_id);

--DROP TABLE IF EXISTS map_contest_user;
CREATE TABLE map_contest_user (
    id              serial          NOT NULL    PRIMARY KEY,
    user_id         integer         NOT NULL    REFERENCES users(id)    ON DELETE CASCADE,
    contest_id      integer         NOT NULL    REFERENCES contests(id) ON DELETE CASCADE,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER map_contest_user_update_row BEFORE UPDATE ON map_contest_user FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE UNIQUE INDEX ON map_contest_user (user_id, contest_id);
CREATE INDEX ON map_contest_user (user_id);
CREATE INDEX ON map_contest_user (contest_id);

CREATE TABLE wait_submissions (
    id              serial          NOT NULL    PRIMARY KEY,
    submission_id   integer         NOT NULL    REFERENCES submissions(id)  ON  DELETE  CASCADE,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER wait_submissions_update_row BEFORE UPDATE ON wait_submissions FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE UNIQUE INDEX ON wait_submissions(submission_id);

CREATE TABLE tags (
    id              serial          NOT NULL     PRIMARY KEY,
    tag             varchar(31)     NOT NULL,
    description     varchar(255)    DEFAULT '',
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER tags_update_row BEFORE UPDATE ON tags FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON tags(tag);

CREATE TABLE map_problem_tag (
    id              serial          NOT NULL        PRIMARY KEY,
    problem_id      integer         NOT NULL        REFERENCES problems(id)     ON DELETE CASCADE,
    tag_id          integer         NOT NULL        REFERENCES tags(id)         ON DELETE CASCADE,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER map_problem_tag_update_row BEFORE UPDATE ON map_problem_tag FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE INDEX ON map_problem_tag (problem_id);
CREATE INDEX ON map_problem_tag (tag_id);
CREATE UNIQUE INDEX ON map_problem_tag (problem_id,tag_id);

CREATE TABLE judge_token (
    id              serial          NOT NULL    PRIMARY KEY,
    addr            varchar(31)     DEFAULT '',
    description     varchar(255)    DEFAULT '',
    token           varchar(255)    NOT NULL,
    created_at      timestamp       DEFAULT date_trunc('second',now()),
    updated_at      timestamp       DEFAULT date_trunc('second',now())
);
CREATE TRIGGER judge_token_update_row BEFORE UPDATE ON judge_token FOR EACH ROW EXECUTE PROCEDURE updated_row();
CREATE UNIQUE INDEX ON judge_token(token);
INSERT INTO judge_token (token) VALUES('TOKEN');


text:
[BetterParams][docs]
====================

[![Build Status][shield-travis]][travis-ci]
[![Coverage Status][shield-inch]][docs]
[![Version][shield-version]][hexpm]
[![License][shield-license]][hexpm]

> Cleaner request parameters in Elixir web applications 🙌

`BetterParams` is a simple Elixir [Plug][plug] that allows passed
request parameters to be called as `atoms` instead of Strings. The
sole purpose of this Plug is to pattern match on maps with atom keys
instead of string keys in routers/controllers to calm my OCD down.

## Usage

Once installed, it lets you pattern match request parameters like
`%{id: id}` instead of `%{"id" => id}` in Phoenix applications:

```elixir
# web/controllers/some_controller.ex

def show(conn, %{id: id}) do
  # do something
end

def create(conn, %{id: id, post: %{title: title, body: body}}) do
  # do something
end
```

#### Notes

 - Implementation uses [`String.to_existing_atom`][string-atom] to prevent
   against [DoS attacks][gh-issue-ddos], so it only converts those params
   to atoms that you use in your application.
 - You can continue to use String keys without breaking your existing
   matches if you want. All request parameters are available for both
   `String` and `Atom` keys (that have already been defined in the
   application).
 - This doesn't pollute your Request Logs with duplicate params.
 - For other `Plug.Router` based applications, you can also access request
   params similarly by calling them like `conn.params[:id]` or
  `conn.params.post.title`.

## Installation

Add `better_params` to your project dependencies in `mix.exs`:

```elixir
def deps do
  [{:better_params, "~> 0.5.0"}]
end
```

### Phoenix Framework

For Phoenix applications, call the plug at the end of the `controller`
method in `web/web.ex` (inside the `quote` block):

```elixir
# web/web.ex

def controller do
  quote do
    use Phoenix.Controller

    # Other stuff...

    plug BetterParams
  end
end
```

Alternatively, you can also call it your Router Pipelines or in
individual controllers directly.

### Other Plug.Router Apps

For other applications using `Plug.Router`, call the Plug anytime after
calling the `:match` and `:dispatch` plugs:

```elixir
defmodule MyApp.Router do
  use Plug.Router

  plug :match
  plug :dispatch
  plug BetterParams

  # Rest of the router...
end

```

### Removing String Keys Entirely

If your use case calls for a params object with _only_ `Atom` keys, you
may pass the option `drop_string_keys` to the plug. Much as it says on
the can, this will replace the `String`-type keys altogether, rather
than preserving them alongside the `Atom` keys.

```elixir
plug BetterParams, drop_string_keys: true
```

## Roadmap

 - [x] Write Tests
 - [x] Write Documentation
 - [x] Symbolize the collective `params` map
 - [x] Option to remove string keys entirely
 - [ ] Symbolize [individual parameter maps][plug-params] (if the need arises)
    - [ ] `path_params`
    - [ ] `body_params`
    - [ ] `query_params`

## Contributing

 - [Fork][github-fork], Enhance, Send PR
 - Lock issues with any bugs or feature requests
 - Implement something from Roadmap
 - Spread the word :heart:

## License

This package is available as open source under the terms of the [MIT License][license].

  [shield-version]:   https://img.shields.io/hexpm/v/better_params.svg
  [shield-license]:   https://img.shields.io/hexpm/l/better_params.svg
  [shield-downloads]: https://img.shields.io/hexpm/dt/better_params.svg
  [shield-travis]:    https://img.shields.io/travis/sheharyarn/better_params/master.svg
  [shield-inch]:      https://inch-ci.org/github/sheharyarn/better_params.svg?branch=master

  [travis-ci]:        https://travis-ci.org/sheharyarn/better_params
  [inch-ci]:          https://inch-ci.org/github/sheharyarn/better_params

  [license]:          https://opensource.org/licenses/MIT
  [hexpm]:            https://hex.pm/packages/better_params
  [plug]:             https://github.com/elixir-lang/plug
  [plug-params]:      https://hexdocs.pm/plug/Plug.Conn.html#module-fetchable-fields
  [string-atom]:      https://hexdocs.pm/elixir/String.html#to_existing_atom/1

  [docs]:             https://hexdocs.pm/better_params

  [github-fork]:      https://github.com/sheharyarn/better_params/fork
  [gh-issue-ddos]:    https://github.com/sheharyarn/better_params/issues/1


text:
class NavbarController {
  constructor($state, authorizationService, authenticationService) {
    "ngInject";
    this.name = 'navbar';
    this.username = "Admin";
    this.password = "Password";
    this.$state = $state;
    this.authorizationService = authorizationService;
    this.authenticationService = authenticationService;
  }

  logout() {
    this.authenticationService.logout();
  }

  isAuthorized() {
    return this.authorizationService.isAuthorized();
  }
}

export default NavbarController;


text:
package org.apache.beam.runners.jet.processors;

import com.hazelcast.cluster.Address;
import com.hazelcast.jet.Traverser;
import com.hazelcast.jet.Traversers;
import com.hazelcast.jet.core.AbstractProcessor;
import com.hazelcast.jet.core.Processor;
import com.hazelcast.jet.core.ProcessorMetaSupplier;
import com.hazelcast.jet.core.ProcessorSupplier;
import com.hazelcast.jet.core.Watermark;
import com.hazelcast.jet.impl.util.ExceptionUtil;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import javax.annotation.Nonnull;
import org.apache.beam.runners.core.construction.SerializablePipelineOptions;
import org.apache.beam.runners.jet.Utils;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.io.UnboundedSource;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.util.WindowedValue;

/**
 * Jet {@link com.hazelcast.jet.core.Processor} implementation for reading from an unbounded Beam
 * source.
 */
@SuppressWarnings({
  "rawtypes", // TODO(https://github.com/apache/beam/issues/20447)
  "nullness",
  "keyfor"
}) // TODO(https://github.com/apache/beam/issues/20497)
public class UnboundedSourceP<T, CmT extends UnboundedSource.CheckpointMark>
    extends AbstractProcessor {

  private UnboundedSource.UnboundedReader<T>[] readers;
  private final List<? extends UnboundedSource<T, CmT>> allShards;
  private final PipelineOptions options;
  private final Coder outputCoder;

  @SuppressWarnings({"FieldCanBeLocal", "unused"})
  private final String ownerId; // do not remove it, very useful for debugging

  private Traverser<Object> traverser;

  private UnboundedSourceP(
      List<? extends UnboundedSource<T, CmT>> allShards,
      PipelineOptions options,
      Coder outputCoder,
      String ownerId) {
    this.allShards = allShards;
    this.options = options;
    this.outputCoder = outputCoder;
    this.ownerId = ownerId;
  }

  @Override
  protected void init(@Nonnull Processor.Context context) throws IOException {
    List<? extends UnboundedSource<T, CmT>> myShards =
        Utils.roundRobinSubList(
            allShards, context.globalProcessorIndex(), context.totalParallelism());
    this.readers = createReaders(myShards, options);

    Function<UnboundedSource.UnboundedReader<T>, byte[]> mapFn =
        (reader) ->
            Utils.encode(
                WindowedValue.timestampedValueInGlobalWindow(
                    reader.getCurrent(), reader.getCurrentTimestamp()),
                outputCoder);

    if (myShards.size() == 0) {
      traverser = Traversers.empty();
    } else if (myShards.size() == 1) {
      traverser = new SingleReaderTraverser<>(readers[0], mapFn);
    } else {
      traverser = new CoalescingTraverser<>(readers, mapFn);
    }

    for (UnboundedSource.UnboundedReader<T> reader : readers) {
      reader.start();
    }
  }

  @Override
  public boolean complete() {
    emitFromTraverser(traverser);
    return readers.length == 0;
  }

  @Override
  public boolean isCooperative() {
    return false;
  }

  @Override
  public void close() {
    Arrays.stream(readers).forEach(UnboundedSourceP::stopReader);
    Arrays.fill(readers, null);
  }

  @SuppressWarnings("unchecked")
  private static <T, CmT extends UnboundedSource.CheckpointMark>
      UnboundedSource.UnboundedReader<T>[] createReaders(
          List<? extends UnboundedSource<T, CmT>> shards, PipelineOptions options) {
    return shards.stream()
        .map(shard -> createReader(options, shard))
        .toArray(UnboundedSource.UnboundedReader[]::new);
  }

  private static long[] initWatermarks(int size) {
    long[] watermarks = new long[size];
    Arrays.fill(watermarks, Long.MIN_VALUE);
    return watermarks;
  }

  private static <T> UnboundedSource.UnboundedReader<T> createReader(
      PipelineOptions options, UnboundedSource<T, ?> shard) {
    try {
      return shard.createReader(options, null);
    } catch (IOException e) {
      throw ExceptionUtil.rethrow(e);
    }
  }

  private static void stopReader(UnboundedSource.UnboundedReader<?> reader) {
    try {
      reader.close();
    } catch (IOException e) {
      throw ExceptionUtil.rethrow(e);
    }
  }

  private static long getMin(long[] instants) {
    long min = instants[0];
    for (int i = 1; i < instants.length; i++) {
      if (instants[i] < min) {
        min = instants[i];
      }
    }
    return min;
  }

  public static <T, CmT extends UnboundedSource.CheckpointMark> ProcessorMetaSupplier supplier(
      UnboundedSource<T, CmT> unboundedSource,
      SerializablePipelineOptions options,
      Coder outputCoder,
      String ownerId) {
    return new UnboundedSourceProcessorMetaSupplier<>(
        unboundedSource, options, outputCoder, ownerId);
  }

  private static class UnboundedSourceProcessorMetaSupplier<
          T, CmT extends UnboundedSource.CheckpointMark>
      implements ProcessorMetaSupplier {

    private final UnboundedSource<T, CmT> unboundedSource;
    private final SerializablePipelineOptions options;
    private final Coder outputCoder;
    private final String ownerId;

    private List<? extends UnboundedSource<T, CmT>> shards;

    private UnboundedSourceProcessorMetaSupplier(
        UnboundedSource<T, CmT> unboundedSource,
        SerializablePipelineOptions options,
        Coder outputCoder,
        String ownerId) {
      this.unboundedSource = unboundedSource;
      this.options = options;
      this.outputCoder = outputCoder;
      this.ownerId = ownerId;
    }

    @Override
    public void init(@Nonnull ProcessorMetaSupplier.Context context) throws Exception {
      shards = unboundedSource.split(context.totalParallelism(), options.get());
    }

    @Nonnull
    @Override
    public Function<? super Address, ? extends ProcessorSupplier> get(
        @Nonnull List<Address> addresses) {
      return address ->
          ProcessorSupplier.of(
              () -> new UnboundedSourceP<>(shards, options.get(), outputCoder, ownerId));
    }
  }

  private static class SingleReaderTraverser<InputT> implements Traverser<Object> {
    private final UnboundedSource.UnboundedReader<InputT> reader;
    private final Function<UnboundedSource.UnboundedReader<InputT>, byte[]> mapFn;
    private long lastWatermark = Long.MIN_VALUE;

    SingleReaderTraverser(
        UnboundedSource.UnboundedReader<InputT> reader,
        Function<UnboundedSource.UnboundedReader<InputT>, byte[]> mapFn) {
      this.reader = reader;
      this.mapFn = mapFn;
    }

    @Override
    public Object next() {
      long wm = reader.getWatermark().getMillis();
      if (wm > lastWatermark) {
        lastWatermark = wm;
        return new Watermark(wm);
      }
      try {
        return reader.advance() ? mapFn.apply(reader) : null;
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }

  private static class CoalescingTraverser<InputT> implements Traverser<Object> {
    private final UnboundedSource.UnboundedReader<InputT>[] readers;
    private final Function<UnboundedSource.UnboundedReader<InputT>, byte[]> mapFn;

    private int currentReaderIndex;
    private long minWatermark = Long.MIN_VALUE;
    private long lastSentWatermark = Long.MIN_VALUE;
    private long[] watermarks;

    CoalescingTraverser(
        UnboundedSource.UnboundedReader<InputT>[] readers,
        Function<UnboundedSource.UnboundedReader<InputT>, byte[]> mapFn) {
      this.readers = readers;
      watermarks = initWatermarks(readers.length);
      this.mapFn = mapFn;
    }

    @Override
    public Object next() {
      if (minWatermark > lastSentWatermark) {
        lastSentWatermark = minWatermark;
        return new Watermark(lastSentWatermark);
      }

      try {
        // trying to fetch a value from the next reader
        for (int i = 0; i < readers.length; i++) {
          currentReaderIndex++;
          if (currentReaderIndex >= readers.length) {
            currentReaderIndex = 0;
          }
          UnboundedSource.UnboundedReader<InputT> currentReader = readers[currentReaderIndex];
          if (currentReader.advance()) {
            long currentWatermark = currentReader.getWatermark().getMillis();
            long origWatermark = watermarks[currentReaderIndex];
            if (currentWatermark > origWatermark) {
              watermarks[currentReaderIndex] =
                  currentWatermark; // todo: we should probably do this only on a timer...
              if (origWatermark == minWatermark) {
                minWatermark = getMin(watermarks);
              }
            }
            return mapFn.apply(currentReader);
          }
        }

        // all advances have failed
        return null;
      } catch (IOException e) {
        throw ExceptionUtil.rethrow(e);
      }
    }
  }
}


text:
package org.gearvrf;

/** Frame Buffer object. */
public class GVRRenderTexture extends GVRTexture {
    /**
     * Constructs a GVRRenderTexture for a frame buffer of the specified size.
     *
     * @param gvrContext
     *            Current gvrContext
     * @param width
     *            Width of the frame buffer.
     * @param height
     *            Height of the frame buffer.
     */
    public GVRRenderTexture(GVRContext gvrContext, int width, int height) {
        super(gvrContext, NativeRenderTexture.ctor(width, height));

        mWidth = width;
        mHeight = height;
    }

    /**
     * Constructs a GVRRenderTexture for a frame buffer of the specified size,
     * with MSAA enabled at the specified sample count.
     *
     * @param gvrContext
     *            Current gvrContext
     * @param width
     *            Width of the frame buffer.
     * @param height
     *            Height of the frame buffer.
     * @param sampleCount
     *            MSAA sample count.
     */
    public GVRRenderTexture(GVRContext gvrContext, int width, int height,
            int sampleCount) {
        super(gvrContext, NativeRenderTexture.ctorMSAA(width, height,
                sampleCount));

        mWidth = width;
        mHeight = height;
    }

    GVRRenderTexture(GVRContext gvrContext, long ptr) {
        super(gvrContext, ptr);
    }

    /**
     * Return the width of GVRRenderTexture (FBO)
     */
    public int getWidth() {
        return mWidth;
    }

    /**
     * Return the height of GVRRenderTexture (FBO)
     */
    public int getHeight() {
        return mHeight;
    }

    private int mWidth, mHeight;
}

class NativeRenderTexture {
    static native long ctor(int width, int height);

    static native long ctorMSAA(int width, int height, int sampleCount);
}


text:
import { combineReducers } from "redux";
import answer from "./answer";

const rootReducer = combineReducers({
    answer,
});

export default rootReducer;


text:
class AddBackgroundToSpreeTaxons < SpreeExtension::Migration[5.1]
  def change
    add_column :spree_taxons, :background_file_name, :string
    add_column :spree_taxons, :background_content_type, :string
    add_column :spree_taxons, :background_file_size, :integer
    add_column :spree_taxons, :background_updated_at, :timestamp
  end
end


text:
import { browser, element, by } from 'protractor';

export class AboutPage {
  navigateTo() {
    return browser.get('/about');
  }

  getParagraphText() {
    return element(by.css('app-root-ngnco .starter-template .row h1')).getText();
  }
}


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

<title>CellEditorListener (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<meta name="keywords" content="javax.swing.event.CellEditorListener interface">
<meta name="keywords" content="editingStopped()">
<meta name="keywords" content="editingCanceled()">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.swing.event

Interface CellEditorListener

All Superinterfaces:

EventListener

All Known Implementing Classes:

BasicTreeUI.CellEditorHandler, JTable, JTable.AccessibleJTable

public interface CellEditorListener
extends EventListener

CellEditorListener defines the interface for an object that listens
 to changes in a CellEditor

Method Summary

Methods

Modifier and Type
Method and Description

void
editingCanceled(ChangeEvent e)

This tells the listeners the editor has canceled editing

void
editingStopped(ChangeEvent e)

This tells the listeners the editor has ended editing

Method Detail

editingStopped

void editingStopped(ChangeEvent e)

This tells the listeners the editor has ended editing

editingCanceled

void editingCanceled(ChangeEvent e)

This tells the listeners the editor has canceled editing

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
package com.sm.replica;

import com.sm.store.StoreParas;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import static com.sm.store.StoreParas.putInt;
import static com.sm.store.StoreParas.toStoreParas;

public class ParaList implements Serializable {
 private static final Log logger = LogFactory.getLog(ParaList.class);

    private int size;
    private List<StoreParas> lists;

    public ParaList(List<StoreParas> lists) {
        if ( lists == null ) throw new RuntimeException("lists can not be null");
        this.lists = lists;
        this.size = lists.size();

    }

    public int getSize() {
        return size;
    }

    public List<StoreParas> getLists() {
        return lists;
    }

    public void setLists(List<StoreParas> lists) {
        this.lists = lists;
        this.size = lists.size();
    }

    public  byte[] toBytes(){
        // int len + byte[]
        int total = 4 * (size+1);
        byte[][] bytes = new byte[size][];
        for ( int i= 0 ; i < size ; i++){
            bytes[i] = lists.get(i).toBytes();
            total += bytes[i].length;
        }
        byte[] toReturn = new byte[total];
        int pos = 0;
        System.arraycopy(putInt( size), 0, toReturn, 0, 4);
        pos += 4;
        for ( int i=0; i < size ; i++) {
            System.arraycopy(putInt(bytes[i].length), 0, toReturn, pos, 4);
            pos += 4;
            System.arraycopy(bytes[i], 0, toReturn, pos, bytes[i].length);
            pos += bytes[i].length;
        }
        return toReturn;
    }

    public static ParaList toParaList(byte[] bytes){
        ByteBuffer buf = ByteBuffer.wrap( bytes);
        int size = buf.getInt();
        ArrayList<StoreParas> list = new ArrayList<StoreParas>(size);
        for ( int i =0; i < size ; i ++){
            // length of StoreParas
            int s = buf.getInt();
            byte[] ds = new byte[s];
            buf.get( ds);
            list.add( toStoreParas( ds));

        }
        return new ParaList(list);

    }
}


text:
Introduce multiline display for warning matching  via :py:func:`pytest.warns` and
enhance match comparison for :py:func:`_pytest._code.ExceptionInfo.match` as returned by :py:func:`pytest.raises`.