text:
require 'active_model'
require 'rails'
require 'roo'

module RailsSpreadsheetReader

  class Base

    include ActiveModel::Model
    include ActiveModel::Validations::Callbacks

    class MethodNotImplementedError < StandardError; end
    class InvalidTypeError < StandardError; end

    attr_accessor :row_number
    attr_accessor :record_with_error
    attr_accessor :copied_errors
    attr_accessor :collection

    BASE_ATTRIBUTES = %w(row_number record_with_error copied_errors collection)

    validate :check_record_with_error

    def check_record_with_error
      if record_with_error.present? and record_with_error.errors.any?
        record_with_error.errors.full_messages.each do |msg|
          @errors.add(:base, msg)
        end
      end
    end

    def self.last_record
      @last_record ||= nil
    end

    def self.last_record=(record)
      @last_record = record
    end

    def self.models
      fail(
          MethodNotImplementedError,
          'Please implement this method in your class.'
      )
    end

    def persist!
      models = self.class.models.is_a?(Array) ? self.class.models : [self.class.models]
      models.each do |model|
        method_name = model.model_name.human.downcase
        if respond_to?(method_name)
          instance = model.new(send(model.model_name.human.downcase))
        else
          instance = model.new(as_json(except: BASE_ATTRIBUTES))
        end
        instance.save!
      end
    end

    # Defines the starting row of the excel where the class should start reading the data.
    #
    # == Returns:
    # A integer representing the starting row of the data.
    #
    def self.starting_row
      2
    end

    # Defines the columns of the excel that the class will read. This method must return
    # a Array of strings/symbols (representing columns names) or a Hash (which map column names to columns indexes).
    #
    # Array Example
    #   def self.headers
    #     [:username, :email, :gender]
    #   end
    #
    # Hash Example
    #   def self.headers
    #     { :username => 0, :email => 1, :gender => 2 }
    #   end
    #
    # == Returns:
    # An Array or a Hash defining the columns of the excel.
    #
    def self.headers
      fail(
          MethodNotImplementedError,
          'Please implement this method in your class.'
      )
    end

    # Returns the Hash representation of a given array using self.format method
    # (which internally uses self.columns). The keys of this Hash are defined
    # in the self.columns method and the values of each key depends on the
    # order of the columns.
    #
    # For example, given the following self.columns definition
    #   def self.headers
    #     [:username, :email, :gender]
    #   end
    # Or
    #   def self.headers
    #     { :username => 0, :email => 1, :gender => 2 }
    #   end
    # Row.formatted([username email@test.cl male]) will return
    # { username: 'username', email: 'email@test.cl', gender: 'male' }
    #
    # == Parameters:
    # array::
    #   Array of values which represents an excel column.
    #
    # == Returns:
    # Hash representation of the given array which maps columns names to the array values.

    def self.formatted_hash(array)

      if format.keys.count > 0
        parsed_row = {}
        format.each_pair { |key, col| parsed_row[key] = array[col] }
        return parsed_row
      end

      return nil
    end

    # Generalizes the constructor of ActiveModel::Model to make it work
    # with an array argument.
    # When an array argument is passed, it calls formatted_hash method
    # to generate a Hash and then pass it to the ActiveModel::Model constructor
    #
    # == Parameters:
    # arr_or_hash::
    #   Array or Hash of values which represents an excel column.

    def initialize(arr_or_hash = {})
      self.copied_errors = ActiveModel::Errors.new(self)
      if arr_or_hash.is_a?(Array)
        super(self.class.formatted_hash(arr_or_hash))
      else
        super(arr_or_hash)
      end
    end

    # Persist all rows of collection if they all are valid
    #
    # == Parameters:
    # row_collection::
    #   SpreadsheetReader::RowCollection instance
    def self.persist(collection)
      if collection.valid?
        ActiveRecord::Base.transaction do
          collection.each do |row|
            # If any of validations fail ActiveRecord::RecordInvalid gets raised.
            # If any of the before_* callbacks return false the action is cancelled and save! raises ActiveRecord::RecordNotSaved.
            begin
              row.persist!
            rescue ActiveRecord::RecordInvalid => e
              row.record_with_error = e.record
              collection.invalid_row = row
              row.check_record_with_error
              rollback
            rescue ActiveRecord::RecordNotSaved => e
              row.model_with_error = e.record
              collection.invalid_row = row
              row.check_record_with_error
              rollback
            end
          end
        end
      end
    end

    def self.open(spreadsheet_file)
      if spreadsheet_file.respond_to?(:original_filename)
        Roo::Spreadsheet.open(spreadsheet_file.path, extension: File.extname(spreadsheet_file.original_filename).delete('.'))
      else
        Roo::Spreadsheet.open(spreadsheet_file)
      end
    end

    # Read and validates the given #spreadsheet_file. Persistence is triggered
    # after all validation pass
    #
    # == Parameters:
    # spreadsheet_file::
    #   File instance
    # == Returns:
    # row_collection::
    #   SpreadsheetReader::RowCollection instance
    def self.read(spreadsheet_file)

      if headers.empty?
        raise MethodNotImplementedError
      end

      spreadsheet = open(spreadsheet_file)
      collection = RailsSpreadsheetReader::RowCollection.new

      # Populate collection
      (starting_row..spreadsheet.last_row).each do |row_number|
        parameters = formatted_hash(spreadsheet.row(row_number))
        parameters[:row_number] = row_number
        parameters[:collection] = collection
        collection << self.new(parameters)
      end

      # Validation and persist
      persist(collection)

      collection
    end

    # Transform an array [a0, a1, a2, ...] to a Hash { a0 => 0, a1 => 1, etc }
    # which is the format required by the #formatted_hash method.
    def self.array_to_hash(arr)
      Hash[[*arr.map { |e| e.to_sym }.map.with_index]]
    end

    private

    # Returns the Hash representation of the defined columns
    def self.format

      if headers.is_a?(Array) or headers.is_a?(Hash)
        return headers.is_a?(Array) ? array_to_hash(headers) : headers
      end

      fail(
          InvalidTypeError,
          'Please check that the self.columns implementation returns a instance of Hash or Array.'
      )

    end

    # Helper for rollbacks inside #after_multiple_row_validations
    def self.rollback
      raise ActiveRecord::Rollback
    end

  end

end


text:
package cn.sixlab.sixtools.site.update;

/**
 * TODO
 *
 * @author 六楼的雨/Patrick Root
 * @date 2017/03/12 22:09
 */
public class Site {
    public static final String WAIT_SUN = "waitSunCom";
    public static final String V6_HAO = "6vHaoNet01";

}

redpajama_set_name: RedPajamaGithub


text:
This branch is currently ***UNSTABLE*** and is not guaranteed to work correctly. When this site hits 1.0, all development will be moved to the [dev branch](../../tree/dev), and only *stable* and *working* code will live in this branch (master).

### Prerequisites
- [Node.js](http://nodejs.org)
- [MongoDB](http://mongodb.org)

### Install
1. `cd` into whatever directory you wish to contain this repository
2. Run `git clone https://github.com/skulbuny/sleazycompany.git`
3. Run `npm i` to install all Node dependencies
4. Run `mongod` to start your Mongo database
5. Run `forever start keystone.js`
6. Open [http://localhost:8008](http://localhost:8008) in your browser.


text:
@protocol UnityViewControllerListener<NSObject>
@optional
- (void)viewDidLayoutSubviews:(NSNotification*)notification;
- (void)viewDidDisappear:(NSNotification*)notification;
- (void)viewWillDisappear:(NSNotification*)notification;
- (void)viewDidAppear:(NSNotification*)notification;
- (void)viewWillAppear:(NSNotification*)notification;

- (void)interfaceWillChangeOrientation:(NSNotification*)notification;
- (void)interfaceDidChangeOrientation:(NSNotification*)notification;
@end

void UnityRegisterViewControllerListener(id<UnityViewControllerListener> obj);
void UnityUnregisterViewControllerListener(id<UnityViewControllerListener> obj);

extern "C" __attribute__((visibility ("default"))) NSString* const kUnityViewDidLayoutSubviews;
extern "C" __attribute__((visibility ("default"))) NSString* const kUnityViewDidDisappear;
extern "C" __attribute__((visibility ("default"))) NSString* const kUnityViewDidAppear;
extern "C" __attribute__((visibility ("default"))) NSString* const kUnityViewWillDisappear;
extern "C" __attribute__((visibility ("default"))) NSString* const kUnityViewWillAppear;
extern "C" __attribute__((visibility ("default"))) NSString* const kUnityInterfaceWillChangeOrientation;
extern "C" __attribute__((visibility ("default"))) NSString* const kUnityInterfaceDidChangeOrientation;

#endif // _TRAMPOLINE_PLUGINBASE_LIFECYCLELISTENER_H_


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    errorHandler = require('./errors.server.controller'),
    Genre = mongoose.model('Genre'),
    _ = require('lodash');

/**
 * Create a Genre
 */
exports.create = function(req, res) {
    var genre = new Genre(req.body);

    genre.save(function(err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.status(201).json(genre);
        }
    });
};

/**
 * Show the current Genre
 */
exports.read = function(req,res) {
    res.json(req.genre);
};

/**
 * Show the Genre by ID
 */
exports.genreByID = function(req, res) {
    Genre.findById(req.params.genreId).exec(function(err,genre) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            if (!genre) {
                return res.status(404).send({
                    message: 'Genre not found'
                });
            }
            res.json(genre);
        }
    });
};

/**
 * Update a Genre
 */
exports.update = function(req, res) {
	var genre = req.genre;

	genre = _.extend(genre, req.body);

	genre.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.json(genre);
		}
	});

};

/**
 * Delete an Genre
 */
exports.delete = function(req, res) {
	var genre = req.genre;

	genre.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.json(genre);
		}
	});
};

/**
 * List of Genres
 */
exports.list = function(req, res) {
    Genre.find().exec(function(err, genres) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.json(genres);
        }
    });
};


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

def actor_with_role(a_role)
  double("Actor", :thwart_role => a_role.name)
end

describe Thwart::RoleRegistry do
  before do
    @role_builder = double("Role Builder")
    @role_builder.class.stub(:set_callback => true)
    @registry = Thwart::RoleRegistry.new(@role_builder)
  end

  it "should initialize a callback on the action creator" do
    store_class = Class.new do
      include ActiveSupport::Callbacks
    end
    store_class.should_receive(:set_callback)
    Thwart::RoleRegistry.new(store_class.new)
  end

  it "should add roles to the registry" do
    role = double("Role")
    @registry.add(role)
    @registry.roles.should include(role)
    @registry.has_role?(role).should == true
  end

  it "should prevent addition of duplicate roles" do
    role = double("Role")
    @registry.add(role)
    lambda {
      @registry.add(role)
    }.should raise_error(Thwart::DuplicateRoleError)
  end
  context "role finding" do
    before do
      @role = double("A Role", :name => :role1)
      @registry.add(@role)
    end
    it "should find nil for nil" do
      @registry.find_actor_role(nil).should == nil
    end
    it "should use the thwart_role attribute" do
      actor = double("Actor", :thwart_role => @role)
      @registry.find_actor_role(actor).should == @role
    end
    it "should convert symbols to roles" do
      actor = double("Actor", :thwart_role => :role1)
      @registry.find_actor_role(actor).should == @role
    end
    it "should convert strings to roles" do
      actor = double("Actor", :thwart_role => "role1")
      @registry.find_actor_role(actor).should == @role
    end
    it "should find nil for symbols pointing to non registered roles " do
      actor = double("Actor", :thwart_role => :role2)
      @registry.find_actor_role(actor).should == nil
    end
  end
  context "querying" do
    it "should return the default if the role can't be found and the gem wide setting is set" do
      Thwart.actor_must_play_role = false
      resp = double("A Bool")
      Thwart.should_receive(:default_query_response).and_return(resp)
      @registry.query(nil, nil, nil).should == resp
    end

    it "should raise an error if the role can't be found and the gem wide setting is set" do
      Thwart.actor_must_play_role = true
      lambda {
        @registry.query(nil, nil, nil)
      }.should raise_error(Thwart::MissingRoleError)
    end

    context "with roles in the registry" do
      before do
        Thwart.actor_must_play_role = true
        Thwart.default_query_response = false
        @role1 = double("Low Level Role", :name => :role1, :query => false)
        @role2 = double("High Level Role", :name => :role2, :query => true)
        @role3 = double("No Rules Role", :name => :role3, :query => nil, :parents => [@role2, @role1])
        @role4 = double("Really low role", :name => :role4, :query => nil, :parents => [@role3])
        [@role1, @role2, @role3, @role4].each do |r|
          @registry.add(r)
        end
      end

      it "should query the role" do
        @registry.query(actor_with_role(@role1), nil, nil).should == false
      end

      it "should log the query path if the gem wide setting is set" do
        Thwart.stub(:log_query_path => true)
        a = actor_with_role(@role1)
        @registry.query(a, nil, nil)
        Thwart.last_query_path.should == [
          {:actor => a, :resource => nil, :action => nil}, {:actor_role => :role1, :resource_name => nil}, "Querying role1", @role1, "Response: false"]
      end

      it "should query the parents in a breadth first order if the role query is unsuccessful" do
        @role3.should_receive(:parents)
        @registry.query(actor_with_role(@role3), nil, nil).should == true # this ensures role2 is checked before role1
      end

      it "should query more than one level of parents" do
        @role3.should_receive(:parents)
        @role4.should_receive(:parents)
        @registry.query(actor_with_role(@role4), nil, nil).should == true # this ensures role2 is checked before role1
      end

      it "should return the default if the role can't be found and the gem wide setting is set" do
        Thwart.actor_must_play_role = false
        @registry.query(actor_with_role(double("A role not in the registry", :name => :not_present)), nil, nil).should == false
      end

      it "should raise an error if the role can't be found and the gem wide setting is set" do
        Thwart.actor_must_play_role = true
        lambda {
          @registry.query(actor_with_role(double("A role not in the registry", :name => :not_present)), nil, nil)
        }.should raise_error(Thwart::MissingRoleError)
      end
    end
  end
end


text:
var Contains = require('../circle/Contains');
var Point = require('../point/Point');

var tmp = new Point();

/**
 * Checks for intersection between the line segment and circle.
 *
 * Based on code by [Matt DesLauriers](https://github.com/mattdesl/line-circle-collision/blob/master/LICENSE.md).
 *
 * @function Phaser.Geom.Intersects.LineToCircle
 * @since 3.0.0
 *
 * @param {Phaser.Geom.Line} line - The line segment to check.
 * @param {Phaser.Geom.Circle} circle - The circle to check against the line.
 * @param {(Phaser.Geom.Point|any)} [nearest] - An optional Point-like object. If given the closest point on the Line where the circle intersects will be stored in this object.
 *
 * @return {boolean} `true` if the two objects intersect, otherwise `false`.
 */
var LineToCircle = function (line, circle, nearest)
{
    if (nearest === undefined) { nearest = tmp; }

    if (Contains(circle, line.x1, line.y1))
    {
        nearest.x = line.x1;
        nearest.y = line.y1;

        return true;
    }

    if (Contains(circle, line.x2, line.y2))
    {
        nearest.x = line.x2;
        nearest.y = line.y2;

        return true;
    }

    var dx = line.x2 - line.x1;
    var dy = line.y2 - line.y1;

    var lcx = circle.x - line.x1;
    var lcy = circle.y - line.y1;

    //  project lc onto d, resulting in vector p
    var dLen2 = (dx * dx) + (dy * dy);
    var px = dx;
    var py = dy;

    if (dLen2 > 0)
    {
        var dp = ((lcx * dx) + (lcy * dy)) / dLen2;

        px *= dp;
        py *= dp;
    }

    nearest.x = line.x1 + px;
    nearest.y = line.y1 + py;

    //  len2 of p
    var pLen2 = (px * px) + (py * py);

    return (
        pLen2 <= dLen2 &&
        ((px * dx) + (py * dy)) >= 0 &&
        Contains(circle, nearest.x, nearest.y)
    );
};

module.exports = LineToCircle;


text:
app.controller("ProductController", ["$routeParams", "$scope", "ProductService", "ImageUploadService", function($routeParams, $scope, ProductService, ImageUploadService) {

	$scope.newProduct = {productId: null, productAccountId: "5", productImageId: null, productAdminFee: "0", productDescription: "", productPrice: null, productShipping: null, productSold: "0", productTitle: ""};
	$scope.alerts = [];
	// $scope.imageFilename = "";

	// $scope.uploadImage = function() {
	// 	console.log($scope.imageFilename);
	// 	// if ($scope.imageFilename.length !== 0) {
	// 		ImageUploadService.create()
	// 			.then(function(result) {
	// 				if(result.data.status === 200) {
	// 					$scope.alerts[0] = {type: "success", msg: result.data.message};
	// 					$scope.newProduct.productImageId = result.data.data;
	// 					$scope.imageFilename = "";
	// 				}
	// 			});
	// 	// }
	// };

	/**
	 * creates a product and sends it to the product API
	 *
	 * @param product the product to send
	 * @param validated true if Angular validated the form, false if not
	 **/

		$scope.createProduct = function(product, validated) {
			// console.log("test");
			if(validated === true) {
				// console.log("testing");
				// $scope.uploadImage();
				// console.log("testing again");
				ProductService.create(product)
					.then(function(result) {
						if(result.data.status === 200) {
							$scope.alerts[0] = {type: "success", msg: result.data.message};
							$scope.newProduct = {productId: null, productAccountId: null, productImageId: null, productAdminFee: null, productDescription: "", productPrice: null, productShipping: null, productSold: null, productTitle: ""};
							$scope.addProductForm.$setPristine();
							$scope.addProductForm.$setUntouched();
						} else {
							$scope.alerts[0] = {type: "danger", msg: result.data.message};
						}
					});
			}
		};

}]);


text:
@implementation RMDocument

- (id)init
{
    self = [super init];
    if (self) {
		employees = [[NSMutableArray alloc] init];

		NSNotificationCenter *nc =
		[NSNotificationCenter defaultCenter];

		[nc addObserver:self
			   selector:@selector(handleColorChange:)
				   name:BNRColorChangedNotification
				 object:nil];
		NSLog(@"Registered with notification center");
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (NSString *)windowNibName
{
	// Override returning the nib file name of the document
	// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
	return @"RMDocument";
}

- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
	[super windowControllerDidLoadNib:aController];
	[tableView setBackgroundColor:
	 [PreferenceController preferenceTableBgColor]];
}

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
	// End editing
	[[tableView window] endEditingFor:nil];
	// Create an NSData object from the employees array
	return [NSKeyedArchiver archivedDataWithRootObject:employees];
}

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
	NSLog(@"About to read data of type %@", typeName);
	NSMutableArray *newArray = nil;
	@try {
		newArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
	}
	@catch (NSException *e) {
		NSLog(@"exception = %@", e);
		if (outError) {
			NSDictionary *d = [NSDictionary
							   dictionaryWithObject:@"The data is corrupted."
							   forKey:NSLocalizedFailureReasonErrorKey];
			*outError = [NSError errorWithDomain:NSOSStatusErrorDomain
											code:unimpErr
										userInfo:d];
		}
		return NO;
	}
	[self setEmployees:newArray];
	return YES;
}

+ (BOOL)autosavesInPlace
{
    return YES;
}

// RMDocumentKVOContext enables this class to differentiate
// between its KVO messages and those intended for a superclass:
static void *RMDocumentKVOContext;
- (void)startObservingPerson:(Person *)person
{
	[person addObserver:self
			 forKeyPath:@"personName"
				options:NSKeyValueObservingOptionOld
				context:&RMDocumentKVOContext];
	[person addObserver:self
			 forKeyPath:@"expectedRaise"
				options:NSKeyValueObservingOptionOld
				context:&RMDocumentKVOContext];
}
- (void)stopObservingPerson:(Person *)person
{
	[person removeObserver:self
				forKeyPath:@"personName"
				   context:&RMDocumentKVOContext];
	[person removeObserver:self
				forKeyPath:@"expectedRaise"
				   context:&RMDocumentKVOContext];
}

- (void)setEmployees:(NSMutableArray *)a
{
	for (Person *person in employees) {
		[self stopObservingPerson:person];
	}

	employees = a;

	for (Person *person in employees) {
		[self startObservingPerson:person];
	}
}

- (void)insertObject:(Person *)p inEmployeesAtIndex:(NSUInteger)index {
    NSLog(@"adding %@ to %@", p, employees);
    // Add the inverse of this operation to the undo stack
    NSUndoManager *undo = [self undoManager];
    [[undo prepareWithInvocationTarget:self]
	 removeObjectFromEmployeesAtIndex:index];
    if (![undo isUndoing]) {
        [undo setActionName:@"Add Person"];
    }
    // Add the Person to the array
	[self startObservingPerson:p];
    [employees insertObject:p atIndex:index];
}
- (void)removeObjectFromEmployeesAtIndex:(NSUInteger)index
{
    Person *p = [employees objectAtIndex:index];
    NSLog(@"removing %@ from %@", p, employees);
    // Add the inverse of this operation to the undo stack
    NSUndoManager *undo = [self undoManager];
    [[undo prepareWithInvocationTarget:self] insertObject:p
                                       inEmployeesAtIndex:index];
    if (![undo isUndoing]) {
        [undo setActionName:@"Remove Person"];
	}
	[self stopObservingPerson:p];
    [employees removeObjectAtIndex:index];
}

- (void)changeKeyPath:(NSString *)keyPath
			 ofObject:(id)obj
			  toValue:(id)newValue
{
	// setValue:forKeyPath: will cause the key-value observing method
    // to be called, which takes care of the undo stuff
    [obj setValue:newValue forKeyPath:keyPath];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if (context != &RMDocumentKVOContext)
    {
		// If the context does not match, this message
        // must be intended for our superclass.
        [super observeValueForKeyPath:keyPath
							 ofObject:object
							   change:change
							  context:context];
		return; }
    NSUndoManager *undo = [self undoManager];
    id oldValue = [change objectForKey:NSKeyValueChangeOldKey];
    // NSNull objects are used to represent nil in a dictionary
    if (oldValue == [NSNull null]) {
        oldValue = nil;
    }
    NSLog(@"oldValue = %@", oldValue);
    [[undo prepareWithInvocationTarget:self] changeKeyPath:keyPath
                                                  ofObject:object
                                                   toValue:oldValue];
    [undo setActionName:@"Edit"];
}

- (IBAction)createEmployee:(id)sender
{
    NSWindow *w = [tableView window];
    // Try to end any editing that is taking place
    BOOL editingEnded = [w makeFirstResponder:w];
    if (!editingEnded) {
        NSLog(@"Unable to end editing");
		return; }
    NSUndoManager *undo = [self undoManager];
    // Has an edit occurred already in this event?
    if ([undo groupingLevel] > 0) {
        // Close the last group
        [undo endUndoGrouping];
        // Open a new group
        [undo beginUndoGrouping];
    }
    // Create the object
    Person *p = [employeeController newObject];
    // Add it to the content array of 'employeeController'
    [employeeController addObject:p];
    // Re-sort (in case the user has sorted a column)
    [employeeController rearrangeObjects];
    // Get the sorted array
    NSArray *a = [employeeController arrangedObjects];
    // Find the object just added
    NSUInteger row = [a indexOfObjectIdenticalTo:p];
    NSLog(@"starting edit of %@ in row %lu", p, row);
    // Begin the edit in the first column
    [tableView editColumn:0
					  row:row
				withEvent:nil
				   select:YES];
}

- (IBAction)removeEmployee:(id)sender
{
	NSArray *selectedPeople = [employeeController selectedObjects];
	NSAlert *alert = [NSAlert alertWithMessageText:
					  @"Do you really want to remove these people?"
									 defaultButton:@"Remove"
								   alternateButton:@"Cancel"
									   otherButton:nil
						 informativeTextWithFormat:@"%d people will be removed.",
					  [selectedPeople count]];
	NSLog(@"Starting alert sheet");
	[alert beginSheetModalForWindow:[tableView window]
					  modalDelegate:self
					 didEndSelector:@selector(alertEnded:code:context:)
						contextInfo:NULL];
}

- (void)alertEnded:(NSAlert *)alert
			  code:(NSInteger)choice
		   context:(void *)v
{
	NSLog(@"Alert sheet ended");
	// If the user chose "Remove", tell the array controller to
	// delete the people
	if (choice == NSAlertDefaultReturn) {
		// The argument to remove: is ignored
		// The array controller will delete the selected objects
		[employeeController remove:nil];
	}
}

- (void)handleColorChange:(NSNotification *)note
{
	NSLog(@"Received notification: %@", note);
	NSColor *color = [[note userInfo] objectForKey:@"color"];
	[tableView setBackgroundColor:color];
}

@end


text:
package edu.ucsc.dbtune.optimizer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import edu.ucsc.dbtune.metadata.Column;
import edu.ucsc.dbtune.metadata.Index;
import edu.ucsc.dbtune.optimizer.plan.Operator;
import edu.ucsc.dbtune.optimizer.plan.SQLStatementPlan;
import edu.ucsc.dbtune.workload.SQLCategory;
import edu.ucsc.dbtune.workload.SQLStatement;

/**
 * The interface to the MySQL optimizer.
 *
 * @author Ivo Jimenez
 */
public class MySQLOptimizer extends AbstractOptimizer
{
    private Connection connection;

    /**
     * Creates a new optimizer for MySQL.
     *
     * @param connection
     *     JDBC connection used to communicate to a PostgreSQL system.
     * @throws SQLException
     *     if an error occurs while communicating to the server.
     */
    public MySQLOptimizer(Connection connection) throws SQLException
    {
        this.connection = connection;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ExplainedSQLStatement explain(SQLStatement sql, Set<Index> configuration)
        throws SQLException
    {
        // XXX: issue #9 (mysqlpp project)
        if (sql.getSQLCategory().isSame(SQLCategory.NOT_SELECT))
            throw new SQLException("Can't explain " + sql.getSQLCategory() + " statements");

        SQLStatementPlan plan;
        Set<Index>       used;
        double           cost;

        create(configuration, connection);

        plan = getPlan(sql);
        used = new HashSet<Index>(plan.getIndexes());
        cost = getCost();

        drop(configuration, connection);

        return new ExplainedSQLStatement(
            sql, plan, this, cost, null, 0.0, new HashMap<Index, Double>(), configuration, used, 1);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Set<Index> recommendIndexes(SQLStatement sql) throws SQLException
    {
        throw new SQLException("Not implemented yet");
    }

    /**
     * Returns the plan for the given statement.
     *
     * @param sql
     *     statement which the plan is obtained for
     * @return
     *     an execution plan
     * @throws SQLException
     *     if something goes wrong while talking to the DBMS
     */
    protected SQLStatementPlan getPlan(SQLStatement sql)
        throws SQLException
    {
        // XXX: issue #105 - populate plan with correctly; height=2 plan is temporary
        SQLStatementPlan plan;
        Statement        stmt;
        ResultSet        rs;
        Operator         operator;
        Index            index;
        String           name;

        stmt = connection.createStatement();
        rs   = stmt.executeQuery("EXPLAIN " + sql.getSQL());
        plan = new SQLStatementPlan(sql, new Operator("root", 0.0, 0));

        while (rs.next()) {
            name = rs.getString("key");

            if (name == null)
                continue;

            operator = new Operator(rs.getString("table"), rs.getLong("rows"), 0);
            index    = catalog.findIndex(name);

            if (index == null)
                throw new SQLException("Can't find index " + name);

            operator.add(index);
            plan.setChild(plan.getRootOperator(), operator);
        }

        rs.close();
        stmt.close();

        return plan;
    }

    /**
     * Returns the cost of the statement that has been just explained.
     *
     * @return
     *     the cost of the plan
     * @throws SQLException
     *     if something goes wrong while talking to the DBMS
     */
    protected double getCost()
        throws SQLException
    {
        Statement stmt = connection.createStatement();
        ResultSet rs   = stmt.executeQuery("SHOW STATUS LIKE 'last_query_cost'");

        if (!rs.next())
            throw new SQLException("No result from SHOW STATUS statement");

        double cost = rs.getDouble("value");

        rs.close();
        stmt.close();

        return cost;
    }

    /**
     * Creates the given configuration as a set of hypothetical indexes in the database.
     *
     * @param configuration
     *     configuration being created
     * @param connection
     *     connection used to communicate with the DBMS
     * @throws SQLException
     *      if an error occurs while communicating with the DBMS
     */
    private static void create(Set<Index> configuration, Connection connection) throws SQLException
    {
        for (Index index : configuration) {
            Statement stmt = connection.createStatement();
            stmt.execute("CREATE HYPOTHETICAL INDEX " + toString(index));
            stmt.close();
        }
    }

    /**
     * Drops the given configuration as a set of hypothetical indexes in the database.
     *
     * @param configuration
     *     configuration being dropped
     * @param connection
     *     connection used to communicate with the DBMS
     * @throws SQLException
     *     if an error occurs while communicating with the DBMS
     */
    private static void drop(Set<Index> configuration, Connection connection) throws SQLException
    {
        for (Index index : configuration) {
            Statement stmt = connection.createStatement();
            stmt = connection.createStatement();
            stmt.execute("DROP INDEX " + index.getName() +
                         " on " + index.getTable().getFullyQualifiedName());
            stmt.close();
        }
    }

    /**
     * Returns a string representation of the given index.
     *
     * @param index
     *     an index
     * @return
     *     a string containing the MySQL-specific string representation of the given index
     * @throws SQLException
     *     if the name of a column contained in the index can't be obtained
     */
    private static String toString(Index index) throws SQLException
    {
        StringBuilder sb    = new StringBuilder();
        boolean       first = true;

        sb.append(index.getName());
        sb.append(" on ");
        sb.append(index.getTable().getFullyQualifiedName());
        sb.append(" (");

        for (Column col : index.columns()) {
            if (first)
                first = false;
            else
                sb.append(",");

            sb.append(col.getName());
            // not supported. Can be specified but it'll be ignored
            // sb.append(index.isAscending(col) ? " ASC" : " DESC");
        }

        sb.append(")");

        return sb.toString();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setFTSDisabled(boolean isFTSDisabled)
    {
        throw new RuntimeException("not yet");
    }
}


text:
<link rel="stylesheet" href="resources/set-style-text.css"/>

The test verifies functionality of protocol method CSS.setStyleTexts for inline elements.


text:
package data

import (
	"context"
	"io"
	"mime"
	"net/http"
	"net/url"
	"time"

	"github.com/pkg/errors"
)

func buildURL(base *url.URL, args ...string) (*url.URL, error) {
	if len(args) == 0 {
		return base, nil
	}
	p, err := url.Parse(args[0])
	if err != nil {
		return nil, errors.Wrapf(err, "bad sub-path %s", args[0])
	}
	return base.ResolveReference(p), nil
}

func readHTTP(ctx context.Context, source *Source, args ...string) ([]byte, error) {
	if source.hc == nil {
		source.hc = &http.Client{Timeout: time.Second * 5}
	}
	u, err := buildURL(source.URL, args...)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
	if err != nil {
		return nil, err
	}
	req.Header = source.Header
	res, err := source.hc.Do(req)
	if err != nil {
		return nil, err
	}
	body, err := io.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	err = res.Body.Close()
	if err != nil {
		return nil, err
	}
	if res.StatusCode != 200 {
		err := errors.Errorf("Unexpected HTTP status %d on GET from %s: %s", res.StatusCode, source.URL, string(body))
		return nil, err
	}
	ctypeHdr := res.Header.Get("Content-Type")
	if ctypeHdr != "" {
		mediatype, _, e := mime.ParseMediaType(ctypeHdr)
		if e != nil {
			return nil, e
		}
		source.mediaType = mediatype
	}
	return body, nil
}


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

<TITLE>
CompositeTransform
</TITLE>

<META NAME="date" CONTENT="2011-05-13">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../dev_javadoc.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.google.appengine.api.images

Class CompositeTransform

java.lang.Object
  com.google.appengine.api.images.Transform
      com.google.appengine.api.images.CompositeTransform

All Implemented Interfaces:
java.io.Serializable

public class CompositeTransform
extends Transform

A transform that represents zero or more transforms executed in series.

See Also:
Serialized Form

Method Summary

 CompositeTransform
concatenate(Transform other)

          Concatenates a transform to the end of this composite transform.

 CompositeTransform
preConcatenate(Transform other)

          Concatenates a transform to the start of this composite transform.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

concatenate

public CompositeTransform concatenate(Transform other)

Concatenates a transform to the end of this composite transform.

Parameters:
other - the transform to be appended

Returns:
this transform with the other transform appended

preConcatenate

public CompositeTransform preConcatenate(Transform other)

Concatenates a transform to the start of this composite transform.

Parameters:
other - the transform to be prepended

Returns:
this transform with the other transform prepended

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
Spree::Product.class_eval do
  has_many :property_categories, through: :product_properties

  def sorted_property_categories
    property_categories.
      order("spree_product_property_categories.position ASC").
      uniq
  end
end


text:
<idea-plugin>
    <id>ca.rightsomegoodgames.mayacharm</id>
    <name>MayaCharm</name>
    <vendor email="chris@rightsomegoodgames.ca" url="https://github.com/cmcpasserby">Chris Cunningham</vendor>

    <depends>com.intellij.modules.lang</depends>
    <depends>com.intellij.modules.platform</depends>
    <depends>com.intellij.modules.python</depends>
    <depends>com.intellij.modules.xdebugger</depends>

    <resource-bundle>MayaCharmBundle</resource-bundle>

    <extensions defaultExtensionNs="com.intellij">
        <projectService serviceImplementation="settings.ProjectSettings"/>
        <applicationService serviceImplementation="settings.ApplicationSettings"/>
        <projectConfigurable instance="settings.MayaSdkConfigurable"/>

        <toolWindow id="MayaLog" anchor="bottom" factoryClass="logconsole.LogWindow" icon="/icons/MayaCharm_ToolWindow.png"/>

        <configurationType implementation="run.MayaCharmConfigType"/>
        <programRunner implementation="run.MayaCharmRunner" order="first"/>
<!--        <programRunner implementation="run.MayaCharmDebugRunner"/>-->

        <xdebugger.attachDebuggerProvider implementation="debugattach.MayaAttachDebuggerProvider"/>
    </extensions>

    <extensions defaultExtensionNs="Pythonid">
        <pythonFlavorProvider implementation="flavors.MayaFlavorProvider" order="first"/>
    </extensions>

    <actions>

        <action id="actions.SendBufferAction"
                class="actions.SendBufferAction"
                icon="/icons/MayaCharm_Action.png">
            <add-to-group group-id="RunMenu" anchor="last"/>
            <keyboard-shortcut keymap="$default" first-keystroke="alt A"/>
        </action>

        <action id="actions.SendSelectionAction"
                class="actions.SendSelectionAction"
                icon="/icons/MayaCharm_Action.png">
            <add-to-group group-id="RunMenu" anchor="last"/>
            <keyboard-shortcut keymap="$default" first-keystroke="alt S"/>
        </action>

        <action id="actions.ConnectToMayaLogAction"
                class="actions.ConnectToMayaLogAction"
                icon="/icons/MayaCharm_Action.png">
            <add-to-group group-id="RunMenu" anchor="last"/>
        </action>

    </actions>

</idea-plugin>


text:
import warnings

import geoalchemy2
from flask import current_app
from shapely.geometry import shape
from sqlalchemy import func

from flask_admin.form import JSONField

from .widgets import LeafletWidget

class GeoJSONField(JSONField):
    widget = LeafletWidget()

    def __init__(self, label=None, validators=None, geometry_type="GEOMETRY",
                 srid='-1', session=None, **kwargs):
        super(GeoJSONField, self).__init__(label, validators, **kwargs)
        self.web_srid = 4326
        self.srid = srid
        if self.srid is -1:
            self.transform_srid = self.web_srid
        else:
            self.transform_srid = self.srid
        self.geometry_type = geometry_type.upper()
        self.session = session

    def _flip_coordinates(self, other_func):
        if current_app.config.get('MAPBOX_FIX_COORDINATES_ORDER'):
            return func.ST_FlipCoordinates(other_func)
        else:
            warnings.warn(
                'Consider setting the Flask config option '
                'MAPBOX_FIX_COORDINATES_ORDER as the current implementation '
                'passes lng/lat coordinates in the wrong order to '
                'Leaflet. Without this setting any coordinates saved will '
                'have flipped coordinates in your database. '
                'Please note that this will become the standard behavior in '
                'the next major version of Flask-Admin.'
            )
            return other_func

    def _value(self):
        if self.raw_data:
            return self.raw_data[0]
        if type(self.data) is geoalchemy2.elements.WKBElement:
            if self.srid is -1:
                return self.session.scalar(
                    func.ST_AsGeoJson(
                        self._flip_coordinates(self.data)
                    )
                )
            else:
                return self.session.scalar(
                    func.ST_AsGeoJson(
                        self._flip_coordinates(
                            func.ST_Transform(self.data, self.web_srid)
                        )
                    )
                )
        else:
            return ''

    def process_formdata(self, valuelist):
        super(GeoJSONField, self).process_formdata(valuelist)
        if str(self.data) is '':
            self.data = None
        if self.data is not None:
            web_shape = self.session.scalar(
                func.ST_AsText(
                    self._flip_coordinates(
                        func.ST_Transform(
                            func.ST_GeomFromText(
                                shape(self.data).wkt,
                                self.web_srid
                            ),
                            self.transform_srid
                        )
                    )
                )
            )
            self.data = 'SRID=' + str(self.srid) + ';' + str(web_shape)


text:
require 'nerve/service_watcher/base'

module Nerve
  module ServiceCheck
    # ServiceCheck that checks nothing, but returns true.  Useful in scenarios
    # where you want the mere fact of nerve running to mean your node is
    # registered.
    class NoopServiceCheck < BaseServiceCheck
      def check
        true
      end
    end

    CHECKS ||= {}
    CHECKS['noop'] = NoopServiceCheck
  end
end


text:
import fs from 'fs'
import os from 'os'
import path from 'path'
import trash from 'trash'
import { replace } from 'react-router-redux'
import { kebabCase, find, endsWith } from 'lodash'

import { takeScreenshot } from 'helpers/takeScreenshot'
import mjml2html from 'helpers/mjml'

import { addAlert } from 'reducers/alerts'
import { openExternalFileOverlay, closeExternalFileOverlay } from 'reducers/externalFileOverlay'

import {
  saveSettings,
  cleanBadProjects,
  saveLastOpenedFolder,
  saveLastExportedFolder,
} from 'actions/settings'

import {
  fsStat,
  recursiveCopy,
  fileDialog,
  fsReadFile,
  fsReadDir,
  fsAccess,
  fsRename,
  fsWriteFile,
  fsMkdir,
  fileExists,
  isValidDir,
} from 'helpers/fs'

const HOME_DIR = os.homedir()

export function addProject(p) {
  return async (dispatch, getState) => {
    if (!p) {
      const state = getState()
      p = fileDialog({
        defaultPath: state.settings.get('lastOpenedFolder') || HOME_DIR,
        properties: ['openDirectory', 'createDirectory'],
      })
      if (!p) {
        return
      }
    }

    await fsAccess(p, fs.constants.R_OK | fs.constants.W_OK)

    dispatch(saveLastOpenedFolder(p))
    dispatch(openProject(p))
  }
}

export function removeProject(p, shouldDeleteFolder = false) {
  return dispatch => {
    dispatch({ type: 'PROJECT_REMOVE', payload: p })
    dispatch(saveSettings())
    if (shouldDeleteFolder) {
      trash(p)
    }
  }
}

export function openProject(projectPath) {
  return dispatch => {
    dispatch(replace(`/project?path=${encodeURIComponent(projectPath)}`))
    dispatch(loadIfNeeded(projectPath))
  }
}

function loadIfNeeded(path) {
  return async (dispatch, getState) => {
    const state = getState()
    const proj = state.projects.find(p => p.get('path') === path)
    if (!proj) {
      const enriched = await loadProject(path)
      dispatch({ type: 'PROJECT_LOAD', payload: enriched })
      dispatch(saveSettings())
    }
  }
}

// read the project directory
// eventually find the index.mjml file inside and generate its html
// (to have nice previews in home)
async function loadProject(p, mjmlPath) {
  const res = { path: p }
  res.isOK = await isValidDir(p)
  if (res.isOK) {
    try {
      let indexFilePath = path.join(p, 'index.mjml')
      const indexExists = await fileExists(indexFilePath)

      if (!indexExists) {
        const dir = await fsReadDir(p)
        const fallback = find(dir, name => endsWith(name, '.mjml'))

        if (fallback) indexFilePath = path.join(p, fallback)
      }

      const mjmlContent = await fsReadFile(indexFilePath, { encoding: 'utf8' })
      const { html: htmlContent } = await mjml2html(mjmlContent, indexFilePath, mjmlPath)
      res.html = htmlContent
    } catch (e) {} // eslint-disable-line
  }
  return res
}

export function loadProjects() {
  return async (dispatch, getState) => {
    const state = getState()
    const { settings } = state

    const projectsPaths = settings.get('projects')

    // eventually get the custom mjml path set in settings
    const mjmlManual = settings.getIn(['mjml', 'engine']) === 'manual'
    const mjmlPath = mjmlManual ? settings.getIn(['mjml', 'path']) : undefined
    const load = proj => loadProject(proj, mjmlPath)

    let enriched = await Promise.all(projectsPaths.map(load))

    // eventually clean settings from bad projects paths
    const pathsToClean = enriched.filter(e => !e.isOK).map(e => e.path)

    if (pathsToClean.length > 0) {
      dispatch(cleanBadProjects(pathsToClean))
      dispatch(saveSettings())
    }

    enriched = enriched.filter(e => e.isOK)

    dispatch({
      type: 'PROJECTS_LOAD',
      payload: enriched,
    })
  }
}

export function updateProjectPreview(p, html) {
  return {
    type: 'PROJECT_UPDATE_PREVIEW',
    payload: {
      path: p,
      html,
    },
  }
}

export function renameProject(oldPath, newPath) {
  return async dispatch => {
    await fsRename(oldPath, newPath)
    dispatch({
      type: 'PROJECT_RENAME',
      payload: { oldPath, newPath },
    })
    dispatch(saveSettings())
  }
}

export function dropFile(filePath) {
  return dispatch => {
    const ext = path.extname(filePath)
    if (ext !== '.mjml') {
      return
    }
    const dir = path.dirname(filePath)
    dispatch(openProject(dir))
  }
}

async function massExport(state, asyncJob, allFiles = false) {
  const projectsToExport = state.projects
    .filter(p => state.selectedProjects.find(path => path === p.get('path')))
    .filter(p => p.get('html'))

  if (projectsToExport.size === 0) {
    return
  }
  const targetPath = fileDialog({
    defaultPath: state.settings.get('lastExportedFolder') || HOME_DIR,
    properties: ['openDirectory', 'createDirectory'],
  })
  if (!targetPath) {
    return
  }
  for (let i = 0; i < projectsToExport.size; i++) {
    const p = projectsToExport.get(i)
    const projPath = p.get('path')
    const projBaseName = path.basename(projPath)

    if (allFiles) {
      // eventually get the custom mjml path set in settings
      const { settings } = state
      const projectsPaths = settings.get('projects')
      const mjmlManual = settings.getIn(['mjml', 'engine']) === 'manual'
      const mjmlPath = mjmlManual ? settings.getIn(['mjml', 'path']) : undefined

      const files = await fsReadDir(projPath)
      const mjmlFiles = files.filter(name => name.includes('.mjml'))
      if (!mjmlFiles.length) return

      const targetDir = path.join(targetPath, kebabCase(projBaseName))
      if (!fs.existsSync(targetDir)) await fsMkdir(targetDir)

      for (const file of mjmlFiles) {
        const mjml = await fsReadFile(path.join(projPath, file), 'utf8')
        const result = await mjml2html(mjml, projPath, mjmlPath)

        const targetName = file.replace('.mjml', '.html')
        const targetPath = path.join(targetDir, targetName)

        await asyncJob(targetPath, result.html)
      }
    } else {
      const projSafeName = `${kebabCase(projBaseName)}.html`
      const filePath = path.join(targetPath, projSafeName)
      await asyncJob(filePath, p, targetPath)
    }
  }
  return targetPath
}

export function exportSelectedProjectsToHTML() {
  return async (dispatch, getState) => {
    const targetPath = await massExport(getState(), (filePath, p) =>
      fsWriteFile(filePath, p.get('html')),
    )
    if (targetPath) {
      dispatch(saveLastExportedFolder(targetPath))
    }
  }
}

export function exportSelectedProjectsAllFilesToHTML() {
  return async (dispatch, getState) => {
    const targetPath = await massExport(getState(), (filePath, html) =>
      fsWriteFile(filePath, html, { flag: 'w' }),
      true
    )
    if (targetPath) {
      dispatch(saveLastExportedFolder(targetPath))
    }
  }
}

export function exportSelectedProjectsToImages(done) {
  return async (dispatch, getState) => {
    const state = getState()

    const targetPath = await massExport(state, async (filePath, p, targetDir) => {
      const html = p.get('html')
      const previewSize = state.settings.get('previewSize')
      const [mobileWidth, desktopWidth] = [previewSize.get('mobile'), previewSize.get('desktop')]
      const [mobileScreenshot, desktopScreenshot] = await Promise.all([
        takeScreenshot(html, mobileWidth, targetDir),
        takeScreenshot(html, desktopWidth, targetDir),
      ])
      await Promise.all([
        fsWriteFile(`${filePath.replace(/.html$/, '')}_mobile.png`, mobileScreenshot),
        fsWriteFile(`${filePath.replace(/.html$/, '')}_desktop.png`, desktopScreenshot),
      ])
    })
    if (targetPath) {
      dispatch(addAlert('Successfully exported to images', 'success'))
      dispatch(saveLastExportedFolder(targetPath))
    }
    done()
  }
}

async function getDuplicatePath(projectPath, increment = 1) {
  if (increment > 10) {
    throw new Error('Cant determine duplicate path')
  }
  const duplicatePath = `${projectPath} (${increment})`
  try {
    await fsStat(duplicatePath)
    return getDuplicatePath(projectPath, increment + 1)
  } catch (err) {
    if (err.code === 'ENOENT') {
      return duplicatePath
    }
    throw err
  }
}

export function duplicateProject(projectPath) {
  return async dispatch => {
    try {
      const newProjectPath = await getDuplicatePath(projectPath)
      await recursiveCopy(projectPath, newProjectPath)
      dispatch(loadIfNeeded(newProjectPath))
    } catch (err) {
      console.log(err) // eslint-disable-line
    }
  }
}

/**
 * As opening external file will trigger an instant app load + project load
 * we need to wait for the reducers to be ready
 */
async function waitUntilLoaded(getState, timeout = 5e3) {
  const { settings, projects } = getState()
  if (settings && projects) {
    return true
  }
  if (timeout <= 0) {
    throw new Error('Loading settings took too long')
  }
  await new Promise(resolve => setTimeout(resolve, 500))
  return waitUntilLoaded(getState, timeout - 500)
}

export function openExternalFile(filePath) {
  return async (dispatch, getState) => {
    const exists = await fileExists(filePath)
    if (!exists) {
      return
    }
    dispatch(openExternalFileOverlay(filePath))
    try {
      const dirName = path.dirname(filePath)
      const validDir = await isValidDir(dirName)
      if (!validDir) {
        throw new Error('Cant open that.')
      }
      await waitUntilLoaded(getState)
      dispatch(openProject(dirName))
    } catch (err) {
      console.log(err) // eslint-disable-line no-console
    }
    dispatch(closeExternalFileOverlay())
  }
}


text:
/* eslint no-new-func: 0 */
import createChainedFunction from '../../src/utils/createChainedFunction';

describe('createChainedFunction', () => {
  it('returns null with no arguments', () => {
    expect(createChainedFunction()).to.equal(null);
  });

  it('returns original function when single function is provided', () => {
    const func1 = sinon.stub();
    createChainedFunction(func1).should.equal(func1);
  });

  it('wraps two functions with another that invokes both when called', () => {
    const func1 = sinon.stub();
    const func2 = sinon.stub();
    const chained = createChainedFunction(func1, func2);

    chained
      .should.not.equal(func1)
      .and.should.not.equal(func2);

    func1.should.not.have.been.called;
    func2.should.not.have.been.called;

    chained();

    func1.should.have.been.calledOnce;
    func2.should.have.been.calledOnce;
  });

  it('wraps multiple functions and invokes them in the order provided', () => {
    const results = [];
    const func1 = () => results.push(1);
    const func2 = () => results.push(2);
    const func3 = () => results.push(3);
    const chained = createChainedFunction(func1, func2, func3);
    chained();
    results.should.eql([1, 2, 3]);
  });

  it('forwards arguments to all chained functions', () => {
    const in1 = 'herpa derpa';
    const in2 = {
      herpa: 'derpa'
    };

    const func = (arg1, arg2) => {
      arg1.should.equal(in1);
      arg2.should.equal(in2);
    };

    const chained = createChainedFunction(func, func, func);
    chained(in1, in2);
  });

  it('throws when func is not provided', () => {
    expect(() => {
      createChainedFunction({ herpa: 'derpa' });
    }).to.throw(/Invalid Argument Type/);
  });

  it('works with new Function call', () => {
    const results = [];
    const func1 = new Function('results', 'results.push(1);');
    const func2 = new Function('results', 'results.push(2);');
    const chained = createChainedFunction(func1, func2);
    chained(results);
    results.should.eql([1, 2]);
  });
});


text:
module.exports = function(grunt)
{
  var jsonpath= require('JSONPath').eval,
      jsrender= require('./jsrender'),
      rdfstore= require('./rdfstore'),
      fs= require('fs'),
      os= require('os'),
      util= require('util'),
      p= require('path'),
      xmlbuilder = require("xmlbuilder"),
      forkqueue= require('./forkqueue'),
      xlsx= require('./lib/xlsx'),
      _ = require('lodash'),
      async = require('async'),
      argv = require('optimist').argv;

  var pageTypes= {},
      cache= {},
      i18n,
      pageQueue,
      store;

  var log= grunt.log,
      verbose= grunt.log.verbose,
      file= grunt.file,
      fail= grunt.fail,
      mem= function ()
      {
         return util.inspect(process.memoryUsage());
      },
      _toJSONLD= function (data,context)
      {
           var ld= _.clone(context),
               transform= context['@transform'],
               prefix= context['@id_prefix'] || '';

           if (prefix in context['@context'])
             ld['@id']= context['@context'][prefix]+data['id'];
           else
             ld['@id']= prefix+data['id'];

           var ld= _.extend(ld,data);

           delete ld['@transform'];
           delete ld['@id_prefix'];

           if (transform) transform(ld,data,context);

           return ld;
      },
      _store= function (cb)
      {
         if (store==null)
           rdfstore.create(function (s)
           {
              store= s;
              cb(s);
           });
         else
           cb(store);
      },
      _context= function (name)
      {
          return _cache('context.'+name,function ()
          {
              try
              {
                  var src= p.join('src','json','context',name+'.js'),
                      js= file.read(src),
                      _ctx;

                  eval('(function (grunt,_,clone,collection,done) { '+js+' })')
                      (grunt,_,_clone,_collection,
                  function (ctx)
                  {
                      _ctx= ctx;
                  });

                  return _ctx;
              }
              catch (ex)
              {
                  fail.fatal(ex+' evaluating '+src);
              }
          });
      },
      _index= function(collection,by)
      {
          var _process= function (arr)
          {
              var idx= {};

              arr.forEach(function (elem)
              {
                  idx[elem[by]]= elem;
              });

              return (function (idx) { return function (by) { return idx[by]; } })(idx);
          };

          if (typeof collection=='string')
            return _cache('index.'+collection+'.'+by,function ()
            {
               return _process(_collection(collection),by);
            });
          else
            return _process(collection,by);
      },
      _mindex= function(collection,by)
      {
          var _process= function (arr)
          {
              var idx= {},
                  _vals= function (obj,path)
                  {
                     var r= [],
                         current= obj;

                     if (Array.isArray(current))
                     {
                          current.forEach(function (el)
                          {
                             r.push.apply(r,_vals(el,path.slice(i+1)));
                          });

                          return r;
                     }

                     for (var i=0;i<path.length-1;i++)
                     {
                        current= current[path[i]]= current[path[i]];
                        if (current===undefined)
                          return [];
                        else
                        if (Array.isArray(current))
                          return _vals(current,path.slice(i+1));
                     }

                     var val= current[path[path.length-1]];

                     if (Array.isArray(val))
                       r.push.apply(r,val);
                     else
                       r.push(val);

                     return r;
                  },
                  _push= function (val,elem)
                  {
                      var vals;
                      if (!(vals=idx[val])) vals= idx[val]= [];
                      vals.push(elem);
                  };

              arr.forEach(function (elem)
              {
                  _vals(elem,by.split('.')).forEach(function (val)
                  {
                       _push(val,elem);
                  });
              });

              return (function (idx) { return function (by) { return idx[by] || []; } })(idx);
          };

          if (typeof collection=='string')
            return _cache('mindex.'+collection+'.'+by,function ()
            {
               return _process(_collection(collection),by);
            });
          else
            return _process(collection,by);
      },
      _cache= function (cid,process)
      {
         var r,
             cids= cid.split('.'),
             current= cache;

         for (var i=0;i<cids.length-1;i++)
            current= current[cids[i]]= current[cids[i]] || {};

         var lcid= cids[cids.length-1];

         if ((r=current[lcid])===undefined)
         {
           r= process();
           current[lcid]= r;
         }

         return r;
      },
      _htmlText= function ()
      {
          var src= p.join('src','html','html.html');

          if (!file.exists(src))
            src= p.join('node_modules','grunt-html-builder','resources','html.html');

          return file.read(src);
      },
      _html= function (config)
      {
          var tpl= jsrender.compile(_htmlText());
          return tpl.render(config);
      },
      _layoutText= function (name)
      {
          return _cache('layout.'+name,function ()
          {
              var src= p.join('src','html','layout',name+'.html');

              if (!file.exists(src))
               fail.fatal('Cannot find layout "'+src+'"');

              return file.read(src);
          });
      },
      _layout= function (config)
      {
          return !config.layout ? false : _layoutText(config.layout);
      },
      _writechunk= function (cdest,data,chunk,hasOthers)
      {
         var dest= p.join('dist/js/data',cdest+(chunk ? '-'+chunk : '')+'.json');
         file.write(dest,
                    JSON.stringify({ chunk: chunk, items: data, hasOthers: hasOthers }));
         log.ok('Generated JSON chunk: '+dest);
      },
      _paginate= function (arr,pageSize)
      {
         var pages= [],
             origForEach= pages.forEach;

         if (arr.length<=pageSize)
           pages.push(arr);
         else
         {
            var count= Math.ceil(arr.length/pageSize);
            for (var i=0;i<count;i++)
            {
               var start= i*pageSize,
                   end= start+pageSize;

               if (end>arr.length) end= arr.length;

               pages.push(arr.slice(start,end));
            }
         }

         pages.forEach= function (cb)
         {
             origForEach.apply(this,[function (page,idx)
             {
                 cb(page,{ current: idx+1, count: pages.length, pages: _.range(1,pages.length+1) });
             }]);
         };

         return pages;
      },
      _chunkdata= function (data,dest,chunk)
      {
           var offset= 0,
               cnt= 0;

           while (offset+chunk<=data.length)
           {
             _writechunk(dest,data.slice(offset,offset+chunk),cnt++,(data.length>(offset+chunk)));
             offset+= chunk;
           }

           if (offset<data.length)
             _writechunk(dest,data.slice(offset,data.length),cnt,false);
      },
      _traverse= function (o, fn)
      {
         for (var i in o)
         {
             fn.apply(null,[i,o[i],o]);
             if (typeof (o[i])=='object')
               _traverse(o[i],fn);
         }
      },
      _clone= function (o)
      {
        return JSON.parse(JSON.stringify(o));
      },
      _alias= function (s)
      {
        return s.replace(/[^a-z0-9]/gi,'-').toLowerCase();
      },
      _collection= function (name)
      {
            var src= p.join('data','json',name+'.json'),
                data= true;

            if (!file.exists(src))
            {
              var src1= src;
              src= p.join('src','json',name+'.json');

              if (!file.exists(src))
                fail.fatal('Cannot find JSON "'+src+'" or "'+src1+'"');

              data= false;
            }

            var r= _cache('collection.'+(data ? 'data' : 'src')+'.'+name,function ()
            {
                try
                {
                    return file.readJSON(src);
                }
                catch (ex)
                {
                    fail.fatal('evaluating JSON :'+ex);
                }
            });

            r.toJSONLD= function (context)
            {
                 var r= [];

                 this.forEach(function (elem,i)
                 {
                      r.push(_toJSONLD(elem,context));
                 });

                 return r;
            }

            return r;
      },
      _parseExcel= function (src)
      {
            var workbook= xlsx.decode(fs.readFileSync(src, "base64"));

            workbook.sheet= function (name)
            {
               var worksheet;

               this.worksheets.forEach(function (s)
               {
                  if (s.name==name)
                  {
                      worksheet= s;
                      return false;
                  }
               });

               return worksheet;
            }

            workbook.worksheets.forEach(function (s)
            {
               s.toJSON= function (fields,_transformFnc)
               {
                  var r= [];

                  this.data.forEach(function (row,idx)
                  {
                      var obj= {},
                          _value= function (value)
                          {
                             if (value)
                               return value.value;
                             else
                               return '';
                          },
                          _val= function (field,value)
                          {
                             var r,
                                 path= field.split('.'),
                                 current= obj;

                             for (var i=0;i<path.length-1;i++)
                                current= current[path[i]]= current[path[i]] || {};

                             current[path[path.length-1]]= _value(value);
                          };

                      for (var i=0;i<fields.length;i++)
                         _val(fields[i],row[i]);

                      if (_transformFnc)
                        obj= _transformFnc(obj,idx);

                      if (Array.isArray(obj))
                        r.concat(obj);
                      else
                      if (obj)
                        r.push(obj);
                  });

                  return r;
               }
            });

            return workbook;
      },
      _excel= function (name)
      {
            var src= p.join('data','excel',name+'.xlsx'),
                data= true;

            if (!file.exists(src))
            {
              var src1= src;
              src= p.join('src','excel',name+'.xlsx');

              if (!file.exists(src))
                fail.fatal('Cannot find excel "'+src+'" or "'+src1+'"');

              data= false;
            }

            var r= _cache('excel.'+(data ? 'data' : 'src')+'.'+name,function ()
            {
                try
                {
                    return _parseExcel(src);
                }
                catch (ex)
                {
                    fail.fatal('parsing excel:'+ex);
                }
            });

            return r;
      },
      _transform= function (data,transformation)
      {
          try
          {
              var src= p.join('src','js','transform',transformation+'.js'),
                  js= file.read(src),
                  _async,
                  ctrl= { cbs: [], async: function (cb) { this.cbs.push(cb); }, trigger: function (err,data) { this.cbs.forEach(function (cb) { cb(err,data); }); } };

              eval('(function (grunt,_,clone,paginate,alias,collection,excel,json,index,mindex,context,prequire,done,async) { '+js+' })')
                  (grunt,_,_clone,_paginate,_alias,_collection,_excel,data,_index,_mindex,_context,
              function (path)
              {
                 return require(process.cwd()+'/node_modules/'+path);
              },
              function (transformed,t2)
              {
                  if (_async)
                  {
                    var ex= transformed;
                    var transformed= t2;

                    if (ex)
                    {
                      verbose.error(ex.stack);
                      fail.fatal(ex+' evaluating '+src);
                      ctrl.trigger(ex,null);
                    }
                    else
                      ctrl.trigger(null,transformed);
                  }
                  else
                    data= transformed;
              },function () { _async= true; });

              if (_async)
                return ctrl;
              else
                return data;
          }
          catch (ex)
          {
              verbose.error(ex.stack);
              fail.fatal(ex+' evaluating '+src);
          }
      },
      _template= function(name)
      {
         return _cache('template.'+name,function ()
         {
             var src= p.join('src','html','template',name+'.html');

             if (file.exists(src))
             {
               var text= file.read(src);
               if (text!=='')
                 return {
                           _tpl: jsrender.compile(text),
                           render: function (data)
                           {
                              try
                              {
                                 return this._tpl.render(data);
                              }
                              catch (ex)
                              {
                                 fail.fatal(ex+' evaluating template "'+src+'"');
                              }
                           }
                        };
               else
                 fail.fatal('Template "'+src+'" is empty');
             }
             else
               fail.fatal('Cannot find template "'+src+'"');
         });
      },
      _blockText= function (name,lang)
      {
         return _cache('block.'+(lang ? '_lang.'+lang+'.' : '')+name,function ()
         {
             var src= p.join('src','html','block',name+'.html');

             if (!file.exists(src)) fail.fatal('Cannot find block "'+src+'"');

             var text= file.read(src);

             return (lang ? jsrender.compile(text).render({}) : text);
         });
      },
      _i18n= function ()
      {
         return _collection('i18n');
      },
      _triples= function (id,cb)
      {
         store.execute("SELECT ?s ?p ?o ?bp ?bo WHERE { { <"+id+"> ?p ?o . filter(!isblank(?o)) } UNION { <"+id+"> ?p ?o . OPTIONAL { ?o ?bp ?bo } filter(isblank(?o)) }  UNION { ?s ?p <"+id+"> } }", function (success, nodes)
         {
             if (!success)
               fail.fatal('Cannot query RDF store for id: '+id);

             cb(nodes);
         });
      },
      _sitemap= function (globalConfig,pages)
      {
            var doc = xmlbuilder.create('urlset');
            doc.att('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9')
            doc.att('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
            doc.att('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd')

            _.filter(pages,function (p){ return !p.isRDF; }).forEach(function (page)
            {
                doc.ele('url')
                       .ele('loc')
                         .txt(globalConfig.sitemap.urlPrefix+(page.path.match(/(^|\/)index$/) ? page.path.substring(0,page.path.length-5) : page.path+'.html'))
                       .up()
                       .ele('changefreq')
                         .txt((page.changefreq ? page.changefreq : globalConfig.sitemap.changefreq))
                       .up()
                       .ele('priority')
                         .txt((page.priority ? page.priority : globalConfig.sitemap.priority))
                       .up()
                    .up();
            });

            grunt.file.write('dist/sitemap.xml',doc.toString({ pretty: true }));
            log.ok('Generated dist/sitemap.xml');
      },
      _filterPages= function (pages)
      {
         var r= pages;

         if (argv.pageType||argv.pagePath)
           log.ok('Filtering pages...');

         if (argv.pageType)
           r= _.filter(r,function (p) { return p.config.name==argv.pageType; });

         if (argv.pagePath)
           r= _.filter(r,function (p) { return p.path.match(new RegExp(argv.pagePath)); });

         return r;
      },
      _pages= function (config,done)
      {
         var pages= [],
             globalConfig= config;

         if (file.exists('src/js/page'))
         file.recurse('src/js/page',function (filepath,rootdir,subdir,filename)
         {
              if (!/\.js$/.exec(filename)) return;

              log.ok('Evaluating '+filename+'...');

              var js= file.read(filepath),
                  _config,
                  addPage= function (config)
                  {
                     if (typeof config.href=='function')
                       config.href= config.href.toString();

                     if (typeof config.postBuild=='function')
                       config.postBuild= config.postBuild.toString();

                     var defaultLanguage,
                         _add= function (config,lang)
                         {

                             pages.push({ path: (lang&&lang!=defaultLanguage ? lang+'/' : '')+(config.path[lang] || config.path), config: config, lang: lang });
                         };
                     config.name= filename.replace('.js','');
                     config.path= config.path || config.name;

                     if (globalConfig.languages)
                     {
                       defaultLanguage= globalConfig.languages[0];
                       globalConfig.languages.forEach(function (lang,idx)
                       {
                          _add(config,lang);
                       });
                     }
                     else
                       _add(config);

                     pageTypes[config.name]= config;
                  },
                  template= function (name,data)
                  {
                      return {
                                _tpl: true,
                                name: name,
                                data: data
                             };
                  },
                  addRdf= function (config)
                  {
                      config.rdf= _toJSONLD(config.data,config.context);

                      _store(function (store)
                      {
                            store.load('application/json', config.rdf, function(success, loaded)
                            {
                                if (!success)
                                  fail.fatal('Cannot load RDF for: '+JSON.stringify(rdf));
                            });
                      });

                      pages.push({ path: config.path, config: config, isRDF: true });

                      return config.rdf;
                  };

              try
              {
                  eval('(function (page,rdf,block,paginate,template,collection,excel,transform,chunkdata,alias,jsonpath,index,mindex,context) { '+js+' })')
                                  (addPage,addRdf,_blockText,_paginate,template,_collection,_excel,_transform,_chunkdata,_alias,jsonpath,_index,_mindex,_context);
              }
              catch (ex)
              {
                  verbose.error(ex.stack);
                  fail.fatal(ex+' evaluating '+filepath);
              }

         });

         if (globalConfig.languages)
           i18n= _i18n();

         var cpus= globalConfig.cpus || os.cpus().length,
              waiting_init_count = cpus;

         pageQueue= new forkqueue(cpus, __dirname+'/lib/builder.js');

         if (typeof globalConfig.postBuild=='function')
           globalConfig.postBuild= globalConfig.postBuild.toString();

         var init= [],
             wconf= { init: true, globalConfig: globalConfig, pageTypes: pageTypes, i18n: i18n, wait: (cpus>1 ? cpus*100 : 1) };

         _(cpus).times(function ()
         {
             init.push(wconf);
         });

         pages= _filterPages(pages);

         if (pages.length)
         {
             log.ok('Launching builders...');

             pageQueue.concat(init);

             pageQueue.on('msg',function (message, worker)
             {

                if(message.inited) {
                  waiting_init_count--
                  if(waiting_init_count === 0)
                    pageQueue.concat(pages)
                }

                if(message.require_init)
                  worker.send({ init: true, globalConfig: globalConfig, pageTypes: pageTypes, i18n: i18n, wait: (cpus>1 ? cpus*100 : 1) })
                if (message.error)
                  fail.fatal('Error from worker:'+message.ex);
                else
                if (message.triples)
                  _triples(message.id,function (triples)
                  {
                       if (worker.stdin.write(new Buffer(JSON.stringify({ id: message.id, triples: triples }))))
                          worker.send('goahead');
                  });

             });

             pageQueue.end(function ()
             {
                log.ok('Generated '+pages.length+' pages');
                if (globalConfig.sitemap) _sitemap(globalConfig,pages);
                done();
             });
         }
         else
           done();

      };

  grunt.html= {
                 collection: _collection
              };

  grunt.registerTask('html-builder', 'Assemble static HTML files', function()
  {
     var config= grunt.config('html-builder') || {},
         time= process.hrtime(),
         done= this.async();

     async.forEach([_pages],function (fn,done)
     {
          fn(config,done);
     },
     function ()
     {
          var diff= process.hrtime(time),
              secs= Math.round((diff[0]*1e9+diff[1])/1e9);
          cache= {};
          log.ok('Stopping after '+secs+'secs, mem used ~'+Math.round(process.memoryUsage().rss/1024/1024)+'MB');
          done();
     });
  });

  grunt.registerTask('html-builder-json', 'Create chunks of JSON files', function()
  {
     var config= grunt.config('html-builder').json,
         done= this.async();

     if (!config)
     {
        done();
        return;
     }

     async.forEachSeries(config,function (config,done)
     {
         var data= (config.collection ? _collection(config.collection) : _excel(config.excel));

         if (config.filter)
           data= jsonpath(data,config.filter);

         if (config.slice)
         {
           _writechunk(config.dest,data.slice.apply(data,config.slice));
           done();
         }
         else
         if (config.chunk)
         {
           _chunkdata(data,config.dest,config.chunk);
           done();
         }
         else
         if (config.transform)
         {
            var dest= p.join('data/json',config.dest+'.json');

            if (file.exists(dest))
             file.delete(dest);

            var transformed= _transform(data,config.transform);

            if (transformed.async)
              transformed.async(function (err,data)
              {
                if (!err)
                {
                    file.write(dest,
                               JSON.stringify(data, undefined, 2));
                    log.ok('Generated JSON collection: '+dest);
                }

                done();
              });
            else
            {
                file.write(dest,
                           JSON.stringify(transformed, undefined, 2));
                log.ok('Generated JSON collection: '+dest);
                done();
            }
         }
         else
         {
           _writechunk(config.dest,data);
           done();
         }

     },
     done);
  });

};


text:
package org.nanohttpd.junit.webserver;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;

/**
 * @author Matthieu Brouillard [matthieu@brouillard.fr]
 */
public class AbstractTestHttpServer {

    protected byte[] readContents(HttpEntity entity) throws IOException {
        InputStream instream = entity.getContent();
        return readContents(instream);
    }

    protected byte[] readContents(InputStream instream) throws IOException {
        byte[] bytes;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024];
            int count;
            while ((count = instream.read(buffer)) >= 0) {
                out.write(buffer, 0, count);
            }
            bytes = out.toByteArray();
        } finally {
            instream.close();
        }
        return bytes;
    }

}


text:
package com.lefu.databus.client;

import com.linkedin.databus.client.DatabusHttpClientImpl;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class ShutdownHook extends Thread {
	private final ComboPooledDataSource dataSource;
	private final DatabusHttpClientImpl client;
	private final ExecuteHandler executeHandler;

	public ShutdownHook(ComboPooledDataSource dataSource, DatabusHttpClientImpl client, ExecuteHandler executeHandler) {
		this.dataSource = dataSource;
		this.client = client;
		this.executeHandler = executeHandler;
	}

	@Override
	public void run() {
		if (this.client != null) {
			try {
				this.client.shutdown();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (this.executeHandler != null) {
			try {
				this.executeHandler.destroy();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (this.dataSource != null) {
			this.dataSource.close();
		}
	}

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: lsh_monster
 * Date: 2015/5/6
 * Time: 19:07
 */

namespace User\Authentication\Storage;

use Zend\Authentication\Storage\StorageInterface;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\AdapterAwareInterface;
use Zend\Db\TableGateway\TableGateway;
use Zend\ServiceManager\ServiceManager;
use Zend\Session\Container;
use Zend\Session\SaveHandler\DbTableGateway;
use Zend\Session\SaveHandler\DbTableGatewayOptions;
use Zend\Session\SessionManager;

class DbSession implements StorageInterface,AdapterAwareInterface{
    protected $table='user_session';
    protected $adapter;
    public function __construct($namespace = null, $member = null, SessionManager $manager = null)
    {
        if ($namespace !== null) {
            $this->namespace = $namespace;
        }
        if ($member !== null) {
            $this->member = $member;
        }
        $this->session   = new Container($this->namespace, $manager);

        $tableGateway=new TableGateway($this->table,$this->adapter);
        $dbTableGatewayOptions= new DbTableGatewayOptions();
        $dbTableGateway=new DbTableGateway($tableGateway,$dbTableGatewayOptions);
        $dbTableGateway->open(null,$this->namespace);
        $this->getManager()->setSaveHandler($dbTableGateway);
    }
    public function getManager(){
        return $this->session->getManager();
    }
    public function isEmpty(){

    }

    public function read(){

    }

    public function write($contents){

    }

    public function clear(){

    }
    public function setDbAdapter(Adapter $adapter){
        $this->adapter=$adapter;

    }
}


text:
{{bg.title}}
                    {{bg.name}}

                    {{bg.createdAt | date:'dd/MM/yyyy @ h:mma'}}

{{bg.body}}

                <form class="form-inline" >

                        Comment:
                        <input type="text" ng-model="newComment.comment" required="true" class="form-control" id="email" placeholder="Enter comment" name="email">

                    <button ng-click="submitComment(bg.postId,bg)" class="btn btn-default">Submit</button>
                </form>

{{bg.comments[$index].comment}}

                      {{bg.comments[$index].username}}
                     {{bg.comments[$index].createdAt | date:'dd/MM/yyyy @ h:mma'}}


text:
package gogitlab

import (
	"encoding/json"
)

const (
	project_issues_url = "/projects/:id/issues"
)

type Milestone struct {
	Id          int    `json:"id,omitempty"`
	IId         int    `json:"iid,omitempty"`
	ProjectId   int    `json:"project_id,omitempty"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	DueDate     string `json:"due_date,omitempty"`
	State       string `json:"state,omitempty"`
	CreatedAt   string `json:"created_at"`
	UpdatedAt   string `json:"updated_at,omitempty"`
}

type Issue struct {
	Id          int        `json:"id"`
	IId         int        `json:"iid"`
	ProjectId   int        `json:"project_id,omitempty"`
	Title       string     `json:"title,omitempty"`
	Description string     `json:"description,omitempty"`
	Labels      []string   `json:"labels,omitempty"`
	Milestone   *Milestone `json:"milestone,omitempty"`
	Assignee    *User      `json:"assignee,omitempty"`
	Author      *User      `json:"author,omitempty"`
	State       string     `json:"state,omitempty"`
	CreatedAt   string     `json:"created_at,omitempty"`
	UpdatedAt   string     `json:"updated_at,omitempty"`
}

type IssueRequest struct {
	Title       string `json:"title"`
	Description string `json:"description,omitempty"`
	AssigneeId  int    `json:"assignee_id,omitempty"`
	MilestoneId int    `json:"milestone_id,omitempty"`
	Labels      string `json:"labels,omitempty"`
}

func (g *Gitlab) AddIssue(projectId string, req *IssueRequest) (issue *Issue, err error) {
	params := map[string]string{
		":id": projectId,
	}
	u := g.ResourceUrl(project_issues_url, params)

	encodedRequest, err := json.Marshal(req)
	if err != nil {
		return
	}

	data, err := g.buildAndExecRequest("POST", u, encodedRequest)
	if err != nil {
		return
	}

	issue = new(Issue)
	err = json.Unmarshal(data, issue)
	if err != nil {
		panic(err)
	}
	return
}


text:
namespace DressZone.Services.Admin
{
    using DressZone.Services.Contracts;

    public class AdminHomeService : IAdminHomeService
    {

    }
}


text:
<!DOCTYPE HTML>

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>raphaeljspie-element Demo</title>

        <link rel="import" href="raphaeljspie-element.html">

This is the raphaeljspie-element, a simple way to multiple RaphaelJS pie charts.

        <raphaeljspie-element class="card full"
          __values="[40, 26, 5, 5, 4, 4, 3, 2, 2, 2]"
          __labels='["Ruby", "JS", "Shell", "Python", "PHP", "C", "Perl", "C++", "Java", "Obj-C"]'>
        </raphaeljspie-element>

        <raphaeljspie-element class="card full" id="responsive"
          __title="Responsive pie"
          __values="[40, 26, 5, 5, 4, 4]"
          __labels='["Ruby", "JS", "Shell", "Python", "PHP", "C"]'
          __radius="2600">
        </raphaeljspie-element>


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    path = require('path'),
    Sanitizer = require(path.resolve('./modules/phrases/server/services/sanitizekeys.server.service')),
	IconMap = mongoose.model('IconMap');

exports.getAllIcons = function(cb) {
    IconMap.findOne({}).lean().exec(function(err, result) {
        cb(result);
    });
};

exports.getIconsForPhrase = function(phrase, cb) {
    /* Client styles must support at least ten colors */
    var AVAILABLE_ICONS = process.env.NUM_AVAILABLE_ICONS || 144;

    function updateIconMap(iconMap, phrase) {
        for (var i = 0; i < phrase.length; ++i) {
            var curChar = Sanitizer.encode(phrase.charAt(i));

            if (!iconMap[curChar]) {
                iconMap[curChar] = Math.ceil((Math.random() + 0.0001) * AVAILABLE_ICONS);
            }
        }
    }

    var promise = IconMap.findOne({}, function(err, doc) {
        if(err)
            console.error('err: ' + err);
        else {
            var iconMap = null;

            if (!doc) {
                iconMap = new IconMap({
                    icons: {}
                });

                updateIconMap(iconMap.icons, phrase);

                iconMap.save(function() {
                    cb(iconMap.icons);
                });
            } else {
                iconMap = doc.icons || {};

                updateIconMap(iconMap, phrase);
                IconMap.update({}, { $set: {icons: iconMap}}, {upsert: true}, function(err) {
                    if (err)
                        console.log('Problem updating icon map ' + err);
                    cb(iconMap);
                });
            }
        }
    });
};


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

	<title>Wireframing Sites</title>

Amazon.com

The website is solving people's problem of having accessing to a wide market of goods at low prices and short shipping times. Given there are so many types of products that a user could be looking for when entering the site, it is difficult to cater the homepage to each user's needs.

Pandora.com

The website is solving people's problem of accessing free music and identifying/finding new music that aligns with their preferences. The process of finding new music for the user is a black box process and thus the site must depends on their song selection alone, hooking the user on the first few songs provided, in order to win the users trust/prove to the user that the site can provide he or she with music he or she likes.

FareCompare.com

The website is solving people's problem of browsing all possible flight choices across the globe - most travel search engines fail when you fly across country borders. There is a challenge of showing the user the flights he or she most desired when there are 1000+ options given the user's initial search criteria.

<!DOCTYPE html>


text:
Using a predicate function, select only the elements of a stream that the predicate function finds truthy.

__Graph__

```
a:                  {1--2--3--4--5--}
filter(isEven, a):  {---2-----4-----}
```

__Signature__

`(a -> Boolean) -> Stream a -> Stream a`

__Usage__

```javascript
const filter = require('flyd/module/filter')

const numbers = flyd.stream()
const largeNumbers = filter(n => n > 5, numbers)

// Collect large numbers into an array
const collect = flyd.scan((ls, n) => ls.concat(n), [], largeNumbers)

numbers(2)(6)(5)(3)(7)(10)(5);
collect() // [6, 7, 10]
```


text:
package com.kamikaze.docidset.compression;

import java.util.BitSet;

import org.apache.lucene.util.OpenBitSet;

public interface CompressedSortedIntegerSegment {

  public OpenBitSet compress(int[] inputSet) throws IllegalArgumentException;

  public long[] compressAlt(int[] inputSet) throws IllegalArgumentException;

  public int[] decompress(BitSet packedSet) throws IllegalArgumentException;

  public int[] decompress(OpenBitSet packedSet);

}


text:
package org.apache.flink.table.planner.plan.optimize.program

import org.apache.flink.configuration.Configuration
import org.apache.flink.table.api.config.OptimizerConfigOptions
import org.apache.flink.table.planner.plan.nodes.FlinkConventions
import org.apache.flink.table.planner.plan.rules.FlinkStreamRuleSets

import org.apache.calcite.plan.hep.HepMatchOrder

/**
  * Defines a sequence of programs to optimize for stream table plan.
  */
object FlinkStreamProgram {

  val SUBQUERY_REWRITE = "subquery_rewrite"
  val TEMPORAL_JOIN_REWRITE = "temporal_join_rewrite"
  val DECORRELATE = "decorrelate"
  val TIME_INDICATOR = "time_indicator"
  val DEFAULT_REWRITE = "default_rewrite"
  val PREDICATE_PUSHDOWN = "predicate_pushdown"
  val JOIN_REORDER = "join_reorder"
  val LOGICAL = "logical"
  val LOGICAL_REWRITE = "logical_rewrite"
  val PHYSICAL = "physical"
  val PHYSICAL_REWRITE = "physical_rewrite"

  def buildProgram(config: Configuration): FlinkChainedProgram[StreamOptimizeContext] = {
    val chainedProgram = new FlinkChainedProgram[StreamOptimizeContext]()

    // rewrite sub-queries to joins
    chainedProgram.addLast(
      SUBQUERY_REWRITE,
      FlinkGroupProgramBuilder.newBuilder[StreamOptimizeContext]
        // rewrite QueryOperationCatalogViewTable before rewriting sub-queries
        .addProgram(FlinkHepRuleSetProgramBuilder.newBuilder
          .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
          .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
          .add(FlinkStreamRuleSets.TABLE_REF_RULES)
          .build(), "convert table references before rewriting sub-queries to semi-join")
        .addProgram(FlinkHepRuleSetProgramBuilder.newBuilder
          .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
          .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
          .add(FlinkStreamRuleSets.SEMI_JOIN_RULES)
          .build(), "rewrite sub-queries to semi-join")
        .addProgram(FlinkHepRuleSetProgramBuilder.newBuilder
          .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION)
          .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
          .add(FlinkStreamRuleSets.TABLE_SUBQUERY_RULES)
          .build(), "sub-queries remove")
        // convert RelOptTableImpl (which exists in SubQuery before) to FlinkRelOptTable
        .addProgram(FlinkHepRuleSetProgramBuilder.newBuilder
          .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
          .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
          .add(FlinkStreamRuleSets.TABLE_REF_RULES)
          .build(), "convert table references after sub-queries removed")
        .build())

    // rewrite special temporal join plan
    chainedProgram.addLast(
      TEMPORAL_JOIN_REWRITE,
      FlinkGroupProgramBuilder.newBuilder[StreamOptimizeContext]
        .addProgram(
          FlinkHepRuleSetProgramBuilder.newBuilder
            .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
            .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
            .add(FlinkStreamRuleSets.EXPAND_PLAN_RULES)
            .build(), "convert correlate to temporal table join")
        .addProgram(
          FlinkHepRuleSetProgramBuilder.newBuilder
            .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
            .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
            .add(FlinkStreamRuleSets.POST_EXPAND_CLEAN_UP_RULES)
            .build(), "convert enumerable table scan")
        .build())

    // query decorrelation
    chainedProgram.addLast(DECORRELATE, new FlinkDecorrelateProgram)

    // convert time indicators
    chainedProgram.addLast(TIME_INDICATOR, new FlinkRelTimeIndicatorProgram)

    // default rewrite, includes: predicate simplification, expression reduction, window
    // properties rewrite, etc.
    chainedProgram.addLast(
      DEFAULT_REWRITE,
      FlinkHepRuleSetProgramBuilder.newBuilder
        .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
        .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
        .add(FlinkStreamRuleSets.DEFAULT_REWRITE_RULES)
        .build())

    // rule based optimization: push down predicate(s) in where clause, so it only needs to read
    // the required data
    chainedProgram.addLast(
      PREDICATE_PUSHDOWN,
      FlinkGroupProgramBuilder.newBuilder[StreamOptimizeContext]
        .addProgram(
          FlinkHepRuleSetProgramBuilder.newBuilder
            .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION)
            .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
            .add(FlinkStreamRuleSets.FILTER_PREPARE_RULES)
            .build(), "filter rules")
        .addProgram(
          FlinkHepRuleSetProgramBuilder.newBuilder
            .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
            .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
            .add(FlinkStreamRuleSets.FILTER_TABLESCAN_PUSHDOWN_RULES)
            .build(), "push predicate into table scan")
        .addProgram(
          FlinkHepRuleSetProgramBuilder.newBuilder
            .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
            .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
            .add(FlinkStreamRuleSets.PRUNE_EMPTY_RULES)
            .build(), "prune empty after predicate push down")
        .build())

    // join reorder
    if (config.getBoolean(OptimizerConfigOptions.TABLE_OPTIMIZER_JOIN_REORDER_ENABLED)) {
      chainedProgram.addLast(
        JOIN_REORDER,
        FlinkGroupProgramBuilder.newBuilder[StreamOptimizeContext]
          .addProgram(FlinkHepRuleSetProgramBuilder.newBuilder
            .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION)
            .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
            .add(FlinkStreamRuleSets.JOIN_REORDER_PREPARE_RULES)
            .build(), "merge join into MultiJoin")
          .addProgram(FlinkHepRuleSetProgramBuilder.newBuilder
            .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
            .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
            .add(FlinkStreamRuleSets.JOIN_REORDER_RULES)
            .build(), "do join reorder")
          .build())
    }

    // optimize the logical plan
    chainedProgram.addLast(
      LOGICAL,
      FlinkVolcanoProgramBuilder.newBuilder
        .add(FlinkStreamRuleSets.LOGICAL_OPT_RULES)
        .setRequiredOutputTraits(Array(FlinkConventions.LOGICAL))
        .build())

    // logical rewrite
    chainedProgram.addLast(
      LOGICAL_REWRITE,
      FlinkHepRuleSetProgramBuilder.newBuilder
        .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
        .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
        .add(FlinkStreamRuleSets.LOGICAL_REWRITE)
        .build())

    // optimize the physical plan
    chainedProgram.addLast(
      PHYSICAL,
      FlinkVolcanoProgramBuilder.newBuilder
        .add(FlinkStreamRuleSets.PHYSICAL_OPT_RULES)
        .setRequiredOutputTraits(Array(FlinkConventions.STREAM_PHYSICAL))
        .build())

    // physical rewrite
    chainedProgram.addLast(
      PHYSICAL_REWRITE,
      FlinkGroupProgramBuilder.newBuilder[StreamOptimizeContext]
        .addProgram(new FlinkChangelogModeInferenceProgram,
          "Changelog mode inference")
        .addProgram(new FlinkMiniBatchIntervalTraitInitProgram,
          "Initialization for mini-batch interval inference")
        .addProgram(
          FlinkHepRuleSetProgramBuilder.newBuilder
            .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
            .setHepMatchOrder(HepMatchOrder.TOP_DOWN)
            .add(FlinkStreamRuleSets.MINI_BATCH_RULES)
            .build(), "mini-batch interval rules")
        .addProgram(
          FlinkHepRuleSetProgramBuilder.newBuilder
            .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION)
            .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
            .add(FlinkStreamRuleSets.PHYSICAL_REWRITE)
            .build(), "physical rewrite")
        .build())

    chainedProgram
  }
}


text:
Windows 10 x64 (19041.329)

_RTL_FEATURE_CONFIGURATION_PRIORITY

   FeatureConfigurationPriorityAll = 0n0

   FeatureConfigurationPriorityService = 0n4

   FeatureConfigurationPriorityUser = 0n8

   FeatureConfigurationPriorityTest = 0n12

   FeatureConfigurationPriorityMax = 0n15