text:
namespace base {
class RunLoop;
}

namespace gfx {
class Point;
}

// A collections of functions designed for use with content_browsertests and
// browser_tests.
// TO BE CLEAR: any function here must work against both binaries. If it only
// works with browser_tests, it should be in chrome\test\base\ui_test_utils.h.
// If it only works with content_browsertests, it should be in
// content\test\content_browser_test_utils.h.

namespace content {

class BrowserContext;
class MessageLoopRunner;
class RenderViewHost;
class WebContents;

// Generate a URL for a file path including a query string.
GURL GetFileUrlWithQuery(const base::FilePath& path,
                         const std::string& query_string);

// Waits for a load stop for the specified |web_contents|'s controller, if the
// tab is currently web_contents.  Otherwise returns immediately.
void WaitForLoadStop(WebContents* web_contents);

#if defined(USE_AURA)
// If WebContent's view is currently being resized, this will wait for the ack
// from the renderer that the resize is complete and for the
// WindowEventDispatcher to release the pointer moves. If there's no resize in
// progress, the method will return right away.
void WaitForResizeComplete(WebContents* web_contents);
#endif  // USE_AURA

// Causes the specified web_contents to crash. Blocks until it is crashed.
void CrashTab(WebContents* web_contents);

// Simulates clicking at the center of the given tab asynchronously; modifiers
// may contain bits from WebInputEvent::Modifiers.
void SimulateMouseClick(WebContents* web_contents,
                        int modifiers,
                        blink::WebMouseEvent::Button button);

// Simulates clicking at the point |point| of the given tab asynchronously;
// modifiers may contain bits from WebInputEvent::Modifiers.
void SimulateMouseClickAt(WebContents* web_contents,
                          int modifiers,
                          blink::WebMouseEvent::Button button,
                          const gfx::Point& point);

// Simulates asynchronously a mouse enter/move/leave event.
void SimulateMouseEvent(WebContents* web_contents,
                        blink::WebInputEvent::Type type,
                        const gfx::Point& point);

// Taps the screen at |point|.
void SimulateTapAt(WebContents* web_contents, const gfx::Point& point);

// Sends a key press asynchronously.
// The native code of the key event will be set to InvalidNativeKeycode().
// |key_code| alone is good enough for scenarios that only need the char
// value represented by a key event and not the physical key on the keyboard
// or the keyboard layout.
// For scenarios such as chromoting that need the native code,
// SimulateKeyPressWithCode should be used.
void SimulateKeyPress(WebContents* web_contents,
                      ui::KeyboardCode key_code,
                      bool control,
                      bool shift,
                      bool alt,
                      bool command);

// Sends a key press asynchronously.
// |code| specifies the UIEvents (aka: DOM4Events) value of the key:
// https://dvcs.w3.org/hg/d4e/raw-file/tip/source_respec.htm
// The native code of the key event will be set based on |code|.
// See ui/base/keycodes/vi usb_keycode_map.h for mappings between |code|
// and the native code.
// Examples of the various codes:
//   key_code: VKEY_A
//   code: "KeyA"
//   native key code: 0x001e (for Windows).
//   native key code: 0x0026 (for Linux).
void SimulateKeyPressWithCode(WebContents* web_contents,
                              ui::KeyboardCode key_code,
                              const char* code,
                              bool control,
                              bool shift,
                              bool alt,
                              bool command);

namespace internal {
// Allow ExecuteScript* methods to target either a WebContents or a
// RenderFrameHost.  Targetting a WebContents means executing the script in the
// RenderFrameHost returned by WebContents::GetMainFrame(), which is the
// main frame.  Pass a specific RenderFrameHost to target it.
class ToRenderFrameHost {
 public:
  ToRenderFrameHost(WebContents* web_contents);
  ToRenderFrameHost(RenderViewHost* render_view_host);
  ToRenderFrameHost(RenderFrameHost* render_frame_host);

  RenderFrameHost* render_frame_host() const { return render_frame_host_; }

 private:
  RenderFrameHost* render_frame_host_;
};
}  // namespace internal

// Executes the passed |script| in the specified frame. The |script| should not
// invoke domAutomationController.send(); otherwise, your test will hang or be
// flaky. If you want to extract a result, use one of the below functions.
// Returns true on success.
bool ExecuteScript(const internal::ToRenderFrameHost& adapter,
                   const std::string& script) WARN_UNUSED_RESULT;

// The following methods executes the passed |script| in the specified frame and
// sets |result| to the value passed to "window.domAutomationController.send" by
// the executed script. They return true on success, false if the script
// execution failed or did not evaluate to the expected type.
bool ExecuteScriptAndExtractInt(const internal::ToRenderFrameHost& adapter,
                                const std::string& script,
                                int* result) WARN_UNUSED_RESULT;
bool ExecuteScriptAndExtractBool(const internal::ToRenderFrameHost& adapter,
                                 const std::string& script,
                                 bool* result) WARN_UNUSED_RESULT;
bool ExecuteScriptAndExtractString(const internal::ToRenderFrameHost& adapter,
                                   const std::string& script,
                                   std::string* result) WARN_UNUSED_RESULT;

// Walks the frame tree of the specified WebContents and returns the sole frame
// that matches the specified predicate function. This function will DCHECK if
// no frames match the specified predicate, or if more than one frame matches.
RenderFrameHost* FrameMatchingPredicate(
    WebContents* web_contents,
    const base::Callback<bool(RenderFrameHost*)>& predicate);

// Predicates for use with FrameMatchingPredicate.
bool FrameMatchesName(const std::string& name, RenderFrameHost* frame);
bool FrameIsChildOfMainFrame(RenderFrameHost* frame);
bool FrameHasSourceUrl(const GURL& url, RenderFrameHost* frame);

// Executes the WebUI resource test runner injecting each resource ID in
// |js_resource_ids| prior to executing the tests.
//
// Returns true if tests ran successfully, false otherwise.
bool ExecuteWebUIResourceTest(WebContents* web_contents,
                              const std::vector<int>& js_resource_ids);

// Returns the cookies for the given url.
std::string GetCookies(BrowserContext* browser_context, const GURL& url);

// Sets a cookie for the given url. Returns true on success.
bool SetCookie(BrowserContext* browser_context,
               const GURL& url,
               const std::string& value);

// Watches title changes on a WebContents, blocking until an expected title is
// set.
class TitleWatcher : public WebContentsObserver {
 public:
  // |web_contents| must be non-NULL and needs to stay alive for the
  // entire lifetime of |this|. |expected_title| is the title that |this|
  // will wait for.
  TitleWatcher(WebContents* web_contents,
               const base::string16& expected_title);
  virtual ~TitleWatcher();

  // Adds another title to watch for.
  void AlsoWaitForTitle(const base::string16& expected_title);

  // Waits until the title matches either expected_title or one of the titles
  // added with AlsoWaitForTitle. Returns the value of the most recently
  // observed matching title.
  const base::string16& WaitAndGetTitle() WARN_UNUSED_RESULT;

 private:
  // Overridden WebContentsObserver methods.
  virtual void DidStopLoading(RenderViewHost* render_view_host) OVERRIDE;
  virtual void TitleWasSet(NavigationEntry* entry, bool explicit_set) OVERRIDE;

  void TestTitle();

  std::vector<base::string16> expected_titles_;
  scoped_refptr<MessageLoopRunner> message_loop_runner_;

  // The most recently observed expected title, if any.
  base::string16 observed_title_;

  DISALLOW_COPY_AND_ASSIGN(TitleWatcher);
};

// Watches a WebContents and blocks until it is destroyed.
class WebContentsDestroyedWatcher : public WebContentsObserver {
 public:
  explicit WebContentsDestroyedWatcher(WebContents* web_contents);
  virtual ~WebContentsDestroyedWatcher();

  // Waits until the WebContents is destroyed.
  void Wait();

 private:
  // Overridden WebContentsObserver methods.
  virtual void WebContentsDestroyed() OVERRIDE;

  scoped_refptr<MessageLoopRunner> message_loop_runner_;

  DISALLOW_COPY_AND_ASSIGN(WebContentsDestroyedWatcher);
};

// Watches a RenderProcessHost and waits for specified destruction events.
class RenderProcessHostWatcher : public RenderProcessHostObserver {
 public:
  enum WatchType {
    WATCH_FOR_PROCESS_EXIT,
    WATCH_FOR_HOST_DESTRUCTION
  };

  RenderProcessHostWatcher(RenderProcessHost* render_process_host,
                           WatchType type);
  // Waits for the render process that contains the specified web contents.
  RenderProcessHostWatcher(WebContents* web_contents, WatchType type);
  virtual ~RenderProcessHostWatcher();

  // Waits until the renderer process exits.
  void Wait();

 private:
  // Overridden RenderProcessHost::LifecycleObserver methods.
  virtual void RenderProcessExited(RenderProcessHost* host,
                                   base::ProcessHandle handle,
                                   base::TerminationStatus status,
                                   int exit_code) OVERRIDE;
  virtual void RenderProcessHostDestroyed(RenderProcessHost* host) OVERRIDE;

  RenderProcessHost* render_process_host_;
  WatchType type_;

  scoped_refptr<MessageLoopRunner> message_loop_runner_;

  DISALLOW_COPY_AND_ASSIGN(RenderProcessHostWatcher);
};

// Watches for responses from the DOMAutomationController and keeps them in a
// queue. Useful for waiting for a message to be received.
class DOMMessageQueue : public NotificationObserver {
 public:
  // Constructs a DOMMessageQueue and begins listening for messages from the
  // DOMAutomationController. Do not construct this until the browser has
  // started.
  DOMMessageQueue();
  virtual ~DOMMessageQueue();

  // Removes all messages in the message queue.
  void ClearQueue();

  // Wait for the next message to arrive. |message| will be set to the next
  // message. Returns true on success.
  bool WaitForMessage(std::string* message) WARN_UNUSED_RESULT;

  // Overridden NotificationObserver methods.
  virtual void Observe(int type,
                       const NotificationSource& source,
                       const NotificationDetails& details) OVERRIDE;

 private:
  NotificationRegistrar registrar_;
  std::queue<std::string> message_queue_;
  scoped_refptr<MessageLoopRunner> message_loop_runner_;

  DISALLOW_COPY_AND_ASSIGN(DOMMessageQueue);
};

}  // namespace content

#endif  // CONTENT_PUBLIC_TEST_BROWSER_TEST_UTILS_H_


text:
New Cookie

    <form (ng-submit)="onSubmit()" #hf="form">

Cookie preview

                    Name
                    <input type="text" class="form-control" required [(ng-model)]="model.name" ng-control="name" #name="form">

                        Name is required

                    Description
                    <input type="text" class="form-control" [(ng-model)]="model.description" ng-control="description">

                    Difficulty
                    <select class="form-control" required [(ng-model)]="model.difficulty" ng-control="difficulty" #difficulty="form">
                        <option *ng-for="#d of difficulties" [value]="d">{{d}}</option>
                    </select>

                        Difficulty is required

                    Image URL
                    <input type="text" class="form-control" required [(ng-model)]="model.url" ng-control="url" #url="form">

                        Image URL is required

                <button type="submit" class="btn btn-primary" [disabled]="!hf.form.valid">Save</button>

    </form>

redpajama_set_name: RedPajamaGithub


text:
//
//  AlbumViewController.m
//  ImageGallery
//
//  Created by Krishantha Jayathilake on 1/22/14.
//  Copyright (c) 2014 Krishantha Jayathilake. All rights reserved.
//

#import "AlbumViewController.h"
#define THUMB_HEIGHT 68.0f;
#define ROW_HEIGHT 80.0f

@interface AlbumViewController ()

typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
typedef void (^ALAssetsGroupEnumerationResultsBlock)(ALAsset *result, NSUInteger index, BOOL *stop);
typedef void (^ALAssetsLibraryGroupsEnumerationResultsBlock)(ALAssetsGroup *group, BOOL *stop);

@property (nonatomic) ALAssetsLibrary *library;
@property (nonatomic) UIBarButtonItem *addButton;
@property (nonatomic) NSMutableArray *assetGroups;

@end

@implementation AlbumViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = NSLocalizedString(@"Photos", nil);

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    self.tableView.rowHeight = ROW_HEIGHT;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self setupGroup];

    self.addButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addButtonClicked)];
    self.navigationItem.leftBarButtonItem = self.addButton;

    self.navigationItem.rightBarButtonItem = self.editButtonItem;

}

- (void)addButtonClicked
{

}

- (void)setupGroup
{
    if (!self.library)
        self.library = [self.class defaultAssetsLibrary];

    if (!self.assetGroups)
        self.assetGroups = [[NSMutableArray alloc] init];
    else
        [self.assetGroups removeAllObjects];

    ALAssetsLibraryGroupsEnumerationResultsBlock resultsBlock = ^(ALAssetsGroup *group, BOOL *stop) {

        if (group)
        {
            //[group setAssetsFilter:assetsFilter];

            if (group.numberOfAssets > 0)
                [self.assetGroups addObject:group];

        }
        else
        {
            [self reloadData];
        }
    };

    ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {

        [self showNotAllowed];

    };

    // Enumerate Camera roll first
    [self.library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
                                      usingBlock:resultsBlock
                                    failureBlock:failureBlock];

    // Then all other groups
    NSUInteger type =
    ALAssetsGroupLibrary | ALAssetsGroupAlbum | ALAssetsGroupEvent |
    ALAssetsGroupFaces | ALAssetsGroupPhotoStream;

    [self.library enumerateGroupsWithTypes:type
                                      usingBlock:resultsBlock
                                    failureBlock:failureBlock];
}

#pragma mark - Reload Data

- (void)reloadData
{
    if (self.assetGroups.count == 0)
        [self showNoAssets];

    [self.tableView reloadData];
}

#pragma mark - ALAssetsLibrary

+ (ALAssetsLibrary *)defaultAssetsLibrary
{
    static dispatch_once_t pred = 0;
    static ALAssetsLibrary *library = nil;
    dispatch_once(&pred, ^{
        library = [[ALAssetsLibrary alloc] init];
    });
    return library;
}

#pragma mark - Not allowed / No assets

- (void)showNotAllowed
{
    self.title              = nil;

    UIView *lockedView      = [[UIView alloc] initWithFrame:self.view.bounds];
    UIImageView *locked     = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CTAssetsPickerLocked"]];

    CGRect rect             = CGRectInset(self.view.bounds, 8, 8);
    UILabel *title          = [[UILabel alloc] initWithFrame:rect];
    UILabel *message        = [[UILabel alloc] initWithFrame:rect];

    title.text              = NSLocalizedString(@"This app does not have access to your photos or videos.", nil);
    title.font              = [UIFont boldSystemFontOfSize:17.0];
    title.textColor         = [UIColor colorWithRed:129.0/255.0 green:136.0/255.0 blue:148.0/255.0 alpha:1];
    title.textAlignment     = NSTextAlignmentCenter;
    title.numberOfLines     = 5;

    message.text            = NSLocalizedString(@"You can enable access in Privacy Settings.", nil);
    message.font            = [UIFont systemFontOfSize:14.0];
    message.textColor       = [UIColor colorWithRed:129.0/255.0 green:136.0/255.0 blue:148.0/255.0 alpha:1];
    message.textAlignment   = NSTextAlignmentCenter;
    message.numberOfLines   = 5;

    [title sizeToFit];
    [message sizeToFit];

    locked.center           = CGPointMake(lockedView.center.x, lockedView.center.y - 40);
    title.center            = locked.center;
    message.center          = locked.center;

    rect                    = title.frame;
    rect.origin.y           = locked.frame.origin.y + locked.frame.size.height + 20;
    title.frame             = rect;

    rect                    = message.frame;
    rect.origin.y           = title.frame.origin.y + title.frame.size.height + 10;
    message.frame           = rect;

    [lockedView addSubview:locked];
    [lockedView addSubview:title];
    [lockedView addSubview:message];

    self.tableView.tableHeaderView  = lockedView;
    self.tableView.scrollEnabled    = NO;
}

- (void)showNoAssets
{
    UIView *noAssetsView    = [[UIView alloc] initWithFrame:self.view.bounds];

    CGRect rect             = CGRectInset(self.view.bounds, 10, 10);
    UILabel *title          = [[UILabel alloc] initWithFrame:rect];
    UILabel *message        = [[UILabel alloc] initWithFrame:rect];

    title.text              = NSLocalizedString(@"No Photos or Videos", nil);
    title.font              = [UIFont systemFontOfSize:26.0];
    title.textColor         = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1];
    title.textAlignment     = NSTextAlignmentCenter;
    title.numberOfLines     = 5;

    message.text            = NSLocalizedString(@"You can sync photos and videos onto your iPhone using iTunes.", nil);
    message.font            = [UIFont systemFontOfSize:18.0];
    message.textColor       = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1];
    message.textAlignment   = NSTextAlignmentCenter;
    message.numberOfLines   = 5;

    [title sizeToFit];
    [message sizeToFit];

    title.center            = CGPointMake(noAssetsView.center.x, noAssetsView.center.y - 10 - title.frame.size.height / 2);
    message.center          = CGPointMake(noAssetsView.center.x, noAssetsView.center.y + 10 + message.frame.size.height / 2);

    [noAssetsView addSubview:title];
    [noAssetsView addSubview:message];

    self.tableView.tableHeaderView  = noAssetsView;
    self.tableView.scrollEnabled    = NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSLog(@"%d",self.assetGroups.count);
    return self.assetGroups.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    // Configure the cell...

    ALAssetsGroup *goup = (ALAssetsGroup *)[self.assetGroups objectAtIndex:indexPath.row];
    CGImageRef posterImage = goup.posterImage;
    size_t height = CGImageGetHeight(posterImage);
    float scale = height / THUMB_HEIGHT;
    cell.imageView.image = [UIImage imageWithCGImage:posterImage scale:scale orientation:UIImageOrientationUp];
    cell.textLabel.text = [goup valueForProperty:ALAssetsGroupPropertyName];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", [goup numberOfAssets]];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    ALAssetsGroup *goup = (ALAssetsGroup *)[self.assetGroups objectAtIndex:indexPath.row];
    if ([[goup valueForProperty:ALAssetsGroupPropertyName] isEqualToString:@"Saved Photos"]) {
        return NO;
    }
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

 */

@end


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

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>org.apache.lucene.facet.util (Lucene 4.6.1 API)</title>
<meta name="date" content="2014-01-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.apache.lucene.facet.util

Classes

FacetsPayloadMigrationReader

MultiCategoryListIterator

OrdinalMappingAtomicReader

PartitionsUtils

PrintTaxonomyStats

ResultSortUtils

TaxonomyMergeUtils


text:
using System.Runtime.InteropServices;
using System.Windows.Forms.VisualStyles;
using Moonfish.Guerilla;
using Moonfish.Guerilla.Tags;

namespace Moonfish.Tags
{
    [GuerillaType(MoonfishFieldType.FieldWordBlockFlags)]
    [StructLayout(LayoutKind.Sequential, Size = 2)]
    public struct BlockFlags16
    {
        public enum BlockType : byte
        {
            Biped = 0,
            Vehicle,
            Weapon,
            Equipment,
            Garbage,
            Projectile,
            Scenery,
            Machine,
            Control,
            LightFixture,
            SoundScenery,
            Crate,
            Creature,
        };

        public enum BlockSource : byte
        {
            Structure = 0,
            Editor,
            Dynamic,
            Legacy
        }

        public BlockType Type;
        public BlockSource Source;

        public BlockFlags16(short flags)
        {
            Type = ( BlockType ) ( flags >> 8 );
            Source = ( BlockSource ) ( flags & 0xFF );
        }

        public override string ToString()
        {
            return $@"Type: {Type} Source: {Source}";
        }
    }
}


text:
using System;
using d60.Cirqus.Events;

namespace d60.Cirqus.Tests.Contracts.Views.Models.LoadingStuffDuringViewLocation
{
    public class NodeAttachedToParentNode : DomainEvent<Node>
    {
        public string ParentNodeId { get; set; }
    }
}


text:
![FiloDB Architecture](filodb_architecture.png)

The code is laid out following the different parts and components.

### Core

These components form the core part of FiloDB and are portable across data stores.
* Memtable: The memtable is a temporary storage for row-format data and is flushed according to a FlushPolicy.
* Reprojector: The Reprojector flushes a set of rows from a Memtable according to a FlushPolicy in order to achieve a desired projection or sort order in the column store. A reprojector outputs Segments.
* ColumnStore: The column store saves and retrieves Segments from the underlying storage.  Includes the ability to merge segments in sorted order.  The core does not implement any particular columnstores, but it contains business logic applicable to all column stores.
* MetaStore: An interface for persistence of database metadata, such as dataset, column, and projection state.

### Cassandra

An implementation of ColumnStore and MetaStore for Apache Cassandra.

### Coordinator

Provides an upper-level, client-facing interface for the core components, and manages the scheduling around the MemTable, Reprojector, flushes, and column store.  Handles different types of streaming data ingestion.

### Spark

Contains the Spark input source for ingesting and querying data from FiloDB.


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostMetasTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('post_metas', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id')->unsigned();
            $table->foreign('post_id')->references('id')->on('posts');
            $table->string('meta_key', 191)->index()->comment('键');
            $table->text('meta_value')->comment('值');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('post_metas');
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace JinianNet.TengSnake.AspNet
{
    public class Handler : IHttpHandler, IRequiresSessionState
    {
        public HttpContext Context { get; private set; }
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public virtual string ClassName
        {
            get { return this.Context.Request["type"]; }
        }

        public virtual string MethodName
        {
            get { return this.Context.Request["method"]; }
        }

        public void ProcessRequest(HttpContext context)
        {
            this.Context = context;
            context.Response.Clear();

            //如果指定了命名空间

            object value = Environment.CreateInstance(ClassName);
            if (value == null)
            {
                throw new NullReferenceException("对象不存在");
            }

            TargetSource source = new TargetSource(value);
            NameValueCollection collection;
            string httpMethod;
            context.Response.ContentType = "application/json";
            switch (context.Request.HttpMethod.Trim().ToUpper())
            {
                case "GET":
                    collection = context.Request.QueryString;
                    httpMethod = "GET";
                    break;
                case "POST":
                    collection = context.Request.Form;
                    httpMethod = "POST";
                    break;
                default:
                    throw new HttpException(405, "不允许的访问方式");
            }
            Processor p = new Processor(source, collection, httpMethod);
            p.Render(MethodName, context.Response.Output);
        }
    }
}


text:
package at.renehollander.interactivecanvas;

import at.renehollander.interactivecanvas.shape.Shape;
import javafx.geometry.Point2D;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;

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

public class InteractiveCanvas extends Canvas {

    public static final boolean DEBUG_MODE = true;

    public static final Paint SELECTION_STROKE_COLOR = Color.BLACK;
    public static final double SELECTION_STROKE_WIDTH = 2;
    public static final Paint SELECTION_BOX_COLOR = Color.GRAY;
    public static final double SELECTION_BOX_SIZE = 10;
    public static final double SELECTION_BOX_HALF_SIZE = SELECTION_BOX_SIZE / 2;

    private List<Shape> shapes;
    private Shape selectedShape;

    public InteractiveCanvas() {
        this(0, 0);
    }

    protected Point2D lastMouseLocation;

    public InteractiveCanvas(double width, double height) {
        super(width, height);
        this.shapes = new ArrayList<Shape>();

        new MouseControl(this);
    }

    public Shape getSelectedShape() {
        return selectedShape;
    }

    public void setSelectedShape(Shape selectedShape) {
        this.selectedShape = selectedShape;
    }

    public List<Shape> getShapes() {
        return this.shapes;
    }

    public void updateCanvas() {
        this.gc().clearRect(0, 0, this.getWidth(), this.getHeight());
        this.getShapes().forEach(this::renderShape);
    }

    private Color[] randomColors = new Color[]{Color.BLUE, Color.RED, Color.GREEN, Color.VIOLET};

    private void renderShape(Shape shape) {
        this.gc().save();

        this.gc().translate(shape.getMetrics().getCenterX(), shape.getMetrics().getCenterY());
        this.gc().rotate(shape.getMetrics().getRotation());
        this.gc().translate(-shape.getMetrics().getCenterX(), -shape.getMetrics().getCenterY());

        shape.draw(this);

        if (this.getSelectedShape() == shape) {
            this.drawSelection(shape);
        }

        this.gc().restore();
        if (DEBUG_MODE) {
            this.gc().save();

            this.gc().setLineWidth(2);
            this.gc().setStroke(Color.VIOLET);
            this.gc().beginPath();
            this.gc().moveTo(shape.getMetrics().getTransformedP1().getX(), shape.getMetrics().getTransformedP1().getY());
            for (Point2D p : shape.getMetrics().getTransformedPoints()) {
                this.gc().lineTo(p.getX(), p.getY());
            }
            this.gc().closePath();
            this.gc().stroke();

            this.gc().setLineWidth(5);
            this.gc().setStroke(Color.BLUE);
            this.gc().strokeLine(shape.getMetrics().getTransformedP1().getX(), shape.getMetrics().getTransformedP1().getY(), shape.getMetrics().getTransformedP1().getX(), shape.getMetrics().getTransformedP1().getY());
            this.gc().setStroke(Color.ORANGE);
            this.gc().strokeLine(shape.getMetrics().getTransformedP2().getX(), shape.getMetrics().getTransformedP2().getY(), shape.getMetrics().getTransformedP2().getX(), shape.getMetrics().getTransformedP2().getY());
            this.gc().setStroke(Color.YELLOW);
            this.gc().strokeLine(shape.getMetrics().getTransformedP3().getX(), shape.getMetrics().getTransformedP3().getY(), shape.getMetrics().getTransformedP3().getX(), shape.getMetrics().getTransformedP3().getY());
            this.gc().setStroke(Color.GREEN);
            this.gc().strokeLine(shape.getMetrics().getTransformedP4().getX(), shape.getMetrics().getTransformedP4().getY(), shape.getMetrics().getTransformedP4().getX(), shape.getMetrics().getTransformedP4().getY());

            this.gc().restore();

            this.gc().save();

            for (int i = 0; i < shape.getMetrics().getPoints().length; i++) {
                Point2D p = shape.getMetrics().getPoints()[i];

                Point2D xy1 = p.subtract(InteractiveCanvas.SELECTION_BOX_HALF_SIZE, InteractiveCanvas.SELECTION_BOX_HALF_SIZE).add(0, 0);
                Point2D xy2 = p.subtract(0, InteractiveCanvas.SELECTION_BOX_HALF_SIZE).add(InteractiveCanvas.SELECTION_BOX_HALF_SIZE, 0);
                Point2D xy3 = p.subtract(0, 0).add(InteractiveCanvas.SELECTION_BOX_HALF_SIZE, InteractiveCanvas.SELECTION_BOX_HALF_SIZE);
                Point2D xy4 = p.subtract(InteractiveCanvas.SELECTION_BOX_HALF_SIZE, 0).add(0, InteractiveCanvas.SELECTION_BOX_HALF_SIZE);

                xy1 = shape.getMetrics().getRotationMatrix().transform(xy1);
                xy2 = shape.getMetrics().getRotationMatrix().transform(xy2);
                xy3 = shape.getMetrics().getRotationMatrix().transform(xy3);
                xy4 = shape.getMetrics().getRotationMatrix().transform(xy4);

                this.gc().setLineWidth(5);
                this.gc().setStroke(randomColors[0]);
                this.gc().strokeLine(xy1.getX(), xy1.getY(), xy1.getX(), xy1.getY());
                this.gc().setStroke(randomColors[1]);
                this.gc().strokeLine(xy2.getX(), xy2.getY(), xy2.getX(), xy2.getY());
                this.gc().setStroke(randomColors[2]);
                this.gc().strokeLine(xy3.getX(), xy3.getY(), xy3.getX(), xy3.getY());
                this.gc().setStroke(randomColors[3]);
                this.gc().strokeLine(xy4.getX(), xy4.getY(), xy4.getX(), xy4.getY());

            }
            this.gc().restore();
        }
    }

    public void drawSelection(Shape shape) {
        this.gc().setStroke(SELECTION_STROKE_COLOR);
        this.gc().setLineWidth(SELECTION_STROKE_WIDTH);
        this.gc().strokeRect(shape.getMetrics().getX(), shape.getMetrics().getY(), shape.getMetrics().getWidth(), shape.getMetrics().getHeight());
        this.gc().setFill(SELECTION_BOX_COLOR);
        this.gc().fillRect(shape.getMetrics().getX() - SELECTION_BOX_HALF_SIZE, shape.getMetrics().getY() - SELECTION_BOX_HALF_SIZE, SELECTION_BOX_SIZE, SELECTION_BOX_SIZE);
        this.gc().fillRect(shape.getMetrics().getXMax() - SELECTION_BOX_HALF_SIZE, shape.getMetrics().getY() - SELECTION_BOX_HALF_SIZE, SELECTION_BOX_SIZE, SELECTION_BOX_SIZE);
        this.gc().fillRect(shape.getMetrics().getX() - SELECTION_BOX_HALF_SIZE, shape.getMetrics().getYMax() - SELECTION_BOX_HALF_SIZE, SELECTION_BOX_SIZE, SELECTION_BOX_SIZE);
        this.gc().fillRect(shape.getMetrics().getXMax() - SELECTION_BOX_HALF_SIZE, shape.getMetrics().getYMax() - SELECTION_BOX_HALF_SIZE, SELECTION_BOX_SIZE, SELECTION_BOX_SIZE);
    }

    public Shape findTarget(double x, double y) {
        for (int i = shapes.size() - 1; i >= 0; i--) {
            Shape shape = shapes.get(i);
            if (shape.getMetrics().contains(x, y)) {
                return shape;
            }
        }
        return null;
    }

    public GraphicsContext gc() {
        return this.getGraphicsContext2D();
    }

}


text:
<?php

namespace Ffm\Hookdocs;

use Ffm\Hookdocs\Display\TableRow;
use Ffm\Hookdocs\Linktypes\LinkInterface;
use phpDocumentor\Reflection\DocBlockFactory;
use PhpParser\Comment\Doc;
use PhpParser\Error;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\ParserFactory;

class FileHandler
{
    protected $file;
    protected $typeClass;
    protected $linkClass;

    /**
     * FileHandler constructor.
     * @param \SplFileObject $file
     * @param string $typeClass
     * @param LinkInterface $linkClass
     */
    public function __construct(\SplFileObject $file, string $typeClass, LinkInterface $linkClass)
    {
        $this->file = $file;
        $this->typeClass = $typeClass;
        $this->linkClass = $linkClass;
    }

    /**
     * @return TableRow[]
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.StaticAccess)
     * @todo reduce cyclomatic complexity of traversing the class
     */
    public function getDocComments(): array
    {
        $contents = $this->file->fread($this->file->getSize());

        $parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
        $factory = DocBlockFactory::createInstance();
        $tagsOutput = [];
        $namespace = '\\';

        try {
            $stmts = $parser->parse($contents);

            foreach ($stmts as $node) {
                if ($node instanceof Namespace_) {
                    $namespace = $node->name;
                }
                if ($node instanceof Class_) {
                    $classObject = new ClassObject($node->name, $namespace, $this->file->getRealPath());

                    foreach ($node->getMethods() as $methods) {
                        $method = null;
                        foreach ($methods->getAttributes() as $key => $attribute) {
                            if ($key === 'comments') {
                                try {
                                    $docblock = $factory->create($attribute[0]->getText());
                                } catch (\InvalidArgumentException $error) { // malformed DocComment
                                    continue;
                                }

                                $typeFactory = new $this->typeClass($method, $docblock, $classObject, $this->linkClass);
                                foreach ($docblock->getTagsByName($typeFactory::TAG_NAME) as $tag) {
                                    $tagsOutput[] =  $typeFactory();
                                }
                            }
                            if ($key === 'startLine') {
                                $method = new MethodObject($methods->name, $attribute);
                            }
                        }
                    }
                }
            }
            // $stmts is an array of statement nodes
        } catch (Error $e) {
            echo 'Parse Error: ', $e->getMessage();
            return [];
        }

        return $tagsOutput;
    }
}


text:
layout: post
date: 2010-05-17
time: "09:00:00"
authors: ["Greg Wilson"]
title: "Day 11: Slides"
category: ["Content"]
---

Today's screencast experiment [link no longer active] is narration over PowerPoint slides: it isn't animation per se, but we'd like your feedback on whether something like this is a good way to explain "big picture" concepts.


text:
using SharpKit.JavaScript;
namespace Ext.form.field
{
    #region Trigger
    /// <inheritdocs />
    ///
    ///
Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
    /// The trigger has no default action, so you must assign a function to implement the trigger click handler by overriding
    /// <see cref="Ext.form.field.Trigger.onTriggerClick">onTriggerClick</see>. You can create a Trigger field directly, as it renders exactly like a combobox for which you
    /// can provide a custom implementation.

    ///
For example:

    ///
<see cref="Ext.ExtContext.define">Ext.define</see>('Ext.ux.CustomTrigger', {
    /// extend: '<see cref="Ext.form.field.Trigger">Ext.form.field.Trigger</see>',
    /// alias: 'widget.customtrigger',
    /// // override onTriggerClick
    /// onTriggerClick: function() {
    /// <see cref="Ext.MessageBox.alert">Ext.Msg.alert</see>('Status', 'You clicked my trigger!');
    /// }
    /// });
    /// <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.form.Panel">Ext.form.FormPanel</see>', {
    /// title: 'Form with TriggerField',
    /// bodyPadding: 5,
    /// width: 350,
    /// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>(),
    /// items:[{
    /// xtype: 'customtrigger',
    /// fieldLabel: 'Sample Trigger',
    /// emptyText: 'click the trigger'
    /// }]
    /// });
    ///

    ///
However, in general you will most likely want to use Trigger as the base class for a reusable component.
    /// <see cref="Ext.form.field.Date">Ext.form.field.Date</see> and <see cref="Ext.form.field.ComboBox">Ext.form.field.ComboBox</see> are perfect examples of this.

    ///
    [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
    public partial class Trigger : Ext.form.field.Text
    {
        ///
        /// false to prevent the user from typing text directly into the field; the field can only have its value set via an
        /// action invoked by the trigger.
        /// Defaults to: <c>true</c>
        ///
        public bool editable;
        ///
        /// true to hide the trigger element and display only the base text field
        /// Defaults to: <c>false</c>
        ///
        public bool hideTrigger;
        ///
        /// true to attach a click repeater to the trigger.
        /// Defaults to: <c>false</c>
        ///
        public bool repeatTriggerClick;
        ///
        /// The base CSS class that is always added to the trigger button. The triggerCls will be appended in
        /// addition to this class.
        /// Defaults to: <c>"x-form-trigger"</c>
        ///
        public JsString triggerBaseCls;
        ///
        /// An additional CSS class used to style the trigger button. The trigger will always get the triggerBaseCls
        /// by default and triggerCls will be appended if specified.
        ///
        public JsString triggerCls;
        ///
        /// The CSS class that is added to the text field when component is read-only or not editable.
        /// Defaults to: <c>"x-trigger-noedit"</c>
        ///
        public JsString triggerNoEditCls;
        ///
        /// The CSS class that is added to the div wrapping the trigger button(s).
        /// Defaults to: <c>"x-form-trigger-wrap"</c>
        ///
        public JsString triggerWrapCls;
        ///
        /// A reference to the TD element wrapping the input element. Only set after the field has been rendered.
        ///
        public Ext.dom.Element inputCell{get;set;}
        ///
        /// A composite of all the trigger button elements. Only set after the field has been rendered.
        ///
        public Ext.dom.CompositeElement triggerEl{get;set;}
        ///
        /// Width of the trigger element. Unless set explicitly, it will be
        /// automatically calculated through creating a temporary element
        /// on page. (That will be done just once per app run.)
        ///
        private JsNumber triggerWidth{get;set;}
        ///
        /// A reference to the TABLE element which encapsulates the input field and all trigger button(s). Only set after the field has been rendered.
        ///
        public Ext.dom.Element triggerWrap{get;set;}
        ///
        /// Returns a set of flags that describe the trigger state. These are just used to easily
        /// determine if the DOM is out-of-sync with the component's properties.
        ///
        private void getTriggerStateFlags(){}
        ///
        /// Get the total width of the trigger button area.
        ///
        /// <returns>
        /// <see cref="Number">Number</see>

The total trigger width

        ///

        /// </returns>
        public JsNumber getTriggerWidth(){return null;}
        ///
        /// The default blur handling must not occur for a TriggerField, implementing this template method as emptyFn disables that.
        /// Instead the tab key is monitored, and the superclass's onBlur is called when tab is detected
        ///
        protected virtual void onBlur(){}
        ///
        /// The function that should handle the trigger's click event. This method does nothing by default until overridden
        /// by an implementing function. See Ext.form.field.ComboBox and Ext.form.field.Date for sample implementations.
        ///
        /// <param name="e">
        /// </param>
        protected void onTriggerClick(EventObject e){}
        ///
        /// Sets the editable state of this field. This method is the runtime equivalent of setting the 'editable' config
        /// option at config time.
        ///
        /// <param name="editable">
True to allow the user to directly edit the field text. If false is passed, the user
        /// will only be able to modify the field using the trigger. Will also add a click event to the text field which
        /// will call the trigger.

        /// </param>
        public void setEditable(bool editable){}
        public Trigger(Ext.form.field.TriggerConfig config){}
        public Trigger(){}
        public Trigger(params object[] args){}
    }
    #endregion
    #region TriggerConfig
    /// <inheritdocs />
    [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
    public partial class TriggerConfig : Ext.form.field.TextConfig
    {
        ///
        /// false to prevent the user from typing text directly into the field; the field can only have its value set via an
        /// action invoked by the trigger.
        /// Defaults to: <c>true</c>
        ///
        public bool editable;
        ///
        /// true to hide the trigger element and display only the base text field
        /// Defaults to: <c>false</c>
        ///
        public bool hideTrigger;
        ///
        /// true to attach a click repeater to the trigger.
        /// Defaults to: <c>false</c>
        ///
        public bool repeatTriggerClick;
        ///
        /// The base CSS class that is always added to the trigger button. The triggerCls will be appended in
        /// addition to this class.
        /// Defaults to: <c>"x-form-trigger"</c>
        ///
        public JsString triggerBaseCls;
        ///
        /// An additional CSS class used to style the trigger button. The trigger will always get the triggerBaseCls
        /// by default and triggerCls will be appended if specified.
        ///
        public JsString triggerCls;
        ///
        /// The CSS class that is added to the text field when component is read-only or not editable.
        /// Defaults to: <c>"x-trigger-noedit"</c>
        ///
        public JsString triggerNoEditCls;
        ///
        /// The CSS class that is added to the div wrapping the trigger button(s).
        /// Defaults to: <c>"x-form-trigger-wrap"</c>
        ///
        public JsString triggerWrapCls;
        public TriggerConfig(params object[] args){}
    }
    #endregion
    #region TriggerEvents
    /// <inheritdocs />
    [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
    public partial class TriggerEvents : Ext.form.field.TextEvents
    {
        public TriggerEvents(params object[] args){}
    }
    #endregion
}


text:
#ifndef _INC_PMCC4_SYSDEP_H_
#define _INC_PMCC4_SYSDEP_H_

/* reduce multiple autoconf entries to a single definition */

#ifdef CONFIG_SBE_PMCC4_HDLC_V7_MODULE
#undef CONFIG_SBE_PMCC4_HDLC_V7
#define CONFIG_SBE_PMCC4_HDLC_V7  1
#endif

#ifdef CONFIG_SBE_PMCC4_NCOMM_MODULE
#undef CONFIG_SBE_PMCC4_NCOMM
#define CONFIG_SBE_PMCC4_NCOMM  1
#endif

/* FLUSH MACROS - if using ioremap_nocache(), then these can be NOOPS,
 * otherwise a memory barrier needs to be inserted.
 */

#define FLUSH_PCI_READ()     rmb()
#define FLUSH_PCI_WRITE()    wmb()
#define FLUSH_MEM_READ()     rmb()
#define FLUSH_MEM_WRITE()    wmb()

/*
 * System dependent callbacks routines, not inlined...
 * For inlined system dependent routines, see include/sbecom_inlinux_linux.h
 */

/*
 * passes received memory token back to the system, <user> is parameter from
 * sd_new_chan() used to create the channel which the data arrived on
 */

void sd_recv_consume(void *token, size_t len, void *user);

void        sd_disable_xmit (void *user);
void        sd_enable_xmit (void *user);
int         sd_line_is_ok (void *user);
void        sd_line_is_up (void *user);
void        sd_line_is_down (void *user);
int         sd_queue_stopped (void *user);

#endif                          /*** _INC_PMCC4_SYSDEP_H_ ***/


text:
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

using ImageMagick;
using Xunit;

namespace Magick.NET.Tests
{
    public partial class MagickImageTests
    {
        public class TheFlipMethod
        {
            [Fact]
            public void ShouldFlipTheImageVertically()
            {
                using (var images = new MagickImageCollection())
                {
                    images.Add(new MagickImage(MagickColors.DodgerBlue, 10, 10));
                    images.Add(new MagickImage(MagickColors.Firebrick, 10, 10));

                    using (var image = images.AppendVertically())
                    {
                        ColorAssert.Equal(MagickColors.DodgerBlue, image, 5, 0);
                        ColorAssert.Equal(MagickColors.Firebrick, image, 5, 10);

                        image.Flip();

                        ColorAssert.Equal(MagickColors.Firebrick, image, 5, 0);
                        ColorAssert.Equal(MagickColors.DodgerBlue, image, 5, 10);
                    }
                }
            }
        }
    }
}


text:
<?php

namespace ErenMustafaOzdal\LaravelUserModule;

use Illuminate\Support\ServiceProvider;

class LaravelUserModuleComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer(config('laravel-user-module.views.user.layout'), 'ErenMustafaOzdal\LaravelUserModule\Http\Composers\AdminComposer');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


text:
using System;

namespace StorybrewCommon.Storyboarding.CommandValues
{
    [Serializable]
    public struct CommandParameter : CommandValue
    {
        public static readonly CommandParameter None = new CommandParameter(ParameterType.None);
        public static readonly CommandParameter FlipHorizontal = new CommandParameter(ParameterType.FlipHorizontal);
        public static readonly CommandParameter FlipVertical = new CommandParameter(ParameterType.FlipVertical);
        public static readonly CommandParameter AdditiveBlending = new CommandParameter(ParameterType.AdditiveBlending);

        public readonly ParameterType Type;

        private CommandParameter(ParameterType type)
        {
            Type = type;
        }

        public string ToOsbString(ExportSettings exportSettings)
        {
            switch (Type)
            {
                case ParameterType.FlipHorizontal: return "H";
                case ParameterType.FlipVertical: return "V";
                case ParameterType.AdditiveBlending: return "A";
                default: throw new InvalidOperationException(Type.ToString());
            }
        }

        public override string ToString() => ToOsbString(ExportSettings.Default);

        public float DistanceFrom(object obj)
        {
            var other = (CommandParameter)obj;
            return other.Type != Type ? 1 : 0;
        }

        public static bool operator ==(CommandParameter left, CommandParameter right)
            => left.Type == right.Type;

        public static bool operator !=(CommandParameter left, CommandParameter right)
            => left.Type != right.Type;

        public static implicit operator bool(CommandParameter obj)
            => obj.Type != ParameterType.None;
    }
}


text:
package _03ComparableBook;

public class Main {
    public static void main(String[] args) {
        Book bookOne = new Book("Animal Farm", 2003, "George Orwell");
        Book bookTwo = new Book("The Documents in the Case", 1930, "Dorothy Sayers", "Robert Eustace");
        Book bookThree = new Book("The Documents in the Case", 2002);
        if (bookOne.compareTo(bookTwo) > 0) {
            System.out.println(String.format("%s is before %s", bookOne.getTitle(), bookTwo.getTitle()));
        } else if (bookOne.compareTo(bookTwo) < 0) {
            System.out.println(String.format("%s is before %s", bookTwo.getTitle(), bookOne.getTitle()));
        } else {
            System.out.println("_04BookComparator.Book are equal");
        }
    }
}


text:
'use strict';

angular.module('customers').controller('CustomersUpdateController', ['$scope', 'Customers', 'Notify',
    function($scope, Customers, Notify ) {
		// Customers update controller logic

        $scope.channelOptions = [
            {id: '1', opt:'Facebook'},
            {id: '2', opt:'Twitter'},
            {id: '3', opt:'Email'}
        ];

        // Update existing Customer
        this.update = function(updatedCustomer) {
            var customer = updatedCustomer ;

            customer.$update(function(response) {

                Notify.sendMsg('UpdatedCustomer', {'id': response._id});

            }, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };
	}
]);


text:
var models = require('../../models')
var mongoose = require('mongoose')

var job = require('./job')

exports.unauthorized = function (app, template) {
	template([
		'jobs'
	], {
		prefix: 'job'
	});

	job.unauthorized(app, template);
}

exports.httpRouter = function (app) {
	job.httpRouter(app);
}

exports.router = function (app) {
	app.get('/playbook/:playbook_id/jobs', get)
		.post('/playbook/:playbook_id/jobs', add)

	job.router(app);
}

function get (req, res) {
	models.Job.find({
		playbook: req.playbook._id
	}).sort('-created').exec(function (err, jobs) {
		res.send(jobs)
	})
}

function add (req, res) {
	var job = new models.Job({
		playbook: req.playbook._id,
		name: req.body.name,
		play_file: req.body.play_file,
		exec_options: req.body.exec_options,
		extra_vars: req.body.extra_vars,
		use_vault: req.body.use_vault
	})

	job.save(function () {
		res.send(job);
	});
}


text:
<!DOCTYPE html>

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

Open up the console (F12) to see output


text:
package org.matcher.expression;

import static org.matcher.builder.BuilderUtils.getTableName;
import static org.matcher.builder.BuilderUtils.toAlias;

import org.matcher.parameter.ParameterBinding;

public class FromExpression extends Expression {

    public FromExpression(Class<?> referent) {
	setReferent(referent);
    }

    @Override
    public String resolve(ParameterBinding bindings) {
	final String tableName = getTableName(getReferent());
	return tableName + " " + toAlias(tableName);
    }
}


text:
package io.anand.springboot;

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(value="/info", description="Operations for Information")
public class InfoController {

	@Autowired
	private InfoService infoService;

	@RequestMapping("/info")
	public String getHealth () {
		return infoService.getHealth();
	}

	@RequestMapping("/info/version")
	public String getVersion () {
		return infoService.getVersion();
	}

	@RequestMapping("/info/build")
	public String getBuild () {
		return infoService.getBuild();
	}
}


text:
package com.mathbeta.rational.common.entity;

/**
 * Created by 147458 on 2017/4/12.
 */
public class Cluster extends BaseEntity {
    private String name;
    private String coordinatorId;
    private String description;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCoordinatorId() {
        return coordinatorId;
    }

    public void setCoordinatorId(String coordinatorId) {
        this.coordinatorId = coordinatorId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}


text:
'use strict';

/* global spawn, catchify,
    uniq, omit, extend, groupBy, filter, invert, takeWhile,
    mongoose, byId, Schema */

let User;

let schema = new Schema(
  {
    name: String,
    timezone: String,
    email: String,
    password: String,
    authRev: Number,
    devices: [{_id: false, gimbalId: String, name: String}],
    reporters: [{_id: false, reporterId: String, name: String}],
  },

  {collection: 'user'}
);

let byEmail = {email: 1};
schema.index(byEmail, {unique: true, sparse: true});

let byName = {name: 1};
schema.index(byName);

let byDevice = {'devices.gimbalId': 1, name: 1};
schema.index(byDevice);

let byDeviceUnique = {'devices.gimbalId': 1};
schema.index(byDeviceUnique, {unique: true, sparse: true});

let byDeviceMap = {'devices.gimbalId': 1, _id: 1};
schema.index(byDeviceMap, {unique: true});

let byReporterUnique = {'reporters.reporterId': 1};
schema.index(byReporterUnique, {unique: true, sparse: true});

let S = schema.statics;

let moment = require('moment-timezone');

// regexp of valid email
S.validEmail = new RegExp(
  '^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)' +
  '|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.' +
  '[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$'
);

// validate email
S.validateEmail = (email) => (
  email && email.length &&
  User.validEmail.test(email)
);

// validate password
S.validatePassword = (password) => (
  password && password.length && password.length >= 6
);

// validate name
S.validateName = (name) => (
  name && name.length && name.length >= 3
);

// validate device
S.validateGimbalId = (device) => (
  device && device.length && /^[a-zA-Z0-9-_]+$/.test(device)
);

// validate reporter id
S.validateReporterId = (reporterId) => (
  reporterId && reporterId.length &&
  reporterId.length >= 16 && S.validateGimbalId(reporterId)
);

// validate timezone
S.validateTimezone = (name) => (
  name && name.length && moment.tz.zone(name)
);

// register user
// {
//   name,
//   email,
//   password,
// }
// {
//   id
// }
S.register = (user) => spawn(function*() {
  if (!User.validateEmail(user.email)) throw ['badEmail'];
  if (!User.validatePassword(user.password)) throw ['badPassword'];
  if (!User.validateName(user.name)) throw ['badName'];
  if (!User.validateName(user.timezone)) throw ['badTimezone'];

  try {
    let found = yield User.findOneAndUpdate({
      name: user.name,
      email: {$exists: false},
    }, {
      $set: user,
      $inc: {authRev: 1},
      $setOnInsert: {},
    }, {
      upsert: true,
      sort: byName,
      new: true,
      select: {},
    }) [catchify]();

    return {id: found._id};
  } catch (err) {
    if (err.code === mongoose.ERROR_DUPLICATE) throw ['exists'];
    throw err;
  }
});

// auto register device
// {
//   deviceName,
//   deviceId,
// }
S.autoRegisterDevice = (user) => spawn(function*() {
  try {
    let found = yield User.findOneAndUpdate({
      name: user.deviceName,
    }, {
      $addToSet: {devices: {
        name: user.deviceName,
        gimbalId: user.deviceId,
      }},

      $setOnInsert: {
        name: user.deviceName,
        authRev: 1,
      },
    }, {
      upsert: true,
      sort: byName,
      new: true,
      select: {},
    }) [catchify]();

    return {id: found._id};
  } catch (err) {
    void err;
  }
});

// login user
// {
//   email,
//   password,
// }
// {
//   id,
//   authRev,
// }
S.login = (user) => spawn(function*() {
  if (!User.validateEmail(user.email)) throw ['badEmail'];
  if (!User.validatePassword(user.password)) throw ['badPassword'];

  let found = yield User.findOne(
    {email: user.email, password: user.password},
    {authRev: 1}
  ).sort(byEmail).exec() [catchify]();

  if (!found) throw ['badAuth'];

  return found.toObject() [omit]('_id') [extend]({id: found._id});
});

// auth user
// {
//   id,
//   authRev,
// }
// {
//   id,
//   name,
//   email,
//   devices: [],
// }
S.auth = (user) => spawn(function*() {
  let found = yield User.findOne(
    {_id: user.id, authRev: user.authRev},
    {name: 1, email: 1, devices: 1, reporters: 1}
  ).sort(byId).exec() [catchify]();

  if (!found) throw ['badToken'];

  return found.toObject() [omit]('_id') [extend]({id: found._id});
});

// get users
// {
//   caller,
//   ids,
//   gimbalIds,
// }
// [{
//   id,
//   name,
//   email,
//   devices: [],
// }]
S.get = (user) => spawn(function*() {

  //jshint maxcomplexity: 15

  //TODO: security; if (!user.ids) user.ids = [null];

  if (user.ids) {
    for (let idIdx in user.ids) {
      let id = user.ids[idIdx];
      if (!id || id === 'me') user.ids[idIdx] = id = user.caller.id;
      if (id === user.caller.id) user.ids[idIdx] = null;
      else if (!user.caller.admin) throw ['denied'];
    }
  }

  let query = {};

  let proj = {
    name: 1,

    //email: 1,
    //devices: 1,

  };

  let sort = byName;
  let noCall = false;

  if (user.ids) {
    let userIds = user.ids [uniq]() [filter](id => id);
    if (!userIds.length) noCall = true;
    query._id = {$in: userIds};
    sort = byId;
  }

  if (user.gimbalIds) {
    let gimbalIds = user.gimbalIds [uniq]();
    if (!gimbalIds.length) noCall = true;
    query.devices =
    proj.devices = {$elemMatch: {gimbalId: {$in: gimbalIds}}};
    if (sort !== byId) sort = byDevice;
  }

  let found = noCall ? [] : yield User.find(query, proj).sort(sort).exec() [catchify]();
  found = found.map(doc => doc.toObject() [omit]('_id') [extend]({id: doc._id}));

  let gimbalIdsInv = user.gimbalIds && user.gimbalIds [invert]();

  if (user.ids) {
    let grouped = found [groupBy](user => user.id);
    found = user.ids.map((id) => {
      if (id) return (grouped[id] || [null]) [0];
      if (!user.gimbalIds) return user.caller;
      return (
        user.caller.devices
        [takeWhile](device => !(device.gimbalId in gimbalIdsInv))
      ).length < user.caller.devices.length;
    });
  } else if (user.gimbalIds) {
    let grouped = found [groupBy](user => user.devices[0].gimbalId);
    found = user.gimbalIds.map(gimbalId => (grouped[gimbalId] || [null]) [0]);
  }

  return found;
});

// add user's device
// {
//   caller,
//   id,
//   device: {
//     gimbalId,
//     name,
//   }
// }
S.deviceAdd = (user) => spawn(function*() {
  if (!User.validateGimbalId(user.device.gimbalId)) throw ['badGimbalId'];
  if (user.id !== user.caller.id) throw ['denied'];
  let stat;

  try {
    stat = yield User.update(
      {_id: user.id, 'devices.gimbalId': {$ne: user.device.gimbalId}},
      {$addToSet: {devices: user.device}}
    ) [catchify]();
  } catch (err) {
    if (err.code === mongoose.ERROR_DUPLICATE) throw ['exists'];
    throw err;
  }

  if (!stat.n) throw ['exists']; //was 'notFound', but nModified doesn't work

  //if (!stat.nModified) throw ['exists'];

  return {gimbalId: user.device.gimbalId};
});

// delete user's device
// {
//   caller,
//   id,
//   gimbalId,
// }
S.deviceRemove = (user) => spawn(function*() {
  if (!User.validateGimbalId(user.gimbalId)) throw ['badGimbalId'];
  if (user.id !== user.caller.id) throw ['denied'];

  let stat = yield User.update(
    {_id: user.id},
    {$pull: {devices: {gimbalId: user.gimbalId}}}
  ) [catchify]();

  if (!stat.n) throw ['notFound'];
  if (!stat.nModified) throw ['notFound'];

  return {gimbalId: user.gimbalId};
});

// add user's reporter
// {
//   caller,
//   id,
//   reporter: {
//     reporterId,
//     name,
//   }
// }
S.reporterAdd = (user) => spawn(function*() {
  if (!User.validateReporterId(user.reporter.reporterId)) throw ['badReporterId'];
  if (user.id !== user.caller.id) throw ['denied'];
  let stat;

  try {
    stat = yield User.update(
      {_id: user.id, 'reporters.reporterId': {$ne: user.reporter.reporterId}},
      {$addToSet: {reporters: user.reporter}}
    ) [catchify]();
  } catch (err) {
    if (err.code === mongoose.ERROR_DUPLICATE) throw ['exists'];
    throw err;
  }

  if (!stat.n) throw ['exists']; //was 'notFound', but nModified doesn't work

  //if (!stat.nModified) throw ['exists'];

  return {reporterId: user.reporter.reporterId};
});

// delete user's reporter
// {
//   caller,
//   id,
//   reporterId,
// }
S.reporterRemove = (user) => spawn(function*() {
  if (!User.validateReporterId(user.reporterId)) throw ['badReporterId'];
  if (user.id !== user.caller.id) throw ['denied'];

  let stat = yield User.update(
    {_id: user.id},
    {$pull: {reporters: {reporterId: user.reporterId}}}
  ) [catchify]();

  if (!stat.n) throw ['notFound'];
  if (!stat.nModified) throw ['notFound'];

  return {reporterId: user.reporterId};
});

//{
//  reporterId
//}
//{
//  id
//}
S.resolveByReporter = (reporter) => spawn(function*() {
  if (!User.validateReporterId(reporter.reporterId)) throw ['badReporterId'];

  let found = yield User.findOne({
    'reporters.reporterId': reporter.reporterId,
  }, {name: 1, timezone: 1}).sort(byReporterUnique) [catchify]();

  if (!found) throw ['notFound'];
  return found [omit]('_id') [extend]({id: found._id});
});

User = module.exports = mongoose.model('User', schema);


text:
# traits/i-visible

This module provides a trait for a component that needs to implement the "visibility" behavior, like "hiding" or "showing".

## Synopsis

* This module provides an abstract class, not a component.

* The trait uses `aria` attributes.

* The trait contains TS logic and default styles.

## Modifiers

| Name     | Description             | Values    | Default |
|----------|-------------------------|-----------|---------|
| `hidden` | The component is hidden | `boolean` | -       |

To support these events, override `initModEvents` in your component and invoke a helper method from the trait.

```typescript
import iVisible from 'traits/i-visible/i-visible';

export default class bButton implements iVisible {
  static override readonly mods: ModsDecl = {
    ...iVisible.mods
  }
}
```

## Events

| Name   | Description                   | Payload description | Payload |
|--------|-------------------------------|---------------------|---------|
| `show` | The component has been shown  | -                   | -       |
| `hide` | The component has been hidden | -                   | -       |

To support these events, override `initModEvents` in your component and invoke a helper method from the trait.

```typescript
import iVisible from 'traits/i-visible/i-visible';

export default class bButton implements iVisible {
  /** @override */
  protected initModEvents(): void {
    super.initModEvents();
    iVisible.initModEvents(this);
  }
}
```

## Helpers

The trait provides a bunch of helper functions to initialize event listeners.

### initModEvents

Initialize modifier event listeners to emit trait events.

```typescript
import iVisible from 'traits/i-visible/i-visible';

export default class bButton implements iVisible {
  /** @override */
  protected initModEvents(): void {
    super.initModEvents();
    iVisible.initModEvents(this);
  }
}
```

## Styles

The trait provides a bunch of optional styles for the component.

```stylus
$p = {
  helpers: true
}

i-visible
  if $p.helpers
    &_hidden_true
      display none
```

To enable these styles, import the trait within your component and call the provided mixin within your component.

```stylus
@import "traits/i-visible/i-visible.styl"

$p = {
  visibleHelpers: true
}

b-button
  i-visible({helpers: $p.visibleHelpers})
```


text:
package org.apache.jackrabbit.oak.plugins.document.mongo;

import java.util.Iterator;
import java.util.concurrent.TimeUnit;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoQueryException;
import com.mongodb.client.MongoCollection;

import org.apache.jackrabbit.oak.plugins.document.AbstractMongoConnectionTest;
import org.apache.jackrabbit.oak.plugins.document.DocumentMK;
import org.apache.jackrabbit.oak.plugins.document.DocumentMKBuilderProvider;
import org.apache.jackrabbit.oak.plugins.document.DocumentNodeStore;
import org.apache.jackrabbit.oak.plugins.document.LeaseCheckMode;
import org.apache.jackrabbit.oak.plugins.document.NodeDocument;
import org.apache.jackrabbit.oak.plugins.document.TestUtils;
import org.apache.jackrabbit.oak.plugins.document.VersionGarbageCollector;
import org.apache.jackrabbit.oak.plugins.document.VersionGarbageCollector.VersionGCStats;
import org.apache.jackrabbit.oak.plugins.document.cache.NodeDocumentCache;
import org.apache.jackrabbit.oak.plugins.document.util.Utils;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.stats.Clock;
import org.junit.Rule;
import org.junit.Test;

import static java.util.concurrent.TimeUnit.HOURS;
import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES;
import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.SD_MAX_REV_TIME_IN_SECS;
import static org.apache.jackrabbit.oak.plugins.document.NodeDocument.SD_TYPE;
import static org.apache.jackrabbit.oak.plugins.document.TestUtils.getAllPreviousDocs;
import static org.apache.jackrabbit.oak.plugins.document.TestUtils.getMaxRangeHeight;
import static org.apache.jackrabbit.oak.plugins.document.TestUtils.merge;
import static org.apache.jackrabbit.oak.plugins.document.mongo.MongoUtils.hasIndex;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class MongoRevisionGCTest extends AbstractMongoConnectionTest {

    @Rule
    public DocumentMKBuilderProvider builderProvider = new DocumentMKBuilderProvider();

    // use a virtual clock, so we can fast-forward in time for revision gc
    private final Clock clock = new Clock.Virtual();

    @Override
    protected Clock getTestClock() throws InterruptedException {
        return clock;
    }

    @Override
    protected DocumentMK.Builder addToBuilder(DocumentMK.Builder mk) {
        // disable lease check because the test fiddles with the virtual clock
        // disable background operations by setting delay to zero. tests perform
        // background operations explicitly to control when changes become
        // visible to other cluster nodes
        return mk.setLeaseCheckMode(LeaseCheckMode.DISABLED).setAsyncDelay(0);
    }

    @Test
    public void gcWithoutCompoundIndex() throws Exception {
        DocumentNodeStore ns = mk.getNodeStore();
        // create some garbage
        NodeBuilder builder = ns.getRoot().builder();
        builder.child("foo");
        merge(ns, builder);
        builder = ns.getRoot().builder();
        builder.child("foo").remove();
        merge(ns, builder);
        // make sure those changes are visible to other cluster nodes
        ns.runBackgroundOperations();

        // wait two hours
        clock.waitUntil(clock.getTime() + TimeUnit.HOURS.toMillis(2));

        MongoCollection<?> nodes = mongoConnection.getDatabase()
                .getCollection(NODES.toString());
        assertTrue(hasIndex(nodes, SD_TYPE, SD_MAX_REV_TIME_IN_SECS));

        // delete compound index
        BasicDBObject keys = new BasicDBObject();
        keys.put(SD_TYPE,1);
        keys.put(SD_MAX_REV_TIME_IN_SECS, 1);
        nodes.dropIndex(keys);
        assertFalse(hasIndex(nodes, SD_TYPE, SD_MAX_REV_TIME_IN_SECS));

        try {
            ns.getVersionGarbageCollector().gc(3, TimeUnit.HOURS);
            fail("gc must fail with exception");
        } catch (MongoQueryException e) {
            // expected
        }

        // get a garbage collector from a fresh document node store
        VersionGarbageCollector gc = builderProvider.newBuilder().setMongoDB(
                mongoConnection.getMongoClient(), mongoConnection.getDBName())
                .clock(clock).setClusterId(2)
                .getNodeStore().getVersionGarbageCollector();

        // clean up garbage older than one hour
        VersionGCStats stats = gc.gc(1, TimeUnit.HOURS);
        assertEquals(1, TestUtils.getDeletedDocGCCount(stats));

    }

    @Test // OAK-9700
    public void malformedPreviousDocument() throws Exception {
        DocumentNodeStore ns = mk.getNodeStore();
        NodeDocument prev = null;
        NodeBuilder b;
        for (;;) {
            b = ns.getRoot().builder();
            b.child("child");
            merge(ns, b);
            b = ns.getRoot().builder();
            b.child("child").remove();
            merge(ns, b);
            ns.runBackgroundOperations();
            NodeDocument doc = ns.getDocumentStore().find(NODES, Utils.getIdFromPath("/child"));
            assertNotNull(doc);
            for (Iterator<NodeDocument> it = getAllPreviousDocs(doc); it.hasNext(); ) {
                prev = it.next();
            }
            if (getMaxRangeHeight(doc) > 0) {
                break;
            }
        }

        // wait two hours
        clock.waitUntil(clock.getTime() + HOURS.toMillis(2));

        // fiddle with prev document in cache and replace it with an invalid one
        MongoDocumentStore store = (MongoDocumentStore) ns.getDocumentStore();
        NodeDocumentCache cache = store.getNodeDocumentCache();
        assertNotNull(prev);
        String prevId = prev.getId();
        assertNotNull(prevId);
        cache.invalidate(prevId);
        cache.get(prevId, () -> new NodeDocument(store, clock.getTime()));

        // must succeed without exception
        try {
            ns.getVersionGarbageCollector().gc(1, HOURS);
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.toString());
        }
    }
}


text:
<?php

/**
 * @namespace
 */
namespace Zend\Form\Element;

/** Zend_Form_Element_Submit */
require_once 'Zend/Form/Element/Submit.php';

/**
 * Button form element
 *
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Button.php 20096 2010-01-06 02:05:09Z bkarwin $
 */
class Button extends Submit
{
    /**
     * Use formButton view helper by default
     * @var string
     */
    public $helper = 'formButton';
}


text:
package org.springframework.richclient.util;

import java.awt.Component;
import java.awt.Container;

import javax.swing.JPanel;
import javax.swing.Spring;
import javax.swing.SpringLayout;

import org.springframework.richclient.core.UIConstants;

/**
 * A 1.4 file that provides utility methods for creating form- or grid-style
 * layouts with SpringLayout. These utilities are used by several programs, such
 * as SpringBox and SpringCompactGrid.
 */
public class SpringLayoutUtils {

    /**
     * A debugging utility that prints to stdout the component's minimum,
     * preferred, and maximum sizes.
     */
    public static void printSizes(Component c) {
        System.out.println("minimumSize = " + c.getMinimumSize());
        System.out.println("preferredSize = " + c.getPreferredSize());
        System.out.println("maximumSize = " + c.getMaximumSize());
    }

    /**
     * Aligns the first rows*cols components of
     * parent in a grid. Each component is as big as the maximum
     * preferred width and height of the components. The parent is made just big
     * enough to fit them all.
     *
     * @param rows
     *            number of rows
     * @param cols
     *            number of columns
     * @param initialX
     *            x location to start the grid at
     * @param initialY
     *            y location to start the grid at
     * @param xPad
     *            x padding between cells
     * @param yPad
     *            y padding between cells
     */
    public static void makeGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad, int yPad) {

        SpringLayout layout;
        try {
            layout = (SpringLayout)parent.getLayout();
        }
        catch (ClassCastException exc) {
            System.err.println("The first argument to makeGrid must use SpringLayout.");
            return;
        }

        Spring xPadSpring = Spring.constant(xPad);
        Spring yPadSpring = Spring.constant(yPad);
        Spring initialXSpring = Spring.constant(initialX);
        Spring initialYSpring = Spring.constant(initialY);
        int max = rows * cols;

        //Calculate Springs that are the max of the width/height so that all
        //cells have the same size.
        Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)).getWidth();
        Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)).getWidth();
        for (int i = 1; i < max; i++) {
            SpringLayout.Constraints cons = layout.getConstraints(parent.getComponent(i));

            maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth());
            maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight());
        }

        //Apply the new width/height Spring. This forces all the
        //components to have the same size.
        for (int i = 0; i < max; i++) {
            SpringLayout.Constraints cons = layout.getConstraints(parent.getComponent(i));

            cons.setWidth(maxWidthSpring);
            cons.setHeight(maxHeightSpring);
        }

        //Then adjust the x/y constraints of all the cells so that they
        //are aligned in a grid.
        SpringLayout.Constraints lastCons = null;
        SpringLayout.Constraints lastRowCons = null;
        for (int i = 0; i < max; i++) {
            SpringLayout.Constraints cons = layout.getConstraints(parent.getComponent(i));
            if (i % cols == 0) { //start of new row
                lastRowCons = lastCons;
                cons.setX(initialXSpring);
            }
            else { //x position depends on previous component
                cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST), xPadSpring));
            }

            if (i / cols == 0) { //first row
                cons.setY(initialYSpring);
            }
            else { //y position depends on previous row
                cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH), yPadSpring));
            }
            lastCons = cons;
        }

        //Set the parent's size.
        SpringLayout.Constraints pCons = layout.getConstraints(parent);
        pCons.setConstraint(SpringLayout.SOUTH, Spring.sum(Spring.constant(yPad), lastCons
                .getConstraint(SpringLayout.SOUTH)));
        pCons.setConstraint(SpringLayout.EAST, Spring.sum(Spring.constant(xPad), lastCons
                .getConstraint(SpringLayout.EAST)));
    }

    /* Used by makeCompactGrid. */
    private static SpringLayout.Constraints getConstraintsForCell(int row, int col, Container parent, int cols) {
        SpringLayout layout = (SpringLayout)parent.getLayout();
        Component c = parent.getComponent(row * cols + col);
        return layout.getConstraints(c);
    }

    /**
     * Aligns the first rows*cols components of
     * parent in a grid. Each component in a column is as wide as
     * the maximum preferred width of the components in that column; height is
     * similarly determined for each row. The parent is made just big enough to
     * fit them all.
     *
     * @param rows
     *            number of rows
     * @param cols
     *            number of columns
     * @param initialX
     *            x location to start the grid at
     * @param initialY
     *            y location to start the grid at
     * @param xPad
     *            x padding between cells
     * @param yPad
     *            y padding between cells
     */
    public static void makeCompactGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad,
            int yPad) {
        SpringLayout layout;
        try {
            layout = (SpringLayout)parent.getLayout();
        }
        catch (ClassCastException exc) {
            System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
            return;
        }

        //Align all cells in each column and make them the same width.
        Spring x = Spring.constant(initialX);
        for (int c = 0; c < cols; c++) {
            Spring width = Spring.constant(0);
            for (int r = 0; r < rows; r++) {
                width = Spring.max(width, getConstraintsForCell(r, c, parent, cols).getWidth());
            }
            for (int r = 0; r < rows; r++) {
                SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols);
                constraints.setX(x);
                constraints.setWidth(width);
            }
            x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
        }

        //Align all cells in each row and make them the same height.
        Spring y = Spring.constant(initialY);
        for (int r = 0; r < rows; r++) {
            Spring height = Spring.constant(0);
            for (int c = 0; c < cols; c++) {
                height = Spring.max(height, getConstraintsForCell(r, c, parent, cols).getHeight());
            }
            for (int c = 0; c < cols; c++) {
                SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols);
                constraints.setY(y);
                constraints.setHeight(height);
            }
            y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
        }

        //Set the parent's size.
        SpringLayout.Constraints pCons = layout.getConstraints(parent);
        pCons.setConstraint(SpringLayout.SOUTH, y);
        pCons.setConstraint(SpringLayout.EAST, x);
    }

    /**
     * %DOC one sentence summary caption%.
     *
     * %long description%.
     *
     * @param contentPane
     * @param i
     * @param j
     */
    public static void makeCompactGridWithStandardBorder(JPanel contentPane, int rows, int cols) {
        makeCompactGrid(contentPane, rows, cols, UIConstants.ONE_SPACE, UIConstants.ONE_SPACE, UIConstants.ONE_SPACE,
                UIConstants.ONE_SPACE);

    }
}


text:
package gameplay;

import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;

import javax.swing.ImageIcon;

public class Torch {

	private Image image;
	private Image f1, f2, f3, f4, f5, f6, f7, f8, f9;
	private int torchIndex = 1;
	private int x;
	private int y;
	private int width;
	private int height;
	private Direction direction;

	public Torch() {

		this.f1 = new ImageIcon(this.getClass().getResource(
				"/images/torch1.png")).getImage();
		this.f2 = new ImageIcon(this.getClass().getResource(
				"/images/torch2.png")).getImage();
		this.f3 = new ImageIcon(this.getClass().getResource(
				"/images/torch3.png")).getImage();
		this.f4 = new ImageIcon(this.getClass().getResource(
				"/images/torch4.png")).getImage();
		this.f5 = new ImageIcon(this.getClass().getResource(
				"/images/torch5.png")).getImage();
		this.f6 = new ImageIcon(this.getClass().getResource(
				"/images/torch6.png")).getImage();
		this.f7 = new ImageIcon(this.getClass().getResource(
				"/images/torch7.png")).getImage();
		this.f8 = new ImageIcon(this.getClass().getResource(
				"/images/torch8.png")).getImage();
		this.f9 = new ImageIcon(this.getClass().getResource(
				"/images/torch9.png")).getImage();
		this.image = f1;
		this.direction = Direction.LEFT;

		setWidth(getImage().getWidth(null));
		setHeight(getImage().getHeight(null));
	}

	/*
	 * Updates the current frame of the torch
	 */
	public void updateFrame() {
		switch (torchIndex) {
		case 1:
			setImage(f1);
			break;
		case 2:
			setImage(f2);
			break;
		case 3:
			setImage(f3);
			break;
		case 4:
			setImage(f4);
			break;
		case 5:
			setImage(f5);
			break;
		case 6:
			setImage(f6);
			break;
		case 7:
			setImage(f7);
			break;
		case 8:
			setImage(f8);
			break;
		case 9:
			setImage(f9);
			break;
		}
		if (torchIndex == 9) {
			torchIndex = 1;
		} else {
			torchIndex += 1;
		}
	}

	// Getters and Setters
	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public Image getImage() {
		return image;
	}

	public void setImage(Image image) {
		this.image = image;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public Direction getDirection() {
		return direction;
	}

	public void setDirection(Direction direction) {
		this.direction = direction;
	}
}


text:
@interface RMButtonStyle : RMBaseStyle

@property(nonatomic, strong) UIFont *font;
@property(nonatomic, strong) UIColor *textColor;
@property(nonatomic) UIColor *highlightedBgColor;
@property(nonatomic) UIColor *highlightedTextColor;
@property(nonatomic, strong) UIColor *disabledBgColor;
@property(nonatomic, strong) UIColor *disabledTextColor;
@property(nonatomic, strong) NSDictionary<NSString *, id> * textAttributes;
@property(nonatomic, strong) NSDictionary<NSString *, id> * hightLightedTextAttributes;
@property(nonatomic, strong) NSDictionary<NSString *, id> * disabledTextAttributes;

@end


text:
using System;

namespace ScriptSharp.ScriptModel {

    interface ISymbolTransformer {

        string TransformSymbol(Symbol symbol, out bool transformChildren);
    }
}


text:
require 'fileutils'

puts "Installing into your rails app.."
plugin_name = 'wee_lightbox'

src =  "#{RAILS_ROOT}/vendor/plugins/#{plugin_name}/files/."
dest = "#{RAILS_ROOT}/public"
options = {:verbose => true}

FileUtils.cp_r(src, dest, options)

puts "All done!"


text:
import React, {Component} from "react";
import MobileSlideNav from './MobileSlideNav.js';
import { scrollBeginRegister, scrollEndRegister, scrollSpyUpdate, scrollBeginRemove, scrollEndRemove, scrollTo } from './modules/scrollFunctions.js';

export default class MobileNavigation extends Component {

  state = { viewSlideOutNav: false }

  componentDidMount() {
    scrollBeginRegister();
    scrollEndRegister();
    scrollSpyUpdate();

    window.addEventListener('scroll', this.animateNavigation)
  }

  componentWillUnmount() {
    scrollBeginRemove();
    scrollEndRemove();

    window.removeEventListener('scroll', this.animateNavigation)
  }

  stopScroll = () => document.querySelector('body').classList.add('stop-scroll')
  startScroll = () => document.querySelector('body').classList.remove('stop-scroll')
  animateNavigation = () => window.pageYOffset > 200 ? this.shrinkNavigation() : this.growNavigation()
  scrollToOffset = offset => scrollTo(offset)
  scrollToComponent = component => this.findOffsetTop(component)
  findOffsetTop = componentId => this.scrollToOffset(document.getElementById(componentId).offsetTop)

  shrinkNavigation = () => {
    Object.assign(document.querySelector('.mobile-nav .hamburger-container').style,{
      backgroundColor:"#000",
      borderColor:'rgba(214, 214, 214, 0.5)',
      transition:'0.5s'
    });
    document.querySelector('.mobile-nav i').style.color = '#fff'
  }

  growNavigation = () => {
    Object.assign(document.querySelector('.mobile-nav .hamburger-container').style,{
      backgroundColor:"transparent",
      color:'#fff',
      borderColor:'transparent',
      transition:'0.5s'
    });
    document.querySelector('.mobile-nav i').style.color = '#fff'
  }

  handleHamburgerClick = () => {
    if(!this.state.viewSlideOutNav){
      this.stopScroll();
      this.setState({ viewSlideOutNav: true })
    }
    if(this.state.viewSlideOutNav){
      this.startScroll();
      this.setState({ viewSlideOutNav: false })
    }
  }

  handleCloseSlideNav = () => {
    this.startScroll();
    this.setState({ viewSlideOutNav: false })
  }

  render() {
    let slide = this.state.viewSlideOutNav;
    return (

          { this.state.viewSlideOutNav ?
            <MobileSlideNav
              closeSlideNav={this.handleCloseSlideNav}
              scrollToComponent={this.scrollToComponent}
            /> :
          null }

    )
  }
}


text:
axistream_spw_lite_1.0
----------------------

# Functionality

The core instantiates a spacewire interface with an AXI-Stream wrapper.

## Slave

The TLAST flag is used to generate an spw EOP byte

## Master

The TLAST flag is generated on the last byte before the EOP byte is sent

# SpaceWire Lite IP
Core uses SpaceWire Lite vhdl files acquired from opencores - https://opencores.org/project/spacewire_light

The SpaceWire Lite VHDL has been un-modified. The source code is located in the ./src directory along with the licenses and original readme


text:
import { agent } from 'supertest';
import expect from 'expect';

import app from '../../../bin/www';

process.env.NODE_ENV = 'test';

// This agent refers to PORT where program is runninng.
const server = agent(app);

describe('Login/Logout API', () => {
  let user;
  describe('Login API', () => {
    it('should login user', (done) => {
      server
        .post('/users/login')
        .send({ email: 'anuonifade@gmail.com', password: 'password' })
        .end((err, res) => {
          user = res.body;
          expect(res.status).toEqual(200);
          expect(res.body.message).toEqual('User authenticated successfully');
          done();
        });
    });

    it('logged in user should have a token', (done) => {
      expect(user.token).toExist();
      done();
    });

    it('should return Wrong Password login user', (done) => {
      server
        .post('/users/login')
        .send({ email: 'anuonifade@gmail.com', password: '123456' })
        .end((err, res) => {
          expect(res.status).toEqual(401);
          expect(res.body.message).toEqual(
            'Authentication failed. Wrong password.');
          done();
        });
    });

    it('should not authorize a user without a token', (done) => {
      server
        .get('/users')
        .end((err, res) => {
          expect(res.status).toEqual(401);
          done();
        });
    });
  });

  describe('Invalid Login', () => {
    it('should not login user with invalid email', (done) => {
      server
        .post('/users/login')
        .send({ email: 'hello@yahoo.com', password: '12345' })
        .end((err, res) => {
          expect(res.status).toEqual(401);
          expect(res.body.message).toEqual(
            'Authentication Failed. User not found.');
          done();
        });
    });

    it('should not authenticate user', (done) => {
      server
        .post('/users/login')
        .end((err, res) => {
          expect(res.status).toEqual(401);
          expect(res.body.message).toEqual(
            'Authentication Failed. User not found.');
          done();
        });
    });

    it('should not authenticate user without password', (done) => {
      server
        .post('/users/login')
        .send({ email: 'anuonifade@gmail.com' })
        .end((err, res) => {
          expect(res.status).toEqual(400);
          expect(res.body.message).toEqual(
            'Error occurred while authenticating user');
          done();
        });
    });
  });

  describe('Logout API', () => {
    it('Should return a message on logout', (done) => {
      server
        .post('/users/logout')
        .end((err, res) => {
          expect(res.status).toEqual(200);
          expect(res.body.message).toEqual('You have successfully logged out');
          done();
        });
    });
  });
});


text:
import React, { Component, PropTypes } from 'react';

const propTypes = {
  icon: PropTypes.string,
  showIcon: PropTypes.bool,
  title: PropTypes.string,
  items: PropTypes.array,
  isSelected: PropTypes.bool,
  onClick: PropTypes.func,
  onItemClick: PropTypes.func,
};

const defaultProps = {
  icon: 'fa fa-circle-o',
  showIcon: true,
  isSelected: false,
  items: [],
};

class TreeSubMenu extends Component {
  constructor(props) {
    super(props);
    this.renderItem = this.renderItems.bind(this);
  }

  renderItems() {
    if (this.props.items.length > 0) {
      return (

          {this.props.items.map((item) => (
            <TreeSubMenu
              {...item}
              onClick={() => this.props.onItemClick(item)}
              onItemClick={this.props.onItemClick}
            />
          ))}

      );
    }

    return '';
  }

  render() {
    return (

          {this.props.showIcon
            ?
            : ''
          }
           {this.props.title}
          {this.props.items.length > 0
            ?

            : ''
          }

        {this.renderItems()}

    );
  }
}

TreeSubMenu.propTypes = propTypes;
TreeSubMenu.defaultProps = defaultProps;

export default TreeSubMenu;


text:
namespace Microsoft.Protocols.TestSuites.MS_OXCMAPIHTTP
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using Microsoft.Protocols.TestSuites.Common;

    /// <summary>
    /// PropertyValueNode with property tag and property value
    /// </summary>
    [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Disable warning SA1401 because it should not be treated like a property.")]
    public class AddressBookTaggedPropertyValue : AddressBookPropertyValue
    {
        /// <summary>
        /// 16-bit unsigned integer that identifies the data type of the property value.
        /// </summary>
        public ushort PropertyType;

            /// <summary>
        /// A 16-bit unsigned integer that identifies the property.
        /// </summary>
        public ushort PropertyId;

        /// <summary>
        /// Serialize the ROP request buffer.
        /// </summary>
        /// <returns>The ROP request buffer serialized.</returns>
        public override byte[] Serialize()
        {
            int index = 0;
            byte[] resultBytes = new byte[this.Size()];
            Array.Copy(BitConverter.GetBytes((ushort)this.PropertyType), 0, resultBytes, index, sizeof(ushort));
            index += sizeof(ushort);
            Array.Copy(BitConverter.GetBytes((ushort)this.PropertyId), 0, resultBytes, index, sizeof(ushort));
            index += sizeof(ushort);
            Array.Copy(base.Serialize(), 0, resultBytes, index, base.Size());
            index += base.Size();
            return resultBytes;
        }

        /// <summary>
        /// Return the Size of this struct.
        /// </summary>
        /// <returns>The Size of this struct.</returns>
        public override int Size()
        {
            int size = sizeof(ushort);
            size += sizeof(ushort);
            size += base.Size();
            return size;
        }

        /// <summary>
        /// Parse bytes in context into TaggedPropertyValueNode
        /// </summary>
        /// <param name="context">The value of Context</param>
        public override void Parse(Context context)
        {
            // Parse PropertyType and assign it to context's current PropertyType
            this.PropertyType = (ushort)BitConverter.ToInt16(context.PropertyBytes, context.CurIndex);
            context.CurProperty.Type = (PropertyType)this.PropertyType;
            context.CurIndex += sizeof(ushort);
            this.PropertyId = (ushort)BitConverter.ToInt16(context.PropertyBytes, context.CurIndex);
            context.CurIndex += sizeof(ushort);
            base.Parse(context);
        }
    }
}


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <nuttx/arch.h>
#include <nuttx/irq.h>

#include "chip/switch.h"
#include "up_internal.h"

/****************************************************************************
 * Private Definitions
 ****************************************************************************/

/****************************************************************************
 * Public Data
 ****************************************************************************/

/* This holds a references to the current interrupt level register storage
 * structure.  If is non-NULL only during interrupt processing.
 */

volatile chipreg_t *current_regs;

/****************************************************************************
 * Private Data
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: up_irqinitialize
 ****************************************************************************/

void up_irqinitialize(void)
{
  current_regs = NULL;

  /* And finally, enable interrupts */

#ifndef CONFIG_SUPPRESS_INTERRUPTS
  asm("ei");
#endif
}

/****************************************************************************
 * Name: up_disable_irq
 *
 * Description:
 *   On many architectures, there are three levels of interrupt enabling: (1)
 *   at the global level, (2) at the level of the interrupt controller,
 *   and (3) at the device level.  In order to receive interrupts, they
 *   must be enabled at all three levels.
 *
 *   This function implements disabling of the device specified by 'irq'
 *   at the interrupt controller level if supported by the architecture
 *   (irqsave() supports the global level, the device level is hardware
 *   specific).
 *
 ****************************************************************************/

void up_disable_irq(int irq)
{
  /* There are no ez80 interrupt controller settings to disable IRQs */
}

/****************************************************************************
 * Name: up_enable_irq
 *
 * Description:
 *   This function implements enabling of the device specified by 'irq'
 *   at the interrupt controller level if supported by the architecture
 *   (irqsave() supports the global level, the device level is hardware
 *   specific).
 *
 ****************************************************************************/

void up_enable_irq(int irq)
{
  /* There are no ez80 interrupt controller settings to enable IRQs */
}