text:
# require 'merb' must happen after Merb::Config is instantiated
require "rubygems"

# Add the local gems dir if found within the app root; any dependencies loaded
# hereafter will try to load from the local gems before loading system gems.
root_key = %w[-m --merb-root].detect { |o| ARGV.index(o) }
root = ARGV[ARGV.index(root_key) + 1] if root_key
root = root.to_a.empty? ? Dir.getwd : root
if File.directory?(gems_dir = File.join(root, "gems")) && !$BUNDLE
  $BUNDLE = true; Gem.clear_paths; Gem.path.unshift(gems_dir)
  # Warn if local merb-core is available but not loaded.
  if File.expand_path($0).index(root) != 0 &&
    (local_mc = Dir[File.join(gems_dir, "specifications", "merb-core-*.gemspec")].last)
    puts "Warning: please use bin/#{File.basename($0)} to load #{File.basename(local_mc, ".gemspec")} from ./gems"
  end
end

require "thread"
require "set"
require "fileutils"
require "socket"
require "pathname"
require "extlib"
require "extlib/dictionary"

Thread.abort_on_exception = true

__DIR__ = File.dirname(__FILE__)

$LOAD_PATH.unshift __DIR__ unless
  $LOAD_PATH.include?(__DIR__) ||
  $LOAD_PATH.include?(File.expand_path(__DIR__))

# Some dependencies tend to require&rescue for optionally required files;
# doing so will load the full rubygems, even though it was just optional.
$MINIGEMS_SKIPPABLE = ['encoding/character/utf-8']

module Merb
  # Create stub module for global controller helpers.
  module GlobalHelpers; end

  class << self
    attr_reader :exiting

    def exiting=(bool)
      Extlib.exiting = bool
      if bool && Extlib.const_defined?("Pooling") && Extlib::Pooling.scavenger
        Extlib::Pooling.scavenger.wakeup
      end
      @exiting = bool
    end

    # Merge environment settings
    #
    # This can allow you to have a "localdev" environment that runs like your "development".
    #   OR
    # A "staging" environment that runs identical to your "production" environment.
    #
    # ==== Examples
    # From any environment config file (ie, development.rb, custom.rb, localdev.rb, etc).
    #   staging.rb:
    #     Merb.merge_env "production"         # We want to use all the settings production uses
    #     Merb::Config.use do |c|
    #       c[:log_level]         = "debug"   # except we want debug log level
    #       c[:log_stream]        = @some_io  # and log to this IO handle
    #       c[:exception_details] = true      # and we want to see exception details
    #     end
    #
    # ==== Parameters
    # env<~String>:: Environment to run like
    # use_db<~Boolean>:: Should Merb use the merged environments DB connection
    #     Defaults to +false+
    #
    # @api public
    def merge_env(env,use_db=false)
      if Merb.environment_info.nil?
        Merb.environment_info = {
          :real_env => Merb.environment,
          :merged_envs => [],
          :db_env => Merb.environment
        }
      end

      #Only load if it hasn't been loaded
      unless Merb.environment_info[:merged_envs].member? env
        Merb.environment_info[:merged_envs] << env

        env_file = Merb.dir_for(:config) / "environments" / ("#{env}.rb")
        if File.exists?(env_file)
          load(env_file)
        else
          Merb.logger.warn! "Environment file does not exist! #{env_file}"
        end
      end

      # Mark specific environment to load when ORM loads,
      # if multiple environments are loaded, the last one
      # with use_db as TRUE will be loaded
      if use_db
        Merb.environment_info[:db_env] = env
      end
    end

    # Start Merb by setting up the Config and then starting the server.
    # Set the Merb application environment and the root path.
    #
    # ==== Parameters
    # argv<String, Hash>::
    #   The config arguments to start Merb with. Defaults to +ARGV+.
    #
    # @api public
    def start(argv = ARGV)
      Merb::Config[:original_log_stream] = Merb::Config[:log_stream]
      Merb::Config[:log_stream] ||= STDOUT
      if Hash === argv
        Merb::Config.setup(argv)
      elsif !argv.nil?
        Merb::Config.parse_args(argv)
      end

      Merb::Config[:log_stream] = STDOUT

      Merb.environment = Merb::Config[:environment]
      Merb.root = Merb::Config[:merb_root]

      case Merb::Config[:action]
      when :kill
        Merb::Server.kill(Merb::Config[:port], 2)
      when :kill_9
        Merb::Server.kill(Merb::Config[:port], 9)
      when :fast_deploy
        Merb::Server.kill("main", "HUP")
      else
        Merb::Server.start(Merb::Config[:port], Merb::Config[:cluster])
        @started = true
      end
    end

    # Start the Merb environment, but only if it hasn't been loaded yet.
    #
    # ==== Parameters
    # argv<String, Hash>::
    #   The config arguments to start Merb with. Defaults to +ARGV+.
    #
    # @api public
    def start_environment(argv=ARGV)
      start(argv) unless (@started ||= false)
    end

    # Restart the Merb environment explicitly.
    #
    # ==== Parameters
    # argv<String, Hash>::
    #   The config arguments to restart Merb with. Defaults to +Merb::Config+.
    #
    # @api public
    def restart_environment(argv={})
      @started = false
      start_environment(Merb::Config.to_hash.merge(argv))
    end

    attr_accessor :environment, :load_paths, :adapter, :environment_info, :started

    alias :env :environment
    alias :started? :started

    Merb.load_paths = Dictionary.new { [Merb.root] } unless Merb.load_paths.is_a?(Dictionary)

    # This is the mechanism for setting up your application layout.
    # There are three application layouts in Merb:
    #
    # 1. Regular app/:type layout of Ruby on Rails fame:
    #
    # app/models       for models
    # app/mailers      for mailers (special type of controllers)
    # app/parts        for parts, Merb components
    # app/views        for templates
    # app/controllers  for controller
    # lib              for libraries
    #
    # 2. Flat application layout:
    #
    # application.rb       for models, controllers, mailers, etc
    # config/init.rb       for initialization and router configuration
    # config/framework.rb  for framework and dependencies configuration
    # views                for views
    #
    # 3. Camping-style "very flat" application layout, where the whole Merb
    # application and configs are contained within a single file.
    #
    # ==== Notes
    # Autoloading for lib uses an empty glob by default. If you
    # want to have your libraries under lib use autoload, add
    # the following to Merb init file:
    #
    # Merb.push_path(:lib, Merb.root / "lib", "**/*.rb") # glob set explicity.
    #
    # Then lib/magicwand/lib/magicwand.rb with MagicWand module will
    # be autoloaded when you first access that constant.
    #
    # ==== Examples
    # This method gives you a way to build up your own application
    # structure, for instance, to reflect the structure Rails
    # uses to simplify transition of legacy application, you can
    # set it up like this:
    #
    # Merb.push_path(:model,      Merb.root / "app" / "models",      "**/*.rb")
    # Merb.push_path(:mailer,     Merb.root / "app" / "models",      "**/*.rb")
    # Merb.push_path(:controller, Merb.root / "app" / "controllers", "**/*.rb")
    # Merb.push_path(:view,       Merb.root / "app" / "views",       "**/*.rb")
    #
    # ==== Parameters
    # type<Symbol>:: The type of path being registered (i.e. :view)
    # path<String>:: The full path
    # file_glob<String>::
    #   A glob that will be used to autoload files under the path. Defaults to
    #   "**/*.rb".
    #
    # @api public
    def push_path(type, path, file_glob = "**/*.rb")
      enforce!(type => Symbol)
      load_paths[type] = [path, file_glob]
    end

    # Removes given types of application components
    # from load path Merb uses for autoloading.
    #
    # ==== Parameters
    # *args<Array(Symbol)>::
    #   component(s) names, for instance, :views, :models
    #
    # ==== Examples
    # Using this combined with Merb::GlobalHelpers.push_path you can make
    # your Merb application use legacy Rails application components.
    #
    # Merb.root = "path/to/legacy/app/root"
    # Merb.remove_paths(:mailer)
    # Merb.push_path(:mailer, Merb.root / "app" / "models", "**/*.rb")
    #
    # Will make Merb use app/models for mailers just like Ruby on Rails does.
    #
    # @api public
    def remove_paths(*args)
      args.each {|arg| load_paths.delete(arg)}
    end

    # ==== Parameters
    # type<Symbol>:: The type of path to retrieve directory for, e.g. :view.
    #
    # ==== Returns
    # String:: The directory for the requested type.
    #
    # @api public
    def dir_for(type)
      Merb.load_paths[type].first
    end

    # ==== Parameters
    # type<Symbol>:: The type of path to retrieve glob for, e.g. :view.
    #
    # ===== Returns
    # String:: The pattern with which to match files within the type directory.
    #
    # @api public
    def glob_for(type)
      Merb.load_paths[type][1]
    end

    # ==== Returns
    # String:: The Merb root path.
    #
    # @api public
    def root
      @root || Merb::Config[:merb_root] || File.expand_path(Dir.pwd)
    end

    # ==== Parameters
    # value<String>:: Path to the root directory.
    #
    # @api public
    def root=(value)
      @root = value
    end

    # ==== Parameters
    # *path::
    #   The relative path (or list of path components) to a directory under the
    #   root of the application.
    #
    # ==== Returns
    # String:: The full path including the root.
    #
    # ==== Examples
    #   Merb.root = "/home/merb/app"
    #   Merb.path("images") # => "/home/merb/app/images"
    #   Merb.path("views", "admin") # => "/home/merb/app/views/admin"
    #
    # @public
    def root_path(*path)
      File.join(root, *path)
    end

    # Return the Merb Logger object for the current thread.
    # Set it up if it does not exist.
    #
    # @api public
    def logger
      Thread.current[:merb_logger] ||= Merb::Logger.new
    end

    # Removes the logger for the current thread (nil).
    #
    # @api public
    def reset_logger!
      Thread.current[:merb_logger] = nil
    end

    # ==== Returns
    # String::
    #   The path to the log file.
    #   If this Merb instance is running as a daemon this will return +STDOUT+.
    #
    # ==== Notes
    # When Merb.testing? the port is modified to become :test - this keeps this
    # special environment situation from ending up in the memoized @streams
    # just once, thereby never taking changes into account again. Now, it will
    # be memoized as :test - and just logging to merb_test.log.
    #
    # @api public
    def log_stream(port = "main")
      port = :test if Merb.testing?
      @streams ||= {}
      @streams[port] ||= begin
        log = if Merb.testing?
          log_path / "merb_test.log"
        elsif !Merb::Config[:daemonize] && !Merb::Config[:force_logging]
          STDOUT
        else
          log_path / "merb.#{port}.log"
        end

        if log.is_a?(IO)
          stream = log
        elsif File.exist?(log)
          stream = File.open(log, (File::WRONLY | File::APPEND))
        else
          FileUtils.mkdir_p(File.dirname(log))
          stream = File.open(log, (File::WRONLY | File::APPEND | File::CREAT))
          stream.write("#{Time.now.httpdate} #{Merb::Config[:log_delimiter]} " \
            "info #{Merb::Config[:log_delimiter]} Logfile created\n")
        end
        stream.sync = true
        stream
      end
    end

    # ==== Returns
    # String:: Path to the log directory which contains the log file.
    #
    # @api public
    def log_path
      case Merb::Config[:log_file]
      when String then File.dirname(Merb::Config[:log_file])
      else Merb.root_path("log")
      end
    end

    # ==== Returns
    # String:: The path of root directory of the Merb framework.
    #
    # @api public
    def framework_root
      @framework_root ||= File.dirname(__FILE__)
    end

    # ==== Returns
    # RegExp::
    #   Regular expression against which deferred actions
    #   are matched by Rack application handler.
    #
    # ==== Notes
    # Concatenates :deferred_actions configuration option values.
    #
    # @api public
    def deferred_actions
      @deferred ||= begin
        if Merb::Config[:deferred_actions].empty?
          /^\0$/
        else
          /#{Merb::Config[:deferred_actions].join("|")}/
        end
      end
    end

    # Perform a hard Exit.
    # Print a backtrace to the merb logger before exiting if verbose is enabled.
    #
    # @api private
    def fatal!(str, e = nil)
      Merb.logger.fatal!
      Merb.logger.fatal!("\e[1;31;47mFATAL: #{str}\e[0m")
      Merb.logger.fatal!

      print_colorized_backtrace(e) if e && Merb::Config[:verbose]

      if Merb::Config[:show_ugly_backtraces]
        raise e
      else
        exit(1)
      end
    end

    # Print a colorized backtrace to the merb logger.
    #
    # @api private
    def print_colorized_backtrace(e)
      e.backtrace.map! do |line|
        line.gsub!(/^#{Merb.framework_root}/, "\e[34mFRAMEWORK_ROOT\e[31m")
      end

      Merb.logger.fatal! "\e[34mFRAMEWORK_ROOT\e[0m = #{Merb.framework_root}"
      Merb.logger.fatal!
      Merb.logger.fatal! "\e[31m#{e.class}: \e[1;31;47m#{e.message}\e[0m"
      e.backtrace.each do |line|
        Merb.logger.fatal! "\e[31m#{line}\e[0m"
      end
    end

    # Set up default variables under Merb
    attr_accessor :klass_hashes, :orm, :test_framework, :template_engine

    # Returns the default ORM for this application. For instance, :datamapper.
    #
    # ==== Returns
    # <Symbol>:: default ORM.
    #
    # @api public
    def orm
      @orm ||= :none
    end

    # @deprecated
    def orm_generator_scope
      Merb.logger.warn!("WARNING: Merb.orm_generator_scope is deprecated!")
      return :merb_default if Merb.orm == :none
      Merb.orm
    end

    # Returns the default test framework for this application. For instance :rspec.
    #
    # ==== Returns
    # <Symbol>:: default test framework.
    #
    # @api public
    def test_framework
      @test_framework ||= :rspec
    end

    # @deprecated
    def test_framework_generator_scope
      Merb.logger.warn!("WARNING: Merb.test_framework_generator_scope is deprecated")
      Merb.test_framework
    end

    # Returns the default template engine for this application. For instance :haml.
    #
    # ==== Returns
    # <Symbol>:: default template engine.
    #
    # @api public
    def template_engine
      @template_engine ||= :erb
    end

    Merb.klass_hashes = []

    # ==== Returns
    # Boolean:: True if Merb is running as an application with bundled gems.
    #
    # ==== Notes
    # Bundling required gems makes your application independent from the
    # environment it runs in. It is a good practice to freeze application
    # framework and gems and is very useful when application is run in
    # some sort of sandbox, for instance, shared hosting with preconfigured gems.
    #
    # @api public
    def bundled?
      $BUNDLE || ENV.key?("BUNDLE")
    end

    # Load configuration and assign the logger.
    #
    # ==== Parameters
    # options<Hash>:: Options to pass on to the Merb config.
    #
    # ==== Options
    # :host<String>::             host to bind to,
    #                             default is 0.0.0.0.
    #
    # :port<Fixnum>::             port to run Merb application on,
    #                             default is 4000.
    #
    # :adapter<String>::          name of Rack adapter to use,
    #                             default is "runner"
    #
    # :rackup<String>::           name of Rack init file to use,
    #                             default is "rack.rb"
    #
    # :reload_classes<Boolean>::  whether Merb should reload
    #                             classes on each request,
    #                             default is true
    #
    # :environment<String>::      name of environment to use,
    #                             default is development
    #
    # :merb_root<String>::        Merb application root,
    #                             default is Dir.pwd
    #
    # :use_mutex<Boolean>::       turns action dispatch synchronization
    #                             on or off, default is on (true)
    #
    # :log_delimiter<String>::    what Merb logger uses as delimiter
    #                             between message sections, default is " ~ "
    #
    # :log_auto_flush<Boolean>::  whether the log should automatically
    #                             flush after new messages are
    #                             added, defaults to true.
    #
    # :log_stream<IO>::           IO handle for logger. Defaults to STDOUT.
    #
    # :log_file<String>::         File path for logger. Overrides :log_stream.
    #
    # :log_level<Symbol>::        logger level, default is :info
    #
    # :disabled_components<Array[Symbol]>::
    #   array of disabled component names,
    #   for instance, to disable json gem,
    #   specify :json. Default is empty array.
    #
    # :deferred_actions<Array(Symbol, String)]>::
    #   names of actions that should be deferred
    #   no matter what controller they belong to.
    #   Default is empty array.
    #
    # Some of these options come from command line on Merb
    # application start, some of them are set in Merb init file
    # or environment-specific.
    #
    # @api public
    def load_config(options = {})
      Merb::Config.setup(Merb::Config.defaults.merge(options))
      Merb::BootLoader::Logger.run
    end

    # Load all basic dependencies (selected BootLoaders only).
    # This sets up Merb framework component paths
    # (directories for models, controllers, etc) using
    # framework.rb or default layout, loads init file
    # and dependencies specified in it and runs before_app_loads hooks.
    #
    # ==== Parameters
    # options<Hash>:: Options to pass on to the Merb config.
    #
    # @api public
    def load_dependencies(options = {})
      load_config(options)
      Merb::BootLoader::BuildFramework.run
      Merb::BootLoader::Dependencies.run
      Merb::BootLoader::BeforeAppLoads.run
    end

    # Reload application and framework classes.
    # See Merb::BootLoader::ReloadClasses for details.
    #
    # @api public
    def reload
      Merb::BootLoader::ReloadClasses.reload
    end

    # ==== Returns
    # Boolean:: True if Merb environment is testing for instance,
    # Merb is running with RSpec, Test::Unit of other testing facility.
    #
    # @api public
    def testing?
      $TESTING ||= env?(:test) || Merb::Config[:testing]
    end

    # Ask the question about which environment you're in.
    # ==== Parameters
    # env<Symbol, String>:: Name of the environment to query
    #
    # ==== Examples
    # Merb.env #=> production
    # Merb.env?(:production) #=> true
    # Merb.env?(:development) #=> false
    #
    # @api public
    def env?(env)
      Merb.env == env.to_s
    end

    # If block was given configures using the block.
    #
    # ==== Parameters
    # &block:: Configuration parameter block, see example below.
    #
    # ==== Returns
    # Hash:: The current configuration.
    #
    # ==== Notes
    # See Merb::GlobalHelpers.load_config for configuration
    # options list.
    #
    # ==== Examples
    #   Merb.config do
    #     beer               "good"
    #     hashish            :foo => "bar"
    #     environment        "development"
    #     log_level          "debug"
    #     use_mutex          false
    #     exception_details  true
    #     reload_classes     true
    #     reload_time        0.5
    #   end
    #
    # @api public
    def config(&block)
      Merb::Config.configure(&block) if block_given?
      Config
    end

    # Disables the given core components, like a Gem for example.
    #
    # ==== Parameters
    # *args:: One or more symbols of Merb internal components.
    #
    # @api public
    def disable(*components)
      disabled_components.push(*components)
    end

    # ==== Parameters
    # Array:: All components that should be disabled.
    #
    # @api public
    def disabled_components=(components)
      disabled_components.replace components
    end

    # ==== Returns
    # Array:: All components that have been disabled.
    #
    # @api public
    def disabled_components
      Merb::Config[:disabled_components] ||= []
    end

    # ==== Returns
    # Boolean:: True if all components (or just one) are disabled.
    #
    # @api public
    def disabled?(*components)
      components.all? { |c| disabled_components.include?(c) }
    end

    # ==== Returns
    # Array(String):: Paths Rakefiles are loaded from.
    #
    # ==== Notes
    # Recommended way to find out what paths Rakefiles
    # are loaded from.
    #
    # @api public
    def rakefiles
      @rakefiles ||= []
    end

    # === Returns
    # Array(String):: Paths generators are loaded from
    #
    # === Notes
    # Recommended way to find out what paths generators are loaded from.
    #
    # @api public
    def generators
      @generators ||= []
    end

    # ==== Parameters
    # *rakefiles:: Rakefile paths to add to the list of Rakefiles.
    #
    # ==== Notes
    # Recommended way to add Rakefiles load path for plugins authors.
    #
    # @api public
    def add_rakefiles(*rakefiles)
      @rakefiles ||= []
      @rakefiles += rakefiles
    end

    # ==== Parameters
    # *generators:: Generator paths to add to the list of generators.
    #
    # ==== Notes
    # Recommended way to add Generator load paths for plugin authors.
    #
    # @api public
    def add_generators(*generators)
      @generators ||= []
      @generators += generators
    end

    # Install a signal handler for a given signal unless signals have
    # been disabled with Merb.disable(:signals)
    # ==== Parameters
    # signal:: The name of the signal to install a handler for.
    # &block:: The block to be run when the given signal is received.
    #
    # @api public
    def trap(signal, &block)
      if Signal.list.include?(signal)
        Kernel.trap(signal, &block) unless Merb.disabled?(:signals)
      end
    end

    def forking_environment?
      !on_windows? && !on_jruby?
    end

    def on_jruby?
      RUBY_PLATFORM =~ Merb::Const::JAVA_PLATFORM_REGEXP
    end

    def on_windows?
      RUBY_PLATFORM =~ Merb::Const::WIN_PLATFORM_REGEXP
    end

  end
end

require "merb-core/autoload"
require "merb-core/server"
require "merb-core/gem_ext/erubis"
require "merb-core/logger"
require "merb-core/version"
require "merb-core/controller/mime"

# Set the environment if it hasn't already been set.
Merb.environment ||= ENV["MERB_ENV"] || Merb::Config[:environment] || (Merb.testing? ? "test" : "development")


text:
package tutorial.core.repositories;

import tutorial.core.models.entities.Blog;
import tutorial.core.models.entities.BlogEntry;
import tutorial.core.services.util.BlogEntryList;
import tutorial.core.services.util.BlogList;

import java.util.List;

public interface BlogRepo {
    public Blog createBlog(Blog data);
    public List<Blog> findAllBlogs();
    public Blog findBlog(Long id);
    public Blog findBlogByTitle(String title);
    public List<Blog> findBlogsByAccount(Long accountId);
}

redpajama_set_name: RedPajamaGithub


text:
var _ = require('@sailshq/lodash');

module.exports = function(self, options) {

  // Set `req.locale` based on `req.query.workflowLocale`, `req.session.locale`,
  // the hostname and/or the URL prefix.
  //
  // If the locale is not present or is not valid, set `req.locale` to the
  // default locale by calling `self.guessLocale`.
  //
  // Store the locale in `req.session.locale` as well unless disabled.

  self.expressMiddleware = {
    before: 'apostrophe-global',
    middleware: function(req, res, next) {
      var to, host, matches, locale, prefix, hostname, subdomain, domain, candidates, setByUs;

      function setLocale(locale) {
        req.locale = locale;
        if (locale) {
          setByUs = true;
        }
        if (self.localeInSession(req)) {
          req.session.locale = locale;
        }
        if (self.apos.hasOwnProperty('i18n')) {
          self.apos.i18n.setLocale(req, locale);
        }
      }

      req.data = req.data || {};
      req.data.workflow = req.data.workflow || {};
      _.assign(req.data.workflow, _.pick(self, 'locales', 'nestedLocales'));

      // Hack to implement bc with the subdomains option
      // by populating self.hostnames for each prefix, as soon as we
      // actually know what the domain name is
      if (self.options.subdomains && (!self.hostnames)) {
        host = self.getHost(req);
        self.hostnames = {};
        matches = host.match(/^([^:.]+)(\.([^:]+))?:?/);
        subdomain = matches[1];
        domain = matches[3];
        if (!_.has(self.locales, subdomain)) {
          domain = host;
          if (domain.match(/(:80|:443)$/)) {
            domain = domain.replace(/:\d+$/, '');
          }
        }
        _.each(self.locales, function(locale, name) {
          if (!name.match(/-draft$/)) {
            if (!locale.private) {
              self.hostnames[name] = name + '.' + domain;
            } else {
              self.hostnames[name] = domain;
            }
          }
        });
      }

      if (req.query.workflowLocale) {
        // Switch locale choice in session via query string, then redirect
        locale = self.apos.launder.string(req.query.workflowLocale);

        if (_.has(self.locales, locale)) {
          setLocale(locale);
        }
        if (self.hostnames) {
          // Don't let a stale hostname just switch it back
          to = req.absoluteUrl.replace(/\??workflowLocale=[^&]+&?/, '');
          matches = to.match(/^(https?:)?\/\/([^/:]+)/);
          hostname = matches[2];
          if (hostname) {
            to = to.replace('//' + hostname, '//' + self.hostnames[self.liveify(req.query.workflowLocale)]);
          }
          return res.redirect(to);
        } else {
          return res.redirect(req.url.replace(/\??workflowLocale=[^&]+&?/, ''));
        }
      }

      // test reqs might not have a headers object
      if (req.headers && req.headers['apostrophe-locale']) {
        // API calls use apostrophe-locale headers
        if (_.has(self.locales, req.headers['apostrophe-locale'])) {
          // To avoid race conditions that can break locale switching,
          // we don't modify the session based on the header
          if (self.apos.hasOwnProperty('i18n')) {
            // Careful, i18n.setLocale does not grasp draft locales
            self.apos.i18n.setLocale(req, self.liveify(req.headers['apostrophe-locale']));
          }
          req.locale = req.headers['apostrophe-locale'];
          return next();
        }
      }

      // Start with all of the non-draft locales as candidates
      // (we implement draft vs. live at the end)

      candidates = _.filter(_.keys(self.locales), function(locale) {
        return locale === self.liveify(locale);
      });

      // Winnow it down by hostname

      if (self.hostnames) {
        host = self.getHost(req);
        matches = host.match(/^[^:]+/);
        if (matches) {
          hostname = matches[0];
          candidates = _.filter(candidates, function(candidate) {
            if (self.locales[candidate] && self.locales[candidate].private) {
              if (!self.apos.permissions.can(req, 'private-locales')) {
                return false;
              }
            }
            return self.hostnames[candidate] === hostname;
          });
        }
      }

      function extractRootLevelLocale(candidates) {
        return _.filter(candidates, function (candidate) {
          const locale = self.locales[candidate];
          return (!locale.private) && (!_.has(self.prefixes, candidate));
        });
      }

      // If we're not down to one yet, winnow it down by prefix
      if ((candidates.length > 1) && self.prefixes) {
        // If we're dealing with a locale which shares the hostname
        // with other locales, but doesn't have a prefix, (i.e. it
        // exists at the root level of the hostname), figure out
        // that locale and set that as the current session's locale.
        if (req.url.match(/^\/(\?|$)/)) {
          // a locale which resides at the root level of a shared
          // hostname won't have a prefix. So we select the candidate
          // which doesn't have a prefix in this case.
          candidates = extractRootLevelLocale(candidates);
        } else {
          matches = req.url.match(/^\/[^/]+/);
          if (matches) {
            prefix = matches[0];

            var filteredCandidates = _.filter(candidates, function (candidate) {
              return self.prefixes[candidate] === prefix;
            });

            // At this stage, if the list of filtered candidates is
            // empty, it means the first fragment of the URI didn't
            // match any of the candidates' locale prefixes.
            //
            // We're here because the hostname filter did not narrow
            // the candidates to one, so this is likely to be a URI
            // for a root-level locale among candidates filtered by
            // hostname.
            //
            // However, it could also be an API URL which doesn't care
            // about the locale or is counting on the existing value
            // of req.locale. To resolve this ambiguity we check for
            // a standardized list of URI prefixes that do not
            // imply a locale. This list can be extended.

            if (filteredCandidates.length === 0) {
              if (!self.isApiCall(req)) {
                candidates = extractRootLevelLocale(candidates);
              }
            } else {
              // if the candidates list isn't empty, the URI's first fragment
              // matched the locale prefix for one of the candidates, in which
              // case it's fairly clear how to proceed.
              candidates = filteredCandidates;
            }
          }
        }
      }

      // If we made it down to one locale, that's the winner
      if (candidates.length === 1) {
        var privateLocale = self.locales[candidates[0]] && self.locales[candidates[0]].private;
        if (privateLocale) {
          if (self.apos.permissions.can(req, 'private-locales')) {
            setLocale(candidates[0]);
          }
        } else {
          setLocale(candidates[0]);
        }
      }
      const hostnameDefaultLocale = self.getLocaleViaHostnameDefault(req);
      if (hostnameDefaultLocale && (!setByUs)) {
        if (self.locales[hostnameDefaultLocale] && self.locales[hostnameDefaultLocale].private) {
          if (self.apos.permissions.can(req, 'private-locales')) {
            setLocale(hostnameDefaultLocale);
          }
        } else {
          setLocale(hostnameDefaultLocale);
        }
      }

      req.locale = self.localeInSession(req) ? req.session.locale : req.locale;
      // Resort to the default locale if (1) there is no indication of what locale to use,
      // (2) the locale isn't configured, or (3) the locale is private and we don't have
      // permission to view private locales.

      if ((!req.locale) || (!_.has(self.locales, req.locale)) ||
        (self.locales[req.locale].private && (!self.apos.permissions.can(req, 'private-locales')))) {
        self.guessLocale(req);
        setLocale(req.locale);
      }

      if (req.user) {
        // Handle preview mode first
        if (!req.session.workflowMode && self.defaultMode === 'preview') {
          req.session.workflowPreview = true;
        }

        req.session.workflowMode = req.session.workflowMode || self.defaultMode;
        if (req.session.workflowMode === 'live') {
          req.locale = self.liveify(req.locale);
          req.session.workflowMode = 'live';
        } else {
          req.locale = self.draftify(req.locale);
          req.session.workflowMode = 'draft';
        }
      }

      if (self.prefixes && self.prefixes[self.liveify(req.locale)] && req.url.match(/^\/(\?|$)/)) {
        // Redirect to home page of appropriate locale
        let newUrl = self.prefixes[self.liveify(req.locale)] + '/';
        const matches = req.url.match(/^\/(\?.*)$/);
        if (matches) {
          newUrl += matches[1];
        }
        return res.redirect(self.options.missingPrefixRedirectStatusCode || 302, newUrl);
      }

      return next();
    }
  };

};


text:
Crypto-pubkey
=============

[![Build Status](https://travis-ci.org/vincenthz/hs-crypto-pubkey.png?branch=master)](https://travis-ci.org/vincenthz/hs-crypto-pubkey)
[![BSD](http://b.repl.ca/v1/license-BSD-blue.png)](http://en.wikipedia.org/wiki/BSD_licenses)
[![Haskell](http://b.repl.ca/v1/language-haskell-lightgrey.png)](http://haskell.org)

An extensive public key cryptography library for haskell.

Features
--------

* RSA
    * all major modes supported: PKCS15, OAEP, PSS
    * Support fast RSA decryption and signing: using RSA key by-product when possible
    * RSA with blinder: not comprimising security for performance.
* DSA
* ECDSA
    * There is no protection against timing attacks yet. Signing may leak the
      public key, verification should be fine.
    * It's slow, not optimized yet.
* Diffie Hellman: just primitives
* ElGamal
    * signature/verification scheme
    * encryption/decryption primitive

TODO
----

See TODO file.

Tests
-----

An extensive battery of tests is available in the Tests directory.
It contains quickcheck properties, and KATs (Known-Answer-Tests).

Benchmarks
----------

Operations (mainly RSA for now) can be benchmarks using the benchmark suite
available in the Benchmarks directory.


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

require('../../config.php');
require_once($CFG->dirroot.'/mod/resource/locallib.php');
require_once($CFG->libdir.'/completionlib.php');

$id       = optional_param('id', 0, PARAM_INT); // Course Module ID
$r        = optional_param('r', 0, PARAM_INT);  // Resource instance ID
$redirect = optional_param('redirect', 0, PARAM_BOOL);

if ($r) {
    if (!$resource = $DB->get_record('resource', array('id'=>$r))) {
        resource_redirect_if_migrated($r, 0);
        print_error('invalidaccessparameter');
    }
    $cm = get_coursemodule_from_instance('resource', $resource->id, $resource->course, false, MUST_EXIST);

} else {
    if (!$cm = get_coursemodule_from_id('resource', $id)) {
        resource_redirect_if_migrated(0, $id);
        print_error('invalidcoursemodule');
    }
    $resource = $DB->get_record('resource', array('id'=>$cm->instance), '*', MUST_EXIST);
}

$course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);

require_course_login($course, true, $cm);
$context = context_module::instance($cm->id);
require_capability('mod/resource:view', $context);

add_to_log($course->id, 'resource', 'view', 'view.php?id='.$cm->id, $resource->id, $cm->id);

// Update 'viewed' state if required by completion system
$completion = new completion_info($course);
$completion->set_module_viewed($cm);

$PAGE->set_url('/mod/resource/view.php', array('id' => $cm->id));

if ($resource->tobemigrated) {
    resource_print_tobemigrated($resource, $cm, $course);
    die;
}

$fs = get_file_storage();
$files = $fs->get_area_files($context->id, 'mod_resource', 'content', 0, 'sortorder DESC, id ASC', false); // TODO: this is not very efficient!!
if (count($files) < 1) {
    resource_print_filenotfound($resource, $cm, $course);
    die;
} else {
    $file = reset($files);
    unset($files);
}

$resource->mainfile = $file->get_filename();
$displaytype = resource_get_final_display_type($resource);
if ($displaytype == RESOURCELIB_DISPLAY_OPEN || $displaytype == RESOURCELIB_DISPLAY_DOWNLOAD) {
    // For 'open' and 'download' links, we always redirect to the content - except
    // if the user just chose 'save and display' from the form then that would be
    // confusing
    if (!isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], 'modedit.php') === false) {
        $redirect = true;
    }
}

if ($redirect) {
    // coming from course page or url index page
    // this redirect trick solves caching problems when tracking views ;-)
    $path = '/'.$context->id.'/mod_resource/content/'.$resource->revision.$file->get_filepath().$file->get_filename();
    $fullurl = moodle_url::make_file_url('/pluginfile.php', $path, $displaytype == RESOURCELIB_DISPLAY_DOWNLOAD);
    redirect($fullurl);
}

switch ($displaytype) {
    case RESOURCELIB_DISPLAY_EMBED:
        resource_display_embed($resource, $cm, $course, $file);
        break;
    case RESOURCELIB_DISPLAY_FRAME:
        resource_display_frame($resource, $cm, $course, $file);
        break;
    default:
        resource_print_workaround($resource, $cm, $course, $file);
        break;
}


text:
namespace arangodb {

/// @brief replication request handler
class RocksDBRestReplicationHandler : public RestReplicationHandler {
 public:
  RocksDBRestReplicationHandler(GeneralRequest*, GeneralResponse*);
  ~RocksDBRestReplicationHandler() {}

 public:

  char const* name() const override final {
    return "RocksDBRestReplicationHandler";
  }

 private:

  /// @brief handle a follow command for the replication log
  void handleCommandLoggerFollow() override;

  /// @brief handle the command to determine the transactions that were open
  /// at a certain point in time
  void handleCommandDetermineOpenTransactions() override;

  /// @brief handle a batch command
  void handleCommandBatch() override;

  /// @brief add or remove a WAL logfile barrier
  void handleCommandBarrier() override;

  /// @brief return the inventory (current replication and collection state)
  void handleCommandInventory() override;

  /// @brief produce list of keys for a specific collection
  void handleCommandCreateKeys() override;

  /// @brief returns a key range
  void handleCommandGetKeys() override;

  /// @brief returns date for a key range
  void handleCommandFetchKeys() override;

  /// @brief remove a list of keys for a specific collection
  void handleCommandRemoveKeys() override;

  /// @brief handle a dump command for a specific collection
  void handleCommandDump() override;

 private:

  /// Manage RocksDBReplicationContext containing the dump state for the initial
  /// sync and incremental sync
  RocksDBReplicationManager* _manager;
};
}

#endif


text:
package org.apache.metron.stellar.dsl;

import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.Token;

import java.util.ArrayList;
import java.util.List;

public class GrammarUtils {

  public static String toSyntaxTree(ParseTree tree) {
    return new AST(tree).toString();
  }

  /**
   * This is a utility class to walk the parse tree for an antlr ParseTree
   */
  private static class AST {

    private final Object payload;
    private final List<AST> children;

    public AST(ParseTree tree) {
      this(null, tree);
    }

    private AST(AST ast, ParseTree tree) {
      this(ast, tree, new ArrayList<>());
    }

    private AST(AST parent, ParseTree tree, List<AST> children) {
      this.payload = getPayload(tree);
      this.children = children;
      if (parent == null) {
        walk(tree, this);
      }
      else {
        parent.children.add(this);
      }
    }

    private Object getPayload(ParseTree tree) {
      if (tree.getChildCount() == 0) {
        return tree.getPayload();
      }
      else {
        String ruleName = tree.getClass().getSimpleName().replace("Context", "");
        return Character.toLowerCase(ruleName.charAt(0)) + ruleName.substring(1);
      }
    }

    private static void walk(ParseTree tree, AST ast) {
      if (tree.getChildCount() == 0) {
        new AST(ast, tree);
      }
      else if (tree.getChildCount() == 1) {
        walk(tree.getChild(0), ast);
      }
      else if (tree.getChildCount() > 1) {
        for (int i = 0; i < tree.getChildCount(); i++) {
          AST temp = new AST(ast, tree.getChild(i));
          if (!(temp.payload instanceof Token)) {
            walk(tree.getChild(i), temp);
          }
        }
      }
    }

    @Override
    public String toString() {
      StringBuilder builder = new StringBuilder();
      AST ast = this;
      List<AST> firstStack = new ArrayList<>();
      firstStack.add(ast);
      List<List<AST>> childListStack = new ArrayList<>();
      childListStack.add(firstStack);
      while (!childListStack.isEmpty()) {
        List<AST> childStack = childListStack.get(childListStack.size() - 1);
        if (childStack.isEmpty()) {
          childListStack.remove(childListStack.size() - 1);
        }
        else {
          ast = childStack.remove(0);
          String caption;
          if (ast.payload instanceof Token) {
            Token token = (Token) ast.payload;
            caption = String.format("TOKEN[type: %s, text: %s]",
                    token.getType(), token.getText().replace("\n", "\\n"));
          }
          else {
            caption = String.valueOf(ast.payload);
          }
          String indent = "";
          for (int i = 0; i < childListStack.size() - 1; i++) {
            indent += (childListStack.get(i).size() > 0) ? "|  " : "   ";
          }
          builder.append(indent)
                  .append(childStack.isEmpty() ? "'- " : "|- ")
                  .append(caption)
                  .append("\n");

          if (ast.children.size() > 0) {
            List<AST> children = new ArrayList<>();
            for (int i = 0; i < ast.children.size(); i++) {
              children.add(ast.children.get(i));
            }
            childListStack.add(children);
          }
        }
      }
      return builder.toString();
    }
  }
}


text:
@interface InfoPageChildViewController ()

@property (nonatomic, strong) NSString *topText;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSString *bottomText;
@property (nonatomic, strong) UIColor *backgroundColour;
@property (nonatomic, strong) UIColor *textColor;
@property (nonatomic, strong) NSURL *url;
@property (nonatomic, strong) NSString *linkTitle;

@end

@implementation InfoPageChildViewController

- (instancetype)initWithTopText:(NSString *)topText
                          image:(UIImage *)image
                     bottomText:(NSString *)bottomText
               backgroundColour:(UIColor *)backgroundColour
                      textColor:(UIColor *)textColor
                            url:(NSURL*)url
                      linkTitle:(NSString*)linkTitle{
    if (self = [super init]) {
        self.topText = topText;
        self.image = image;
        self.bottomText = bottomText;
        self.backgroundColour = backgroundColour;
        self.textColor = textColor;
        if (url){
            self.url = url;
        }
        self.linkTitle = linkTitle;
    }

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

  self.screenName = @"InfoPageChildViewController";

    self.topLabel.text = self.topText;
    self.imageView.image = self.image;
    self.bottomLabel.text = self.bottomText;

    self.view.backgroundColor = self.backgroundColour;

    self.topLabel.textColor = self.textColor;
    self.bottomLabel.textColor = self.textColor;

    [self addLink:self.url];
}

- (void)viewDidAppear:(BOOL)animated{
    if (self.url){
        UITapGestureRecognizer *tap;
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(promptToOpenURL:)];
        [self.imageView setUserInteractionEnabled:YES];
        [self.imageView addGestureRecognizer:tap];
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(promptToOpenURL:)];
        [self.bottomLabel addGestureRecognizer:tap];
    }
}

- (void)addLink:(NSURL*)url{
    if (url){
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(promptToOpenURL:)];
        [self.imageView addGestureRecognizer:tap];
        [self.imageView setUserInteractionEnabled:YES];
        [self.bottomLabel addGestureRecognizer:tap];
    }
}

- (void)promptToOpenURL:(NSURL*)url{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:self.linkTitle
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"No", nil)
                                          otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex) {
        [[UIApplication sharedApplication] openURL:self.url];
    }
}

@end


text:
require "rails_helper"

describe UserAnonymizer do

  describe "make_anonymous" do
    let(:admin) { Fabricate(:admin) }
    let(:user) { Fabricate(:user, username: "edward", auth_token: "mysecretauthtoken") }

    subject(:make_anonymous) { described_class.make_anonymous(user, admin) }

    it "changes username" do
      make_anonymous
      expect(user.reload.username).to match(/^anon\d{3,}$/)
    end

    it "changes email address" do
      make_anonymous
      expect(user.reload.email).to eq("#{user.username}@example.com")
    end

    it "turns off all notifications" do
      make_anonymous
      user.reload
      expect(user.email_digests).to eq(false)
      expect(user.email_private_messages).to eq(false)
      expect(user.email_direct).to eq(false)
      expect(user.email_always).to eq(false)
      expect(user.mailing_list_mode).to eq(false)
    end

    it "resets profile to default values" do
      user.update_attributes( name: "Bibi", date_of_birth: 19.years.ago, title: "Super Star" )

      profile = user.user_profile(true)
      profile.update_attributes( location: "Moose Jaw",
                                 website: "www.bim.com",
                                 bio_raw: "I'm Bibi from Moosejaw. I sing and dance.",
                                 bio_cooked: "I'm Bibi from Moosejaw. I sing and dance.",
                                 profile_background: "http://example.com/bg.jpg",
                                 bio_cooked_version: 2,
                                 card_background: "http://example.com/cb.jpg")
      make_anonymous
      user.reload

      expect(user.name).not_to be_present
      expect(user.date_of_birth).to eq(nil)
      expect(user.title).not_to be_present
      expect(user.auth_token).to eq(nil)

      profile = user.user_profile(true)
      expect(profile.location).to eq(nil)
      expect(profile.website).to eq(nil)
      expect(profile.bio_cooked).to eq(nil)
      expect(profile.profile_background).to eq(nil)
      expect(profile.bio_cooked_version).to eq(nil)
      expect(profile.card_background).to eq(nil)
    end

    it "removes the avatar" do
      upload = Fabricate(:upload, user: user)
      user.user_avatar = UserAvatar.new(user_id: user.id, custom_upload_id: upload.id)
      user.uploaded_avatar_id = upload.id # chosen in user preferences
      user.save!
      expect { make_anonymous }.to change { Upload.count }.by(-1)
      user.reload
      expect(user.user_avatar).to eq(nil)
      expect(user.uploaded_avatar_id).to eq(nil)
    end

    it "logs the action" do
      expect { make_anonymous }.to change { UserHistory.count }.by(1)
    end

    it "removes external auth assocations" do
      user.twitter_user_info = TwitterUserInfo.create(user_id: user.id, screen_name: "example", twitter_user_id: "examplel123123")
      user.google_user_info = GoogleUserInfo.create(user_id: user.id, google_user_id: "google@gmail.com")
      user.github_user_info = GithubUserInfo.create(user_id: user.id, screen_name: "example", github_user_id: "examplel123123")
      user.facebook_user_info = FacebookUserInfo.create(user_id: user.id, facebook_user_id: "example")
      user.single_sign_on_record = SingleSignOnRecord.create(user_id: user.id, external_id: "example", last_payload: "looks good")
      user.oauth2_user_info = Oauth2UserInfo.create(user_id: user.id, uid: "example", provider: "example")
      UserOpenId.create(user_id: user.id, email: user.email, url: "http://example.com/openid", active: true)
      make_anonymous
      user.reload
      expect(user.twitter_user_info).to eq(nil)
      expect(user.google_user_info).to eq(nil)
      expect(user.github_user_info).to eq(nil)
      expect(user.facebook_user_info).to eq(nil)
      expect(user.single_sign_on_record).to eq(nil)
      expect(user.oauth2_user_info).to eq(nil)
      expect(user.user_open_ids.count).to eq(0)
    end

    it "removes api key" do
      ApiKey.create(user_id: user.id, key: "123123123")
      expect { make_anonymous }.to change { ApiKey.count }.by(-1)
      user.reload
      expect(user.api_key).to eq(nil)
    end

  end

end


text:
local io = { open = io.open }
local setmetatable = setmetatable
local string = { match = string.match }
-- }}}

-- Thermal: provides temperature levels of ACPI thermal zones
module("vicious.thermal")

-- {{{ Thermal widget type
local function worker(format, thermal_zone)
    -- Get an ACPI thermal zone
    local f = io.open("/proc/acpi/thermal_zone/"..thermal_zone.."/temperature")
    -- Handler for incompetent users
    if not f then return {"N/A"} end
    local line = f:read("*line")
    f:close()

    local temperature = string.match(line, "[%d]?[%d]?[%d]")

    return {temperature}
end
-- }}}

setmetatable(_M, { __call = function(_, ...) return worker(...) end })


text:
using namespace std;
class Test
{
public:
    Test(int n=0);
    void print();
private:
    int data;

};

#endif // TEST_H_INCLUDED


text:
layout: post-index
title: All Posts
---


text:
/**
 * pt_br lang variables
 * Brazilian Portuguese
 *
 * Authors :
 *           Marcio Barbosa (mpg) <mpg@mpg.com.br>
 * Last Updated : November 26, 2005
 * TinyMCE Version : 2.0RC4
 */
tinyMCE.addToLang('',{
directionality_ltr_desc : 'Direcionamento da esquerda para direita',
directionality_rtl_desc : 'Direcionamento da direita para esquerda'
});


text:
package sociam.pybossa.graphics2g.test;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;

public class ImageWithAnImage {

	// the hight of the text
	static int height = 140;

	public static void main(String[] args) {

		File file = combineTextWithImage(
				"Is this content relevant for some real-world event related to #BRITs2016? #t34563",
				"https://pbs.twimg.com/media/CcIm3uOUkAILSIs.jpg");
		if (file != null){
			System.out.println(file.getAbsolutePath());
		}else{
			System.err.println("error");
		}

	}

	public static File combineTextWithImage(String text, String ImageURL) {

		try {

			URL url = new URL(ImageURL);
			BufferedImage img1 = ImageIO.read(url);

			BufferedImage img2 = convertStringToImage(text, img1.getWidth());
			File combinedImage = draw(img1, img2);
			return combinedImage;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	private static File draw(BufferedImage img1, BufferedImage img2) {
		try {
			int widthImg1 = img1.getWidth();
			int heightImg1 = img1.getHeight();
			int heightImg2 = img2.getHeight();
			BufferedImage img = new BufferedImage(widthImg1, heightImg1 + heightImg2, BufferedImage.TYPE_INT_RGB);
			img.createGraphics().setColor(Color.RED);
			boolean image1Drawn = img.createGraphics().drawImage(img1, 0, 20 + img2.getHeight(), null);
			if (!image1Drawn) {
				System.out.println("Problems drawing first image");
			}
			boolean image2Drawn = img.createGraphics().drawImage(img2, 0, 0, null);
			if (!image2Drawn) {
				System.out.println("Problems drawing second image");
			}

			File final_image = new File("Final.jpg");
			if (ImageIO.write(img, "jpeg", final_image)) {
				return final_image;
			} else {
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}

	private static BufferedImage convertStringToImage(String text, int width) {

		try {
			BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_BINARY);
			Graphics2D g2d = img.createGraphics();

			Font font = new Font("Arial", Font.PLAIN, 20);
			g2d.setFont(font);
			FontMetrics fm = g2d.getFontMetrics();
			g2d.dispose();
			img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
			g2d = img.createGraphics();
			g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
					RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
			g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
			g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
			g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
			g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
			g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
			g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
			// g2d.setColor(Color.BLUE);
			// g2d.fillRect(0, 0, width, height);
			g2d.setFont(font);
			g2d.setColor(Color.WHITE);
			// g2d.fillRect(0, 0, width, height);
			fm = g2d.getFontMetrics();

			int x = 20;
			int y = 30;
			if (fm.stringWidth(text) < width) {
				g2d.drawString(text, x, height / 2);
			} else {
				String[] words = text.split("\\s+");
				String currentLine = words[0];
				for (int i = 1; i < words.length; i++) {
					String tmp = currentLine + " " + words[i];
					if (fm.stringWidth(tmp) < width) {
						currentLine = currentLine + " " + words[i];
					} else {
						g2d.drawString(currentLine, x, y);
						y += fm.getHeight();
						currentLine = words[i];
					}
				}
				if (currentLine.trim().length() > 0) {
					g2d.drawString(currentLine, x, y);
				}
			}
			g2d.dispose();
			return img;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
}


text:
<!DOCTYPE HTML>

<title>DeepEyeStore (Xponents Core API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-02-02">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

copyright             OpenSextant.org, 2013-2021

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Package org.opensextant.annotations

Interface DeepEyeStore

public interface DeepEyeStore

DeepEyeStore is an abstraction of a data store that stores records and
 annotations.
 For example, we built annotation stores implementing DeepEyeStore using
 MongoDB, Postgres, Elasticsearch and SQLite backends.

Author:

ubaldino

Method Summary

<button role="tab" aria-selected="true" aria-controls="memberSummary_tabpanel" tabindex="0" onkeydown="switchTab(event)" id="t0" class="activeTableTab">All Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t2" class="tableTab" onclick="show(2);">Instance Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t3" class="tableTab" onclick="show(4);">Abstract Methods</button>

Modifier and Type
Method
Description

void
add(java.util.Collection<Annotation> aList)

add a list of entity annotations.

void
add(Annotation A)

add a single Annotation.

void
add(Record R)

Add new record.

void
connect()

void
disconnect()

Record
findRecord(java.lang.String id)

find a single record.

java.util.List<Annotation>
findSimilar(Annotation q)

given the shell of a annot, find similar records.

java.util.List<Record>
findSimilar(Record q)

given the shell of a record, find similar records.

void
save(Record R)

Suggested Save operation: check if exists, update if it does, otherwise
 insert.

void
update(Annotation A)

Update an existing annotation.

void
update(Record R)

The implementation of a record update

void
updateState(Record R)

Update only the state of a record

Method Detail

connect

void connect()
      throws DeepEyeException

Throws:

DeepEyeException

disconnect

void disconnect()

add

void add(Record R)
  throws DeepEyeException

Add new record.

Throws:

DeepEyeException

update

void update(Record R)
     throws DeepEyeException

The implementation of a record update

Parameters:

R - record to update

Throws:

DeepEyeException - on failure to update Record

save

void save(Record R)
   throws DeepEyeException

Suggested Save operation: check if exists, update if it does, otherwise
 insert. This is typically
 adjustable behavior.

Parameters:

R -

Throws:

DeepEyeException - on failure to save Record, because system was down,
                          lack of privileges,
                          or inability to overwrite existing.

updateState

void updateState(Record R)
          throws DeepEyeException

Update only the state of a record

Throws:

DeepEyeException

findRecord

Record findRecord(java.lang.String id)
           throws DeepEyeException

find a single record. Avoid the overhead of a cursor for "findOne" query.
 Where you know you are
 looking for one or none.

Parameters:

id -

Returns:

Deepeye Record object

Throws:

DeepEyeException

add

void add(Annotation A)
  throws DeepEyeException

add a single Annotation.

Throws:

DeepEyeException

add

void add(java.util.Collection<Annotation> aList)
  throws DeepEyeException

add a list of entity annotations.

Parameters:

aList -

Throws:

DeepEyeException

update

void update(Annotation A)
     throws DeepEyeException

Update an existing annotation. This does nothing if the annotation does not
 exist in the
 database.

Throws:

DeepEyeException

findSimilar

java.util.List<Record> findSimilar(Record q)
                            throws DeepEyeException

given the shell of a record, find similar records.

Throws:

DeepEyeException

findSimilar

java.util.List<Annotation> findSimilar(Annotation q)

given the shell of a annot, find similar records.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

copyright             OpenSextant.org, 2013-2021

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2013–2022. All rights reserved.


text:
START_ATF_NAMESPACE
    namespace vc_attributes
    {
        namespace helper_attributes
        {
            #pragma pack(push, 4)
            template<>
            struct attributeAttribute
            {
                int ValidOn;
                bool AllowMultiple;
                bool Inherited;
            };
            #pragma pack(pop)
        }; // end namespace helper_attributes
    }; // end namespace vc_attributes
END_ATF_NAMESPACE


text:
#include "_CrossEngine.h"

namespace CrossEngine {

	CEntityEffect::CEntityEffect(DWORD dwName, CSceneManager *pSceneManager)
		: CEntityRenderable(dwName, pSceneManager)
		, m_bPlaying(FALSE)
		, m_bPause(FALSE)

		, m_currTime(0.0f)
		, m_beginTime(0.0f)
		, m_durationTime(0.0f)
	{

	}

	CEntityEffect::~CEntityEffect(VOID)
	{
		m_ptrEffect.SetNull();
	}

	//
	// »ñµÃÀàÐÍ
	//
	CEntity::TYPE CEntityEffect::GetType(VOID) const
	{
		return CEntity::EFFECT;
	}

	//
	// »ñµÃ¿ÉäÖȾ
	//
	BOOL CEntityEffect::IsRenderable(VOID) const
	{
		return TRUE;
	}

	//
	// ÉèÖÃÌØЧ
	//
	BOOL CEntityEffect::SetEffect(const CHAR *szName)
	{
		ASSERT(szName);
		return SetEffect(HashValue(szName));
	}

	//
	// ÉèÖÃÌØЧ
	//
	BOOL CEntityEffect::SetEffect(DWORD dwName)
	{
		return SetEffect(EffectManager()->QueryResource(dwName));
	}

	//
	// ÉèÖÃÌØЧ
	//
	BOOL CEntityEffect::SetEffect(const CEffectPtr &ptrEffect)
	{
		//
		// 1. ²ÎÊý°²È«¼ì²é
		//
		if (ptrEffect.IsNull() || ptrEffect->IsValid() == FALSE) {
			return FALSE;
		}

		//
		// 2. ÉèÖÃÌØЧ
		//
		m_ptrEffect = CEffectPtr(EffectManager()->CreateResource());
		m_ptrEffect->CopyFrom(ptrEffect.GetPointer());
		m_ptrEffect->SetName(Engine()->GetNextEffectName());

		//
		// 3. ÉèÖðüΧºÐ
		//
		AABBCopy(&m_aabbLocal, m_ptrEffect->GetAABB());

		return TRUE;
	}

	//
	// »ñµÃÌØЧ
	//
	const CEffectPtr& CEntityEffect::GetEffect(VOID) const
	{
		return m_ptrEffect;
	}

	//
	// ²¥·Å
	//
	VOID CEntityEffect::Play(FLOAT beginTime, FLOAT durationTime, BOOL bImmediately)
	{
		//
		// 1. ²ÎÊý°²È«¼ì²é
		//
		if (m_ptrEffect.IsNull() || m_ptrEffect->IsValid() == FALSE) {
			return;
		}

		//
		// 2. ֹͣ
		//
		Stop(bImmediately);

		//
		// 3. ²¥·Å
		//
		m_bPlaying = TRUE;
		m_bPause = FALSE;

		m_currTime = 0.0f;
		m_beginTime = beginTime;
		m_durationTime = durationTime;
	}

	//
	// ֹͣ
	//
	VOID CEntityEffect::Stop(BOOL bImmediately)
	{
		//
		// 1. ²ÎÊý°²È«¼ì²é
		//
		if (m_ptrEffect.IsNull() || m_ptrEffect->IsValid() == FALSE) {
			return;
		}

		//
		// 2. ֹͣ
		//
		m_bPlaying = FALSE;

		//
		// 3. Í£Ö¹Á£×ÓϵͳºÍÉùÒô
		//
		const CEffect::SoundMap &sounds = m_ptrEffect->GetSounds();
		const CEffect::ParticleSystemMap &particleSystems = m_ptrEffect->GetParticleSystems();

		for (CEffect::SoundMap::const_iterator itSound = sounds.begin(); itSound != sounds.end(); ++itSound) {
			CEffect::SOUND *pSound = itSound->second;
			ASSERT(pSound);

			SoundSystem()->Stop(pSound->pChannel);
			pSound->pChannel = NULL;
		}

		for (CEffect::ParticleSystemMap::const_iterator itParticleSystem = particleSystems.begin(); itParticleSystem != particleSystems.end(); ++itParticleSystem) {
			CEffect::PARTICLESYSTEM *pParticleSystem = itParticleSystem->second;
			ASSERT(pParticleSystem);
			ASSERT(pParticleSystem->pParticleSystem);

			pParticleSystem->pParticleSystem->Stop(bImmediately);
		}
	}

	//
	// ÔÝÍ£
	//
	VOID CEntityEffect::Pause(VOID)
	{
		//
		// 1. ²ÎÊý°²È«¼ì²é
		//
		if (m_ptrEffect.IsNull() || m_ptrEffect->IsValid() == FALSE) {
			return;
		}

		//
		// 2. ÔÝÍ£
		//
		m_bPause = TRUE;

		//
		// 3. ÔÝÍ£Á£×ÓϵͳºÍÉùÒô
		//
		const CEffect::SoundMap &sounds = m_ptrEffect->GetSounds();
		const CEffect::ParticleSystemMap &particleSystems = m_ptrEffect->GetParticleSystems();

		for (CEffect::SoundMap::const_iterator itSound = sounds.begin(); itSound != sounds.end(); ++itSound) {
			CEffect::SOUND *pSound = itSound->second;
			ASSERT(pSound);

			SoundSystem()->Pause(pSound->pChannel);
		}

		for (CEffect::ParticleSystemMap::const_iterator itParticleSystem = particleSystems.begin(); itParticleSystem != particleSystems.end(); ++itParticleSystem) {
			CEffect::PARTICLESYSTEM *pParticleSystem = itParticleSystem->second;
			ASSERT(pParticleSystem);
			ASSERT(pParticleSystem->pParticleSystem);

			pParticleSystem->pParticleSystem->Pause();
		}
	}

	//
	// ¼ÌÐø
	//
	VOID CEntityEffect::Resume(VOID)
	{
		//
		// 1. ²ÎÊý°²È«¼ì²é
		//
		if (m_ptrEffect.IsNull() || m_ptrEffect->IsValid() == FALSE) {
			return;
		}

		//
		// 2. ¼ÌÐø
		//
		m_bPause = FALSE;

		//
		// 3. ¼ÌÐøÁ£×ÓϵͳºÍÉùÒô
		//
		const CEffect::SoundMap &sounds = m_ptrEffect->GetSounds();
		const CEffect::ParticleSystemMap &particleSystems = m_ptrEffect->GetParticleSystems();

		for (CEffect::SoundMap::const_iterator itSound = sounds.begin(); itSound != sounds.end(); ++itSound) {
			CEffect::SOUND *pSound = itSound->second;
			ASSERT(pSound);

			SoundSystem()->Resume(pSound->pChannel);
		}

		for (CEffect::ParticleSystemMap::const_iterator itParticleSystem = particleSystems.begin(); itParticleSystem != particleSystems.end(); ++itParticleSystem) {
			CEffect::PARTICLESYSTEM *pParticleSystem = itParticleSystem->second;
			ASSERT(pParticleSystem);
			ASSERT(pParticleSystem->pParticleSystem);

			pParticleSystem->pParticleSystem->Resume();
		}
	}

	//
	// ²¥·Å״̬
	//
	BOOL CEntityEffect::IsPlaying(VOID)
	{
		return m_bPlaying && m_bPause == FALSE;
	}

	//
	// ¸üе½ÏÂÒ»Ö¡
	//
	BOOL CEntityEffect::NextFrame(FLOAT deltaTime)
	{
		//
		// 1. ²ÎÊý°²È«¼ì²é
		//
		if (m_ptrEffect.IsNull() || m_ptrEffect->IsValid() == FALSE) {
			return FALSE;
		}

		//
		// 2. ʱ¼äµÝ½ø
		//
		if (IsPlaying()) {
			m_currTime += deltaTime;
		}

		//
		// 3. ¸üе½ÏÂÒ»Ö¡
		//
		BOOL bShakePlaying = FALSE;
		BOOL bSoundPlaying = FALSE;
		BOOL bParticleSystemPlaying = FALSE;
		BOOL bParticleSystemGfxPlaying = FALSE;

		if (m_currTime > m_beginTime && (m_currTime < m_beginTime + m_durationTime || m_durationTime < EPSILON_E3)) {
			if (IsPlaying()) {
				bShakePlaying = UpdateShakes(deltaTime);
				bSoundPlaying = UpdateSounds(deltaTime);
				bParticleSystemPlaying = UpdateParticleSystems(deltaTime);
			}

			// ˵Ã÷: äÖȾÁ£×ӿɲ»Êܲ¥·Å¿ØÖÆ, ÔÚ²¥·ÅÍ£Ö¹ºóÁ£×Ó¿ÉËæÆäÉúÃüÖÜÆÚ×Ô¶¯ÏûÍö!!!
			bParticleSystemGfxPlaying = UpdateParticleSystemsGfx(deltaTime);
		}

		return bShakePlaying || bSoundPlaying || bParticleSystemPlaying || bParticleSystemGfxPlaying ? TRUE : FALSE;
	}

	//
	// ¸üÐÂÁ£×Óϵͳ
	//
	BOOL CEntityEffect::UpdateParticleSystems(FLOAT deltaTime)
	{
		BOOL bPlaying = FALSE;

		FLOAT localTime = m_currTime - m_beginTime;
		const CEffect::ParticleSystemMap &particleSystems = m_ptrEffect->GetParticleSystems();

		for (CEffect::ParticleSystemMap::const_iterator itParticleSystem = particleSystems.begin(); itParticleSystem != particleSystems.end(); ++itParticleSystem) {
			CEffect::PARTICLESYSTEM *pParticleSystem = itParticleSystem->second;
			ASSERT(pParticleSystem);
			ASSERT(pParticleSystem->pParticleSystem);

			if (localTime > pParticleSystem->beginTime && (localTime < pParticleSystem->beginTime + pParticleSystem->durationTime || pParticleSystem->durationTime < EPSILON_E3)) {
				if (pParticleSystem->pParticleSystem->IsPlaying() == FALSE) {
					pParticleSystem->pParticleSystem->Play(FALSE);
				}
			}
			else {
				if (pParticleSystem->pParticleSystem->IsPlaying()) {
					pParticleSystem->pParticleSystem->Stop();
				}
			}

			// ×¢Òâ: Á£×Óϵͳ»¹Ã»¿ªÊ¼²¥·Å»òÕßÑ»·²¥·Å»òÕß»¹Î´²¥·Å½áÊø¾ùÈÏΪÊÇ»¹ÔÚ²¥·ÅÖÐ!!!
			if (localTime < pParticleSystem->beginTime + pParticleSystem->durationTime || pParticleSystem->durationTime < EPSILON_E3 || pParticleSystem->pParticleSystem->IsPlayFinish() == FALSE) {
				bPlaying |= TRUE;
			}
		}

		return bPlaying;
	}

	//
	// ¸üÐÂÁ£×ÓϵͳͼÐÎ
	//
	BOOL CEntityEffect::UpdateParticleSystemsGfx(FLOAT deltaTime)
	{
		BOOL bPlaying = FALSE;

		FLOAT localTime = m_currTime - m_beginTime;
		const CEffect::ParticleSystemMap &particleSystems = m_ptrEffect->GetParticleSystems();

		for (CEffect::ParticleSystemMap::const_iterator itParticleSystem = particleSystems.begin(); itParticleSystem != particleSystems.end(); ++itParticleSystem) {
			CEffect::PARTICLESYSTEM *pParticleSystem = itParticleSystem->second;
			ASSERT(pParticleSystem);
			ASSERT(pParticleSystem->pParticleSystem);

			if (pParticleSystem->pParticleSystem->IsPlayFinish() == FALSE) {
				pParticleSystem->pParticleSystem->SetScale(m_pSceneNode->GetWorldScale());
				pParticleSystem->pParticleSystem->SetPosition(m_pSceneNode->GetWorldPosition());
				pParticleSystem->pParticleSystem->SetOrientation(m_pSceneNode->GetWorldOrientation());

				pParticleSystem->pParticleSystem->Update(deltaTime);
				pParticleSystem->pParticleSystem->UpdateGfx(m_pSceneManager->GetMainCameraEntity());

				bPlaying |= TRUE;
			}
		}

		return bPlaying;
	}

	//
	// ¸üÐÂÉùÒô
	//
	BOOL CEntityEffect::UpdateSounds(FLOAT deltaTime)
	{
		BOOL bPlaying = FALSE;

		FLOAT localTime = m_currTime - m_beginTime;
		const CEffect::SoundMap &sounds = m_ptrEffect->GetSounds();

		for (CEffect::SoundMap::const_iterator itSound = sounds.begin(); itSound != sounds.end(); ++itSound) {
			CEffect::SOUND *pSound = itSound->second;
			ASSERT(pSound);

			if (localTime > pSound->beginTime && (localTime < pSound->beginTime + pSound->durationTime || pSound->durationTime < EPSILON_E3)) {
				if (SoundSystem()->IsPlaying(pSound->pChannel) == FALSE && pSound->pChannel == NULL) {
					pSound->pChannel = SoundSystem()->Play(pSound->ptrSound->GetSound(), FALSE, pSound->bLoop, TRUE);
				}

				if (SoundSystem()->IsPlaying(pSound->pChannel)) {
					SoundSystem()->SetSoundPosition(pSound->pChannel, m_pSceneNode->GetWorldPosition());
					SoundSystem()->SetSoundVolume(pSound->pChannel, pSound->volume);
				}
			}
			else {
				if (pSound->pChannel) {
					SoundSystem()->Stop(pSound->pChannel);
					pSound->pChannel = NULL;
				}
			}

			// ×¢Òâ: ÉùÒô»¹Ã»¿ªÊ¼²¥·Å»òÕßÑ»·²¥·Å¾ùÈÏΪÊÇ»¹ÔÚ²¥·ÅÖÐ!!!
			if (localTime < pSound->beginTime + pSound->durationTime || pSound->durationTime < EPSILON_E3) {
				bPlaying |= TRUE;
			}
		}

		return bPlaying;
	}

	//
	// ¸üÐÂÕð¶¯
	//
	BOOL CEntityEffect::UpdateShakes(FLOAT deltaTime)
	{
		BOOL bPlaying = FALSE;

		FLOAT localTime = m_currTime - m_beginTime;
		const CEffect::ShakeMap shakes = m_ptrEffect->GetShakes();

		VEC3 distance;
		Vec3Sub(&distance, m_pSceneNode->GetWorldPosition(), m_pSceneManager->GetMainCameraEntity()->GetPosition());

		FLOAT len = Vec3Length(&distance);
		FLOAT len2 = Vec3Length2(&distance);

		for (CEffect::ShakeMap::const_iterator itShake = shakes.begin(); itShake != shakes.end(); ++itShake) {
			CEffect::SHAKE *pShake = itShake->second;
			ASSERT(pShake);

			FLOAT x = 0.0f;
			FLOAT y = 0.0f;
			FLOAT z = 0.0f;

			if (localTime > pShake->beginTime && (localTime < pShake->beginTime + pShake->durationTime || pShake->durationTime < EPSILON_E3)) {
				FLOAT attenuation = pShake->constantAttenuation + pShake->linearAttenuation*len + pShake->quadraticAttenuation*len2;
				FLOAT invAttenuation = attenuation < EPSILON_E3 ? 0.0f : 1.0f / attenuation;

				x = (pShake->minShake[0] + (FRandomValue() * (pShake->maxShake[0] - pShake->minShake[0]))) * invAttenuation;
				y = (pShake->minShake[1] + (FRandomValue() * (pShake->maxShake[1] - pShake->minShake[1]))) * invAttenuation;
				z = (pShake->minShake[2] + (FRandomValue() * (pShake->maxShake[2] - pShake->minShake[2]))) * invAttenuation;
			}

			// ×¢Òâ: Õ𶯻¹Ã»¿ªÊ¼²¥·Å»òÕßÑ»·²¥·Å¾ùÈÏΪÊÇ»¹ÔÚ²¥·ÅÖÐ!!!
			if (localTime < pShake->beginTime + pShake->durationTime || pShake->durationTime < EPSILON_E3) {
				bPlaying |= TRUE;
			}

			m_pSceneManager->GetMainCameraEntity()->SetShake(x, y, z);
		}

		return bPlaying;
	}

	//
	// ¸üÐÂäÖȾ¶ÓÁÐ
	//
	VOID CEntityEffect::UpdateRenderQuene(const CEntityCamera *pCamera)
	{
		//
		// 1. ²ÎÊý°²È«¼ì²é
		//
		if (m_ptrEffect.IsNull() || m_ptrEffect->IsValid() == FALSE) {
			return;
		}

		//
		// 2. ¸üÐÂäÖȾ¶ÓÁÐ
		//
		const CEffect::ParticleSystemMap &particleSystems = m_ptrEffect->GetParticleSystems();

		for (CEffect::ParticleSystemMap::const_iterator itParticleSystem = particleSystems.begin(); itParticleSystem != particleSystems.end(); ++itParticleSystem) {
			CEffect::PARTICLESYSTEM *pParticleSystem = itParticleSystem->second;
			ASSERT(pParticleSystem);
			ASSERT(pParticleSystem->pParticleSystem);

			if (pParticleSystem->pParticleSystem->IsPlayFinish() == FALSE) {
				m_pSceneManager->AddSceneRenderQuene(pCamera, this, pParticleSystem->pParticleSystem->GetMaterial().GetPointer());
			}
		}
	}

	//
	// äÖȾ
	//
	VOID CEntityEffect::Render(const CMaterial *pMaterial) const
	{
		//
		// 1. ²ÎÊý°²È«¼ì²é
		//
		if (m_ptrEffect.IsNull() || m_ptrEffect->IsValid() == FALSE) {
			return;
		}

		//
		// 2. äÖȾ
		//
		const CEffect::ParticleSystemMap &particleSystems = m_ptrEffect->GetParticleSystems();

		for (CEffect::ParticleSystemMap::const_iterator itParticleSystem = particleSystems.begin(); itParticleSystem != particleSystems.end(); ++itParticleSystem) {
			CEffect::PARTICLESYSTEM *pParticleSystem = itParticleSystem->second;
			ASSERT(pParticleSystem);
			ASSERT(pParticleSystem->pParticleSystem);

			if (pParticleSystem->pParticleSystem->IsPlayFinish() == FALSE) {
				if (pParticleSystem->pParticleSystem->GetMaterial().GetPointer() == pMaterial) {
					pParticleSystem->pParticleSystem->Render(m_pSceneManager->GetMainCameraEntity());
				}
			}
		}
	}

}


text:
//
//  LFVideoCapture.h
//  LFLiveKit
//
//  Created by LaiFeng on 16/5/20.
//  Copyright © 2016年 LaiFeng All rights reserved.
//

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import "LFLiveVideoConfiguration.h"

@class LFVideoCapture;
/** LFVideoCapture callback videoData */
@protocol LFVideoCaptureDelegate <NSObject>
- (void)captureOutput:(nullable LFVideoCapture *)capture pixelBuffer:(nullable CVPixelBufferRef)pixelBuffer;
@end

@interface LFVideoCapture : NSObject

#pragma mark - Attribute
///=============================================================================
/// @name Attribute
///=============================================================================

/** The delegate of the capture. captureData callback */
@property (nullable, nonatomic, weak) id<LFVideoCaptureDelegate> delegate;

/** The running control start capture or stop capture*/
@property (nonatomic, assign) BOOL running;

/** The preView will show OpenGL ES view*/
@property (null_resettable, nonatomic, strong) UIView *preView;

/** The captureDevicePosition control camraPosition ,default front*/
@property (nonatomic, assign) AVCaptureDevicePosition captureDevicePosition;

/** The beautyFace control capture shader filter empty or beautiy */
@property (nonatomic, assign) BOOL beautyFace;

/** The torch control capture flash is on or off */
@property (nonatomic, assign) BOOL torch;

/** The mirror control mirror of front camera is on or off */
@property (nonatomic, assign) BOOL mirror;

/** The beautyLevel control beautyFace Level, default 0.5, between 0.0 ~ 1.0 */
@property (nonatomic, assign) CGFloat beautyLevel;

/** The brightLevel control brightness Level, default 0.5, between 0.0 ~ 1.0 */
@property (nonatomic, assign) CGFloat brightLevel;

/** The torch control camera zoom scale default 1.0, between 1.0 ~ 3.0 */
@property (nonatomic, assign) CGFloat zoomScale;

/** The videoFrameRate control videoCapture output data count */
@property (nonatomic, assign) NSInteger videoFrameRate;

/*** The warterMarkView control whether the watermark is displayed or not ,if set ni,will remove watermark,otherwise add *.*/
@property (nonatomic, strong, nullable) UIView *warterMarkView;

/* The currentImage is videoCapture shot */
@property (nonatomic, strong, nullable) UIImage *currentImage;

/* The saveLocalVideo is save the local video */
@property (nonatomic, assign) BOOL saveLocalVideo;

/* The saveLocalVideoPath is save the local video  path */
@property (nonatomic, strong, nullable) NSURL *saveLocalVideoPath;

#pragma mark - Initializer
///=============================================================================
/// @name Initializer
///=============================================================================
- (nullable instancetype)init UNAVAILABLE_ATTRIBUTE;
+ (nullable instancetype)new UNAVAILABLE_ATTRIBUTE;

/**
   The designated initializer. Multiple instances with the same configuration will make the
   capture unstable.
 */
- (nullable instancetype)initWithVideoConfiguration:(nullable LFLiveVideoConfiguration *)configuration NS_DESIGNATED_INITIALIZER;

@end


text:
/*
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE', which is part of this source code package.
 *
 * Partialy financiated as part of the protocol between UTAustin I Portugal - UTA-P.
 * [2017] - [2018] University of Minho, Filipe Costa Oliveira
 * All Rights Reserved.
 */

#ifndef SRC_IMAGEBOUNDS_H__
#define SRC_IMAGEBOUNDS_H__

/* BEGIN BOOST */
#include <boost/process.hpp>
#include <boost/filesystem/operations.hpp>                // for directory_iterator
#include <boost/filesystem/path.hpp>                      // for path, operator==, oper...
#include <boost/iterator/iterator_facade.hpp>             // for iterator_facade_base
#include <boost/thread.hpp>                               // for thread
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
/* END BOOST */

#include <math.h>                        // for fabs, ceil, pow, M_PI
#include <algorithm>                     // for max_element, min_element
#include <cassert>                       // for assert
#include <cstdio>                        // for perror, size_t, NULL, SEEK_END
#include <iomanip>                       // for operator<<, setfill, setw
#include <iostream>                      // for operator<<, basic_ostream
#include <iterator>                      // for distance
#include <limits>                        // for numeric_limits
#include <string>                        // for allocator, char_traits, to_s...
#include <vector>                        // for vector, vector<>::iterator
#include <iosfwd>                         // for string
#include <algorithm>                    // for std::transform

#include <opencv2/core/hal/interface.h>  // for CV_8UC1, CV_32F, CV_32FC1
#include <opencv2/imgproc/imgproc_c.h>   // for cvGetSpatialMoment
#include <opencv2/imgproc/types_c.h>     // for ::CV_THRESH_BINARY, CvMoments
#include <opencv2/core.hpp>              // for minMaxLoc, normalize, Exception
#include <opencv2/core/base.hpp>         // for NormTypes::NORM_MINMAX, Code...
#include <opencv2/core/cvstd.hpp>        // for Ptr
#include <opencv2/core/cvstd.inl.hpp>    // for operator<<, String::String
#include <opencv2/core/ptr.inl.hpp>      // for Ptr::operator->, Ptr::Ptr<T>
#include <opencv2/core/version.hpp>      // for CV_MAJOR_VERSION
#include <opencv2/features2d.hpp>        // for SimpleBlobDetector::Params
#include <opencv2/imgcodecs.hpp>         // for imwrite
#include <opencv2/imgproc.hpp>           // for Canny, boundingRect, drawCon...
#include <opencv2/video/tracking.hpp>    // for findTransformECC, ::MOTION_E...
#include <opencv2/core/mat.hpp>      // for Mat
#include <opencv2/core/mat.inl.hpp>  // for Mat::~Mat
#include <opencv2/core/matx.hpp>     // for Vec4d
#include <opencv2/core/types.hpp>    // for Point3d, Point, Rect, Point2d
#include <opencv2/opencv.hpp>

#include <boost/bind.hpp>

#include "unit_cell.hpp"
#include "application_log.hpp"
#include "base_image.hpp"

using namespace cv;

//BOOST_GEOMETRY_REGISTER_POINT_2D(cv::Point2d, double, boost::geometry::cs::cartesian, x, y)

class ImageBounds {
  private:

    bool update_roi_boundary_polygon_from_full_boundaries();
    cv::Point2d op_px_to_nm ( cv::Point2i point, const double pixel_size_nm_x, const double pixel_size_nm_y );
    bool generate_boundary_polygon_w_margin_nm();

    /* Loggers */
    ApplicationLog::ApplicationLog* logger = nullptr;
    bool _flag_logger = false;

    BaseImage* base_image = nullptr;
    bool _flag_base_image = false;

  protected:

    /***************************/
    /* image boundary analysis */
    /***************************/
    int hysteresis_threshold = 85;
    int max_contour_distance_px = 19;

    int hysteresis_threshold_range_bottom_limit = 1;
    int hysteresis_threshold_range_top_limit = 255;
    int max_contour_distance_px_range_bottom_limit = 1;
    int max_contour_distance_px_range_top_limit = 255;

    /***************************/
    /* image boundary analysis */
    /***************************/

    // the next 2 vectors are position-related to the whole image
    std::vector<cv::Point2i> full_boundary_polygon;
    bool _flag_full_boundary_polygon = false;
    std::vector<cv::Point2i> full_boundary_polygon_w_margin;
    bool _flag_full_boundary_polygon_w_margin = false;

    // the next 2 vectors are position-related to the ROI of the experimental image
    std::vector<cv::Point2i> roi_boundary_polygon;
    bool _flag_roi_boundary_polygon = false;
    cv::Rect roi_boundary_rect;
    bool _flag_roi_boundary_rect = false;
    cv::Mat roi_boundary_image;
    bool _flag_roi_boundary_image = false;

    int roi_left_padding_px = 0;
    int roi_top_padding_px = 0;
    int roi_left_padding_px_w_margin = 0;
    int roi_top_padding_px_w_margin = 0;

    std::vector<Point2i> roi_boundary_polygon_w_margin;
    bool _flag_roi_boundary_polygon_w_margin = false;
    std::vector<Point2d> roi_boundary_polygon_w_margin_nm;
    bool _flag_roi_boundary_polygon_w_margin_nm = false;
    cv::Rect roi_boundary_rect_w_margin;
    bool _flag_roi_boundary_rect_w_margin = false;
    cv::Mat roi_boundary_image_w_margin;
    bool _flag_roi_boundary_image_w_margin = false;

    double full_boundary_polygon_margin_x_nm = 0.0f;
    int full_boundary_polygon_margin_x_px = 0;

    double full_boundary_polygon_margin_y_nm = 0.0f;
    int full_boundary_polygon_margin_y_px = 0;

    double boundary_polygon_length_x_nm = 0.0f;
    int boundary_polygon_length_x_px = 0;
    bool _flag_boundary_polygon_length_x_nm = false;
    double boundary_polygon_length_y_nm = 0.0f;
    int boundary_polygon_length_y_px = 0;
    bool _flag_boundary_polygon_length_y_nm = false;

    cv::Mat experimental_image_contours;

  public:
    ImageBounds();

    bool calculate_boundaries_from_full_image();
    bool update_roi_images_from_rect();
    /** getters **/
    // flag getters
    bool get_flag_full_boundary_polygon(){ return _flag_full_boundary_polygon; }
    bool get_flag_full_boundary_polygon_w_margin(){ return _flag_full_boundary_polygon_w_margin; }
    bool get_flag_roi_boundary_polygon(){ return _flag_roi_boundary_polygon; }
    bool get_flag_roi_boundary_rect(){ return _flag_roi_boundary_rect; }
    bool get_flag_roi_boundary_image(){ return _flag_roi_boundary_image; }
    bool get_flag_roi_boundary_polygon_w_margin(){ return _flag_roi_boundary_polygon_w_margin; }
    bool get_flag_roi_boundary_polygon_w_margin_nm(){ return _flag_roi_boundary_polygon_w_margin_nm; }
    bool get_flag_roi_boundary_rect_w_margin(){ return _flag_roi_boundary_rect_w_margin; }
    bool get_flag_roi_boundary_image_w_margin(){ return _flag_roi_boundary_image_w_margin; }
    bool get_flag_boundary_polygon_length_x_nm(){ return _flag_boundary_polygon_length_x_nm; }
    bool get_flag_boundary_polygon_length_y_nm(){ return _flag_boundary_polygon_length_y_nm; }

    // var getters
    int get_hysteresis_threshold(){ return hysteresis_threshold; }
    int get_max_contour_distance_px(){ return max_contour_distance_px; }
    // threshold limits
    int get_hysteresis_threshold_range_bottom_limit(){ return hysteresis_threshold_range_bottom_limit; }
    int get_hysteresis_threshold_range_top_limit(){ return hysteresis_threshold_range_top_limit; }
    int get_max_contour_distance_px_range_bottom_limit(){ return max_contour_distance_px_range_bottom_limit; }
    int get_max_contour_distance_px_range_top_limit(){ return max_contour_distance_px_range_top_limit; }

    std::vector<cv::Point2i> get_full_boundary_polygon(){ return full_boundary_polygon; }
    std::vector<cv::Point2i> get_full_boundary_polygon_w_margin(){ return full_boundary_polygon_w_margin; }
    // the next 2 vectors are position-related to the ROI of the experimental image
    std::vector<cv::Point2i> get_roi_boundary_polygon(){ return roi_boundary_polygon; }
    cv::Rect get_roi_boundary_rect(){ return roi_boundary_rect; }
    cv::Mat get_roi_boundary_image(){ return roi_boundary_image; }
    cv::Mat get_roi_boundary_image_visualization(){ return base_image->get_image_visualization( roi_boundary_image ); }
    std::vector<cv::Point2i> get_roi_boundary_polygon_w_margin(){ return roi_boundary_polygon_w_margin; }
    std::vector<cv::Point2d> get_roi_boundary_polygon_w_margin_nm(){ return roi_boundary_polygon_w_margin_nm; }
    cv::Rect get_roi_boundary_rect_w_margin(){ return roi_boundary_rect_w_margin; }
    cv::Mat get_roi_boundary_image_w_margin(){ return roi_boundary_image_w_margin; }
    double get_full_boundary_polygon_margin_x_nm(){ return full_boundary_polygon_margin_x_nm; }
    int get_full_boundary_polygon_margin_x_px(){ return full_boundary_polygon_margin_x_px; }
    double get_full_boundary_polygon_margin_y_nm(){ return full_boundary_polygon_margin_y_nm; }
    int get_full_boundary_polygon_margin_y_px(){ return full_boundary_polygon_margin_y_px; }

    double get_boundary_polygon_length_x_nm(){ return boundary_polygon_length_x_nm; }
    double get_boundary_polygon_length_x_px(){ return boundary_polygon_length_x_px; }
    double get_boundary_polygon_length_y_nm(){ return boundary_polygon_length_y_nm; }
    double get_boundary_polygon_length_y_px(){ return boundary_polygon_length_y_px; }

    /** getters **/
    // flag getters
    bool get_flag_logger(){ return _flag_logger; }
    /* Loggers */
    ApplicationLog::ApplicationLog* get_logger(){ return logger; }

    /** setters **/
    bool set_hysteresis_threshold( int threshold );
    bool set_max_contour_distance_px( int max_distance );

    bool set_full_boundary_polygon_margin_x_nm( double value );
    bool set_full_boundary_polygon_margin_y_nm( double value );

    bool set_roi_boundary_rect( cv::Rect );

    bool set_base_image( BaseImage* base_image_ptr );

    cv::Point2i op_Point2i_padding (cv::Point2d point, const int padd_x, const int  padd_y );

    /* Loggers */
    bool set_application_logger( ApplicationLog::ApplicationLog* logger );

    void print_var_state();
    friend std::ostream& operator<< (std::ostream& stream, const ImageBounds& image);
    virtual std::ostream& output(std::ostream& stream) const;

};

#endif


text:
'use strict'

var test = require('tap').test
var timers = require('timers')
var helper = require('../../lib/agent_helper')
var verifySegments = require('./verify.js')

var HAS_SETIMMEDIATE = !!global.setImmediate

test('setTimeout', function testSetTimeout(t) {
  var agent = setupAgent(t)
  helper.runInTransaction(agent, function transactionWrapper() {
    timers.setTimeout(function anonymous() {
      verifySegments(t, agent, 'timers.setTimeout')
    }, 0)
  })
})

test('setImmediate', function testSetImmediate(t) {
  if (!HAS_SETIMMEDIATE) {
    t.ok('setImmediate not defined')
    return t.end()
  }

  var agent = setupAgent(t)
  helper.runInTransaction(agent, function transactionWrapper(transaction) {
    timers.setImmediate(function anonymous() {
      t.equal(agent.getTransaction(), transaction)
      t.equal(agent.getTransaction().trace.root.children.length, 0)
      t.end()
    })
  })
})

test('setInterval', function testSetInterval(t) {
  var agent = setupAgent(t)
  helper.runInTransaction(agent, function transactionWrapper() {
    var interval = timers.setInterval(function anonymous() {
      clearInterval(interval)
      verifySegments(t, agent, 'timers.setInterval')
    }, 10)
  })
})

test('global setTimeout', function testSetTimeout(t) {
  var agent = setupAgent(t)
  helper.runInTransaction(agent, function transactionWrapper() {
    setTimeout(function anonymous() {
      verifySegments(t, agent, 'timers.setTimeout')
    }, 0)
  })
})

test('global setImmediate', function testSetImmediate(t) {
  if (!HAS_SETIMMEDIATE) {
    t.ok('setImmediate not defined')
    return t.end()
  }

  var agent = setupAgent(t)
  helper.runInTransaction(agent, function transactionWrapper(transaction) {
    setImmediate(function anonymous() {
      t.equal(agent.getTransaction(), transaction)
      t.equal(agent.getTransaction().trace.root.children.length, 0)
      t.end()
    })
  })
})

test('global setInterval', function testSetInterval(t) {
  var agent = setupAgent(t)
  helper.runInTransaction(agent, function transactionWrapper() {
    var interval = setInterval(function anonymous() {
      clearInterval(interval)
      verifySegments(t, agent, 'timers.setInterval')
    }, 10)
  })
})

test('nextTick', function testNextTick(t) {
  var agent = setupAgent(t)
  helper.runInTransaction(agent, function transactionWrapper(transaction) {
    process.nextTick(function callback() {
      t.equal(agent.getTransaction(), transaction)
      t.equal(agent.getTransaction().trace.root.children.length, 0)
      t.end()
    })
  })
})

test('clearTimeout', function testNextTick(t) {
  var agent = setupAgent(t)
  var timer = setTimeout(fail)

  clearTimeout(timer)

  helper.runInTransaction(agent, function transactionWrapper(transaction) {
    process.nextTick(function callback() {
      var timer = setTimeout(fail)
      t.notOk(transaction.trace.root.children[0].ignore)
      clearTimeout(timer)
      t.ok(transaction.trace.root.children[0].ignore)
      setTimeout(t.end.bind(t))
    })
  })

  function fail() {
    t.fail()
  }
})

test('clearImmediate', function testNextTick(t) {
  if (!HAS_SETIMMEDIATE) {
    t.ok('setImmediate not defined')
    return t.end()
  }

  var agent = setupAgent(t)
  var timer = setImmediate(fail)

  clearImmediate(timer)

  helper.runInTransaction(agent, function transactionWrapper(transaction) {
    process.nextTick(function callback() {
      var timer = setImmediate(fail)
      t.notOk(transaction.trace.root.children[0])
      clearImmediate(timer)
      setImmediate(t.end.bind(t))
    })
  })

  function fail() {
    t.fail()
  }
})

test('clearImmediate', function testNextTick(t) {
  var agent = setupAgent(t)
  var timer = setInterval(fail)

  clearInterval(timer)

  helper.runInTransaction(agent, function transactionWrapper(transaction) {
    process.nextTick(function callback() {
      var timer = setInterval(fail)
      t.notOk(transaction.trace.root.children[0].ignore)
      clearInterval(timer)
      t.notOk(transaction.trace.root.children[0].ignore)
      setImmediate(t.end.bind(t))
    })
  })

  function fail() {
    t.fail()
  }
})

test('clearTimeout', function testNextTick(t) {
  var agent = setupAgent(t)
  var timer = setTimeout(fail)

  clearTimeout(timer)

  helper.runInTransaction(agent, function transactionWrapper(transaction) {
    process.nextTick(function callback() {
      var timer = setTimeout(fail)
      t.notOk(transaction.trace.root.children[0].ignore)
      clearTimeout(timer)
      t.ok(transaction.trace.root.children[0].ignore)
      setTimeout(t.end.bind(t))
    })
  })

  function fail() {
    t.fail()
  }
})

function setupAgent(t) {
  var agent = helper.instrumentMockedAgent()
  t.tearDown(function tearDown() {
    helper.unloadAgent(agent)
  })

  return agent
}


text:
@class PNChannel;

#pragma mark - Public interface declaration

@interface PNHereNowRequest : PNBaseRequest

#pragma mark Class methods

+ (PNHereNowRequest *)whoNowRequestForChannels:(NSArray *)channels clientIdentifiersRequired:(BOOL)isClientIdentifiersRequired
                                   clientState:(BOOL)shouldFetchClientState;

#pragma mark - Instance methods

- (id)initWithChannels:(NSArray *)channels clientIdentifiersRequired:(BOOL)isClientIdentifiersRequired
           clientState:(BOOL)shouldFetchClientState;

#pragma mark -

@end


text:
layout: article
title: "UMDF Invited Talk"
share: false
external-url: http://www.umdf.org/site/c.piKYL1PHLtF/b.4864979/k.C003/Home.htm
image:
  teaser: LOGO-UMDFt.png
  feature: banner-short-apb.png
---
Gargi's research into nuclear mitochondrial insertions was selected as a talk at the annual UMDF symposium.


text:
    bottom: 0;
    left: 10px;
    margin-left: 5px;
    width: 100%;
}

#myThumbnailCarousel .carousel-indicators li {
    border: medium none;
    border-radius: 0;
    float: left;
    height: 44px;
    margin-bottom: 5px;
    margin-left: 0;
    margin-right: 5px !important;
    margin-top: 0;
    width: 120px;
}

#myThumbnailCarousel .carousel-indicators img {
    border: 2px solid #FFFFFF;
    float: left;
    height: 44px;
    left: 0;
    width: 120px;
}

#myThumbnailCarousel .carousel-indicators .active img {
    border: 2px solid #39b3d7;

}


text:
License
=======

.. literalinclude:: ../LICENSE

.. note::
    In applying this license, CERN does not waive the privileges and immunities
    granted to it by virtue of its status as an Intergovernmental Organization or
    submit itself to any jurisdiction.


text:
import '@kadira/storybook/addons';
//  To add the knobs addon
import '@kadira/storybook-addon-knobs/register';
// Add the Redux Listener addon
import 'storybook-addon-redux-listener/register';


text:
<template name="tutorial.next_steps.html">
  {{#markdown}}

# What's next?

Congratulations on your newly built angular-meteor app! Don't forget to deploy it again so your friends can use the new features.

Here are some options for where you can go next:

1. [Full API reference](/api)
2. [Contribute to our project](https://github.com/Urigo/angular-meteor#contributing)
3. Follow and comment on our [Roadmap](https://trello.com/b/Wj9U0ulk/angular-meteor)
4. Join other developers on the [Meteor forum](https://forums.meteor.com/)

  {{/markdown}}
</template>


text:
namespace geode {

template<class T0,class T1> struct AssertSame { static const bool value = false; };
template<class T> struct AssertSame<T,T> { static const bool value = true; };

#define STATIC_ASSERT_SAME(T0,T1) \
  static_assert(geode::AssertSame<T0,T1>::value,"Given types do not match")

}


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

<title>All Classes</title>
<meta name="date" content="2014-01-09">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

VunglePub

VunglePub.EventListener

VunglePub.Gender


text:
var Class = require('../shared/lib/Class').Class,
    State = require('../shared/State'),
    util = require('../shared/util');

// Entity Base Class ----------------------------------------------------------
// ----------------------------------------------------------------------------
var Entity = Class(function(server, stateClass) {

    // Entity State Class
    stateClass = stateClass || State;

    // References
    this._server = server;
    this._player = null;

    // Basics
    this._id = null;

    // Last received input tick from the client
    this._clientTick = server.getTick() - 1;

    // State
    this._lastState = new stateClass(server);
    this._state = new stateClass(server);
    this._velocity = new stateClass(server);

    // Previous States
    this._states = [];
    this._savedState = null;

    // Events to be send to clients with the next tick
    this._eventQueue = [];

}, {

    // Public -----------------------------------------------------------------
    sendEvent: function(event) {
        this._eventQueue.push(event);
    },

    tick: function(tick, maxStateBufferSize) {

        // Store state of the last tick
        this._lastState.set(this._state);

        // Store private state on the server
        var state = this._state.get(true);
        this._states.push({
            state: state,
            tick: tick,
            clientTick: this._clientTick
        });

        if (this._states.length > maxStateBufferSize) {
            this._states.shift();
        }

        // Return public state
        return this._state.get(false);

    },

    rewind: function(tick) {

        this._savedState = this._state.get(true);
        for(var i = this._states.length - 1; i >= 0; i--) {

            var state = this._states[i];
            if (state.tick === tick) {
                // TODO if we don't find any state, rewind to the oldest possible?
                this.setState(state.state);
                break;
            }

        }

    },

    forward: function() {
        this.setState(this._savedState);
    },

    destroy: function() {

        // Remove from server
        this._server.removeEntity(this);

        // Clear references
        this._state = null;
        this._states.length = 0;
        this._states = null;
        this._server = null;
        this._remote = null;

    },

    // Updates ----------------------------------------------------------------
    applyState: function(tick, state, config) {

        // Set velocity from state delta
        this._state.velocity(state, this._velocity);

        // Apply Level Collision
        this._server.getLevel().applyEntityCollision(
            this, this._state, this._velocity
        );

        // Update state with velocity
        this._state.update(this._velocity);

    },

    // Setter -----------------------------------------------------------------
    setId: function(id) {
        this._id = id;
    },

    setPlayer: function(player) {

        this._player = player;
        this._server.setEntityPlayer(this, player);

        this.log('Player Set');

    },

    setClientTick: function(tick) {
        this._clientTick = tick;
    },

    setState: function(state) {
        this._state.set(state, false);
    },

    // Getter -----------------------------------------------------------------
    getId: function() {
        return this._id;
    },

    getClientTick: function() {
        return this._clientTick;
    },

    getPlayer: function() {
        return this._player;
    },

    getPrivateState: function() {
        return this._state.get(true);
    },

    getEvents: function() {
        var events = this._eventQueue.slice();
        this._eventQueue.length = 0;
        return events;
    },

    isVisible: function() {
        return true;
    },

    isVisibleToPlayer: function(player) {
        return true;
    },

    isFriendOfPlayer: function(player) {
        return this._player === player;
    },

    // Serialization ----------------------------------------------------------
    serialize: function(isPrivate) {
        return [
            this._id,
            this.TypeId,
            this._player ? this._player.getId() : 0,
            this._state.get(isPrivate)
        ];
    },

    // Logging ----------------------------------------------------------------
    log: function() {
        util.log(this.toString(), arguments);
    },

    toString: function() {

        if (this._player) {
            return '[ Entity #' + this._id + ' | ' + this._player + ' ]';

        } else {
            return '[ Entity #' + this._id + ' | No Player ]';
        }

    }

});

// Exports --------------------------------------------------------------------
module.exports = Entity;