text:
require 'optparse'

class Pickler
  class Runner

    class Base
      attr_reader :argv

      def initialize(argv)
        @argv = argv
        @tty = $stdout.tty?
        @opts = OptionParser.new
        @opts.version = "0.0"
        @opts.banner = "Usage: pickler #{self.class.command_name} #{self.class.banner_arguments}"
        @opts.base.long["help"] = OptionParser::Switch::NoArgument.new do
          help = @opts.help.chomp.chomp + "\n"
          help += "\n#{self.class.description}" if self.class.description
          puts help
          @exit = 0
        end
        @opts.separator("")
      end

      def self.options
        @options ||= []
      end

      def self.on(*args, &block)
        options << args
        define_method("option_#{args.object_id}", &block)
      end

      def self.banner_arguments(value = nil)
        if value
          @banner_arguments = value
        else
          @banner_arguments || (arity.zero? ? "" : "...")
        end
      end

      def self.summary(value = nil)
        if value
          @summary = value
        else
          @summary
        end
      end

      def self.description(value = nil)
        if value
          @description = value
        else
          @description || "#@summary."
        end
      end

      def self.command_name
        name.split('::').last.gsub(/(.)([A-Z])/) {"#$1-#$2"}.downcase
      end

      def self.method_name
        command_name.gsub('-','_')
      end

      def self.process(&block)
        define_method(:process, &block)
      end

      def self.arity
        instance_method(:process).arity
      end

      def arity
        self.class.arity
      end

      def pickler
        @pickler ||= Pickler.new(Dir.getwd)
      end

      def abort(message)
        raise Error, message
      end

      def too_many
        abort "too many arguments"
      end

      def run
        self.class.options.each do |arguments|
          @opts.on(*arguments, &method("option_#{arguments.object_id}"))
        end
        begin
          @opts.parse!(@argv)
        rescue OptionParser::InvalidOption
          abort $!.message
        end
        return @exit if @exit
        minimum = arity < 0 ? -1 - arity : arity
        if arity >= 0 && arity < @argv.size
          too_many
        elsif minimum > @argv.size
          abort "not enough arguments"
        end
        process(*@argv)
      end

      def process(*argv)
        pickler.send(self.class.method_name,*argv)
      end

      def color?
        case pickler.config["color"]
        when "always" then true
        when "never"  then false
        else
          @tty && RUBY_PLATFORM !~ /mswin|mingw/
        end
      end

      def colorize(code, string)
        if color?
          "\e[#{code}m#{string}\e[00m"
        else
          string.to_s
        end
      end

      def puts_summary(story)
        summary = "%6d " % story.id
        type  = story.estimate || TYPE_SYMBOLS[story.story_type]
        state = STATE_SYMBOLS[story.current_state]
        summary << colorize("3#{STATE_COLORS[story.current_state]}", state) << ' '
        summary << colorize("01;3#{TYPE_COLORS[story.story_type]}", type) << ' '
        summary << story.name
        puts summary
      end

      def puts_full(story)
        puts colorize("01;3#{TYPE_COLORS[story.story_type]}", story.name)
        puts "Type:      #{story.story_type}".rstrip
        if story.story_type == "release"
          puts "Deadline:  #{story.deadline}".rstrip
        else
          puts "Estimate:  #{story.estimate}".rstrip
        end
        puts "State:     #{story.current_state}".rstrip
        puts "Labels:    #{story.labels.join(', ')}".rstrip
        puts "Requester: #{story.requested_by}".rstrip
        puts "Owner:     #{story.owned_by}".rstrip
        puts "URL:       #{story.url}".rstrip
        puts unless story.description =~ /^\s*$/
        story.description_lines.each do |line|
          puts "  #{line}".rstrip
        end
        story.notes.each do |note|
          puts
          puts "  #{colorize('01', note.author)} (#{note.date})"
          puts(*note.lines(72).map {|l| "    #{l}".rstrip})
        end
      end

      def paginated_output
        stdout = $stdout
        if @tty && pager = pickler.config["pager"]
          # Modeled after git
          ENV["LESS"] ||= "FRSX"
          IO.popen(pager,"w") do |io|
            $stdout = io
            yield
          end
        else
          yield
        end
      rescue Errno::EPIPE
      ensure
        $stdout = stdout
      end

    end

    def self.[](command)
      klass_name = command.to_s.capitalize.gsub(/[-_](.)/) { $1.upcase }
      if klass_name =~ /^[A-Z]\w*$/ && const_defined?(klass_name)
        klass = const_get(klass_name)
        if Class === klass && klass < Base
          return klass
        end
      end
    end

    def self.commands
      constants.map {|c| Runner.const_get(c)}.select {|c| Class === c && c < Runner::Base}.sort_by {|r| r.command_name}.uniq
    end

    def self.command(name, &block)
      const_set(name.to_s.capitalize.gsub(/[-_](.)/) { $1.upcase },Class.new(Base,&block))
    end

    command :show do
      banner_arguments "<story>"
      summary "Show details for a story"

      on "--full", "default format" do |full|
        @format = :full
      end

      on "--raw", "same as the .feature" do |raw|
        @format = :raw
      end

      process do |*args|
        case args.size
        when 0
          puts "#{pickler.project_id} #{pickler.project.name}"
        when 1
          feature = pickler.feature(args.first)
          story = feature.story
          case @format
          when :raw
            puts feature.story.to_s(pickler.format) if feature.story
          else
            paginated_output do
              puts_full feature.story
            end
          end
        else
          too_many
        end
      end
    end

    command :search do
      banner_arguments "[query]"
      summary "List all stories matching a query"

      def modifications
        @modifications ||= {}
      end
      [:label, :type, :state].each do |o|
        on "--#{o} #{o.to_s.upcase}" do |value|
          modifications[o] = value
        end
      end
      [:requester, :owner, :mywork].each do |o|
        on "--#{o}[=USERNAME]" do |value|
          modifications[o] = value || pickler.real_name
        end
      end
      on "--[no-]includedone", "include accepted stories" do |value|
        modifications[:includedone] = value
        @iterations ||= []
        @iterations << :done?
      end

      on "-b", "--backlog", "filter results to future iterations" do |c|
        @iterations ||= []
        @iterations << :backlog?
      end

      on "-c", "--current", "filter results to current iteration" do |b|
        @iterations ||= []
        @iterations << :current?
      end

      on "--[no-]full", "show full story, not a summary line" do |b|
        @full = b
      end

      process do |*argv|
        argv << modifications unless modifications.empty?
        if argv == [{:includedone => true}]
          # Bypass the 200 search results limitation
          stories = pickler.project.stories
        else
          stories = pickler.project.stories(*argv)
        end
        if @iterations && @iterations != [:done?]
          stories.reject! {|s| !@iterations.any? {|i| s.send(i)}}
        end
        paginated_output do
          first = true
          stories.each do |story|
            if @full
              puts unless first
              puts_full story
            else
              puts_summary story
            end
            first = false
          end
        end
      end
    end

    command :push do
      banner_arguments "[story] ..."
      summary "Upload stories"
      description <<-EOF
Upload the given story or all features with a tracker url in a comment on the
first line.  Features with a blank comment in the first line will created as
new stories.
      EOF

      process do |*args|
        args.replace(pickler.local_features) if args.empty?
        args.each do |arg|
          pickler.feature(arg).push
        end
      end
    end

    command :pull do
      banner_arguments "[story] ..."
      summary "Download stories"
      description <<-EOF
Download the given story story to the features/ directory.  With no arguments,
downloads all stories that look like Cucumber features (with "Scenario:" in
the body).  The version without arguments is mainly useful for syncing
existing features.
      EOF

      process do |*args|
        args.replace(pickler.scenario_features) if args.empty?
        args.each do |arg|
          pickler.feature(arg).pull
        end
      end
    end

    command :start do
      banner_arguments "<story> [basename]"
      summary "Pull a story and mark it started"
      description <<-EOF
Pull a given story and change its state to started.  If basename is given
and no local file exists, features/basename.feature will be created.  Give a
basename of "-" to use a downcased, underscored version of the story name as
the basename.
      EOF

      process do |story, *args|
        pickler.feature(story).start(args.first)
      end
    end

    command :finish do
      banner_arguments "<story>"
      summary "Push a story and mark it finished"

      process do |story|
        pickler.feature(story).finish
      end
    end

    command :deliver do
      banner_arguments "[story] ..."
      summary "Mark stories delivered"
      on "--all-finished", "deliver all finished stories" do
        @all = true
      end
      process do |*args|
        if @all
          pickler.deliver_all_finished_stories
        end
        args.each do |arg|
          pickler.story(arg).transition!('delivered')
        end
      end
    end

    command :unstart do
      banner_arguments "[story] ..."
      summary "Mark stories unstarted"
      on "--all-started", "unstart all started stories" do
        @all = true
      end
      process do |*args|
        if @all
          pickler.project.stories(:state => "started").each do |story|
            story.transition!('unstarted')
          end
        end
        args.each do |arg|
          pickler.story(arg).transition!('unstarted')
        end
      end
    end

    command :unschedule do
      banner_arguments "[story] ..."
      summary "Move stories to icebox"
      process do |*args|
        args.each do |arg|
          pickler.story(arg).transition!('unscheduled')
        end
      end
    end

    command :browse do
      banner_arguments "[story]"
      summary "Open a story in the web browser"
      description <<-EOF
Open project or a story in the web browser.

Requires launchy (gem install launchy).
      EOF

      on "--dashboard" do
        @special = "dashboard"
      end
      on "--faq" do
        @special = "help"
      end
      on "--profile", "get your API Token here" do
        @special = "profile"
      end
      on "--time", "not publicly available" do
        @special = "time_shifts?project=#{pickler.project_id}"
      end

      process do |*args|
        too_many if args.size > 1 || @special && args.first
        if args.first
          url = pickler.story(args.first).url
        elsif @special
          url = "http://www.pivotaltracker.com/#@special"
        else
          url = "http://www.pivotaltracker.com/projects/#{pickler.project_id}/stories"
        end
        require 'launchy'
        Launchy.open(url)
      end
    end

    command :comment do
      banner_arguments "<story> <paragraph> ..."
      summary "Post a comment to a story"

      process do |story, *paragraphs|
        pickler.story(story).comment!(paragraphs.join("\n\n"))
      end
    end

    command :install_vim_plugin do
      banner_arguments "[directory]"
      summary "install pickler.vim"

      process do |*argv|
        source = File.expand_path('../../../plugin/pickler.vim', __FILE__)
        require 'fileutils'
        directory = argv.first ||
          if RUBY_PLATFORM =~ /win/i
            "#{ENV['USERPROFILE']}/vimfiles/plugin"
          else
            File.expand_path('~/.vim/plugin')
          end
        FileUtils.mkdir_p(directory)
        FileUtils.cp(source, directory)
        puts "Installed to #{directory}/pickler.vim."
        puts "Be sure to keep it up to date!"
      end
    end

    def initialize(argv)
      @argv = argv
    end

    COLORS = {
      :black   => 0,
      :red     => 1,
      :green   => 2,
      :yellow  => 3,
      :blue    => 4,
      :magenta => 5,
      :cyan    => 6,
      :white   => 7
    }

    STATE_COLORS = {
      nil           => COLORS[:black],
      "rejected"    => COLORS[:red],
      "accepted"    => COLORS[:green],
      "delivered"   => COLORS[:yellow],
      "unscheduled" => COLORS[:white],
      "started"     => COLORS[:magenta],
      "finished"    => COLORS[:cyan],
      "unstarted"   => COLORS[:blue]
    }

    STATE_SYMBOLS = {
      "unscheduled" => "  ",
      "unstarted"   => ":|",
      "started"     => ":/",
      "finished"    => ":)",
      "delivered"   => ";)",
      "rejected"    => ":(",
      "accepted"    => ":D"
    }

    TYPE_COLORS = {
      'chore'   => COLORS[:blue],
      'feature' => COLORS[:magenta],
      'bug'     => COLORS[:red],
      'release' => COLORS[:cyan]
    }

    TYPE_SYMBOLS = {
      "feature" => "*",
      "chore"   => "%",
      "release" => "!",
      "bug"     => "/"
    }

    def run
      command = @argv.shift
      if klass = self.class[command]
        result = klass.new(@argv).run
        exit result.respond_to?(:to_int) ? result.to_int : 0
      elsif ['help', '--help', '-h', '', nil].include?(command)
        puts "usage: pickler <command> [options] [arguments]"
        puts
        puts "Commands:"
        self.class.commands.each do |command|
          puts "    %-19s %s" % [command.command_name, command.summary]
        end
        puts
        puts "Run pickler <command> --help for help with a given command"
      else
        raise Error, "Unknown pickler command #{command}"
      end
    rescue Pickler::Error
      $stderr.puts "#$!"
      exit 1
    rescue Interrupt
      $stderr.puts "Interrupted!"
      exit 130
    end

  end
end


text:
#include <pcl/point_types.h>
#include <pcl/impl/instantiate.hpp>
#include <pcl/features/vfh.h>
#include <pcl/features/impl/vfh.hpp>

// Instantiations of specific point types
#ifdef PCL_ONLY_CORE_POINT_TYPES
  PCL_INSTANTIATE_PRODUCT(VFHEstimation, ((pcl::PointXYZ)(pcl::PointXYZI)(pcl::PointXYZRGBA)(pcl::PointNormal))((pcl::Normal)(pcl::PointNormal))((pcl::VFHSignature308)))
#else
  PCL_INSTANTIATE_PRODUCT(VFHEstimation, (PCL_XYZ_POINT_TYPES)(PCL_NORMAL_POINT_TYPES)((pcl::VFHSignature308)))
#endif

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.ServiceProcess;
using MonitoringPlatform.Models;

namespace MonitoringPlatform.Repositories
{
    public interface IServicesRepository
    {
        IList<ServiceModel> GetServices();
    }

    public class ServicesRepository : IServicesRepository
    {

        public IList<ServiceModel> GetServices()
        {
            var windowsServices = ServiceController.GetServices();

            IList<ServiceModel> serviceModels = new List<ServiceModel>(windowsServices.Length);

            foreach (ServiceController serviceController in windowsServices)
            {
                var serviceModel = new ServiceModel();
                serviceModel.ServiceName = serviceController.ServiceName;

                switch (serviceController.Status)
                {
                    case ServiceControllerStatus.ContinuePending:
                    case ServiceControllerStatus.PausePending:
                    case ServiceControllerStatus.StartPending:
                    case ServiceControllerStatus.StopPending:
                        serviceModel.Status = WindowsServiceStatus.Intermediate;
                        break;
                    case ServiceControllerStatus.Paused:
                        serviceModel.Status = WindowsServiceStatus.Paused;
                        break;
                    case ServiceControllerStatus.Running:
                        serviceModel.Status = WindowsServiceStatus.Running;
                        break;
                    case ServiceControllerStatus.Stopped:
                        break;
                }

                serviceModels.Add(serviceModel);
            }

            return serviceModels;
        }
    }

}


text:
<?php
namespace Video\Model;

class Video
{
	public $id;
	public $link;
	public $description;

	public function exchangeArray($data)
    {
    	$this->id = (!empty($data['id'])) ? $data['id'] : null;
		$this->link = (!empty($data['link'])) ? $data['link'] : null;
		$this->description = (!empty($data['description'])) ? $data['description'] : null;
    }
}


text:
.. _built_in_extensions:

Built-in Extensions
===================

Nameko includes a number of built-in :ref:`extensions <extensions>`. This section introduces them and gives brief examples of their usage.

RPC
---

Nameko includes an implementation of RPC over AMQP. It comprises the ``@rpc`` entrypoint, a proxy for services to talk to other services, and a standalone proxy that non-Nameko clients can use to make RPC calls to a cluster:

.. literalinclude:: examples/rpc.py

.. literalinclude:: examples/standalone_rpc.py

Normal RPC calls block until the remote method completes, but proxies also have an asynchronous calling mode to background or parallelize RPC calls:

.. literalinclude:: examples/async_rpc.py

In a cluster with more than one instance of the target service, RPC requests round-robin between instances. The request will be handled by exactly one instance of the target service.

AMQP messages are ack'd only after the request has been successfully processed. If the service fails to acknowledge the message and the AMQP connection is closed (e.g. if the service process is killed) the broker will revoke and then allocate the message to the available service instance.

Request and response payloads are serialized into JSON for transport over the wire.

Events (Pub-Sub)
----------------

Nameko Events is an asynchronous messaging system, implementing the Publish-Subscriber pattern. Services dispatch events that may be received by zero or more others:

.. literalinclude:: examples/events.py

The :class:`~nameko.events.EventHandler` entrypoint has three ``handler_type``\s that determine how event messages are received in a cluster:

    * ``SERVICE_POOL`` -- event handlers are pooled by service name and one instance from each pool receives the event, similar to the cluster behaviour of the RPC entrypoint. This is the default handler type.
    * ``BROADCAST`` -- every listening service instance will receive the event.
    * ``SINGLETON`` -- exactly one listening service instance will receive the event.

An example of using the ``BROADCAST`` mode:

.. literalinclude:: examples/event_broadcast.py

Events are serialized into JSON for transport over the wire.

HTTP GET & POST
---------------

Nameko's HTTP entrypoint supports simple GET and POST:

.. literalinclude:: examples/http.py

.. code-block:: shell

    $ nameko run http
    starting services: http_service

.. code-block:: shell

    $ curl -i localhost:8000/get/42
    HTTP/1.1 200 OK
    Content-Type: text/plain; charset=utf-8
    Content-Length: 13
    Date: Fri, 13 Feb 2015 14:51:18 GMT

    {'value': 42}

.. code-block:: shell

    $ curl -i -d "post body" localhost:8000/post
    HTTP/1.1 200 OK
    Content-Type: text/plain; charset=utf-8
    Content-Length: 19
    Date: Fri, 13 Feb 2015 14:55:01 GMT

    received: post body

The HTTP entrypoint is built on top of `werkzeug <http://werkzeug.pocoo.org/>`_. Service methods must return one of:

- a string, which becomes the response body
- a 2-tuple ``(status code, response body)``
- a 3-tuple ``(status_code, headers dict, response body)``
- an instance of :class:`werkzeug.wrappers.Response`

.. literalinclude:: examples/advanced_http.py

.. code-block:: shell

    $ nameko run advanced_http
    starting services: advanced_http_service

.. code-block:: shell

    $ curl -i localhost:8000/privileged
    HTTP/1.1 403 FORBIDDEN
    Content-Type: text/plain; charset=utf-8
    Content-Length: 9
    Date: Fri, 13 Feb 2015 14:58:02 GMT

.. code-block:: shell

    curl -i localhost:8000/headers
    HTTP/1.1 201 CREATED
    Location: https://www.example.com/widget/1
    Content-Type: text/plain; charset=utf-8
    Content-Length: 0
    Date: Fri, 13 Feb 2015 14:58:48 GMT

You can control formatting of errors returned from your service by overriding :meth:`~nameko.web.HttpRequestHandler.response_from_exception`:

.. literalinclude:: examples/http_exceptions.py

.. code-block:: shell

    $ nameko run http_exceptions
    starting services: http_service

.. code-block:: shell

    $ curl -i http://localhost:8000/custom_exception
    HTTP/1.1 400 BAD REQUEST
    Content-Type: application/json
    Content-Length: 72
    Date: Thu, 06 Aug 2015 09:53:56 GMT

    {"message": "Argument `foo` is required.", "error": "INVALID_ARGUMENTS"}

Timer
-----

The :class:`~nameko.timers.Timer` is a simple entrypoint that fires once per a configurable number of seconds. The timer is not "cluster-aware" and fires on all services instances.

.. literalinclude:: examples/timer.py


text:
/*
    //COLLECTION
    NAME: {
        name: "COLLECTION NAME",
        insert: "ON CREATED",
        find: "ON FOUND",
        update: "ON UPDATED",
        remove: "ON REMOVED"
    }
*/

$.ku4webApp.config.collections = {

    //NOTE: Set your store type here. This defines how collections will persist
    //      data. The default is localStorage. Type memory will only persist
    //      for the duration of the application run. Whereas, localStorage and
    //      indexedDB will persist until the storage mechanism is cleared.
    "ku4StoreType": "localStorage" // memory | localStorage | indexedDB

    //ADD YOUR COLLECTIONS HERE
};


text:
package jdbreport.source;

import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.util.*;
import java.util.logging.Level;

import jdbreport.model.ReportException;

/**
 * @version 3.1 15.12.2014
 * @author Andrey Kholmanskih
 *
 */
public class JdbcDataSet extends  AbstractDataSet {

	private String id;

	private String query;

	private String masterId;

	private DbSource source;

	private ResultSet rs;

	private PreparedStatement stat;

	private boolean eof = true;

	private Params params;

	private String preparedQuery;

	private Map<Object, Object> vars;
	private Collection<String> columns;

	public JdbcDataSet() {
		super();
	}

	public JdbcDataSet(String id) {
		super(id);
	}

	public void setVars(Map<Object, Object> vars) {
		this.vars = vars;
	}

	public boolean next() throws ReportException {
		if (isEof())
			return false;
		try {
			eof = !rs.next();
			return !eof;
		} catch (SQLException e) {
			eof = true;
			throw new ReportException(e);
		}
	}

	public boolean isEof() {
		return eof;
	}

	public Object getValue(int index) throws ReportException {
		try {
			return rs.getObject(index);
		} catch (SQLException e) {
			throw new ReportException(e);
		}
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @param query
	 *            The query to set.
	 */
	public void setQuery(String query) {
		this.query = query.trim();
		preparedQuery = null;
	}

	/**
	 * @return the query
	 */
	public String getQuery() {
		return query;
	}

	public DbSource getSource() {
		return source;
	}

	public void setSource(DbSource source) {
		if (this.source != source) {
			this.source = source;
			preparedQuery = null;
			stat = null;
			rs = null;
		}
	}

	private void prepareParams() throws ReportException {
		params = new Params();
		preparedQuery = params.prepareParams(getQuery());
		if (!preparedQuery.toUpperCase().startsWith("SELECT ")) {
			preparedQuery = null;
			throw new ReportException(MessageFormat.format(Messages
					.getString("JdbcDataSet.invalid_query"), getQuery(), getId()));
		}
		initParams();
	}

	private void initParams() throws ReportException {
		if (vars != null) {
			for (int i = 0; i < params.size(); i++) {
				Object value = vars.get(params.getName(i));
				if (value != null) {
					params.setValue(i, value);
				}
			}
		}
	}

	private void prepare() throws ReportException {
		if (stat != null)
			return;
		try {
			if (preparedQuery == null)
				prepareParams();
			stat = source.getConnection().prepareStatement(preparedQuery);
			ParameterMetaData md = stat.getParameterMetaData();
			for (int i = 0; i < getParams().size(); i++) {
				getParams().setSQLType(i, md.getParameterType(i + 1));
			}
			columns = new HashSet<>();
			try {
				for (int i = 0; i < stat.getMetaData().getColumnCount(); i++) {
					columns.add(stat.getMetaData().getColumnName(i + 1));
				}
			} catch (SQLException e) {
				throw new ReportException(e);
			}
		} catch (Exception e) {
			throw new ReportException(e);
		}

	}

	public void open() throws ReportException {
		if (rs == null) {
			reopen();
		}
	}

	public boolean reopen() throws ReportException {
		prepare();
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		} finally {
			rs = null;
		}
		try {
			ParameterMetaData metaData = stat.getParameterMetaData();
			for (int i = 0; i < getParams().size(); i++) {
				Object value = getParams().getValue(i);
				if (value == null)
					stat.setNull(i + 1, getParams().getSQLType(i));
				else {
					if (metaData.getParameterType(i + 1) == Types.DATE && value instanceof String) {
						try {
							Date d = DateFormat.getDateInstance().parse((String)value);
							stat.setDate(i + 1, new java.sql.Date(d.getTime()));
						} catch (Exception e) {
							stat.setObject(i + 1, value);
						}
					} else {
						stat.setObject(i + 1, value);
					}
				}
			}
			rs = stat.executeQuery();
			eof = !rs.next();
			return !eof;
		} catch (SQLException e) {
			throw new ReportException(e);
		}
	}

	public void close() {
		if (rs == null)
			return;
		try {
			rs.close();
			stat.close();
		} catch (SQLException e) {
			logger.log(Level.SEVERE, e.getMessage());
		} finally {
			stat = null;
			rs = null;
			eof = true;
		}
	}

	public String getMasterId() {
		return masterId;
	}

	public void setMasterId(String masterId) {
		this.masterId = masterId;
		if (this.masterId != null && this.masterId.length() == 0) {
			this.masterId = null;
		}
	}

	public Object getValue(String name) throws ReportException {
		try {
			return eof ? null : rs.getObject(name);
		} catch (SQLException e) {
			throw new ReportException(e);
		}
	}

	@Override
	public Object getValue(Object current, String name) throws ReportException {
		if (current == null) return null;
		return ((Map)current).get(name);
	}

	@Override
	public boolean containsKey(String name) {
		return columns.contains(name);
	}

	public Collection<String> getColumnNames() throws ReportException {
		open();
		return columns;
	}

	public DataSetParams getParams() throws ReportException  {
		if (params == null) {
			prepare();
		}
		return params;
	}

	public Object getCurrentObject() throws ReportException {
		if (columns == null)
			open();
		HashMap<String, Object> map = new HashMap<>();
		for (String column : columns) {
			map.put(column, getValue(column));
		}
		return map;
	}

	public boolean hasNext() {
		if (preparedQuery == null)
			try {
				open();
			} catch (ReportException e) {
				logger.log(Level.SEVERE, e.getMessage(), e);
			}
		return !eof;
	}
}


text:
package eu.mosaic_cloud.platform.tools.v2.cloudlets.callbacks;

import eu.mosaic_cloud.platform.v2.cloudlets.core.Callback;
import eu.mosaic_cloud.platform.v2.cloudlets.core.CallbackArguments;
import eu.mosaic_cloud.platform.v2.cloudlets.core.CloudletController;
import eu.mosaic_cloud.tools.callbacks.core.CallbackCompletion;
import eu.mosaic_cloud.tools.exceptions.core.FallbackExceptionTracer;
import eu.mosaic_cloud.tools.transcript.core.Transcript;
import eu.mosaic_cloud.tools.transcript.tools.TranscriptExceptionTracer;

import com.google.common.base.Preconditions;

public class DefaultCallback<TContext>
			extends Object
			implements
				Callback<TContext>
{
	protected DefaultCallback () {
		super ();
		this.transcript = Transcript.create (this, true);
		this.exceptions = TranscriptExceptionTracer.create (this.transcript, FallbackExceptionTracer.defaultInstance);
	}

	public void initialize (@SuppressWarnings ("unused") final TContext context, final CloudletController<?> cloudlet) {
		Preconditions.checkNotNull (cloudlet);
		this.cloudlet = cloudlet;
	}

	protected void enforceCallbackArguments (final TContext context, final CallbackArguments arguments) {
		Preconditions.checkNotNull (arguments);
		this.enforceCloudlet (context, arguments.cloudlet);
	}

	protected void enforceCloudlet (@SuppressWarnings ("unused") final TContext context, final CloudletController<?> cloudlet) {
		Preconditions.checkNotNull (cloudlet);
		if ((this.cloudlet != null) && (this.cloudlet != cloudlet))
			throw (new IllegalArgumentException ());
	}

	protected CallbackCompletion<Void> handleUnhandledCallback (@SuppressWarnings ("rawtypes") final Class<? extends Callback> category, final String callback, final TContext context, final CallbackArguments arguments, final boolean positive, final boolean couldDestroy) {
		this.enforceCallbackArguments (context, arguments);
		this.traceCallback (category, callback, context, arguments, positive);
		if (positive)
			this.transcript.traceDebugging ("unhandled successfull callback `%{class}:%s` for cloudlet `%{object:identity}` within context `%{object:identity}`; ignoring!", category, callback, arguments.cloudlet, context);
		else
			this.transcript.traceWarning ("unhandled failure callback `%{class}:%s` for cloudlet `%{object:identity}` within context `%{object:identity}`; ignoring!", category, callback, arguments.cloudlet, context);
		if (!positive && couldDestroy)
			this.cloudlet.destroy ();
		return (DefaultCallback.Succeeded);
	}

	protected void traceCallback (@SuppressWarnings ("rawtypes") final Class<? extends Callback> category, final String callback, final TContext context, final CallbackArguments arguments, final boolean positive) {
		this.enforceCallbackArguments (context, arguments);
		if (positive)
			this.transcript.traceDebugging ("triggered (positive) callback `%{class}:%s` for cloudlet `%{object:identity}` within context `%{object:identity}`; ignoring!", category, callback, arguments.cloudlet, context);
		else
			this.transcript.traceWarning ("triggered (negative) callback `%{class}:%s` for cloudlet `%{object:identity}` within context `%{object:identity}`; ignoring!", category, callback, arguments.cloudlet, context);
	}

	@Deprecated
	protected CloudletController<?> cloudlet;
	@Deprecated
	protected final TranscriptExceptionTracer exceptions;
	@Deprecated
	protected final Transcript transcript;
	public static final CallbackCompletion<Void> Succeeded = CallbackCompletion.createOutcome ();
	protected static final CallbackCompletion<Void> NotImplemented = CallbackCompletion.createFailure (new UnsupportedOperationException ());
}


text:
from __future__ import absolute_import
from behave.formatter.base import Formatter
import base64
import six
try:
    import json
except ImportError:
    import simplejson as json

# -----------------------------------------------------------------------------
# CLASS: JSONFormatter
# -----------------------------------------------------------------------------
class JSONFormatter(Formatter):
    name = 'json'
    description = 'JSON dump of test run'
    dumps_kwargs = {}
    split_text_into_lines = True   # EXPERIMENT for better readability.

    json_number_types = six.integer_types + (float,)
    json_scalar_types = json_number_types + (six.text_type, bool, type(None))

    def __init__(self, stream_opener, config):
        super(JSONFormatter, self).__init__(stream_opener, config)
        # -- ENSURE: Output stream is open.
        self.stream = self.open()
        self.feature_count = 0
        self.current_feature = None
        self.current_feature_data = None
        self._step_index = 0

    def reset(self):
        self.current_feature = None
        self.current_feature_data = None
        self._step_index = 0

    # -- FORMATTER API:
    def uri(self, uri):
        pass

    def feature(self, feature):
        self.reset()
        self.current_feature = feature
        self.current_feature_data = {
            'keyword': feature.keyword,
            'name': feature.name,
            'tags': list(feature.tags),
            'location': six.text_type(feature.location),
            'status': None,     # Not known before feature run.
        }
        element = self.current_feature_data
        if feature.description:
            element['description'] = feature.description

    def background(self, background):
        element = self.add_feature_element({
            'type': 'background',
            'keyword': background.keyword,
            'name': background.name,
            'location': six.text_type(background.location),
            'steps': [],
        })
        if background.name:
            element['name'] = background.name
        self._step_index = 0

        # -- ADD BACKGROUND STEPS: Support *.feature file regeneration.
        for step_ in background.steps:
            self.step(step_)

    def scenario(self, scenario):
        element = self.add_feature_element({
            'type': 'scenario',
            'keyword': scenario.keyword,
            'name': scenario.name,
            'tags': scenario.tags,
            'location': six.text_type(scenario.location),
            'steps': [],
        })
        if scenario.description:
            element['description'] = scenario.description
        self._step_index = 0

    def scenario_outline(self, scenario_outline):
        element = self.add_feature_element({
            'type': 'scenario_outline',
            'keyword': scenario_outline.keyword,
            'name': scenario_outline.name,
            'tags': scenario_outline.tags,
            'location': six.text_type(scenario_outline.location),
            'steps': [],
            'examples': [],
        })
        if scenario_outline.description:
            element['description'] = scenario_outline.description
        self._step_index = 0

    @classmethod
    def make_table(cls, table):
        table_data = {
            'headings': table.headings,
            'rows': [ list(row) for row in table.rows ]
        }
        return table_data

    def examples(self, examples):
        e = {
            'type': 'examples',
            'keyword': examples.keyword,
            'name': examples.name,
            'location': six.text_type(examples.location),
        }

        if examples.table:
            e['table'] = self.make_table(examples.table)

        element = self.current_feature_element
        element['examples'].append(e)

    def step(self, step):
        s = {
            'keyword': step.keyword,
            'step_type': step.step_type,
            'name': step.name,
            'location': six.text_type(step.location),
        }

        if step.text:
            text = step.text
            if self.split_text_into_lines and "\n" in text:
                text = text.splitlines()
            s['text'] = text
        if step.table:
            s['table'] = self.make_table(step.table)
        element = self.current_feature_element
        element['steps'].append(s)

    def match(self, match):
        args = []
        for argument in match.arguments:
            argument_value = argument.value
            if not isinstance(argument_value, self.json_scalar_types):
                # -- OOPS: Avoid invalid JSON format w/ custom types.
                # Use raw string (original) instead.
                argument_value = argument.original
            assert isinstance(argument_value, self.json_scalar_types)
            arg = {
                'value': argument_value,
            }
            if argument.name:
                arg['name'] = argument.name
            if argument.original != argument_value:
                # -- REDUNDANT DATA COMPRESSION: Suppress for strings.
                arg['original'] = argument.original
            args.append(arg)

        match_data = {
            'location': six.text_type(match.location) or "",
            'arguments': args,
        }
        if match.location:
            # -- NOTE: match.location=None occurs for undefined steps.
            steps = self.current_feature_element['steps']
            steps[self._step_index]['match'] = match_data

    def result(self, result):
        steps = self.current_feature_element['steps']
        steps[self._step_index]['result'] = {
            'status': result.status,
            'duration': result.duration,
        }
        if result.error_message and result.status == 'failed':
            # -- OPTIONAL: Provided for failed steps.
            error_message = result.error_message
            if self.split_text_into_lines and "\n" in error_message:
                error_message = error_message.splitlines()
            result_element = steps[self._step_index]['result']
            result_element['error_message'] = error_message
        self._step_index += 1

    def embedding(self, mime_type, data):
        step = self.current_feature_element['steps'][-1]
        step['embeddings'].append({
            'mime_type': mime_type,
            'data': base64.b64encode(data).replace('\n', ''),
        })

    def eof(self):
        """
        End of feature
        """
        if not self.current_feature_data:
            return

        # -- NORMAL CASE: Write collected data of current feature.
        self.update_status_data()

        if self.feature_count == 0:
            # -- FIRST FEATURE:
            self.write_json_header()
        else:
            # -- NEXT FEATURE:
            self.write_json_feature_separator()

        self.write_json_feature(self.current_feature_data)
        self.current_feature_data = None
        self.feature_count += 1

    def close(self):
        self.write_json_footer()
        self.close_stream()

    # -- JSON-DATA COLLECTION:
    def add_feature_element(self, element):
        assert self.current_feature_data is not None
        if 'elements' not in self.current_feature_data:
            self.current_feature_data['elements'] = []
        self.current_feature_data['elements'].append(element)
        return element

    @property
    def current_feature_element(self):
        assert self.current_feature_data is not None
        return self.current_feature_data['elements'][-1]

    def update_status_data(self):
        assert self.current_feature
        assert self.current_feature_data
        self.current_feature_data['status'] = self.current_feature.status

    # -- JSON-WRITER:
    def write_json_header(self):
        self.stream.write('[\n')

    def write_json_footer(self):
        self.stream.write('\n]\n')

    def write_json_feature(self, feature_data):
        self.stream.write(json.dumps(feature_data, **self.dumps_kwargs))
        self.stream.flush()

    def write_json_feature_separator(self):
        self.stream.write(",\n\n")

# -----------------------------------------------------------------------------
# CLASS: PrettyJSONFormatter
# -----------------------------------------------------------------------------
class PrettyJSONFormatter(JSONFormatter):
    """
    Provides readable/comparable textual JSON output.
    """
    name = 'json.pretty'
    description = 'JSON dump of test run (human readable)'
    dumps_kwargs = { 'indent': 2, 'sort_keys': True }


text:
A PHP library for converting HTML to formatted plain text.

[![Build Status](https://travis-ci.org/mtibben/html2text.png?branch=master)](https://travis-ci.org/mtibben/html2text)

## Basic Usage
```php
$html = new \Html2Text\Html2Text('Hello, "<b>world</b>"');

echo $html->getText();  // Hello, "WORLD"
```

## History

This library started life on the blog of Jon Abernathy http://www.chuggnutt.com/html2text

A number of projects picked up the library and started using it - among those was RoundCube mail. They made a number of updates to it over time to suit their webmail client.

Now it has been extracted as a standalone library. Hopefully it can be of use to others.


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.uiDesigner.propertyInspector.renderers;

import com.intellij.openapi.util.NlsSafe;
import org.jetbrains.annotations.NotNull;

import java.awt.*;

/**
 * @author Anton Katilin
 * @author Vladimir Kondratyev
 */
public final class InsetsPropertyRenderer extends LabelPropertyRenderer<Insets> {
  private final StringBuffer myBuffer;

  public InsetsPropertyRenderer(){
    myBuffer=new StringBuffer();
  }

  @Override
  protected void customize(@NotNull final Insets value){
    setText(formatText(value));
  }

  public @NlsSafe String formatText(final Insets value) {
    myBuffer.setLength(0);
    myBuffer.append('[');
    myBuffer.append(value.top).append(", ");
    myBuffer.append(value.left).append(", ");
    myBuffer.append(value.bottom).append(", ");
    myBuffer.append(value.right);
    myBuffer.append("]");

    // [jeka] important! do not use toString() on the StringBuffer that is reused
    return myBuffer.substring(0, myBuffer.length());
  }
}


text:
package com.zaradai.mocks;

import com.zaradai.net.retry.DelayPolicy;

import static org.mockito.Mockito.mock;

public class DelayPolicyMocker {
    public static DelayPolicy create() {
        return mock(DelayPolicy.class);
    }
}


text:
/****************************************************************************
** Meta object code from reading C++ file 'optionsmodel.h'
**
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/

#include "qt/optionsmodel.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'optionsmodel.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.6.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif

QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_OptionsModel_t {
    QByteArrayData data[6];
    char stringdata0[85];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
    Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
    qptrdiff(offsetof(qt_meta_stringdata_OptionsModel_t, stringdata0) + ofs \
        - idx * sizeof(QByteArrayData)) \
    )
static const qt_meta_stringdata_OptionsModel_t qt_meta_stringdata_OptionsModel = {
    {
QT_MOC_LITERAL(0, 0, 12), // "OptionsModel"
QT_MOC_LITERAL(1, 13, 18), // "displayUnitChanged"
QT_MOC_LITERAL(2, 32, 0), // ""
QT_MOC_LITERAL(3, 33, 4), // "unit"
QT_MOC_LITERAL(4, 38, 26), // "coinControlFeaturesChanged"
QT_MOC_LITERAL(5, 65, 19) // "hideTrayIconChanged"

    },
    "OptionsModel\0displayUnitChanged\0\0unit\0"
    "coinControlFeaturesChanged\0"
    "hideTrayIconChanged"
};
#undef QT_MOC_LITERAL

static const uint qt_meta_data_OptionsModel[] = {

 // content:
       7,       // revision
       0,       // classname
       0,    0, // classinfo
       3,   14, // methods
       0,    0, // properties
       0,    0, // enums/sets
       0,    0, // constructors
       0,       // flags
       3,       // signalCount

 // signals: name, argc, parameters, tag, flags
       1,    1,   29,    2, 0x06 /* Public */,
       4,    1,   32,    2, 0x06 /* Public */,
       5,    1,   35,    2, 0x06 /* Public */,

 // signals: parameters
    QMetaType::Void, QMetaType::Int,    3,
    QMetaType::Void, QMetaType::Bool,    2,
    QMetaType::Void, QMetaType::Bool,    2,

       0        // eod
};

void OptionsModel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
    if (_c == QMetaObject::InvokeMetaMethod) {
        OptionsModel *_t = static_cast<OptionsModel *>(_o);
        Q_UNUSED(_t)
        switch (_id) {
        case 0: _t->displayUnitChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 1: _t->coinControlFeaturesChanged((*reinterpret_cast< bool(*)>(_a[1]))); break;
        case 2: _t->hideTrayIconChanged((*reinterpret_cast< bool(*)>(_a[1]))); break;
        default: ;
        }
    } else if (_c == QMetaObject::IndexOfMethod) {
        int *result = reinterpret_cast<int *>(_a[0]);
        void **func = reinterpret_cast<void **>(_a[1]);
        {
            typedef void (OptionsModel::*_t)(int );
            if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&OptionsModel::displayUnitChanged)) {
                *result = 0;
                return;
            }
        }
        {
            typedef void (OptionsModel::*_t)(bool );
            if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&OptionsModel::coinControlFeaturesChanged)) {
                *result = 1;
                return;
            }
        }
        {
            typedef void (OptionsModel::*_t)(bool );
            if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&OptionsModel::hideTrayIconChanged)) {
                *result = 2;
                return;
            }
        }
    }
}

const QMetaObject OptionsModel::staticMetaObject = {
    { &QAbstractListModel::staticMetaObject, qt_meta_stringdata_OptionsModel.data,
      qt_meta_data_OptionsModel,  qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};

const QMetaObject *OptionsModel::metaObject() const
{
    return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}

void *OptionsModel::qt_metacast(const char *_clname)
{
    if (!_clname) return Q_NULLPTR;
    if (!strcmp(_clname, qt_meta_stringdata_OptionsModel.stringdata0))
        return static_cast<void*>(const_cast< OptionsModel*>(this));
    return QAbstractListModel::qt_metacast(_clname);
}

int OptionsModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QAbstractListModel::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 3)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 3;
    } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
        if (_id < 3)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 3;
    }
    return _id;
}

// SIGNAL 0
void OptionsModel::displayUnitChanged(int _t1)
{
    void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
    QMetaObject::activate(this, &staticMetaObject, 0, _a);
}

// SIGNAL 1
void OptionsModel::coinControlFeaturesChanged(bool _t1)
{
    void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
    QMetaObject::activate(this, &staticMetaObject, 1, _a);
}

// SIGNAL 2
void OptionsModel::hideTrayIconChanged(bool _t1)
{
    void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
    QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
QT_END_MOC_NAMESPACE


text:
using Coevery.ContentManagement.Handlers;
using Coevery.Tests.ContentManagement.Models;

namespace Coevery.Tests.ContentManagement.Handlers {
    public class BetaPartHandler : ContentHandler {
        public BetaPartHandler() {
            Filters.Add(new ActivatingFilter<BetaPart>("beta"));
        }
    }
}


text:
package com.google.devrel.training.conference.form;

import com.google.common.collect.ImmutableList;

import java.util.Date;
import java.util.List;

/**
 * A simple Java object (POJO) representing a Conference form sent from the client.
 */
public class ConferenceForm {
    /**
     * The name of the conference.
     */
    private String name;

    /**
     * The description of the conference.
     */
    private String description;

    /**
     * Topics that are discussed in this conference.
     */
    private List<String> topics;

    /**
     * The city where the conference will take place.
     */
    private String city;

    /**
     * The start date of the conference.
     */
    private Date startDate;

    /**
     * The end date of the conference.
     */
    private Date endDate;

    /**
     * The capacity of the conference.
     */
    private int maxAttendees;

    private ConferenceForm() {}

    /**
     * Public constructor is solely for Unit Test.
     * @param name
     * @param description
     * @param topics
     * @param city
     * @param startDate
     * @param endDate
     * @param maxAttendees
     */
    public ConferenceForm(String name, String description, List<String> topics, String city,
                          Date startDate, Date endDate, int maxAttendees) {
        this.name = name;
        this.description = description;
        this.topics = topics == null ? null : ImmutableList.copyOf(topics);
        this.city = city;
        this.startDate = startDate == null ? null : new Date(startDate.getTime());
        this.endDate = endDate == null ? null : new Date(endDate.getTime());
        this.maxAttendees = maxAttendees;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public List<String> getTopics() {
        return topics;
    }

    public String getCity() {
        return city;
    }

    public Date getStartDate() {
        return startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public int getMaxAttendees() {
        return maxAttendees;
    }
}


text:
package org.griphyn.vdl.karajan.lib;

import k.rt.Stack;

import org.globus.cog.karajan.analyzer.ArgRef;
import org.globus.cog.karajan.analyzer.Signature;
import org.griphyn.vdl.mapping.DSHandle;

/** Determines if a variable is 'restartable'; that is, if we restart the
    workflow, will this variable still have its content.
*/

public class IsRestartable extends SwiftFunction {
    private ArgRef<DSHandle> var;

    @Override
    protected Signature getSignature() {
        return new Signature(params("var"));
    }

    @Override
    public Object function(Stack stack) {
        DSHandle var = this.var.getValue(stack);
        return Boolean.valueOf(var.isRestartable());
    }
}


text:
#ifndef _RDPGLYPHS_H
#define _RDPGLYPHS_H

struct rdp_font_char
{
    int offset;    /* x */
    int baseline;  /* y */
    int width;     /* cx */
    int height;    /* cy */
    int incby;
    int bpp;
    char *data;
    int data_bytes;
};

struct rdp_text
{
    RegionPtr reg;
    int font;
    int x;
    int y;
    int flags;
    int mixmode;
    char data[256];
    int data_bytes;
    struct rdp_font_char* chars[256];
    int num_chars;
    struct rdp_text* next;
};

int
rdpGlyphDeleteRdpText(struct rdp_text* rtext);
void
rdpGlyphs(CARD8 op, PicturePtr pSrc, PicturePtr pDst,
          PictFormatPtr maskFormat,
          INT16 xSrc, INT16 ySrc, int nlists, GlyphListPtr lists,
          GlyphPtr *glyphs);

#endif


text:
namespace AsyncMqttClientInternals {
class PubAckPacket : public Packet {
 public:
  explicit PubAckPacket(ParsingInformation* parsingInformation, OnPubAckInternalCallback callback);
  ~PubAckPacket();

  void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
  void parsePayload(char* data, size_t len, size_t* currentBytePosition);

 private:
  ParsingInformation* _parsingInformation;
  OnPubAckInternalCallback _callback;

  uint8_t _bytePosition;
  char _packetIdMsb;
  uint16_t _packetId;
};
}  // namespace AsyncMqttClientInternals


text:
'use strict';

//dependencies
var config = require('./config'),
    express = require('express'),
    mongoStore = require('connect-mongo')(express),
    http = require('http'),
    path = require('path'),
    passport = require('passport'),
    crypto = require("crypto"),
    utils = require("./utils"),
    mongoose = require('mongoose');

//create express app
var app = express();

//setup the web server
app.server = http.createServer(app);

//setup mongoose
app.db = mongoose.createConnection(config.mongodb.uri);
app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
app.db.once('open', function () {
  //and... we have a data store
});

//config data models
require('./models')(app, mongoose);

//setup the session store
app.sessionStore = new mongoStore({ url: config.mongodb.uri });

//config express in all environments
app.configure(function(){
  //settings
  app.disable('x-powered-by');
  app.set('mysite', config.mysite);
  app.set('port', config.port);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('strict routing', true);
  app.set('project-name', config.projectName);
  app.set('subtitle', config.subtitle);
  app.set('company-name', config.companyName);
  app.set('system-email', config.systemEmail);
  app.set('crypto-key', config.cryptoKey);
  app.set('require-account-verification', config.requireAccountVerification);

  //smtp settings
  app.set('smtp-from-name', config.smtp.from.name);
  app.set('smtp-from-address', config.smtp.from.address);
  app.set('smtp-credentials', config.smtp.credentials);

  //middleware
  app.use(express.favicon(__dirname + '/public/assets/img/favicon.ico'));
  app.use(express.logger('dev'));
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({
    secret: config.cryptoKey,
    store: app.sessionStore
  }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);

  //error handler
  //app.use(require('./views/http/index').http500);

  //global locals
  app.locals.projectName = app.get('project-name');
  app.locals.subtitle = app.get('subtitle');
  app.locals.copyrightYear = new Date().getFullYear();
  app.locals.copyrightName = app.get('company-name');
});

//config express in dev environment
app.configure('development', function(){
  app.use(express.errorHandler());
});

//setup passport
require('./passport')(app, passport);

//route requests
require('./routes')(app, passport);

//listen up
app.server.listen(app.get('port'), function(){
  //and... we're live
});


text:
<?php

namespace common\models;

use \common\models\base\Product as BaseProduct;
use yii\db\Expression;

/**
 * This is the model class for table "product".
 */
class Product extends BaseProduct
{
    public static function findOrCreate($attributes)
    {
        if ($model = self::find()->where($attributes)->one()) {
            return $model;
        }
        $model = new self;
        $model->attributes = $attributes;
        return $model;
    }

    public function beforeValidate()
    {
        $this->updateTimestamps();
        return parent::beforeValidate();
    }

    // -- private

    private function updateTimestamps()
    {
        if ($this->isNewRecord) {
            $this->created_at = new Expression('NOW()');
        } else {
            $this->updated_at = new Expression('NOW()');
        }
    }
}


text:
namespace BeerApp.Web.Controllers
{
    using System.Web.Mvc;
    using Data.Models;
    using Microsoft.AspNet.Identity;
    using Services.Data;
    using Services.Web;

    [Authorize]
    public class BeerVotesController : BaseController
    {
        private readonly IBeerVotesService votes;

        public BeerVotesController(IBeerVotesService votes, IIdentifierProvider identifier)
        {
            this.votes = votes;
        }

        // TODO:Fix logic
        [HttpPost]
        public ActionResult Vote(int beerId, int voteType)
        {
            if (voteType > 1)
            {
                voteType = 1;
            }

            if (voteType < -1)
            {
                voteType = -1;
            }

            var userId = this.User.Identity.GetUserId();
            var vote = this.votes.GetByUserAndBeerId(userId, beerId);

            if (vote == null)
            {
                vote = new BeerVote
                {
                    VoterId = userId,
                    BeerId = beerId,
                    Type = (VoteType) voteType
                };
                this.votes.AddVote(vote);
            }
            else
            {
                if (vote.Type == VoteType.Neutral)
                {
                    vote.Type = (VoteType) voteType;
                }
                else if (vote.Type != (VoteType)voteType)
                {
                    vote.Type = VoteType.Neutral;
                }

                this.votes.SaveVoteChanges();
            }

            var beerVoteCount = this.votes.CountVotes(beerId);

            return this.Json(new { Count = beerVoteCount });
        }
    }
}


text:
package maga.item;
import maga.character.Player;

public class Steak extends Item {

    /**
     * Creating a variable of the type Ketchup
     */
    private boolean ketchup = false;

    /**
     * Constructor for the object Steak
     */
    public Steak(){
        super("Steak");
    }

    /**
     * Method checks if the Steak has ketchup on it
     * @return boolean
     */
    public boolean hasKetchup(){
        return this.ketchup;
    }

    /**
     * Creates a "use" method for the "Steak" item. The method searches for
     * a "Ketchup" item, and can't be used if there isn't one in the inventory.
     * @param player
     */
    @Override
    public void use(Player player) {
        for(Item item : player.getItems()) {
            if(item.getName().equals("Ketchup")){
                this.ketchup = true;
                this.setName("Steak-with-ketchup");
                return;
            }
        }

    }
}